4
* Copyright 2012 Massive Dynamics.
6
* Permission is hereby granted, free of charge, to any person obtaining a copy
7
* of this software and associated documentation files (the "Software"), to deal
8
* in the Software without restriction, including without limitation the rights
9
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
* copies of the Software, and to permit persons to whom the Software is
11
* furnished to do so, subject to the following conditions:
13
* The above copyright notice and this permission notice shall be included in
14
* all copies or substantial portions of the Software.
16
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24
package biz.massivedynamics.sourcery.management;
27
import org.yaml.snakeyaml.Yaml;
30
* A simple Yaml resource manager
32
* @param <T> The type of resource to load
36
public abstract class SimpleYamlResourceManager<T> extends FileResourceManager<T> {
39
* Creates a new simple Yaml resource manager
41
* @param file The file to use
44
public SimpleYamlResourceManager(final File file) {
51
* @return The resource
57
final Yaml rawYaml = new Yaml();
58
//Get a file input stream
59
FileInputStream stream = null;
62
stream = new FileInputStream(this.getFile());
64
final T data = (T) rawYaml.load(stream);
67
} catch (FileNotFoundException ex) {
69
this.save(this.getDefault());
70
//Load the default values
71
return this.getDefault();
77
} catch (IOException ex) {
78
//Couldn't close the stream for some reason
84
public void save(final T raw) {
86
final Yaml rawYaml = new Yaml();
88
FileWriter writer = null;
90
//Set up the file writer
91
writer = new FileWriter(this.getFile());
93
rawYaml.dump(raw, writer);
94
} catch (FileNotFoundException ex) {
96
//Maky any parent directories
97
this.getFile().getParentFile().mkdirs();
98
//See if we can create a file
99
if (this.getFile().createNewFile()) {
103
//Couldn't create the file! Nothing will be saved.
104
} catch (IOException ex1) {
105
//You don't want to know
107
} catch (IOException ex) {
111
if (writer != null) {
114
} catch (IOException ex) {
115
//Seriously, this will NEVER happen unless you break something on purpose!