/*
|
* To change this license header, choose License Headers in Project Properties.
|
* To change this template file, choose Tools | Templates
|
* and open the template in the editor.
|
*/
|
package de.uhilger.mediaz.conf;
|
|
import com.google.gson.Gson;
|
import de.uhilger.mediaz.App;
|
import de.uhilger.mediaz.Server;
|
import de.uhilger.mediaz.entity.Ablage;
|
import de.uhilger.mediaz.entity.ConfigurationElement;
|
import java.io.BufferedReader;
|
import java.io.File;
|
import java.io.FileInputStream;
|
import java.io.FileNotFoundException;
|
import java.io.FileReader;
|
import java.io.FileWriter;
|
import java.io.IOException;
|
import java.io.InputStreamReader;
|
import java.util.logging.Logger;
|
|
/**
|
*
|
* @author ulrich
|
*/
|
public class Store {
|
|
private static final Logger logger = Logger.getLogger(Store.class.getName());
|
|
|
private static final String typeAblage = "Ablage";
|
|
/**
|
* Ein Objekt als JSON in eine Datei schreiben
|
*
|
* Es wird in den Ordner geschrieben, der von conf angegeben ist
|
*
|
* Wenn es z.B. ein Ablage-Objekt ist, wird das Objekt in die Datei
|
* [conf]/Ablage/[name der Ablage].json geschrieben
|
*
|
* Der Name der Ablage muss eindeutig sein
|
*
|
*
|
* @param o
|
*/
|
public File writeToFile(ConfigurationElement o) throws IOException {
|
Gson gson = new Gson();
|
String className = o.getClass().getSimpleName();
|
logger.finer(className);
|
File dir = new File(App.getInitParameter(App.getRs(App.RB_AP_CONF)), className);
|
dir.mkdirs();
|
File file = new File(dir, o.getName());
|
if(file.exists()) {
|
file.delete();
|
}
|
FileWriter fw = new FileWriter(file);
|
fw.write(gson.toJson(o));
|
fw.flush();
|
fw.close();
|
return file;
|
}
|
|
public ConfigurationElement readFromFile(File file) throws ClassNotFoundException, FileNotFoundException, IOException {
|
String type = typeFromName(file);
|
StringBuilder sb = new StringBuilder();
|
FileReader in = new FileReader(file);
|
BufferedReader r = new BufferedReader(in);
|
String line = r.readLine();
|
while(line != null) {
|
sb.append(line);
|
line = r.readLine();
|
}
|
r.close();
|
in.close();
|
String json = sb.toString();
|
Gson gson = new Gson();
|
switch(type) {
|
case typeAblage:
|
return gson.fromJson(json, Ablage.class);
|
default:
|
Ablage ablage = new Ablage();
|
ablage.setName("Test");
|
return ablage;
|
}
|
}
|
|
private String typeFromName(File file) {
|
//String path = file.getPath();
|
//logger.info(path);
|
String[] parts = file.getPath().split(App.getRs(Server.RB_SLASH));
|
//for(String part : parts) {
|
//logger.info(part);
|
//}
|
//logger.info("" + parts.length);
|
logger.info(parts[parts.length-2]);
|
return parts[parts.length-2];
|
}
|
}
|