summaryrefslogtreecommitdiffstats
path: root/Essentials/src/net/ess3/storage/AbstractDelayedYamlFileReader.java
blob: 71413834928a7763a6f52893261486c250f783e8 (plain)
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
package net.ess3.storage;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import net.ess3.api.IEssentials;
import org.bukkit.Bukkit;


public abstract class AbstractDelayedYamlFileReader<T extends StorageObject> implements Runnable
{
	private final Class<T> clazz;
	private final IEssentials ess;

	public AbstractDelayedYamlFileReader(final IEssentials ess, final Class<T> clazz)
	{
		this.clazz = clazz;
		this.ess = ess;
	}

	public void schedule(boolean instant)
	{
		if (instant)
		{
			run();
		}
		else
		{
			ess.getPlugin().scheduleAsyncDelayedTask(this);
		}
	}

	public abstract File onStart();

	@Override
	public void run()
	{
		final File file = onStart();
		synchronized (file)
		{
			try
			{
				final FileReader reader = new FileReader(file);
				try
				{
					final T object = new YamlStorageReader(reader, ess.getPlugin()).load(clazz);
					onSuccess(object);
				}
				finally
				{
					try
					{
						reader.close();
					}
					catch (IOException ex)
					{
						Bukkit.getLogger().log(Level.SEVERE, "File can't be closed: " + file.toString(), ex);
					}
				}

			}
			catch (FileNotFoundException ex)
			{
				onException(ex);
				Bukkit.getLogger().log(Level.INFO, "File not found: " + file.toString());
			}
			catch (ObjectLoadException ex)
			{
				onException(ex);
				File broken = new File(file.getAbsolutePath() + ".broken." + System.currentTimeMillis());
				file.renameTo(broken);
				Bukkit.getLogger().log(Level.SEVERE, "The file " + file.toString() + " is broken, it has been renamed to " + broken.toString(), ex.getCause());
			}
		}
	}

	public abstract void onSuccess(T object);

	public abstract void onException(Exception exception);
}