package codeine.utils;

import java.lang.reflect.Type;

import javax.inject.Inject;

import org.apache.log4j.Logger;

import com.google.gson.Gson;

public class JsonFileUtils {
	
	private static final Logger log = Logger.getLogger(JsonFileUtils.class);

	private Gson gson;
	
	@Inject
	public JsonFileUtils(Gson gson) {
		super();
		this.gson = gson;
	}


	public <T> T getConfFromFile(String file, Class<T> clazz) {
		log.info("parsing file " + file);
		if (!FilesUtils.exists(file)) {
			return ReflectionUtils.newInstance(clazz);
		}
		return gson.fromJson(TextFileUtils.getContents(file), clazz);
	}
	public <T> T getConfFromFile(String file, Type clazz, T defaulValue) {
		log.info("parsing file " + file);
		if (!FilesUtils.exists(file)) {
			return defaulValue;
		}
		return gson.fromJson(TextFileUtils.getContents(file), clazz);
	}


	public <T> void setContent(String file, T json) {
		TextFileUtils.setContents(file, gson.toJson(json));
	}


	@SuppressWarnings("unchecked")
	public <T> T getConfFromFile(String file, T defaultValue) {
		T $ = null;
		try {
			$ = (T) getConfFromFile(file, defaultValue.getClass());
		} catch (Exception e) {
			log.info("could not get conf from file, will use default " + e.getMessage());
			log.debug("e", e);
		}
		return $ == null ? defaultValue : $;
	}
}

@@ -148,16 +148,61 @@
 n.Gson;%0D
+%0Aimport com.google.gson.JsonSyntaxException;%0D
 %0A%0D%0Apubli
@@ -731,24 +731,25 @@
 zz, T defaul
+t
 Value) %7B%0D%0A%09%09
@@ -834,16 +834,17 @@
 n defaul
+t
 Value;%0D%0A
@@ -842,38 +842,60 @@
 tValue;%0D%0A%09%09%7D%0D%0A%09%09
-return
+T $ = null;%0D%0A%09%09try %7B%0D%0A%09%09%09$ =
  gson.fromJson(T
@@ -931,24 +931,131 @@
 ), clazz);%0D%0A
+%09%09%7D catch (JsonSyntaxException e) %7B%0D%0A%09%09%09e.printStackTrace();%0D%0A%09%09%7D%0D%0A%09%09return $ == null ? defaultValue : $;%0D%0A
 %09%7D%0D%0A%0D%0A%0D%0A%09pub

fix for api return null on error