Skip to content
ManageJSonConfigFile.java 2.35 KiB
Newer Older
xtof's avatar
xtof committed
package org.josast.databaseSync.config;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import java.util.logging.Logger;

import org.apache.commons.io.IOUtils;

import org.json.JSONException;
import org.json.JSONObject;

public class ManageJSonConfigFile {
	private static Logger appLogger = Logger.getLogger("AmsatLogger");

	private String configRepository = "config";
	private String configName = "Data.json";

	public int SaveConfigFile(Object bean) {
		ManageFolder mn = new ManageFolder(configRepository);
		mn.createdDirectories();
		Path filepath = Paths.get(mn.getRepositoryPath() + "\\"+configName);

		int erreur = 0;

		JSONObject jasonObject = new JSONObject(bean);

		try {
			if (!Files.exists(filepath)) {
				Files.createFile(filepath);
				Files.writeString(filepath, "  " + "\r\n", StandardOpenOption.CREATE);
			}

			Files.writeString(filepath, jasonObject.toString() + "\r\n", StandardOpenOption.CREATE);
			if (Files.size(filepath) < 10) {
				appLogger.severe("file not created ");
				erreur = -1;
			}

		} catch (IOException e) {
			appLogger.severe(e.toString());
			erreur = -1;
		}

		return erreur;
	}
	
	public Object readJson(Object object )
	{
		Object tempobject = null;
		String RepositoryPath = System.getProperty("user.dir") + "\\"+configRepository;
		System.out.println(RepositoryPath);
		Path filepath = Paths.get(RepositoryPath + "\\"+configName);
		    try {
		    	
		      InputStream is = Files.newInputStream(filepath);
 		      String text = IOUtils.toString(is, "UTF-8");
		      JSONObject myJsonObject = new JSONObject(text);
		      tempobject =  toBean(myJsonObject, object);
		      
		    } catch (IOException | JSONException e) {
		    	e.printStackTrace();
		    	appLogger.severe("Erreor reading json file"+filepath.getFileName());
		    }
			return tempobject;
		  
	           
	}
	

	public static Object toBean(JSONObject jobject, Object object) {
		
	    for (Field field : object.getClass().getDeclaredFields()) {
	        try {
				field.set(object, jobject.getString(field.getName()));
			} catch (IllegalArgumentException | IllegalAccessException | JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
	    return object;
	}

}