summaryrefslogtreecommitdiffstats
path: root/Essentials/src/net/ess3/storage/AbstractDelayedYamlFileWriter.java
blob: ade8eeb93748ee1e297dbc2b90bb16e2725df8c0 (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
package net.ess3.storage;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import net.ess3.api.IEssentials;
import org.bukkit.Bukkit;


public abstract class AbstractDelayedYamlFileWriter implements Runnable
{
	private final IEssentials ess;
	private final ReentrantLock lock = new ReentrantLock(); // TODO: Needed?

	public AbstractDelayedYamlFileWriter(final IEssentials ess)
	{
		this.ess = ess;
	}

	public void schedule()
	{
		ess.getPlugin().scheduleAsyncDelayedTask(this);
	}

	public abstract File getFile();

	public abstract StorageObject getObject();

	@Override
	public void run()
	{
		final File file = getFile();
		synchronized (file)
		{
			PrintWriter pw = null;
			try
			{
				final StorageObject object = getObject();
				final File folder = file.getParentFile();
				if (!folder.exists())
				{
					folder.mkdirs();
				}
				pw = new PrintWriter(file);
				new YamlStorageWriter(pw).save(object);
			}
			catch (FileNotFoundException ex)
			{
				Bukkit.getLogger().log(Level.SEVERE, file.toString(), ex);
			}
			finally
			{
				onFinish();
				if (pw != null)
				{
					pw.close();
				}
			}
		}
	}

	public abstract void onFinish();
}