package org.injac.indexing.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

import java.io.IOException;
import java.util.ResourceBundle;


import org.apache.log4j.Logger;

public class BeanPhoenix {
	static Logger logger = Logger.getLogger("INJAC_INDEX");
	static ResourceBundle resBundle = ResourceBundle.getBundle("indexation");
	static String  beanPath = resBundle.getString("indexPath")+"/";	
	
	public static void saveBean(Object bean){
		saveBean(bean, beanPath+bean.getClass().getName()+".ser");
	}
	
	public static Object loadBean(Class beanClass){
		return loadBean(beanPath+beanClass.getName()+".ser");
	}
	
	public static void saveBean(Object bean,String path){
		
		File beanFile = new File(path);
		try{
			FileOutputStream fileOS= new FileOutputStream(beanFile);
			ObjectOutputStream os = new ObjectOutputStream(fileOS);
			os.writeObject(bean); 
			os.close();
			fileOS.close();
		}catch(java.io.FileNotFoundException fe){
			logger.error("file not found :" + beanFile.getAbsolutePath()+"\n"+fe.getMessage());
		}catch(IOException ioe){
			logger.error("persistence error :"+ioe.getMessage());
		}
	}
	public static Object loadBean(String path){
		
		Object bean=null;
		File beanFile = new File(path);
		if(!beanFile.exists())
			return bean;
		try{
			FileInputStream fileInS= new FileInputStream(beanFile);
			ObjectInputStream inS = new ObjectInputStream(fileInS);
			bean = inS.readObject(); 
			inS.close();
			fileInS.close();
			
		}catch(java.io.FileNotFoundException fe){
			logger.error("file not found :" + beanFile.getAbsolutePath()+"\n"+fe.getMessage());
		}catch(Exception e)
		{
			logger.error("persistence error :"+e.getMessage());
		}
		return bean;
	}
	
}
