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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
|
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n.tl;
import com.google.common.io.Files;
import java.io.*;
import java.math.BigDecimal;
import java.math.MathContext;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.ess3.api.InvalidWorldException;
import org.bukkit.*;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
public class EssentialsConf extends YamlConfiguration
{
protected static final Logger LOGGER = Logger.getLogger("Essentials");
protected final File configFile;
protected String templateName = null;
protected static final Charset UTF8 = Charset.forName("UTF-8");
private Class<?> resourceClass = EssentialsConf.class;
private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor();
private final AtomicInteger pendingDiskWrites = new AtomicInteger(0);
private final AtomicBoolean transaction = new AtomicBoolean(false);
public EssentialsConf(final File configFile)
{
super();
this.configFile = configFile.getAbsoluteFile();
}
private final byte[] bytebuffer = new byte[1024];
public synchronized void load()
{
if (pendingDiskWrites.get() != 0)
{
LOGGER.log(Level.INFO, "File {0} not read, because it''s not yet written to disk.", configFile);
return;
}
if (!configFile.getParentFile().exists())
{
if (!configFile.getParentFile().mkdirs())
{
LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()));
}
}
// This will delete files where the first character is 0. In most cases they are broken.
if (configFile.exists() && configFile.length() != 0)
{
try
{
final InputStream input = new FileInputStream(configFile);
try
{
if (input.read() == 0)
{
input.close();
configFile.delete();
}
}
catch (IOException ex)
{
LOGGER.log(Level.SEVERE, null, ex);
}
finally
{
try
{
input.close();
}
catch (IOException ex)
{
LOGGER.log(Level.SEVERE, null, ex);
}
}
}
catch (FileNotFoundException ex)
{
LOGGER.log(Level.SEVERE, null, ex);
}
}
if (!configFile.exists())
{
if (legacyFileExists())
{
convertLegacyFile();
}
else if (altFileExists())
{
convertAltFile();
}
else if (templateName != null)
{
LOGGER.log(Level.INFO, tl("creatingConfigFromTemplate", configFile.toString()));
createFromTemplate();
}
else
{
return;
}
}
try
{
final FileInputStream inputStream = new FileInputStream(configFile);
try
{
long startSize = configFile.length();
if (startSize > Integer.MAX_VALUE)
{
throw new InvalidConfigurationException("File too big");
}
ByteBuffer buffer = ByteBuffer.allocate((int)startSize);
int length;
while ((length = inputStream.read(bytebuffer)) != -1)
{
if (length > buffer.remaining())
{
ByteBuffer resize = ByteBuffer.allocate(buffer.capacity() + length - buffer.remaining());
int resizePosition = buffer.position();
buffer.rewind();
resize.put(buffer);
resize.position(resizePosition);
buffer = resize;
}
buffer.put(bytebuffer, 0, length);
}
buffer.rewind();
final CharBuffer data = CharBuffer.allocate(buffer.capacity());
CharsetDecoder decoder = UTF8.newDecoder();
CoderResult result = decoder.decode(buffer, data, true);
if (result.isError())
{
buffer.rewind();
data.clear();
LOGGER.log(Level.INFO, "File " + configFile.getAbsolutePath().toString() + " is not utf-8 encoded, trying " + Charset.defaultCharset().displayName());
decoder = Charset.defaultCharset().newDecoder();
result = decoder.decode(buffer, data, true);
if (result.isError())
{
throw new InvalidConfigurationException("Invalid Characters in file " + configFile.getAbsolutePath().toString());
}
else
{
decoder.flush(data);
}
}
else
{
decoder.flush(data);
}
final int end = data.position();
data.rewind();
super.loadFromString(data.subSequence(0, end).toString());
}
finally
{
inputStream.close();
}
}
catch (IOException ex)
{
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
}
catch (InvalidConfigurationException ex)
{
File broken = new File(configFile.getAbsolutePath() + ".broken." + System.currentTimeMillis());
configFile.renameTo(broken);
LOGGER.log(Level.SEVERE, "The file " + configFile.toString() + " is broken, it has been renamed to " + broken.toString(), ex.getCause());
}
}
public boolean legacyFileExists()
{
return false;
}
public void convertLegacyFile()
{
LOGGER.log(Level.SEVERE, "Unable to import legacy config file.");
}
public boolean altFileExists()
{
return false;
}
public void convertAltFile()
{
LOGGER.log(Level.SEVERE, "Unable to import alt config file.");
}
private void createFromTemplate()
{
InputStream istr = null;
OutputStream ostr = null;
try
{
istr = resourceClass.getResourceAsStream(templateName);
if (istr == null)
{
LOGGER.log(Level.SEVERE, tl("couldNotFindTemplate", templateName));
return;
}
ostr = new FileOutputStream(configFile);
byte[] buffer = new byte[1024];
int length = 0;
length = istr.read(buffer);
while (length > 0)
{
ostr.write(buffer, 0, length);
length = istr.read(buffer);
}
}
catch (IOException ex)
{
LOGGER.log(Level.SEVERE, tl("failedToWriteConfig", configFile.toString()), ex);
}
finally
{
try
{
if (istr != null)
{
istr.close();
}
}
catch (IOException ex)
{
Logger.getLogger(EssentialsConf.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
if (ostr != null)
{
ostr.close();
}
}
catch (IOException ex)
{
LOGGER.log(Level.SEVERE, tl("failedToCloseConfig", configFile.toString()), ex);
}
}
}
public void setTemplateName(final String templateName)
{
this.templateName = templateName;
}
public File getFile()
{
return configFile;
}
public void setTemplateName(final String templateName, final Class<?> resClass)
{
this.templateName = templateName;
this.resourceClass = resClass;
}
public void startTransaction()
{
transaction.set(true);
}
public void stopTransaction()
{
transaction.set(false);
save();
}
public void save()
{
try
{
save(configFile);
}
catch (IOException ex)
{
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
}
}
public void saveWithError() throws IOException
{
save(configFile);
}
@Override
public synchronized void save(final File file) throws IOException
{
if (!transaction.get())
{
delayedSave(file);
}
}
public synchronized void forceSave()
{
try
{
Future<?> future = delayedSave(configFile);
if (future != null)
{
future.get();
}
}
catch (InterruptedException ex)
{
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
}
catch (ExecutionException ex)
{
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
}
}
private Future<?> delayedSave(final File file)
{
if (file == null)
{
throw new IllegalArgumentException("File cannot be null");
}
final String data = saveToString();
if (data.length() == 0)
{
return null;
}
pendingDiskWrites.incrementAndGet();
Future<?> future = EXECUTOR_SERVICE.submit(new WriteRunner(configFile, data, pendingDiskWrites));
return future;
}
private static class WriteRunner implements Runnable
{
private final File configFile;
private final String data;
private final AtomicInteger pendingDiskWrites;
private WriteRunner(final File configFile, final String data, final AtomicInteger pendingDiskWrites)
{
this.configFile = configFile;
this.data = data;
this.pendingDiskWrites = pendingDiskWrites;
}
@Override
public void run()
{
//long startTime = System.nanoTime();
synchronized (configFile)
{
if (pendingDiskWrites.get() > 1)
{
// Writes can be skipped, because they are stored in a queue (in the executor).
// Only the last is actually written.
pendingDiskWrites.decrementAndGet();
//LOGGER.log(Level.INFO, configFile + " skipped writing in " + (System.nanoTime() - startTime) + " nsec.");
return;
}
try
{
Files.createParentDirs(configFile);
if (!configFile.exists())
{
try
{
LOGGER.log(Level.INFO, tl("creatingEmptyConfig", configFile.toString()));
if (!configFile.createNewFile())
{
LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()));
return;
}
}
catch (IOException ex)
{
LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()), ex);
return;
}
}
final FileOutputStream fos = new FileOutputStream(configFile);
try
{
final OutputStreamWriter writer = new OutputStreamWriter(fos, UTF8);
try
{
writer.write(data);
}
finally
{
writer.close();
}
}
finally
{
fos.close();
}
}
catch (IOException e)
{
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
finally
{
//LOGGER.log(Level.INFO, configFile + " written to disk in " + (System.nanoTime() - startTime) + " nsec.");
pendingDiskWrites.decrementAndGet();
}
}
}
}
public boolean hasProperty(final String path)
{
return isSet(path);
}
public Location getLocation(final String path, final Server server) throws InvalidWorldException
{
final String worldString = (path == null ? "" : path + ".") + "world";
final String worldName = getString(worldString);
if (worldName == null || worldName.isEmpty())
{
return null;
}
final World world = server.getWorld(worldName);
if (world == null)
{
throw new InvalidWorldException(worldName);
}
return new Location(world,
getDouble((path == null ? "" : path + ".") + "x", 0),
getDouble((path == null ? "" : path + ".") + "y", 0),
getDouble((path == null ? "" : path + ".") + "z", 0),
(float)getDouble((path == null ? "" : path + ".") + "yaw", 0),
(float)getDouble((path == null ? "" : path + ".") + "pitch", 0));
}
public void setProperty(final String path, final Location loc)
{
set((path == null ? "" : path + ".") + "world", loc.getWorld().getName());
set((path == null ? "" : path + ".") + "x", loc.getX());
set((path == null ? "" : path + ".") + "y", loc.getY());
set((path == null ? "" : path + ".") + "z", loc.getZ());
set((path == null ? "" : path + ".") + "yaw", loc.getYaw());
set((path == null ? "" : path + ".") + "pitch", loc.getPitch());
}
@Override
public ItemStack getItemStack(final String path)
{
final ItemStack stack = new ItemStack(
Material.valueOf(getString(path + ".type", "AIR")),
getInt(path + ".amount", 1),
(short)getInt(path + ".damage", 0));
final ConfigurationSection enchants = getConfigurationSection(path + ".enchant");
if (enchants != null)
{
for (String enchant : enchants.getKeys(false))
{
final Enchantment enchantment = Enchantment.getByName(enchant.toUpperCase(Locale.ENGLISH));
if (enchantment == null)
{
continue;
}
final int level = getInt(path + ".enchant." + enchant, enchantment.getStartLevel());
stack.addUnsafeEnchantment(enchantment, level);
}
}
return stack;
/*
* ,
* (byte)getInt(path + ".data", 0)
*/
}
public void setProperty(final String path, final ItemStack stack)
{
final Map<String, Object> map = new HashMap<String, Object>();
map.put("type", stack.getType().toString());
map.put("amount", stack.getAmount());
map.put("damage", stack.getDurability());
Map<Enchantment, Integer> enchantments = stack.getEnchantments();
if (!enchantments.isEmpty())
{
Map<String, Integer> enchant = new HashMap<String, Integer>();
for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet())
{
enchant.put(entry.getKey().getName().toLowerCase(Locale.ENGLISH), entry.getValue());
}
map.put("enchant", enchant);
}
// getData().getData() is broken
//map.put("data", stack.getDurability());
set(path, map);
}
public void setProperty(String path, List object)
{
set(path, new ArrayList(object));
}
public void setProperty(String path, Map object)
{
set(path, new LinkedHashMap(object));
}
public Object getProperty(String path)
{
return get(path);
}
public void setProperty(final String path, final BigDecimal bigDecimal)
{
set(path, bigDecimal.toString());
}
public void setProperty(String path, Object object)
{
set(path, object);
}
public void removeProperty(String path)
{
set(path, null);
}
@Override
public synchronized Object get(String path)
{
return super.get(path);
}
@Override
public synchronized Object get(String path, Object def)
{
return super.get(path, def);
}
public synchronized BigDecimal getBigDecimal(final String path, final BigDecimal def)
{
final String input = super.getString(path);
return toBigDecimal(input, def);
}
public static BigDecimal toBigDecimal(final String input, final BigDecimal def)
{
if (input == null || input.isEmpty())
{
return def;
}
else
{
try
{
return new BigDecimal(input, MathContext.DECIMAL128);
}
catch (NumberFormatException e)
{
return def;
}
catch (ArithmeticException e)
{
return def;
}
}
}
@Override
public synchronized boolean getBoolean(String path)
{
return super.getBoolean(path);
}
@Override
public synchronized boolean getBoolean(String path, boolean def)
{
return super.getBoolean(path, def);
}
@Override
public synchronized List<Boolean> getBooleanList(String path)
{
return super.getBooleanList(path);
}
@Override
public synchronized List<Byte> getByteList(String path)
{
return super.getByteList(path);
}
@Override
public synchronized List<Character> getCharacterList(String path)
{
return super.getCharacterList(path);
}
@Override
public synchronized ConfigurationSection getConfigurationSection(String path)
{
return super.getConfigurationSection(path);
}
@Override
public synchronized double getDouble(String path)
{
return super.getDouble(path);
}
@Override
public synchronized double getDouble(final String path, final double def)
{
return super.getDouble(path, def);
}
@Override
public synchronized List<Double> getDoubleList(String path)
{
return super.getDoubleList(path);
}
@Override
public synchronized List<Float> getFloatList(String path)
{
return super.getFloatList(path);
}
@Override
public synchronized int getInt(String path)
{
return super.getInt(path);
}
@Override
public synchronized int getInt(String path, int def)
{
return super.getInt(path, def);
}
@Override
public synchronized List<Integer> getIntegerList(String path)
{
return super.getIntegerList(path);
}
@Override
public synchronized ItemStack getItemStack(String path, ItemStack def)
{
return super.getItemStack(path, def);
}
@Override
public synchronized Set<String> getKeys(boolean deep)
{
return super.getKeys(deep);
}
@Override
public synchronized List<?> getList(String path)
{
return super.getList(path);
}
@Override
public synchronized List<?> getList(String path, List<?> def)
{
return super.getList(path, def);
}
@Override
public synchronized long getLong(String path)
{
return super.getLong(path);
}
@Override
public synchronized long getLong(final String path, final long def)
{
return super.getLong(path, def);
}
@Override
public synchronized List<Long> getLongList(String path)
{
return super.getLongList(path);
}
public synchronized Map<String, Object> getMap()
{
return map;
}
@Override
public synchronized List<Map<?, ?>> getMapList(String path)
{
return super.getMapList(path);
}
@Override
public synchronized OfflinePlayer getOfflinePlayer(String path)
{
return super.getOfflinePlayer(path);
}
@Override
public synchronized OfflinePlayer getOfflinePlayer(String path, OfflinePlayer def)
{
return super.getOfflinePlayer(path, def);
}
@Override
public synchronized List<Short> getShortList(String path)
{
return super.getShortList(path);
}
@Override
public synchronized String getString(String path)
{
return super.getString(path);
}
@Override
public synchronized String getString(String path, String def)
{
return super.getString(path, def);
}
@Override
public synchronized List<String> getStringList(String path)
{
return super.getStringList(path);
}
@Override
public synchronized Map<String, Object> getValues(boolean deep)
{
return super.getValues(deep);
}
@Override
public synchronized Vector getVector(String path)
{
return super.getVector(path);
}
@Override
public synchronized Vector getVector(String path, Vector def)
{
return super.getVector(path, def);
}
@Override
public synchronized boolean isBoolean(String path)
{
return super.isBoolean(path);
}
@Override
public synchronized boolean isConfigurationSection(String path)
{
return super.isConfigurationSection(path);
}
@Override
public synchronized boolean isDouble(String path)
{
return super.isDouble(path);
}
@Override
public synchronized boolean isInt(String path)
{
return super.isInt(path);
}
@Override
public synchronized boolean isItemStack(String path)
{
return super.isItemStack(path);
}
@Override
public synchronized boolean isList(String path)
{
return super.isList(path);
}
@Override
public synchronized boolean isLong(String path)
{
return super.isLong(path);
}
@Override
public synchronized boolean isOfflinePlayer(String path)
{
return super.isOfflinePlayer(path);
}
@Override
public synchronized boolean isSet(String path)
{
return super.isSet(path);
}
@Override
public synchronized boolean isString(String path)
{
return super.isString(path);
}
@Override
public synchronized boolean isVector(String path)
{
return super.isVector(path);
}
@Override
public synchronized void set(String path, Object value)
{
super.set(path, value);
}
}
|