package market;

import java.text.*;
import java.util.*;
import java.util.Calendar;
import java.io.*;
import java.sql.*;
import java.util.StringTokenizer;
import java.io.RandomAccessFile;
import market.util.*;

/**
 * This is m_docs cache server. <br>
 * Creation date: (27.1.2000 “. 14:52:56)
 * @author: tin
 */
public class DocsCacher {
	
/**
 * Contain element whit field: <br>
 * int srcKey - number of source on SrcServer <br>
 * long lastModified - number of milliseconds since January 1, 1970, 00:00:00 GMT <br>
 * byte flag - field status (TRY_DOWNLOAD, LOAD, UPDATE, FAILED )
 * This fields is information for document in store in cache. 
 */
	public static market.util.M_DocsCachElem[] m_docs_cached;

	public int lastElem;

/**
 * contians a reference to the DB
 */ 
	public static Connection m_docsDBConn;
	public long killDay = ~(long)0xFFFFFFF;
	private long OneDay = (long) 24*3600*1000; // One day in millis second
	protected final static int MAX_MDOCS_ELEM = 1000;
/**
 * DocsCacher constructor comment.
 */
public DocsCacher() {
	super();
	
	m_docsDBConnect();
	m_docs_cached = new market.util.M_DocsCachElem[MAX_MDOCS_ELEM];
	 
}
/**
 * Create file structure in ConfigMarket.m_DocsFilePath directory .
 * Creation date: (31.1.2000 “. 20:21:22)
 * @return boolean
 */
public boolean createFileStructor() {

	String dirName = null ;	
	File outputFile;

	try{
		for ( char cNum = '0'; cNum <= '9'; cNum++ ){
			dirName = ConfigMarket.m_DocsFilePath + File.separatorChar + String.valueOf( cNum );
			outputFile = new File( dirName );
			outputFile.mkdirs();
		}

		return saveFile( 0, "Necessary for m_docs. \nPlease don't remove!");		
	}catch( Exception e ){
	    ConfigMarket.logWriter.log( "M_DocsCacher: Can't create directory: " + dirName 
		    						+":"+e.getMessage(), LogPrinter.ERROR);
		return false;
	}
	
}
/**
 * Create file structure and DB tables.
 * Creation date: (02.3.2000 “. 21:30:23)
 * @return boolean
 */
public boolean createMDocs_Structure() {
	
	if ( createTables() ){
		if ( createFileStructor() ) {
			return true;			
		}	
	}
		
	return false;
}
/**
 * Establish connection with a DB and create tables
 * Creation date: (25.1.2000 “. 15:49:41)
 */

public boolean createTables() {
	if (!m_docsDBConnect()) {
		ConfigMarket.logWriter.log("DocsCacher: Can't conect to DB !", LogPrinter.ERROR);
		return false;
	}
	if (!tableExists(Const.m_docsTableName, m_docsDBConn)) {
		boolean ready = true;
		do {
			
			try {
				//it is suppoused that db named as it's written in sDBName is already created
				String host = ConfigMarket.hostM_docsDB + "/" + ConfigMarket.m_docsDBName;
				Connection m_docsDBConn = DriverManager.getConnection(host, ConfigMarket.m_docsDBUser, ConfigMarket.m_docsDBPassword);
				Statement Stmt = m_docsDBConn.createStatement();
				Stmt.executeQuery(Const.sSQLCreateM_docsTable);
				Stmt.close();
				m_docsDBDisConnect();
				ready = true;
			} catch (SQLException E) {
				if (isBreakDBConn()) {
					if (repareConn()) {
						ready = false;
						continue;
					}
				}
				ConfigMarket.logWriter.log("DocsCacher: SQLException: " + E.getMessage(), LogPrinter.ERROR);
				ConfigMarket.logWriter.log("DocsCacher: SQLState:     " + E.getSQLState(), LogPrinter.ERROR);
				ConfigMarket.logWriter.log("DocsCacher: VedorError:  " + E.getErrorCode(), LogPrinter.ERROR);
				return false;
			} catch (Exception E) {
				ConfigMarket.logWriter.log("DocsCacher: " + E.getMessage(), LogPrinter.ERROR);
				return false;
			}
		} while (!ready);
		
	}
	return true;
}
/**
 * Try to get Document from m_docs cache. Description: <br>
 * 1. Search srcKey in cache table. <br>
 * 2.1. If find srcKey check time. <br>
 * 2.2. If can't find srcKey set flag tryDownload and return null. <br>
 * 3. If document is old set flag update and return null. <br>
 * 4. If document is not old set flag load. <br>
 * 5. Get path to document and update DB. <br>
 * 6. Get document, reset flag and return document. <br>
 * Creation date: (27.1.2000 “. 16:08:22)
 * @return market.util.M_Docs_Result
 * @param srcKey long
 * @param lastModified long
 */
public synchronized M_Docs_Result getDocument( long srcKey, long lastModified ) {

	M_Docs_Result result = new M_Docs_Result();
	byte status;
	
// * 1. Search srcKey in cache table.
	M_DocsCachElem elem = searchSrcKey( srcKey );	
	if ( null != elem ){
// * 2.1. If find srcKey check time.
	   do{
	   		synchronized ( elem ){
	   			if ( 0 == elem.flag ){
		   			if ( (lastModified - elem.lastModified ) > OneDay ){
// * 3. If document is old set flag update and return null. 
						elem.flag = Const.UPDATE;
						elem.lastModified = lastModified;
						result.set( null, Const.UPDATE );
						return result;					
					}
					else{
// * 4. If document is not old set flag LOAD.
						status = elem.flag = Const.LOAD;
						result.set( null, Const.LOAD );
						break;
					}
				}
	   			else if	( (Const.LOAD_FAILED == elem.flag) || (Const.DOWNLOAD_FAILED == elem.flag) ){
//!!! if docoment can't download set info in log file	   			
					result.set( null, elem.flag );
					return result;					
	   			}	
	   		}  // synchronized
	   		try{ 
	   			wait();
	   		}catch( Exception e){
		   		System.out.println("\nDocs_cacher: "+e);
	   		}		
	   } while( true );		
	}
	else{
// * 2.2. If can't find srcKey set flag TRY_DOWNLOAD and return null. <br>
		elem = new M_DocsCachElem( srcKey, lastModified, Const.TRY_DOWNLOAD );
		insertElem( elem );
		result.set( null, Const.TRY_DOWNLOAD );
		return result;					
	} 
	
// * 5. Get path to document and update DB. <br>
		// m_docsDBCountDB( srcKey );

// * 6. Get document, reset flag and return document. <br>
		result.document = loadFile( srcKey );
		if ( null == result.document ){
	   		synchronized ( elem ){
				elem.flag = Const.LOAD_FAILED;
				elem.lastModified = System.currentTimeMillis();
			}
			result.status = Const.LOAD_FAILED;
		}
		else {
			m_docsDBCount( srcKey, 1 );
	   		synchronized ( elem ){
				elem.flag = 0;
				result.status = Const.OK;
			}
		}
			
 		return result;
}
/**
 * Insert element in table.
 * Creation date: (28.1.00 17:54:45)
 * @return boolean
 * @param elem market.util.M_DocsCachElem
 */
protected synchronized boolean insertElem( M_DocsCachElem elem ) {
	
// Check exist
	if ( lastElem < m_docs_cached.length ){
		m_docs_cached[lastElem++] = elem;
		return true;
	}	 
	
	return false;
}
/**
 * Check DB connection, return true if all OK .
 * Creation date: (19.4.2000 “. 18:56:51)
 * @return boolean
 */
protected boolean isBreakDBConn() {
	try {
		if (m_docsDBConn.isClosed()) {
			return true;
		} else
			return false;
			
	} catch (Exception e) {
	    ConfigMarket.logWriter.log( "M_DocsCacher: " + e.getMessage(), LogPrinter.ERROR);
		return true;
	}
}
/**
 * Load cache in memory from DB.
 * Creation date: (27.1.2000 “. 18:14:17)
 * @return boolean
 */
public boolean loadCache() {
	if (null == loadFile(0))
		return false;
	String SQLStat;

	//	M_DocsDBElem(int srcKey, long lastModified, long fetchData, int usedCounts )

	M_DocsCachElem elem;
	SQLStat = "SELECT SrcKey, LastModified FROM " + Const.m_docsTableName;
	
	boolean ready = true;
	do {
		
		try {
			Statement Stmt = m_docsDBConn.createStatement();
			ResultSet RS = Stmt.executeQuery(SQLStat);
			long dateInMillis;
			int srcKey;
			lastElem = 0;
			while (RS.next()) {
				srcKey = RS.getInt(1);
				dateInMillis = mDateInMillis(RS.getDate(2));
				elem = new M_DocsCachElem(srcKey, dateInMillis, Const.OK);
				m_docs_cached[lastElem++] = elem;
			}
			RS.close();
			Stmt.close();
			ready = true;
		} catch (SQLException E) {
			if (isBreakDBConn()) {
				if (repareConn()) {
					ready = false;
					continue;
				}
			}
			
			ConfigMarket.logWriter.log("M_DocsCacher: Can't load cache:" + "\nSQLException: " + E.getMessage() + "\nSQLState:     " + E.getSQLState() + "\nVedorError:  " + E.getErrorCode(), LogPrinter.ERROR);
			return false;
		} catch (Exception E) {
			ConfigMarket.logWriter.log("M_DocsCacher: Can't load cache:" + E.getMessage(), LogPrinter.ERROR);
			return false;
		}
	} while (!ready);
	
	return true;
}
/**
 * Load file from file system.
 * Creation date: (30.1.2000 “. 14:13:21)
 * @return java.lang.String
 * @param srcKey long
 */
public String loadFile( long srcKey ) {

	String fileName = resolveFullName( srcKey );
	FileReader read;
	char[] buffer = new char[ Const.MAX_BUFFER_SIZE ];
	String document = "" ;
		
	try {
		read = new FileReader( fileName ); // (OutputStream) file );

	} catch( IOException e ){
		ConfigMarket.logWriter.log("M_Docs_Cacher: Can't open file " + fileName , LogPrinter.ERROR);
		return null;
	}
	
	try {
		int length;
	
		while ( ( length = read.read( buffer )) != -1 ){
			
			document = document + new String( buffer, 0, length ) ;
		}
	} catch( IOException e ){
		ConfigMarket.logWriter.log("M_Docs_Cacher: Can't read from file " + fileName , LogPrinter.ERROR);
		return null;
	}

	try {
		read.close();
		return document;
	} catch( IOException e ){
		ConfigMarket.logWriter.log("M_Docs_Cacher: Can't close file " + fileName, LogPrinter.ERROR);
		return null;
	}
}
/**
 * Establish a connection with the db.
 * first load the proper driver, then connect to the db
 * Creation date: (12/20/99 4:03:08 AM)
 * @return boolean
 */
 
public static boolean m_docsDBConnect() {
	// load the driver
	try {
		Class.forName(ConfigMarket.m_docsDBDriver).newInstance();
	} catch (Exception E) {
	    ConfigMarket.logWriter.log( "DocsCacher: Unable to load driver : " + E.getMessage(), LogPrinter.ERROR);
		E.printStackTrace();
	}
	// establish a connection and put a reference to it in the srcDBConn field
	try {
		m_docsDBConn = DriverManager.getConnection( ConfigMarket.hostM_docsDB +"/"+ ConfigMarket.m_docsDBName, 
													ConfigMarket.m_docsDBUser,  ConfigMarket.m_docsDBPassword);
		return true;
	} catch (SQLException E) {
	    ConfigMarket.logWriter.log( "DocsCacher: SQLException: " + E.getMessage(), LogPrinter.ERROR);
	    ConfigMarket.logWriter.log( "DocsCacher: SQLState:     " + E.getSQLState(), LogPrinter.ERROR);
	    ConfigMarket.logWriter.log( "DocsCacher: VedorError:  " + E.getErrorCode(), LogPrinter.ERROR);
		return false;
	}
 	catch ( Exception E ) {		
	    ConfigMarket.logWriter.log( "DocsCacher: " + E.getMessage(), LogPrinter.ERROR);
		return false;  		
	}

}
/**
 * Update field UsedCount in m_docs DB.
 * Creation date: (30.1.2000 “. 14:10:33)
 * @param srcKey long
 * @param usedCounts int
 */
public boolean m_docsDBCount(long srcKey, int usedCounts) {
	String SQLStat;
	SQLStat = "UPDATE " + Const.m_docsTableName + " SET UsedCount = UsedCount + " + String.valueOf(usedCounts);
	SQLStat = SQLStat + " WHERE SrcKey = " + String.valueOf(srcKey);
	ConfigMarket.logWriter.log("M_Docs_Cacher: going to execute: " + SQLStat, LogPrinter.DEBUG_2);
	
	boolean ready = true;
	do {
		try {
			Statement Stmt = m_docsDBConn.createStatement();
			Stmt.executeQuery(SQLStat);
			Stmt.close();
			ready = true;
		} catch (SQLException E) {
			if (isBreakDBConn()) {
				if (repareConn()) {
					ready = false;
					continue;
				}
			}
			ConfigMarket.logWriter.log("M_DocsCacher: Can't count SrcKey=" + srcKey + " :" + 
				"\nSQLException: " + E.getMessage() + 
				"\nSQLState:     " + E.getSQLState() + 
				"\nVedorError:  " + E.getErrorCode(), LogPrinter.ERROR);
			return false;
		}
	} while (!ready);
	
	return true;
}
/**
 * Closes the connection to the database
 * Creation date: (12/20/99 4:14:19 AM)
 * @return boolean
 */
public static boolean m_docsDBDisConnect() {
	
	try {
		if ( m_docsDBConn != null) m_docsDBConn.close();
		return true;
		
	}catch ( Exception E ) {
	    ConfigMarket.logWriter.log( "DocsCacher: Can't close DBConection:" + E.getMessage(), LogPrinter.ERROR);
		return false;  		
	}

}
/**
 * Find a srcKey with given Src object. if not found, return 0. <br>
 * Creation date: (12/22/99 6:43:32 PM)
 * @return int
 * @param GivenSrc srcserver.Src
 */
private M_DocsDBElem m_docsDBLoad(long srcKey) {
	String SQLStat;

	//	M_DocsDBElem(int srcKey, long lastModified, long fetchData, int usedCounts )

	M_DocsDBElem res = null ;
	SQLStat = "SELECT LastModified FROM " + Const.m_docsTableName + " WHERE SrcKey = ";
	SQLStat = SQLStat + String.valueOf(srcKey);
	
	boolean ready = true;
	do {
		
		try {
			Statement Stmt = m_docsDBConn.createStatement();
			ResultSet RS = Stmt.executeQuery(SQLStat);
			if (RS.next()) {
				java.sql.Date dat = RS.getDate(1);
				res = new M_DocsDBElem(srcKey, 10000, 123, 1);
			} else {
				res = null;
			}
			RS.close();
			Stmt.close();
			ready = true;
		} catch (SQLException E) {
			if (isBreakDBConn()) {
				if (repareConn()) {
					ready = false;
					continue;
				}
			}
			ConfigMarket.logWriter.log("M_DocsCacher: Can't load elem with SrcKey=" + srcKey + " :" + "\nSQLException: " + E.getMessage() + "\nSQLState:     " + E.getSQLState() + "\nVedorError:  " + E.getErrorCode(), LogPrinter.ERROR);
			ready = true;
		}
	} while (!ready);
	
	return res;
}
/**
 * Insert a m_docs object in the m_docs table with a free key
 * Creation date: (12/22/99 4:44:54 AM)
 * @return boolean
 */
private boolean m_docsDBRegisterSource(long srcKey, long lastModified, int usedCounts, String error ) {
	
	M_DocsDBElem res = m_docsDBLoad(srcKey);
	if (null != res)
		return false;
		
	String SQLStat;
	SQLStat = "INSERT INTO " + Const.m_docsTableName + Const.FieldNames ;
	SQLStat = SQLStat + "VALUES (" + String.valueOf(srcKey) + ", '";
	SQLStat = SQLStat + String.valueOf(new java.sql.Date(lastModified)) + "', '";
	SQLStat = SQLStat + String.valueOf(new java.sql.Date(System.currentTimeMillis())) + "' ,";
	SQLStat = SQLStat + String.valueOf(usedCounts) + " , '" + error + "' ) ";

	ConfigMarket.logWriter.log("M_DocsCacher: going to execute: " + SQLStat, LogPrinter.DEBUG_2);
	
	boolean ready = true;
	do{
		
		try {
			Statement Stmt = m_docsDBConn.createStatement();
			Stmt.executeQuery(SQLStat);
			Stmt.close();
			ready = true;
		} catch (SQLException E) {
			if (isBreakDBConn()) {
				if (repareConn()) {
					ready = false;
					continue;
				}
			}
			ConfigMarket.logWriter.log("M_DocsCacher: Can't registred SrcKey=" + srcKey + " :" + "\nSQLException: " + E.getMessage() + "\nSQLState:     " + E.getSQLState() + "\nVedorError:  " + E.getErrorCode(), LogPrinter.ERROR);
			return false;
		}
		
	} while( !ready );
	
	return true;
}
/**
 * Update field UsedCount and LastModified in m_docs DB.
 * Creation date: (30.1.2000 “. 14:10:33)
 * @param srcKey long
 * @param lastModified long
 * @param usedCounts int
 */
private boolean m_docsDBSetError(long srcKey, String error ) {
	String SQLStat;
	SQLStat = "UPDATE " + Const.m_docsTableName + " SET Error = '" + error + 
							"' WHERE SrcKey = " + String.valueOf(srcKey);
	ConfigMarket.logWriter.log("M_DocsCacher: going to execute: " + SQLStat, LogPrinter.DEBUG_2);
	
	boolean ready = true;
	do {
		
		try {
			Statement Stmt = m_docsDBConn.createStatement();
			Stmt.executeQuery(SQLStat);
			Stmt.close();
			ready = true;
		} catch (SQLException E) {
			if (isBreakDBConn()) {
				if (repareConn()) {
					ready = false;
					continue;
				}
			}
			ConfigMarket.logWriter.log("M_DocsCacher: Can't update SrcKey=" + srcKey + " :" + "\nSQLException: " + E.getMessage() + "\nSQLState:     " + E.getSQLState() + "\nVedorError:  " + E.getErrorCode(), LogPrinter.ERROR);
			return false;
		}
	} while (!ready);
	
	return true;
}
/**
 * Update field UsedCount and LastModified in m_docs DB.
 * Creation date: (30.1.2000 “. 14:10:33)
 * @param srcKey long
 * @param lastModified long
 * @param usedCounts int
 */
private boolean m_docsDBUpdate(long srcKey, long lastModified, int usedCounts) {
	String SQLStat;
	SQLStat = "UPDATE " + Const.m_docsTableName + " SET UsedCount = " + String.valueOf(usedCounts);
	SQLStat = SQLStat + ", LastModified = '" + new java.sql.Date(lastModified) + "' WHERE SrcKey = " + String.valueOf(srcKey);
	ConfigMarket.logWriter.log("M_DocsCacher: going to execute: " + SQLStat, LogPrinter.DEBUG_2);
	
	boolean ready = true;
	do {
		
		try {
			Statement Stmt = m_docsDBConn.createStatement();
			Stmt.executeQuery(SQLStat);
			Stmt.close();
			ready = true;
		} catch (SQLException E) {
			if (isBreakDBConn()) {
				if (repareConn()) {
					ready = false;
					continue;
				}
			}
			ConfigMarket.logWriter.log("M_DocsCacher: Can't update srcKey=" + srcKey + " :" + "\nSQLException: " + E.getMessage() + "\nSQLState:     " + E.getSQLState() + "\nVedorError:  " + E.getErrorCode(), LogPrinter.ERROR);
			return false;
		}
	} while (!ready);
	
	return true;
}
/**
 * Starts the application.
 * @param args an array of command-line arguments
 */
public static void main(java.lang.String[] args) {


	ConfigMarket.init( "h:\\testmarket\\cfg_SR\\market.cfg" );
	DocsCacher m_cacher = new DocsCacher();
	m_cacher.createFileStructor();
	
//	m_cacher.createFileStructor();

	if ( ! m_cacher.loadCache()) {
		System.out.println(" jf;jhas;fa ");
		
		m_cacher.createMDocs_Structure();
		
		return;
	}

	
	String host = "jdbc:mysql://www.market.esof:3306/marketesof";
	
	try {
		m_cacher.m_docsDBConn = DriverManager.getConnection( host, "root", "" );
		
		Statement Stmt = m_cacher.m_docsDBConn.createStatement();
		Stmt.executeQuery( Const.sSQLCreateM_docsTable );
		Stmt.close();

	} catch (SQLException E) {
		System.out.println("SQLException: " + E.getMessage());
		System.out.println("SQLState:     " + E.getSQLState());
		System.out.println("VendorError:  " + E.getErrorCode());
	}

	m_cacher.createTables();
	//m_cacher.m_docsDBConnect();

	
	long time1 = System.currentTimeMillis();
	long time = 0;
	java.sql.Date dat = new java.sql.Date(time1);
	try{
		 time= DateFormat.getDateInstance().parse( "1998-05-19" ).getTime();
	}catch( Exception e ){
	}	
	java.sql.Date dat1 = new java.sql.Date( time );
	
	long time2 = time1- time;
	long time3 = time1&m_cacher.killDay;
	
	if ( time2 > -m_cacher.killDay ) {
		System.out.println("\n time=  "+ time+"\n time1= "+ time1 );
	}
	else{
		System.out.println("\n time1= "+ time1+"\n time=  "+ time );
	}		
	
	if ( ! m_cacher.loadCache()) {
		System.out.println(" jf;jhas;fa "+ time+dat1+time3 );
		return;
	}
		
	
	M_Docs_Result res = m_cacher.getDocument( 4, time );
	
/*
	String t = m_cacher.resolveFullName( 2345 );
	System.out.println( t );
*/
	//System.out.println( m_cacher.saveFile( 3456, "String document" ) );
//	System.out.println( m_cacher.loadFile( 3456 ) );

//	m_cacher.createTables();

	
	m_cacher.m_docsDBRegisterSource( 234, 123453, 345, "TEST M_DOCS" );

	m_cacher.m_docsDBLoad( 234 );	

	m_cacher.m_docsDBCount( 234, 5 );
	m_cacher.m_docsDBCount( 4, 5 );	
}
/**
 * Convert java.sql.Date to millis from 1970 year.
 * Creation date: (04.2.2000 “. 19:07:18)
 * @return long
 * @param date java.sql.Date
 */
private long mDateInMillis(java.sql.Date date) {
	java.util.Date date1;
	try{
		date1 = DateFormat.getDateInstance().parse( date.toString() );
	}catch( ParseException e ){
		return 0;
	}	
	return date1.getTime();
}
/**
 * Try to repare connection to DB.
 * Creation date: (19.4.2000 “. 19:02:08)
 * @return boolean
 */
protected boolean repareConn() {
	int trays = 3;
	boolean isReconn = false;
	while (!isReconn && (trays > 0)) {
		trays--;
		isReconn = m_docsDBConnect();
		if (!isReconn) {
			try {
				Thread.sleep(1000);
			}catch(Exception e) {
			};
		} else
			ConfigMarket.logWriter.log("M_DocsCacher: Reconnect to DB.", LogPrinter.DEBUG_2);
	}
	return isReconn;
}
/**
 * Return full file name. 
 * Creation date: (31.1.2000 “. 18:10:42)
 * @return java.lang.String
 * @param srcKey long
 */
public String resolveFullName( long srcKey ) {

	StringBuffer fullName = new StringBuffer( ConfigMarket.m_DocsFilePath ); 
	
	String fileName = String.valueOf( srcKey );
	String subDir =  fileName.substring( fileName.length()-1 );
	
	fullName.append( File.separatorChar );
	fullName.append( subDir );
	fullName.append( File.separatorChar );
	fullName.append( fileName );
	fullName.append( "." );
	fullName.append( Const.M_DOCS_FILE_EXT );

	return ( fullName.toString() ) ;
}
/**
 * market.thread.Parser call this method to save or update m_docs docoment and DB.
 * Creation date: (27.1.2000 “. 16:23:23)
 * @return boolean
 * @param srcKey long
 * @param document java.lang.String
 */
public boolean saveDocument( long srcKey, String document ) {

	M_DocsCachElem elem = searchSrcKey( srcKey );

	if ( null != elem ){
		synchronized ( elem ){
			switch ( elem.flag ) {
				case (Const.UPDATE): m_docsDBUpdate( srcKey , elem.lastModified, 1 ); break; 
				case (Const.TRY_DOWNLOAD): m_docsDBRegisterSource( srcKey, elem.lastModified, 1, "NO ERROR" ); break;
				case (Const.LOAD_FAILED): m_docsDBUpdate( srcKey , elem.lastModified, 1 ); break; 
				default : return false;
			}

			saveFile( srcKey, document );

			elem.flag = Const.OK;

			return true;
						
		}						
	}
	return false;
}
/**
 * Save file in file system.
 * Creation date: (31.1.2000 “. 17:40:23)
 * @return boolean
 * @param srcKey long
 * @param document java.lang.String
 */
private boolean saveFile(long srcKey, String document ) {

	String fileName = resolveFullName( srcKey );
	FileWriter prn;
		
	try {
		//FileOutputStream file = new FileOutputStream( fileName );
		prn = new FileWriter( fileName ); // (OutputStream) file );
	} catch( IOException e ){
		ConfigMarket.logWriter.log( "M_Docs_Cacher: Can't create file " + fileName , LogPrinter.ERROR);
		return false;
	}
	
	try {
		prn.write( document );
	} catch( IOException e ){
		ConfigMarket.logWriter.log( "M_Docs_Cacher: Can't write file " + fileName , LogPrinter.ERROR);
		return false;
	}

	try {
		prn.close();
		return true;
	} catch( IOException e ){
		ConfigMarket.logWriter.log( "M_Docs_Cacher: Can't close file " + fileName , LogPrinter.ERROR);
		return false;
	}
}
/**
 * Look for element with field m_docs_cached[...].srcKey equal srcKey.
 * Creation date: (28.1.2000 “. 15:45:13)
 * @return market.util.M_DocsCachElem
 * @param srcKey long
 */
public M_DocsCachElem searchSrcKey( final long srcKey ) {

	M_DocsCachElem elem;
	
	for ( int i=0; i < lastElem ; i++ ){
		elem = m_docs_cached[i];
		synchronized ( elem ){
			if ( srcKey == elem.srcKey ){
				// mayby set in queue 
				return elem;
			}	
		}	
	}	
	return null;
}
/**
 * This method checks if the table with table name and db exists. If exists returns true, else false.
 * @returns boolean
 */
public static boolean tableExists( String FindTable, Connection dbConn) {
	String SQLQuery = "SHOW TABLES LIKE " + "\"" + FindTable + "\"";
	try {
		int count;
		Statement Stmt = dbConn.createStatement();
		ResultSet RS = Stmt.executeQuery(SQLQuery);
		if (RS.next()) {
			RS.close();
			Stmt.close();
			return true;
		} else {
			RS.close();
			Stmt.close();
			return false;
		}
	} catch (SQLException E) {
		return false;
	}
}
/**
 * Load Cache from file. This is test method.
 * Creation date: (28.1.2000 “. 14:46:00)
 * @return boolean
 */
public boolean testLoadCache() {

	 try { 	
		RandomAccessFile fileIn = new RandomAccessFile("c:\\temp\\srcCache.txt","r");  //  TUK TRQBVA DA ZADADETE
		String fullText="";												 //   IMETO NA TXT FILA
		StringTokenizer st;
		String lineString= fileIn.readLine();		

  	    lineString= fileIn.readLine();
		while (lineString != null){
  		  fullText= fullText + lineString+"\n";
		  lineString= fileIn.readLine();
  		}
		fileIn.close();
			
		st = new StringTokenizer( fullText );
		m_docs_cached = new M_DocsCachElem[ st.countTokens() ];

		int srcKey, i = 0;
		long time;
		String temp;
		
		while ( st.hasMoreTokens() ){
		  temp = st.nextToken();
		  srcKey = Integer.valueOf(temp).intValue();
		  temp = st.nextToken();
		  time = Long.valueOf(temp).longValue();
   
		  m_docs_cached[i++] =  new M_DocsCachElem( srcKey, time , (byte)0 );
		  
	  	}
		 
		lastElem = i;

	 }catch( Exception e ){
	     return false;
	 }
	 
	 return true;
}
/**
 * Set flag FAILED on element with srcKey and store error in m_docs DB. Downloader call this method in case of error.
 * Creation date: (27.1.2000 “. 16:51:47)
 * @param srcKey long
 * @param error java.lang.String 
 */
public void tryFail(long srcKey, String error ) {
	M_DocsCachElem elem = searchSrcKey( srcKey );

	if ( null != elem ){
		synchronized ( elem ) {
			elem.flag = Const.DOWNLOAD_FAILED;
			elem.lastModified = System.currentTimeMillis();
			m_docsDBSetError( srcKey, error );
		}
	}
	else{
		elem = new M_DocsCachElem( srcKey, System.currentTimeMillis(), Const.DOWNLOAD_FAILED ); 
		insertElem( elem );
		if ( m_docsDBSetError( srcKey, error ) ){
			m_docsDBRegisterSource( srcKey, System.currentTimeMillis(), 0 , error );
		}	
	}		
}
}

