package market.servlets;

import market.market_util.*;
import java.net.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.lang.*;
import java.sql.*;

/**
 * This is market_wrServer servlet that handels the requests from wrProcessor and returns <br>
 * wrKey for specific wr.
 * Last Updated : 27.06.2000
 * @author: Nikolai Rangelov
 */
public class market_wrServer extends HttpServlet implements m_wrServer {
	private static int MarketKey = Constants.No_MarketKey; // We gets marketKey once
	private static Connection market_wrdbConn = null; // Connection to local DB
	private static market_wrCacher market_wrCT = null;
	private static LogPrinter market_wrLog = null;
	private static volatile int ServletCounter = 0;
	public static wrServerRMI wrConnection = null;
	
	private static volatile byte ServletState = Constants.NOT_INITED;
	private static volatile byte ServletErrorState = Constants.NO_ERROR;
	
	public static volatile Object SynchroReconn = null;
	public static volatile Object SynchroCount = null;	
	public static volatile Object SynchroRegistering = null;	
	public static volatile Object SynchroInit = null;
	private static volatile boolean IsReconn = false;
	
/**
 * This method connects market_wrServer to wrServer (system) using RMI connection. If the request is for <br>
 * registration we get back the responced wrKey. If the request is for counting nothing is returned.
 * @return wrKey long - if we have registration
 *	       <br> 2 - if count succeed
 * 		   <br> market_util.Constants.RETRY - if error occur
 * 		   <br> market_util.Constants.No_Key - if returned wrKey from the system is not greater then 0
 */

private long connect_to_RMIrwServer(long SwrKey, String SwrString, short SlangKey, long SwrCounts, int SsrcKey, String SReqType) {
	/*	if (SReqType.equalsIgnoreCase(Constants.cs_REGISTRATION)) {
	long rwKey;
	try {
	wrKey = wrConnection.wrServerRegisterMethodFlow(SwrString, SlangKey, SwrCounts, SsrcKey, (short) MarketKey);
	} catch (IOException e) {
	market_wrLog.log("market_wrServer (connect_to_RMIwrServer) : Error in connecting to wrServer with RMI. : (" + Constants.RETRY + ")\n" + e, LogPrinter.ERROR);
	return Constants.RETRY;
	}
	market_wrLog.log("market_wrServer (connect_to_RMIwrServer) : RegCon to wrServer : " + wrKey, LogPrinter.DEBUG);
	if (wrKey > 0)
	return wrKey;
	else
	return Constants.No_Key;
	} //if
	else
	if (SReqType.equalsIgnoreCase(Constants.cs_COUNTING)) {
	try {
	if (!wrConnection.wrServerCountMethodFlow(SwrKey, SwrCounts, SwrKey, (short) MarketKey)) {
	market_wrLog.log("market_wrServer (connect_to_RMIwrServer) : Count to wrServer faild.", LogPrinter.ERROR);
	return Constants.RETRY;
	}
	market_wrLog.log("market_wrServer (connect_to_RMIwrServer) : Count to wrServer succeeded.", LogPrinter.DEBUG);
	return 2;
	} catch (IOException e) {
	market_wrLog.log("market_wrServer (connect_to_RMIwrServer) : Error in connecting to wrServer with RMI.\n" + e, LogPrinter.ERROR);
	return Constants.RETRY;
	} catch (Exception e) {
	market_wrLog.log("market_wrServer (connect_to_RMIwrServer) : Exception in connecting to wrServer with RMI.\n" + e, LogPrinter.ERROR);
	return Constants.RETRY;
	}
	} else 
	*/ {
		market_wrLog.log("market_wrServer (connect_to_RMIwrServer) : Not a valid operation given (" + SReqType + ").", LogPrinter.ERROR);
		return Constants.RETRY;
	}
}
/**
 * This method connects market_wrServer to wrServer (system) using RMI connection. If the request is for <br>
 * registration we get back the responced wrKey. If the request is for counting nothing is returned.
 * @return wrKey long - if we have registration
 *	       <br> 2 - if count succeed
 * 		   <br> market_util.Constants.RETRY - if error occur
 * 		   <br> market_util.Constants.No_Key - if returned wrKey from the system is not greater then 0
 */

private long connect_to_wrServer(long SwrKey, String SwrString, short SlangKey, long SwrCounts, int SsrcKey, String SReqType) {
	InputStream in = null;
	if (SReqType.equalsIgnoreCase(Constants.cs_REGISTRATION)) {
		StringBuffer ret_wrKey = new StringBuffer(6);
		try {
			URL ServletURL = new URL(market_wrConf.S_wrServerHostName + Constants.cs_ReqType + "=" + Constants.cs_REGISTRATION + "&" + Constants.cs_WR_STRING + "=" + URLEncoder.encode(SwrString) + "&" + Constants.cs_LANG_KEY + "=" + SlangKey + "&" + Constants.cs_WR_COUNTS + "=" + SwrCounts + "&" + Constants.cs_SRC_KEY + "=" + SsrcKey + "&" + Constants.cs_MARKET_KEY + "=" + MarketKey);
			in = ServletURL.openStream();
			long b;
			if (in != null) {
				while ((b = in.read()) != -1)
					ret_wrKey.append((char) b);
				in.close();
			} else {
				market_wrLog.log("market_wrServer (connect_to_wrServer) : Error in openning connecting to wrServer with : " + market_wrConf.S_wrServerHostName + Constants.cs_ReqType + "=" + Constants.cs_REGISTRATION + "&" + Constants.cs_WR_STRING + "=" + URLEncoder.encode(SwrString) + "&" + Constants.cs_SRC_KEY + "=" + SsrcKey + "&" + Constants.cs_LANG_KEY + "=" + SlangKey + "&" + Constants.cs_WR_COUNTS + "=" + SwrCounts + "&" + Constants.cs_MARKET_KEY + "=" + MarketKey, LogPrinter.ERROR);
				return Constants.RETRY;
			}
		} catch (IOException e) {
			market_wrLog.log("market_wrServer (connect_to_wrServer) : Error in connecting to wrServer with : " + market_wrConf.S_wrServerHostName + Constants.cs_ReqType + "=" + Constants.cs_REGISTRATION + "&" + Constants.cs_WR_STRING + "=" + URLEncoder.encode(SwrString) + "&" + Constants.cs_SRC_KEY + "=" + SsrcKey + "&" + Constants.cs_LANG_KEY + "=" + SlangKey + "&" + Constants.cs_WR_COUNTS + "=" + SwrCounts + "&" + Constants.cs_MARKET_KEY + "=" + MarketKey, LogPrinter.ERROR);
			return Constants.RETRY;
		} catch (Exception t) {
			market_wrLog.log("market_wrServer (connect_to_wrServer) : Error thrown in connecting to wrServer with : " + market_wrConf.S_wrServerHostName + Constants.cs_ReqType + "=" + Constants.cs_REGISTRATION + "&" + Constants.cs_WR_STRING + "=" + URLEncoder.encode(SwrString) + "&" + Constants.cs_SRC_KEY + "=" + SsrcKey + "&" + Constants.cs_LANG_KEY + "=" + SlangKey + "&" + Constants.cs_WR_COUNTS + "=" + SwrCounts + "&" + Constants.cs_MARKET_KEY + "=" + MarketKey, LogPrinter.ERROR);
			return Constants.RETRY;
		}
		if (Long.valueOf(ret_wrKey.toString()).longValue() > 0) {
			market_wrLog.log("market_wrServer (connect_to_wrServer) : RegCon to wrServer returned : " + ret_wrKey.toString(), LogPrinter.DEBUG);
			return Long.valueOf(ret_wrKey.toString()).longValue();
		} else {
			market_wrLog.log("market_wrServer (connect_to_wrServer) : RegCon to wrServer returned : " + ret_wrKey.toString(), LogPrinter.ERROR);
			return Constants.No_Key;
		}
	} //if
	else
		if (SReqType.equalsIgnoreCase(Constants.cs_COUNTING)) {
			try {
				URL ServletURL = new URL(market_wrConf.S_wrServerHostName + Constants.cs_ReqType + "=" + Constants.cs_COUNTING + "&" + Constants.cs_WR_KEY + "=" + SwrKey + "&" + Constants.cs_WR_COUNTS + "=" + SwrCounts + "&" + Constants.cs_SRC_KEY + "=" + SsrcKey + "&" + Constants.cs_MARKET_KEY + "=" + MarketKey);
				in = ServletURL.openStream();
				in.close();
				market_wrLog.log("market_wrServer (connect_to_wrServer) : Count to wrServer scceeded.", LogPrinter.DEBUG);
				return 2;
			} catch (IOException e) {
				market_wrLog.log("market_wrServer (connect_to_wrServer) : Error in connecting to wrServer with : " + market_wrConf.S_wrServerHostName + Constants.cs_ReqType + "=" + Constants.cs_COUNTING + "&" + Constants.cs_WR_KEY + "=" + SwrKey + "&" + Constants.cs_WR_COUNTS + "=" + SwrCounts + "&" + Constants.cs_SRC_KEY + "=" + SsrcKey + "&" + Constants.cs_MARKET_KEY + "=" + MarketKey + "\n" + e, LogPrinter.ERROR);
				return Constants.RETRY;
			} catch (Exception t) {
				market_wrLog.log("market_wrServer (connect_to_wrServer) : Error thrown in connecting to wrServer with : " + market_wrConf.S_wrServerHostName + Constants.cs_ReqType + "=" + Constants.cs_COUNTING + "&" + Constants.cs_WR_KEY + "=" + SwrKey + "&" + Constants.cs_WR_COUNTS + "=" + SwrCounts + "&" + Constants.cs_SRC_KEY + "=" + SsrcKey + "&" + Constants.cs_MARKET_KEY + "=" + MarketKey + "\n" + t, LogPrinter.ERROR);
				return Constants.RETRY;
			}
		} else {
			market_wrLog.log("market_wrServer (connect_to_wrServer) : Not a valid operation given (" + SReqType + ").", LogPrinter.ERROR);
			return Constants.RETRY;
		}
}
/**
 * The method destroys market_wrServer servlet. It calls the market_wrdbDeInit() method to deinit
 * <br>the servlet.
 */
public void destroy() {
	market_wrServerDeInit();
	if (market_wrLog != null) {
		market_wrLog.destroy();
		market_wrLog = null;
	}
	ServletState = Constants.NOT_INITED;
	ServletErrorState = Constants.NO_ERROR;
	super.destroy();
}
/**
 * Inits the market_wrServer servlet and creates synchro objects, log file and inits configuration file.
 */

public void init(ServletConfig config) throws ServletException {
	super.init(config); //This statement must always be here !!!
	SynchroRegistering = null;
	SynchroRegistering = new Object();
	SynchroReconn = null;
	SynchroReconn = new Object();
	SynchroInit = null;
	SynchroInit = new Object();
	SynchroCount = null;
	SynchroCount = new Object();
	MarketKey = Constants.No_MarketKey;
	ServletErrorState = Constants.NO_ERROR;
	if (SynchroInit == null || SynchroReconn == null || SynchroRegistering == null) {
		ServletState = Constants.NOT_INITED;
		ServletErrorState = Constants.OBJECT_ERROR;
	} else {
		//get propertis from jsrv properties file		
		String path = getInitParameter(Constants.cfg_String_for_jserv_conf);
		if (path == null) {
			ServletState = Constants.NOT_INITED;
			ServletErrorState = Constants.PROPERTIES_FILE_ERROR;
		} else {
			// set server's configuration file
			if (!market_wrConf.init(path)) {
				ServletState = Constants.NOT_INITED;
				ServletErrorState = Constants.CONF_FILE_ERROR;
			} else {
				// set log file
				market_wrLog = LogPrinter.makeLogPrinter(market_wrConf.market_wrLogPath);
				market_wrLog.setLogLevel(market_wrConf.FileLogLevel);
				market_wrLog.setScreenLogLevel(market_wrConf.ScreenLogLevel);
				if (market_wrLog == null) {
					ServletState = Constants.NOT_INITED;
					ServletErrorState = Constants.LOG_ERROR;
				} else {
					// if everything is ok we set the servlet to wait to started
					ServletState = Constants.STOPED;
					ServletErrorState = Constants.NO_ERROR;
					market_wrLog.log("market_wrServer (init) : Servlet loaded but not inited.", LogPrinter.INFO);
					market_wrLog.flush();
				}
			}
		}
	}
}
/**
 * Method for inner testing.
 * @param args java.lang.String[]
 */
public static void main(String[] args) {
	market_wrServer wr = new market_wrServer();
	wr.SynchroRegistering = null;
	wr.SynchroRegistering = new Object();
	wr.SynchroReconn = null;
	wr.SynchroReconn = new Object();
	wr.SynchroInit = null;
	wr.SynchroInit = new Object();
	wr.SynchroCount = null;
	wr.SynchroCount = new Object();

	ServletErrorState = Constants.NO_ERROR;
	wr.market_wrServerInit(MarketKey);
//	wr.market_wrMethodFlow("pepe is pitch" , (short)2 , (long)1 , 23);
}
/**
 * This method checks the servlet state and returns if the process can continue.
 * @return boolean
 */
private boolean market_wrCheckServletState() {
	try {
		switch (ServletState) {
			case (Constants.NOT_INITED) :
				if (market_wrLog != null) {
					market_wrLog.log("market_wrServer (market_wrMethodFlow) : Servlet is not inited.", LogPrinter.ERROR);
					market_wrLog.flush();
				}
				return false;
			case (Constants.STOPED) :
				if (market_wrLog != null) {
					market_wrLog.log("market_wrServer (market_wrMethodFlow) : Servlet is stoped.", LogPrinter.ERROR);
					market_wrLog.flush();
				}
				return false;
			case (Constants.LOCKED) :
				if (market_wrLog != null) {
					market_wrLog.log("market_wrServer (market_wrMethodFlow) : Servlet is locked.", LogPrinter.ERROR);
					market_wrLog.flush();
				}
				return false;
			case (Constants.PROCESS_ERROR) :
				if (market_wrLog != null) {
					market_wrLog.log("market_wrServer (market_wrMethodFlow) : Servlet has error " + ServletErrorState, LogPrinter.ERROR);
					market_wrLog.flush();
				}
				return false;
			case (Constants.INITING) : // 0
				Thread.sleep(2000);
				if (ServletState != Constants.READY)
					return false;
				else
					return true;
			case (Constants.INIT_ERROR) : // 
				if (market_wrLog != null) {
					market_wrLog.log("market_wrServer (market_wrMethodFlow) : There was error in the init process.", LogPrinter.ERROR);
					market_wrLog.flush();
				}
				return false;
			case (Constants.READY) :
				return true;
			case (Constants.CONN_ERROR) :
				synchronized (SynchroReconn) {
					if (ServletState == Constants.CONN_ERROR)
						if (!IsReconn) {
							IsReconn = true;
							if (!market_wrdbConnect()) {
								IsReconn = false;
								market_wrLog.log("market_wrServer (market_wrMethodFlow) : Connection to " + dbFields.db_market_wrServerDB + " cannot be re-established.", LogPrinter.ERROR);
								market_wrLog.flush();
								return false;
							} else {
								IsReconn = false;
								ServletState = Constants.READY;
								market_wrLog.log("market_wrServer (market_wrMethodFlow) : Connection to " + dbFields.db_market_wrServerDB + " re-established.", LogPrinter.INFO);
								market_wrLog.flush();
								return true;
							}
						}
				} //synchro
				Thread.sleep(2000);
				if (ServletState != Constants.READY)
					return false;
				else
					return true;
			default :
				if (market_wrLog != null) {
					market_wrLog.log("market_wrServer (market_wrMethodFlow) : Unknow ServletState " + ServletState, LogPrinter.ERROR);
					market_wrLog.flush();
				}
				return false;
		} //switch			
	} catch (Exception e) {
		if (market_wrLog != null) {
			market_wrLog.log("market_wrServer (market_wrMethodFlow) : There was error in checking ServletState.", LogPrinter.ERROR);
			market_wrLog.flush();
		}
		return false;
	}
}
/**
 * This method chechs the tables for Market_wr DB. If a table is missing then the method creates it.
 * @return boolean 
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed
 */
private boolean market_wrCheckTable(int MK) {
	String SQLStat = null;
	String result_wrTable = null;
	try {
		for (char p = 'a'; p <= 'z'; p++) {
			result_wrTable = Constants.market_wrWhichTable(p, MK);
			if (!dbFields.TableExists(result_wrTable, market_wrdbConn)) {
				SQLStat = "CREATE TABLE " + result_wrTable + " (" + dbFields.db_wrKey + " " + dbFields.db_type_wrKey + "," + dbFields.db_langKey + " " + dbFields.db_type_langKey + "," + dbFields.db_wrString + " " + dbFields.db_type_wrString + "," + dbFields.db_wrCounts + " " + dbFields.db_type_wrCounts + "," + dbFields.db_wrRegDate + " " + dbFields.db_type_wrRegDate + "," + dbFields.db_wrLastCount + " " + dbFields.db_type_wrLastCount + ")";
				if (!dbFields.CreateTable(SQLStat, market_wrdbConn)) {
					market_wrLog.log("market_wrServer (market_wrCheckTable) : Error in creating " + result_wrTable + " table.", LogPrinter.ERROR);
					market_wrLog.flush();
					return false;
				}
			}
			result_wrTable = null;
		} //for

		result_wrTable = Constants.market_wrWhichTable(Constants.cc_NumberTableBaseKey, MK);
		if (!dbFields.TableExists(result_wrTable, market_wrdbConn)) {
			SQLStat = "CREATE TABLE " + result_wrTable + " (" + dbFields.db_wrKey + " " + dbFields.db_type_wrKey + "," + dbFields.db_langKey + " " + dbFields.db_type_langKey + "," + dbFields.db_wrString + " " + dbFields.db_type_wrString + "," + dbFields.db_wrCounts + " " + dbFields.db_type_wrCounts + "," + dbFields.db_wrRegDate + " " + dbFields.db_type_wrRegDate + "," + dbFields.db_wrLastCount + " " + dbFields.db_type_wrLastCount + ")";
			if (!dbFields.CreateTable(SQLStat, market_wrdbConn)) {
				market_wrLog.log("market_wrServer (market_wrCheckTable) : Error in creating " + result_wrTable + " table.", LogPrinter.ERROR);
				market_wrLog.flush();
				return false;
			}
		}
		result_wrTable = null;
		result_wrTable = Constants.market_wrWhichTable(Constants.cc_OtherTableBaseKey, MK);
		if (!dbFields.TableExists(result_wrTable, market_wrdbConn)) {
			SQLStat = "CREATE TABLE " + result_wrTable + " (" + dbFields.db_wrKey + " " + dbFields.db_type_wrKey + "," + dbFields.db_langKey + " " + dbFields.db_type_langKey + "," + dbFields.db_wrString + " " + dbFields.db_type_wrString + "," + dbFields.db_wrCounts + " " + dbFields.db_type_wrCounts + "," + dbFields.db_wrRegDate + " " + dbFields.db_type_wrRegDate + "," + dbFields.db_wrLastCount + " " + dbFields.db_type_wrLastCount + ")";
			if (!dbFields.CreateTable(SQLStat, market_wrdbConn)) {
				market_wrLog.log("market_wrServer (market_wrCheckTable) : Error in creating " + result_wrTable + " table.", LogPrinter.ERROR);
				market_wrLog.flush();
				return false;
			}
		}
		result_wrTable = null;
		SQLStat = null;
		market_wrLog.log("market_wrServer (market_wrCheckTable) : Tables checked.", LogPrinter.INFO);
		market_wrLog.flush();
		return true;
	} catch (SQLException e) {
		if (market_wrdbReconnect()) {
			market_wrLog.log("market_wrServer (market_wrCheckTable) : db Reconnected.", LogPrinter.INFO);
			market_wrLog.flush();
			return market_wrCheckTable(MK); 
		} else {
			market_wrLog.log("market_wrServer (market_wrCheckTable) : SQL Statement error - " + SQLStat, LogPrinter.ERROR);
			market_wrLog.flush();
			return false;
		}
	} catch (Exception e2) {
		market_wrLog.log("market_wrServer (market_wrCheckTable) : Exception - " + e2, LogPrinter.ERROR);
		market_wrLog.flush();
		return false;
	}
}
/**
 * This method connects the market_wrServer servlet to Market_wr DB
 * @return boolean 
 *	       <br> true  - if the method succeed (we have connection)
 * 		   <br> false - if the method failed (we don't have connection)
 */
private boolean market_wrdbConnect() {
	try {
		Class.forName(market_wrConf.db_Drivers).newInstance();
		market_wrLog.log("market_wrServer (market_wrdbConnect) : Got a driver to " + dbFields.db_market_wrServerDB + " db.", LogPrinter.INFO);
	} catch (Exception E) {
		market_wrLog.log("market_wrServer (market_wrdbConnect) : Unable to load a driver to " + dbFields.db_market_wrServerDB + " db. Exception : " + E, LogPrinter.ERROR);
		market_wrLog.flush();
		return false;
	}
	market_wrdbConn = null;
	try {
		market_wrdbConn = DriverManager.getConnection(market_wrConf.db_host + dbFields.db_market_wrServerDB, market_wrConf.db_user, market_wrConf.db_password);
		market_wrLog.log("market_wrServer (market_wrdbConnect) : Conection to " + dbFields.db_market_wrServerDB + " db Established.", LogPrinter.INFO);
		if (market_wrdbConn == null || market_wrdbConn.isClosed()) {
			market_wrLog.flush();
			return false;
		}
		market_wrLog.flush();		
		return true;
	} catch (SQLException E) {
		market_wrLog.log("market_wrServer (market_wrdbConnect) : SQLException in getting Connection to " + dbFields.db_market_wrServerDB + " db : " + E, LogPrinter.ERROR);
		market_wrLog.log("market_wrServer (market_wrdbConnect) : SQLException: " + E.getMessage(), LogPrinter.ERROR);
		market_wrLog.log("market_wrServer (market_wrdbConnect) : SQLState:     " + E.getSQLState(), LogPrinter.ERROR);
		market_wrLog.flush();
		return false;
	}
}
/**
 * This method disconnects the market_wrServer servlet from Market_wr DB softly. If there is error during 
 * <br> disconneting procedure the connection is disconnected hard way (equals null).
 */

private void market_wrdbDisConnect() {
	try {
		if (market_wrdbConn != null) {
			market_wrdbConn.close();
			market_wrLog.log("market_wrServer (market_wrdbDisConnect) : " + dbFields.db_market_wrServerDB + " closed.", LogPrinter.INFO);
			market_wrLog.flush();
			market_wrdbConn = null;
		}
		return;
	} catch (Exception e) {
		market_wrLog.log("market_wrServer (market_wrdbDisConnect) : Cannot close the " + dbFields.db_market_wrServerDB + " db \n" + e, LogPrinter.ERROR);
		market_wrLog.flush();
		return;
	}
}
/**
 * Reconnects market_wrdbConn to Market_wr DB if servlet had lost its connection.
 * @return boolean
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed
 */
private boolean market_wrdbReconnect() {
	try {
		if (market_wrdbConn == null || market_wrdbConn.isClosed()) {			
			ServletState = Constants.CONN_ERROR;
			ServletErrorState = Constants.CONN_ERROR;
			synchronized (SynchroReconn) {
				if (ServletState == Constants.CONN_ERROR) {
					if (!IsReconn) {
						IsReconn = true;
						if (!market_wrdbConnect()) {
							market_wrLog.log("market_wrServer (market_wrdbReconnect) : market_wrdbConnect() failure.", LogPrinter.ERROR);
							IsReconn = false;
							market_wrLog.flush();
							return false;
						}
						IsReconn = false;
						ServletState = Constants.READY;
						ServletErrorState = Constants.NO_ERROR;
						market_wrLog.log("market_wrServer (market_wrdbReconnect) : Reconnection to db done.", LogPrinter.INFO);
						return true;
					} else {
						Thread.sleep(1000);
						if (ServletState == Constants.READY) {
							return true;
						}
					}
				} else
					if (ServletState == Constants.READY) {
						return true;
					}
			}
		} else {
			market_wrLog.log("market_wrServer (market_wrdbReconnect) : Possible SQL Statement error. db is connected." , LogPrinter.ERROR);
			market_wrLog.flush();
		}
		return false;
	} catch (Exception ex) {
		market_wrLog.log("market_wrServer (market_wrdbReconnect) : Exception in re-connect: " + ex, LogPrinter.ERROR);
		market_wrLog.flush();
		return false;
	}
}
/**
 * This method does the main servlet's job. It splits counting procedure from registration.
 * @return wrKey long - the wrKey for requested wrString
 *	<br> market_util.Constants.RETRY - if error occurs and it can not be repaired
 * @param wrString String - the wrString for the resolving wr
 * @param langKey short - the language key for the wr
 * @param wrCounts long - the count of wr(sentance) in the src(source file)
 * @param srcKey int - the srcKey index of the the source file
 */
public long market_wrMethodFlow(String wrString, short langKey, long wrCounts, int srcKey) {
	if (!market_wrCheckServletState())
		return Constants.RETRY;
	if (wrString == null || langKey < 1 || wrCounts < 1 || srcKey < 1) {
		market_wrLog.log("market_wrServer (market_wrMethodFlow) : Wrong input Parameters : wrString - " + wrString + ", langKey - " + langKey + ", wrCounts - " + wrCounts + ", srcKey - " + srcKey, LogPrinter.ERROR);
		market_wrLog.flush();
		return Constants.RETRY;
	}
	wrString = wrString.toLowerCase();
	if (!Constants.ValidateString(wrString)) {
		market_wrLog.log("market_wrServer (market_wrMethodFlow) : Not valid wrString given (" + wrString + ")", LogPrinter.ERROR);
		market_wrLog.flush();
		return Constants.RETRY;
	}
	synchronized (SynchroCount) {
		ServletCounter++;
	}

//   start here
	
	try {
		market_wrLog.log("-------------------- Begins WR --------------------------", LogPrinter.DEBUG_2);
		long wrKey = market_wrResolveString(wrString, langKey, wrCounts);
		if (Constants.No_Key == wrKey) {
			long answerKey = connect_to_wrServer(0, wrString, langKey, wrCounts, srcKey, Constants.cs_REGISTRATION);
			if (answerKey < 1) {
				market_wrLog.log("market_wrServer (market_wrMethodFlow) : Error in getting wrKey (" + answerKey + ") from wrServer.", LogPrinter.ERROR);
				market_wrLog.flush();
				synchronized (SynchroCount) {
					ServletCounter--;
				}
				return Constants.RETRY;
			} else {
				wrKey = answerKey;
				if (!market_wrRegisterWr(wrKey, wrString, langKey, wrCounts)) {
					market_wrLog.log("market_wrServer (market_wrMethodFlow) : Error on wrRegisterWr function!", LogPrinter.ERROR);
					market_wrLog.flush();
					synchronized (SynchroCount) {
						ServletCounter--;
					}
					return Constants.RETRY;
				}
			}
		} //if(res1==Cons
		else
			if (wrKey == 0) {
				market_wrLog.log("market_wrServer (market_wrMethodFlow) : Error on wrResolveString function.", LogPrinter.ERROR);
				market_wrLog.flush();
				synchronized (SynchroCount) {
					ServletCounter--;
				}
				return Constants.RETRY;
			} else
				if (2 != connect_to_wrServer(wrKey, "", (short) 0, wrCounts, srcKey, Constants.cs_COUNTING)) {
					market_wrLog.log("market_wrServer (market_wrMethodFlow) : Error in connecting to wrServer for counting.", LogPrinter.ERROR);
					market_wrLog.flush();
					synchronized (SynchroCount) {
						ServletCounter--;
					}
					return Constants.RETRY;
				}
		market_wrLog.log("market_wrServer (market_wrMethodFlow) : Result is : " + wrKey, LogPrinter.DEBUG);
		synchronized (SynchroCount) {
			ServletCounter--;
		}
		return wrKey;
	} catch (ThreadDeath t) {
		market_wrLog.log("market_wrServer (market_wrMethodFlow) : End of thread life", LogPrinter.ERROR);
		market_wrLog.flush();
		synchronized (SynchroCount) {
			ServletCounter--;
		}
		throw new ThreadDeath();
	}
}
/**
 * The method inserts new record in the local (Market_wr) DB with all wr parameters needed
 * @return boolean
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed
 */

private boolean market_wrRegisterWr(long RwrKey, String RwrString, short RlangKey, long RwrCounts) {
	long res_wrKey = Constants.No_Key;
	java.sql.Date Now = new java.sql.Date(System.currentTimeMillis());
	String SQLStat1 = "SELECT " + dbFields.db_wrKey + " FROM " + Constants.market_wrWhichTable(RwrString.charAt(0), MarketKey) + " WHERE " + dbFields.db_wrString + " = " + Constants.DBString(RwrString) + " AND " + dbFields.db_langKey + " = " + String.valueOf(RlangKey);
	String SQLStat2 = "INSERT INTO " + Constants.market_wrWhichTable(RwrString.charAt(0), MarketKey) + " (" + dbFields.db_wrKey + "," + dbFields.db_langKey + "," + dbFields.db_wrString + "," + dbFields.db_wrCounts + "," + dbFields.db_wrRegDate + "," + dbFields.db_wrLastCount + ") values(" + RwrKey + "," + RlangKey + "," + Constants.DBString(RwrString) + "," + RwrCounts + ",'" + Now + "','" + Now + "')";
	synchronized (SynchroRegistering) {
		try {
			Statement Stmt = market_wrdbConn.createStatement();
			ResultSet RS = Stmt.executeQuery(SQLStat1);
			if (RS.next()) {
				res_wrKey = RS.getLong(1);
				market_wrLog.log("market_wrServer (market_wrRegisterWr) : Instances = " + ServletCounter, LogPrinter.DEBUG);
				while (RS.next()) {
					market_wrLog.log("market_wrServer (market_wrRegisterWr) : INFO DUBLICATED (never will be used): wrKey = " + RS.getLong(1) + ", langKey = " + RlangKey + ", wrString : " + RwrString + ":", LogPrinter.ERROR);
				}
				if (!market_wrCT.wrRegisterCachField(res_wrKey, RwrString, RlangKey, (int) RwrCounts)) {
					market_wrLog.log("market_wrServer (market_wrRegisterWr) : Result from Cache Register is false.", LogPrinter.ERROR);
					market_wrLog.flush();
					RS.close();
					Stmt.close();
					if (market_wrUpdateWr(RwrString, res_wrKey, RwrCounts)) {
						market_wrLog.log("market_wrServer (market_wrRegisterWr) : wr - " + RwrString + " updated in the DB.", LogPrinter.DEBUG);
						return true;
					}
					market_wrLog.log("market_wrServer (market_wrRegisterWr) : Failure updating wr - " + RwrString + " in the DB.", LogPrinter.DEBUG);
					market_wrLog.flush();
					return false;
				}
			} else {
				try {
					Statement stmt = market_wrdbConn.createStatement();
					int result = stmt.executeUpdate(SQLStat2);
					if (result == 1) {
						market_wrLog.log("market_wrServer (market_wrRegisterWr) : info inserted.", LogPrinter.DEBUG);
					} else {
						market_wrLog.log("market_wrServer (market_wrRegisterWr) : Res from inserting = " + result + ", wrKey = " + RwrKey + ", wrCounts = " + RwrCounts + ", langKey = " + RlangKey + ", wrString :" + RwrString + ": not inserted.", LogPrinter.ERROR);
					}
					stmt.close();
				} catch (SQLException e1) {
					if (market_wrdbReconnect()) {
						market_wrLog.log("market_wrServer (market_wrRegisterWr) : db Reconnected.", LogPrinter.INFO);
						market_wrLog.flush();
						RS.close();
						Stmt.close();
						return market_wrRegisterWr(RwrKey, RwrString, RlangKey, RwrCounts);
					} else {
						market_wrLog.log("market_wrServer (market_wrRegisterWr) : SQL Statement error - " + SQLStat2 + " Exception : " + e1, LogPrinter.ERROR);
						market_wrLog.flush();
						RS.close();
						Stmt.close();
						return false;
					}
				} catch (NumberFormatException e2) {
					market_wrLog.log("market_wrServer (market_wrRegisterWr) : error format - " + SQLStat2 + " (" + RwrKey + "," + RlangKey + "," + RwrString + "," + RwrCounts + ")\n" + e2, LogPrinter.ERROR);
					market_wrLog.flush();
					RS.close();
					Stmt.close();
					return false;
				}
			}
			RS.close();
			Stmt.close();
			return true;
		} catch (SQLException E) {
			if (market_wrdbReconnect()) {
				market_wrLog.log("market_wrServer (market_wrRegisterRw) : db Reconnected.", LogPrinter.INFO);
				market_wrLog.flush();
				return market_wrRegisterWr(RwrKey, RwrString, RlangKey, RwrCounts);
			} else {
				market_wrLog.log("market_wrServer (market_wrRegisterRw) : SQL Statement error - " + SQLStat1 + " Exception : " + E, LogPrinter.ERROR);
				market_wrLog.flush();
				return false;
			}
		} catch (NumberFormatException e2) {
			market_wrLog.log("market_wrServer (market_wrRegisterWr) : error format - " + SQLStat1 + " (" + RwrKey + "," + RlangKey + "," + RwrString + "," + RwrCounts + ")\n" + e2, LogPrinter.ERROR);
			market_wrLog.flush();
			return false;
		}
	} //synchro
}
/**
 * Checks if the requested wr with wrString and langKey exists in the Cache Table and/or <br>local (Market_wr) DB
 * @return long
 * 			<br>wrKey - if the wr is found
 *			<br>    0 - if error occurs
 *			<br> market_util.Constants.RETRY - if the wr is not found
 */

private long market_wrResolveString(String twrString, short tlangKey, long twrCounts) {
	long res_wrKey = market_wrCT.wrResolveString(twrString, tlangKey, (int) twrCounts);
	String SQLStat = null;
	if (res_wrKey == Constants.No_Key) {
		try {
			SQLStat = "SELECT " + dbFields.db_wrKey + " FROM " + Constants.market_wrWhichTable(twrString.charAt(0), MarketKey) + " WHERE " + dbFields.db_wrString + " = " + Constants.DBString(twrString) + " AND " + dbFields.db_langKey + " = " + String.valueOf(tlangKey);
			Statement Stmt = market_wrdbConn.createStatement();
			ResultSet RS = Stmt.executeQuery(SQLStat);
			if (RS.next()) {
				res_wrKey = RS.getLong(1);
				while (RS.next()) {
					market_wrLog.log("market_wrServer (market_wrResolveString) : INFO DUBLICATED (never will be used): wrKey = " + RS.getLong(1) + ", langKey = " + tlangKey + ", wrString : " + twrString + ":", LogPrinter.ERROR);
					market_wrLog.flush();
				}				
				if (res_wrKey > 0) {
					market_wrLog.log("market_wrServer (market_wrResolveString) : Instances = " + ServletCounter, LogPrinter.DEBUG);
					if (!market_wrCT.wrRegisterCachField(res_wrKey, twrString, tlangKey, (int) twrCounts)) {
						market_wrLog.log("market_wrServer (market_wrResolveString) : Result from Cache Register is false.", LogPrinter.ERROR);
						RS.close();
						Stmt.close();
						if (market_wrUpdateWr(twrString, res_wrKey, twrCounts)) {
							market_wrLog.log("market_wrServer (market_wrResolveString) : wr - " + twrString + " updated in the DB.", LogPrinter.DEBUG);
							return res_wrKey;
						}
						market_wrLog.log("market_wrServer (market_wrResolveString) : Failure updating wr - " + twrString + " in the DB.", LogPrinter.ERROR);
						market_wrLog.flush();
						return 0;
					}
				}
			}
			RS.close();
			Stmt.close();
			market_wrLog.log("market_wrServer (market_wrResolveString) : Result is : " + res_wrKey, LogPrinter.DEBUG);
		} catch (SQLException E) {
			if (market_wrdbReconnect()) {
				market_wrLog.log("market_wrServer (market_wrResolveString) : db Reconnected.", LogPrinter.INFO);
				market_wrLog.flush();
				return market_wrResolveString(twrString, tlangKey, twrCounts);
			} else {
				market_wrLog.log("market_wrServer (market_wrResolveString) : SQL Statement error - " + SQLStat + " Exception : " + E, LogPrinter.ERROR);
				market_wrLog.flush();
				return 0;
			}
		} catch (NumberFormatException e) {
			market_wrLog.log("market_wrServer (market_wrResolveString) : error format - " + SQLStat + " (" + res_wrKey + "," + tlangKey + "," + twrString + "," + twrCounts + ")\n" + e, LogPrinter.ERROR);
			market_wrLog.flush();
			return 0;
		}
	}
	return res_wrKey;
}
/**
 * Deinits the servlet. Free all resources that the servlet had allocated with market_wrServletInit.
 * @return boolean
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed but deinitin is done by hard way
 */
private boolean market_wrServerDeInit() {
	try {
		if (market_wrLog != null) {
			market_wrLog.log("market_wrServer (market_wrServerDeInit) : --------------------- Deinitialisation of the servlet begins...", LogPrinter.INFO);
		}
		if (market_wrCT != null) {
			market_wrCT.destroy();
		}
		market_wrCT = null;		
		if (market_wrdbConn != null) {
			market_wrdbDisConnect();
		}
		market_wrdbConn = null;		
		if (market_wrLog != null) {
			market_wrLog.log("market_wrServer (market_wrServerDeInit) : ---------------------- Deinitialisation of the servlet done. Servlet destroyed.", LogPrinter.INFO);			
			market_wrLog.flush();
		}
		wrConnection = null;
		ServletCounter = 0;
		return true;
	} catch (Exception e) {
		market_wrdbConn = null;
		wrConnection = null;
		ServletCounter = 0;
		return false;
	}
}
/**
 * Makes the primary init. This method allocates the base resources and sets the ServletState and <br>
 * ServletErrorState vaiables which hold the moment state of the servlet and the error(if occured).
 * @return boolean
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed 
 */

public byte market_wrServerInit(int MK) {
	//first we try to deinit the servlet 
	boolean deinit = false;
	deinit = market_wrServerDeInit();
	market_wrLog.log("market_wrServer (market_wrServerInit) : -------- Initialisation begins ...", LogPrinter.INFO);
	market_wrLog.flush();

	// 1. Get The valid market key for parikular market
	if (MK < 1) {
		ServletState = Constants.INIT_ERROR;
		ServletErrorState = Constants.GET_MARKET_KEY_ERROR;
		market_wrLog.log("market_wrServer (market_wrServerInit) : Error in setting MarketKey (" + MK + ")! Servlet is not set and will not continue!", LogPrinter.ERROR);
		market_wrLog.flush();
		return ServletErrorState;
	}
	
	// 2. Connecting to DB
	if (!market_wrdbConnect()) {
		market_wrLog.log("market_wrServer (market_wrServerInit) : market_wrdbConnect() failure.", LogPrinter.ERROR);
		market_wrLog.flush();
		ServletState = Constants.INIT_ERROR;
		ServletErrorState = Constants.DB_CONN_ERROR;
		return ServletErrorState;
	}
	market_wrLog.log("market_wrServer (market_wrServerInit) : DB connected.", LogPrinter.INFO);

	// 3. Try connection to wrServer. If the wrServer has a state Ready then we continue otherwise the servlet will not be started.
	InputStream in = null;
	StringBuffer ret_wrServerServletState = new StringBuffer(6);
	try {
		URL ServletURL = new URL(market_wrConf.S_wrServerHostName + Constants.cs_ReqType + "=" + Constants.cs_GET_SYSTEM_SERVLET_STATE);
		in = ServletURL.openStream();
		long b;
		if (in != null) {
			while ((b = in.read()) != -1)
				ret_wrServerServletState.append((char) b);
			in.close();
		} else {
			ServletState = Constants.INIT_ERROR;
			ServletErrorState = Constants.SYSTEM_CONN_ERROR;
			market_wrLog.log("market_wrServer (market_wrServerInit) : Error in openning connecting to wrServer with : " + market_wrConf.S_wrServerHostName + Constants.cs_ReqType + "=" + Constants.cs_GET_SYSTEM_SERVLET_STATE, LogPrinter.ERROR);
			market_wrLog.flush();
			return ServletErrorState;
		}
		if (Byte.valueOf(ret_wrServerServletState.toString()).byteValue() == Constants.READY) {
			market_wrLog.log("market_wrServer (market_wrServerInit) : Http connection to " + market_wrConf.S_wrServerHostName + " (wrServer) checked and is ready. System returned : " + ret_wrServerServletState.toString(), LogPrinter.INFO);
		} else {
			ServletState = Constants.INIT_ERROR;
			ServletErrorState = Constants.SYSTEM_CONN_ERROR;
			market_wrLog.log("market_wrServer (market_wrServerInit) : wrServer http test connection to " + market_wrConf.S_wrServerHostName + " failed. wrServer not ready. It returned : " + ret_wrServerServletState.toString(), LogPrinter.ERROR);
			market_wrLog.flush();
			return ServletErrorState;
		}
	} catch (IOException e) {
		ServletState = Constants.INIT_ERROR;
		ServletErrorState = Constants.SYSTEM_CONN_ERROR;
		market_wrLog.log("market_wrServer (market_wrServerInit) : Error in connecting to wrServer with : " + market_wrConf.S_wrServerHostName + Constants.cs_ReqType + "=" + Constants.cs_GET_SYSTEM_SERVLET_STATE + "\n" + e, LogPrinter.ERROR);
		market_wrLog.flush();
		return ServletErrorState;
	} catch (Exception t) {
		ServletState = Constants.INIT_ERROR;
		ServletErrorState = Constants.SYSTEM_CONN_ERROR;
		market_wrLog.log("market_wrServer (market_wrServerInit) : Error thrown in connecting to wrServer with : " + market_wrConf.S_wrServerHostName + Constants.cs_ReqType + "=" + Constants.cs_GET_SYSTEM_SERVLET_STATE + "\n" + t, LogPrinter.ERROR);
		market_wrLog.flush();
		return ServletErrorState;
	}

	// 4. Create cache and save thread
	if (market_wrCT != null) {
		market_wrCT.destroy();
	}
	market_wrCT = null;
	market_wrCT = new market_wrCacher(MK, market_wrLog);
	if (market_wrCT == null) {
		market_wrLog.log("market_wrServer (market_wrServerInit) : Cache Table is not loaded.", LogPrinter.ERROR);
		market_wrLog.flush();
		ServletState = Constants.INIT_ERROR;
		ServletErrorState = Constants.CACHE_ERROR;
		return ServletErrorState;
	}
	if (market_wrCT.State != Constants.READY) {
		if (market_wrCT.State == Constants.SAVE_THREAD_ERROR) {
			market_wrLog.log("market_wrServer (market_wrServerInit) : Cache Table is not inited. Save Thread start failed. CT State - " + market_wrCT.State, LogPrinter.ERROR);
			market_wrLog.flush();
			ServletState = Constants.INIT_ERROR;
			ServletErrorState = Constants.SAVE_THREAD_ERROR;
		} else {
			market_wrLog.log("market_wrServer (market_wrServerInit) : Cache Table is not inited. State - " + market_wrCT.State, LogPrinter.ERROR);
			market_wrLog.flush();
			ServletState = Constants.INIT_ERROR;
			ServletErrorState = Constants.CACHE_ERROR;
		}
		return ServletErrorState;
	}
	market_wrLog.log("market_wrServer (market_wrServerInit) : Cache Table loaded.", LogPrinter.INFO);

	// 5. Check/Create tables
	if (!market_wrCheckTable(MK)) {
		market_wrLog.log("market_wrServer (market_wrServerInit) : Error in creating tables.", LogPrinter.ERROR);
		market_wrLog.flush();
		ServletState = Constants.INIT_ERROR;
		ServletErrorState = Constants.TABLES_ERROR;
		return ServletErrorState;
	}
	market_wrLog.log("market_wrServer (market_wrServerInit) : Tables are OK.", LogPrinter.INFO);

	// 6. Set the matket key for particular market
	MarketKey = MK;
	market_wrLog.log("market_wrServer (market_wrServerInit) : MarketKey set to : " + MarketKey, LogPrinter.INFO);
	market_wrLog.log("market_wrServer (market_wrServerInit) : ------- Initialisation finished. Servlet ready to work.", LogPrinter.INFO);
	market_wrLog.flush();
	ServletState = Constants.READY;
	ServletErrorState = Constants.NO_ERROR;
	return ServletErrorState;
}
/**
 * Sets all wr parameters send throught http flow from wrProcessor and handled by the service method.
 * @return wrStructure market_util.wrParameters - wr structure with all parameters set in it
 * 		<br> null - if there is failure in the method
 */
 
private market_wrParameters market_wrSet_wrParam(HttpServletRequest req) throws NullPointerException {
	market_wrParameters market_wr = new market_wrParameters();
	String temp = null;
	try {
		temp = req.getParameter(Constants.cs_WR_STRING);
		if (!Constants.ValidateString(temp)) {
			market_wrLog.log("market_wrServer (market_wrSet_wrParam) : Not valid wrString given (" + temp + ")", LogPrinter.ERROR);
			market_wrLog.flush();
			return null;
		} else
			market_wr.wrString = temp.toLowerCase().trim();
		temp = req.getParameter(Constants.cs_LANG_KEY);
		if (Short.valueOf(temp).shortValue() < 1) {
			market_wrLog.log("market_wrServer (market_wrSet_wrParam) : langKey should be greater than 0 (" + temp + ")", LogPrinter.ERROR);
			market_wrLog.flush();			
			return null;
		} else
			market_wr.langKey = Short.valueOf(temp).shortValue();
		temp = req.getParameter(Constants.cs_WR_COUNTS);
		if (Long.valueOf(temp).longValue() < 1) {
			market_wrLog.log("market_wrServer (market_wrSet_wrParam) : wrCounts should be greater than 0 (" + temp + ")", LogPrinter.ERROR);
			market_wrLog.flush();			
			return null;
		} else
			market_wr.wrCounts = Long.valueOf(temp).longValue();
		temp = req.getParameter(Constants.cs_SRC_KEY);
		if (Integer.valueOf(temp).intValue() < 1) {
			market_wrLog.log("market_wrServer (market_wrSet_wrParam) : srcKey should be greater than 0 (" + temp + ")", LogPrinter.ERROR);
			market_wrLog.flush();			
			return null;
		} else
			market_wr.srcKey = Integer.valueOf(temp).intValue();
	} catch (Exception t) {
		market_wrLog.log("market_wrServer (market_wrSet_rwParam) : Wrong Paramerter (" + temp + ") : wrString - " + market_wr.wrString + ", langKey - " + market_wr.langKey + ", rwCounts - " + market_wr.wrCounts + ", srcKey - " + market_wr.srcKey + "\n" + t, LogPrinter.ERROR);
		market_wrLog.flush();		
		return null;
	}
	temp = null;
	return market_wr;
}
/**
 * Updates the wr properties in the DB. If Cache registration had failed then this method is called.
 * @return boolean
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed 
 */

private boolean market_wrUpdateWr(String wrString, long wrKey, long wrCounts) {
	String SQLStat = null;
	try {
		SQLStat = "UPDATE " + Constants.market_wrWhichTable(wrString.charAt(0), MarketKey) + " SET " + dbFields.db_wrCounts + " = " + dbFields.db_wrCounts + " + " + String.valueOf(wrCounts) + "," + dbFields.db_wrLastCount + " = '" + (new java.sql.Date(System.currentTimeMillis())) + "' WHERE " + dbFields.db_wrKey + " = " + String.valueOf(wrKey);
		if (market_wrdbConn == null)
			throw new SQLException();
		Statement stmt = market_wrdbConn.createStatement();
		int result = stmt.executeUpdate(SQLStat);
		if (result == 1) {
			market_wrLog.log("market_wrServer (market_wrUpdateWr) : wrString = " + wrString + " updated in the DB.", LogPrinter.DEBUG);
		} else {
			market_wrLog.log("market_wrServer (market_wrUpdateWr) : Res from updating = " + result + ", wrKey = " + wrKey + ", wrCounts = " + wrCounts + ", wrString :" + wrString + ": not updated.", LogPrinter.ERROR);
			market_wrLog.flush();
		}
		stmt.close();
		return true;		
	} catch (SQLException e) {
		if (market_wrdbReconnect()) {
			market_wrLog.log("market_wrServer (market_wrUpdateWr) : db Reconnected.", LogPrinter.INFO);
			market_wrLog.flush();
			return market_wrUpdateWr(wrString, wrKey, wrCounts);
		} else {
			market_wrLog.log("market_wrServer (market_wrUpdateWr) : SQL Statement error - " + SQLStat + " Exception : " + e, LogPrinter.ERROR);
			market_wrLog.flush();
			return false;
		}
	} catch (NumberFormatException e) {
		market_wrLog.log("market_wrServer (market_wrUpdateWr) : error format - " + SQLStat + " (" + wrKey + "," + wrString + ", " + wrCounts + ")\n" + e, LogPrinter.ERROR);
		market_wrLog.flush();
		return false;
	} catch (Exception e) {
		market_wrLog.log("market_wrServer (market_wrUpdateWr) : Exception - " + SQLStat + "\n" + e, LogPrinter.ERROR);
		market_wrLog.flush();
		return false;
	}
}
/**
 * This method serves the http requests. Reurns wrKey if is requested. It also handles many other requests <bt>
 * that are explained in the servlet documentation. 
 * @return wrKey - it is always String (because of the http answer). If the wrKey is market_util.Constants.RETRY
 * <br>then error has occured (something is wrong).
 */

public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
	res.setContentType("text/html");
	PrintWriter out = res.getWriter();
	String Status = "";
	String RT = req.getParameter(Constants.cs_ReqType);
	if (RT != null) {
		byte nreq = -1;
		try {
			nreq = Byte.valueOf(RT).byteValue();
		} catch (NumberFormatException e) {
			market_wrLog.log("market_wrServer (service) : Request Type error. Not a valid number - " + RT, LogPrinter.ERROR);
			market_wrLog.flush();
			out.close();
			return;
		}
		switch (nreq) {

			// ReqType = 3	
			case (Constants.TASK_GET_CONFIG) :
				Status = "Configuration for market_wrServer loaded.<br>ServletState - " + ServletState + ". ServletErrorState - " + ServletErrorState;
				market_wrLog.log("market_wrServer (service) : " + Status, LogPrinter.INFO);
				market_wrLog.flush();
				market_wrConf.wrFormConfigParam(out, Status);
				out.close();
				return;

				// ReqType = 4					
			case (Constants.TASK_SAVE_CONFIG) :
				String value = req.getParameter(Constants.cs_ConfSaveValue);
				if (value == null) {
					Status = "Error on save congiguration input value string!<br>ServletState - " + ServletState + ". ServletErrorState - " + ServletErrorState;
					market_wrLog.log("market_wrServer (service) : " + Status, LogPrinter.ERROR);
					market_wrConf.wrFormConfigParam(out, Status);
					out.close();
					market_wrLog.flush();
					return;
				} else {
					if (!market_wrConf.wrSaveCfgFile(value)) {
						Status = "Error in market_wrConf.wrSaveCfgFile function!<br>ServletState - " + ServletState + ". ServletErrorState - " + ServletErrorState;
						market_wrLog.log("market_wrServer (service) : " + Status, LogPrinter.ERROR);
						market_wrConf.wrFormConfigParam(out, Status);
						out.close();
						market_wrLog.flush();
						return;
					}
					market_wrConf.wrLoadProperty(market_wrConf.wrcfgPath);
					Status = "market_wrServer servlet properties saved successfully.<br>ServletState - " + ServletState + ". ServletErrorState - " + ServletErrorState;
					market_wrLog.log("market_wrServer (service) : " + Status, LogPrinter.INFO);
					market_wrConf.wrFormConfigParam(out, Status);
					out.close();
					market_wrLog.flush();
					return;
				}

				// ReqType = 5
			case (Constants.TASK_RELOAD) :
				byte tempSS = 0;
				if (ServletState == Constants.INITING) {
					Status = "market_wrServer servlet properties are reloaded by another user at the moment .<br>ServletState - " + ServletState + ". ServletErrorState - " + ServletErrorState;
					market_wrLog.log("market_wrServer (service) : " + Status, LogPrinter.INFO);
				} else {
					synchronized (SynchroInit) {
						if (ServletState == Constants.INITING) {
							Status = "market_wrServer servlet properties are reloaded by another user at the moment .<br>ServletState - " + ServletState + ". ServletErrorState - " + ServletErrorState;
							market_wrLog.log("market_wrServer (service) : " + Status, LogPrinter.INFO);
						} else {
							tempSS = ServletState;
							ServletState = Constants.INITING;
							if (ServletCounter == 0) {
								if (market_wrServerInit(MarketKey) == Constants.NO_ERROR) {
									Status = "market_wrServer servlet properties reloaded.<br>ServletState - " + ServletState + ". ServletErrorState - " + ServletErrorState;
									market_wrLog.log("market_wrServer (service) : " + Status, LogPrinter.INFO);
								} else {
									Status = "market_wrServer servlet properties cannot be reloaded. You sould chenge them to proceed!<br>ServletState - " + ServletState + ". ServletErrorState - " + ServletErrorState;
									market_wrLog.log("market_wrServer (service) : " + Status, LogPrinter.ERROR);
								}
							} else {
								try {
									long Wait_Time = ServletCounter * Constants.Req_Life_Millis;
									if (Wait_Time > Constants.Max_Wait_Before_Reload) {
										Thread.sleep(Constants.Max_Wait_Before_Reload);
									} else {
										Thread.sleep(Wait_Time);
									}
									synchronized (SynchroCount) {
										if (ServletCounter == 0) {
											if (market_wrServerInit(MarketKey) == Constants.NO_ERROR) {
												Status = "market_wrServer servlet properties reloaded. <br>ServletState - " + ServletState + ". ServletErrorState - " + ServletErrorState;
												market_wrLog.log("market_wrServer (service) : " + Status, LogPrinter.INFO);
											} else {
												Status = "market_wrServer servlet properties cannot be reloaded. You sould chenge them to proceed!<br>ServletState - " + ServletState + ". ServletErrorState - " + ServletErrorState;
												market_wrLog.log("market_wrServer (service) : " + Status, LogPrinter.ERROR);
											}
										} else {
											Status = "market_wrServer servlet is running and can not be reloaded. It has " + ServletCounter + " working instances.<br>ServletState - " + ServletState + ". ServletErrorState - " + ServletErrorState;
											market_wrLog.log("market_wrServer (service) : " + Status, LogPrinter.ERROR);
											ServletState = tempSS;
										}
									} // SynchroCount
								} catch (InterruptedException e) {
									Status = "Exception in sleeping.<br>ServletState - " + ServletState + ". ServletErrorState - " + ServletErrorState;
									market_wrLog.log("market_wrServer (service) : " + Status, LogPrinter.ERROR);
									market_wrLog.flush();
									ServletState = tempSS;
								}
							}
						} // else
					} // SynchroInit
				}
				market_wrConf.wrFormConfigParam(out, Status);
				out.close();
				market_wrLog.flush();
				return;

				// ReqType = 8			
			case (Constants.TASK_GET_SERVLET_STATE) :
				market_wrLog.log("market_wrServer (service) : ServletState is " + ServletState, LogPrinter.DEBUG);
				market_wrLog.flush();
				out.print(ServletState);
				out.close();
				return;

				// ReqType = 9			
			case (Constants.TASK_GET_SERVLET_ERROR_STATE) :
				market_wrLog.log("market_wrServer (service) : ServletErrorState is " + ServletErrorState, LogPrinter.DEBUG);
				market_wrLog.flush();
				out.print(ServletErrorState);
				out.close();
				return;

				// ReqType = 12	
			case (Constants.TASK_GET_SERVLET_COUNTER) :
				market_wrLog.log("market_wrServer (service) : ServletCounter is " + ServletCounter, LogPrinter.DEBUG);
				market_wrLog.flush();
				out.print(ServletCounter);
				out.close();
				return;

				// ReqType = 11
			case (Constants.TASK_CHANGE_LOG_LEVELS) :
				int LogLevel = -1;
				String Level = null;
				Level = req.getParameter(Constants.FileLogLevel);
				if (Level == null) {
					out.println("A change for File Log Level not requested. It is " + market_wrLog.getLogLevel() + ". It won't be changed. Query is : " + req.getQueryString());
					market_wrLog.log("market_wrServer (service) : File Log Level not requested. It won't be changed. Query is : " + req.getQueryString(), LogPrinter.INFO);
				} else {
					try {
						LogLevel = Integer.valueOf(Level).intValue();
						if (LogLevel > -1 && LogLevel <= LogPrinter.ALL) {
							market_wrLog.setLogLevel(LogLevel);
							out.println("File Log Level changed to " + LogLevel + ".");
							market_wrLog.log("market_wrServer (service) : File Log Level changed " + LogLevel + ".", LogPrinter.INFO);
						} else {
							out.println("File Log Level NOT changed becausse it is not valid (" + LogLevel + "). Current File Log Level is : " + market_wrLog.getLogLevel());
							market_wrLog.log("market_wrServer (service) : Not a valid File Log Level sent (" + LogLevel + ").", LogPrinter.ERROR);
							market_wrLog.flush();
						}
					} catch (Exception e) {
						out.println("Error in request sequence for File Log Level. Qurey is : " + req.getQueryString() + ". Current File Log Level is : " + market_wrLog.getLogLevel());
						market_wrLog.log("market_wrServer (service) : Error in request sequence for File Log Level. Qurey is : " + req.getQueryString() + ". Current File Log Level is : " + market_wrLog.getLogLevel(), LogPrinter.ERROR);
						market_wrLog.flush();
					}
				}
				out.print("<br>");
				Level = req.getParameter(Constants.ScreenLogLevel);
				if (Level == null) {
					out.println("A change for Screen Log Level not requested. It is " + market_wrLog.getScreenLogLevel() + ". It won't be changed. Query is : " + req.getQueryString());
					market_wrLog.log("market_wrServer (service) : Screen Log Level not requested. It won't be changed. Query is : " + req.getQueryString(), LogPrinter.INFO);
				} else {
					try {
						LogLevel = Integer.valueOf(Level).intValue();
						if (LogLevel > -1 && LogLevel <= LogPrinter.ALL) {
							market_wrLog.setScreenLogLevel(LogLevel);
							out.println("Screen Log Level changed to " + LogLevel + ".");
							market_wrLog.log("market_wrServer (service) : Screen Log Level changed " + LogLevel + ".", LogPrinter.INFO);
						} else {
							out.println("Screen Log Level NOT changed becausse it is not valid (" + LogLevel + "). Current Screen Log Level is : " + market_wrLog.getLogLevel());
							market_wrLog.log("market_wrServer (service) : Not a valid Screen Log Level sent (" + LogLevel + ").", LogPrinter.ERROR);
							market_wrLog.flush();
						}
					} catch (Exception e) {
						out.println("Error in request sequence for Screen Log Level. Qurey is : " + req.getQueryString() + ". Current File Log Level is : " + market_wrLog.getScreenLogLevel());
						market_wrLog.log("market_wrServer (service) : Error in request sequence for Screen Log Level. Qurey is : " + req.getQueryString() + ". Current Screen Log Level is : " + market_wrLog.getScreenLogLevel(), LogPrinter.ERROR);
						market_wrLog.flush();
					}
				}
				market_wrLog.flush();
				out.close();
				return;

				// If nothing matches	
			default :
				market_wrLog.log("market_wrServer (service) : Not a valid ReqType given - " + nreq, LogPrinter.ERROR);
				out.close();
				market_wrLog.flush();
				return;
		} //switch				
	} else {
		market_wrParameters market_wr = market_wrSet_wrParam(req);
		if (market_wr == null) {
			market_wrLog.log("market_wrServer (service) : Error on input parameters. Try again!", LogPrinter.ERROR);
			out.print(Constants.RETRY);
			out.close();
			market_wrLog.flush();
			return;
		} else {

			// This is the process for single registation or counting
			market_wr.wrKey = market_wrMethodFlow(market_wr.wrString, market_wr.langKey, market_wr.wrCounts, market_wr.srcKey);
			if (market_wr.wrKey == Constants.RETRY) {
				market_wrLog.log("market_wrServer (service) : RESULT for |" + market_wr.wrString + "| is " + market_wr.wrKey + "\n", LogPrinter.ERROR);
			} else {
				market_wrLog.log("market_wrServer (service) : RESULT for |" + market_wr.wrString + "| is " + market_wr.wrKey + "\n", LogPrinter.DEBUG);
			}
			out.print(market_wr.wrKey);
			out.close();
			market_wr = null;
			return;
		}
	} //else If(RT..
}
}

