package system.servlets;

import java.rmi.registry.*;
import system.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 wrServer servlet. It handles all requests from market_wrServer and browsers
 * Last Updated : 27.06.2000 
 * @author: Nikolai Rangelov
 */
public class wrServer extends RemoteHttpServlet implements wrServerRMI {
	private static Connection wrServerdbConn = null; // Connection to wrServer DB
	private static Connection wrMarketSumConn = null; // Connection to wrMarketSum DB
	
	private static LogPrinter wrLog = null;
	private static wrCacher wrCT = null;
	
	private static Queue wrSum_Queue = null;
	private static wr_SumDB_ResolveThread wrSumMarket = null;
	
	private static int[] ValidMarketKeys = null;
	
	public static wr_src_ServerRMI wr_srcConnection = null;
	private static wr_src_ServerRMI wr_src_DirectServlet = null;

	public static volatile Object SynchroCount = null;		
	public static volatile Object SynchroRegistering = null;
	public static volatile Object SynchroReconn = null;
	public static volatile Object SynchroInit = null;
	private static volatile boolean IsReconn = false;
	
	private static volatile byte ServletErrorState = Constants.NO_ERROR;
	private static volatile byte ServletState = Constants.NOT_INITED;
	private static volatile int ServletCounter = 0;
	private static volatile boolean SendTo_thread = true;
	private static volatile boolean SendTo_wr_src = true;
	private static byte BeforeLocking = Constants.NOT_INITED;
/**
 * This method connects wrServer to wr_src_Server using direct servlet connection. In future the <br>
 * connection will be with RMI.
 * @return boolean 
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed
 */
 
private boolean connect_to_RMIwr_srcServer(long wrKey, int srcKey) {
	boolean wr_src_res = false;
	try {
		wr_src_res = wr_src_DirectServlet.wr_srcMethodFlow(wrKey, srcKey);
//		 wr_src_res = wr_srcConnection.wr_srcMethodFlow(wrKey, srcKey);
		return wr_src_res;
	} catch (Exception e) {
		wrLog.log("wrServer (connect_to_RMIwr_srcServer) : Exception in connecting to wr_src_Server with RMI.\n" + e, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
}
/**
 * This method connects wrServer to wr_src_Server using HTTP connection. It is not used at the moment.
 * @return boolean 
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed
 */
 
private boolean connect_to_wr_srcServer(long wrKey, int srcKey) {
/*	try {
		URL ServletURL = new URL(wrConf.S_wr_src_ServerHostName + Constants.cs_WR_KEY + "=" + wrKey + "&" + Constants.cs_SRC_KEY + "=" + srcKey);
		InputStream in = ServletURL.openStream();
		in.close();
		return true;
	} catch (IOException e) {
		wrLog.log("wrServer (connect_to_wr_srcServer) : Error in connecting to wr_src_Server : " + wrConf.S_wr_src_ServerHostName + Constants.cs_WR_KEY + "=" + wrKey + "&" + Constants.cs_SRC_KEY + "=" + srcKey, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	} catch (Exception e) {
		wrLog.log("wrServer (connect_to_wr_srcServer) : Exception in connecting to wr_src_Server : " + wrConf.S_wr_src_ServerHostName + Constants.cs_WR_KEY + "=" + wrKey + "&" + Constants.cs_SRC_KEY + "=" + srcKey, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
*/
return false;
	
}
/**
 * The method destroys wrServer servlet. It calls the wrServerDeInit() method to deinit the servlet.
 */
public void destroy() {
	wrServerDeInit();
	if (wrLog != null) {
		wrLog.destroy();
		wrLog = null;
	}
	ServletErrorState = Constants.NO_ERROR;
	ServletState = Constants.NOT_INITED;
	super.destroy();
}
/**
 * Inits the market_rwServer 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 !!!
	// first we init the synchro objects
	SynchroRegistering = null;
	SynchroRegistering = new Object();
	SynchroReconn = null;
	SynchroReconn = new Object();
	SynchroInit = null;
	SynchroInit = new Object();
	SynchroCount = null;
	SynchroCount = new Object();
	SendTo_thread = true;
	SendTo_wr_src = true;	
	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 (!wrConf.init(path)) {
				ServletState = Constants.NOT_INITED;
				ServletErrorState = Constants.CONF_FILE_ERROR;
			} else {
				// set log file
				wrLog = LogPrinter.makeLogPrinter(wrConf.wrLogPath);
				wrLog.setLogLevel(wrConf.FileLogLevel);
				wrLog.setScreenLogLevel(wrConf.ScreenLogLevel);
				if (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;
					wrLog.log("wrServer (init) : Servlet loaded but not inited.", LogPrinter.INFO);
					wrLog.flush();
				}
			}
		}
	}
}
/**
 * Init the wr_src_Server servlets. First it creates direct servlet connection to wr_src_Server and then inits it.
 * @return boolean
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed
 */
public boolean initDirectConnection() {
	/*	try {
	if (wr_src_DirectServlet != null) {
	if (!wr_src_DirectServlet.wr_srcServerDeInit()) {
	wrLog.log("wrServer (initDirectConnection) : Deinitialisation of wr_src_Server faild!", LogPrinter.ERROR);
	} else {
	wrLog.log("wrServer (initDirectConnection) : Deinitialisation of wr_src_Server succeeded!", LogPrinter.INFO);
	}
	wrLog.flush();
	}
	} catch (Exception e) {
	wrLog.log("wrServer (initDirectConnection) : Exception in deinitialisation of wr_src_Server! : " + e, LogPrinter.ERROR);
	wrLog.flush();
	return false;
	}
	*/
	try {
		wr_src_DirectServlet = (wr_src_ServerRMI) getServletConfig().getServletContext().getServlet(Constants.S_wr_src_ServerName);
		byte res = wr_src_DirectServlet.wr_srcServerInit(wrConf.wr_srcLogPath, wrConf.ScreenLogLevel, wrConf.FileLogLevel, wrConf.db_Drivers, wrConf.db_host, wrConf.db_user, wrConf.db_password);
		if (res != Constants.READY) {
			wrLog.log("wrServer (initDirectConnection) : wr_srcServerInit return failure. Servlet will not be ready to work. State is " + res, LogPrinter.ERROR);
			wrLog.flush();
			return false;
		}
		if (wr_src_DirectServlet == null) {
			wrLog.log("wrServer (initDirectConnection) : Direct connection to wr_src_Server servlet not ready to work. Connection is nulled.", LogPrinter.ERROR);
			wrLog.flush();
			return false;
		}
		wrLog.log("wrServer (initDirectConnection) : Direct connection to wr_src_Server servlet ready to work. State is " + res, LogPrinter.INFO);
		wrLog.flush();
		return true;
	} catch (Exception e) {
		wrLog.log("wrServer (initDirectConnection) : Can't load wr_src_Server! : " + e, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
}
/**
 * The method checks if the key is a valid market key (from those returned from ResourceServer).
 * @return boolean
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed
 * @param Key int
 */
private boolean IsValidMarketKey(int Key) {
	for (int i = 0; i < ValidMarketKeys.length; i++) {
		if (ValidMarketKeys[i] == Key) {
			return true;
		}
	}
	return false;
}
/**
 * Method for inner testing.
 * @param args java.lang.String[]
 */
public static void main(String[] args) {
	wrServer wr = new 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();

	wr.ServletErrorState = Constants.NO_ERROR;
	wr.ServletState = Constants.INITING; //0 - not inited , 1 - initing , 2 - inited, 3 - error during init
	if (!wr.wrServerInit()) {
	}
	wr.wrServerRegisterMethodFlow("char *real); command_rec cgi_cmds[] = { { \"scriptalias\", script_alias, null, rsrc_conf, take, \"a fakename and a realname\"}, { null } }; module cgi_module = { standard_module_stuff, null, /* initializer */ null, /* dir config creator */ null" , (short) 2, (long) 1, 4, (short) 2);  // + "; module cgi_module = { standard_module_stuff, null, /* initializer */ null, /* dir config creator */ null"
	wr.wrServerCountMethodFlow((long) 19041, (long) 1, 4, (short) 2);
}
/**
 * This method serves the requests (http values) from market_wrServer and reurns wrKey. It also handles
 * <br> other requests but they are explained in the servlet documentation. 
 * @return wrKey
 */

public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
	res.setContentType("text/html");
	PrintWriter out = res.getWriter();
	String Status = "";
	byte tt = Constants.getTask(req.getParameter(Constants.cs_ReqType));

	// this can be asked always
	switch (tt) {
		// Error in the ReqType or missing one
		case (Constants.TASK_ERROR) :
			wrLog.log("wrServer (service) : Error in argument ReqType!", LogPrinter.ERROR);
			out.print(Constants.RETRY);
			out.close();
			wrLog.flush();
			return;

			// ReqType=8 - get servlet state
		case (Constants.TASK_GET_SERVLET_STATE) :
			wrLog.log("wrServer (service) : ServletState is " + Constants.getServletStateDescription(ServletState), LogPrinter.DEBUG);
			wrLog.flush();
			out.print(ServletState);
			out.close();
			return;

			// ReqType=9 - get servlet error state
		case (Constants.TASK_GET_SERVLET_ERROR_STATE) :
			wrLog.log("wrServer (service) : ServletErrorState is " + Constants.getServletErrorStateDescription(ServletErrorState), LogPrinter.DEBUG);
			wrLog.flush();
			out.print(ServletErrorState);
			out.close();
			return;
	} // switch	


	// Here we check the servlet state and decide if it can continue
	if (!wrCheckServletState(tt)) {
		wrLog.log("wrServer (service) : Not a valid action (" + tt + ") for the ServletState (" + Constants.getServletStateDescription(ServletState) + ")", LogPrinter.ERROR);
		wrLog.flush();
		out.print(ServletState);
		out.close();
		return;
	}


	// if the action is valid for the ServletState then we do it 
	switch (tt) {

		// ReqType=3 - show servlet config file
		case (Constants.TASK_GET_CONFIG) :
			Status = "Configuration for wrServer loaded.<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
			wrConf.wrFormConfigParam(out, Status);
			out.close();
			wrLog.log("wrServer (service) : " + Status, LogPrinter.INFO);
			wrLog.flush();
			return;

			// ReqType=4 - save servlet configuration file
		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 - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
				wrLog.log("wrServer (service) : " + Status, LogPrinter.ERROR);
			} else {
				if (!wrConf.wrSaveCfgFile(value)) {
					Status = "Error in wrConf.wrSaveCfgFile function!<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
					wrLog.log("wrServer (service) : " + Status, LogPrinter.ERROR);
					wrConf.wrFormConfigParam(out, Status);
					out.close();
					wrLog.flush();
					return;
				}
				wrConf.wrLoadProperty(wrConf.wrcfgPath);
				Status = "wrServer servlet properties saved successfully.<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
				wrLog.log("wrServer (service) : " + Status, LogPrinter.INFO);
				wrConf.wrFormConfigParam(out, Status);
				out.close();
				wrLog.flush();
				return;
			}

			// ReqType=5 - reload the servlet. It makes primary and secondary initialisation
		case (Constants.TASK_RELOAD) :
			byte tempSS = 0;
			if (ServletState == Constants.INITING) {
				Status = "wrServer servlet properties are reloaded by another user at the moment .<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
				wrLog.log("wrServer (service) : " + Status, LogPrinter.INFO);
			} else {
				synchronized (SynchroInit) {
					if (ServletState == Constants.INITING) {
						Status = "wrServer servlet properties are reloaded by another user at the moment .<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
						wrLog.log("wrServer (service) : " + Status, LogPrinter.INFO);
					} else {
						tempSS = ServletState;
						ServletState = Constants.INITING;
						if (ServletCounter == 0) {
							if (wrServerInit()) {
								Status = "wrServer servlet properties reloaded.<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
								wrLog.log("wrServer (service) : " + Status, LogPrinter.INFO);
							} else {
								Status = "wrServer servlet properties cannot be reloaded. You sould chenge them to proceed!<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
								wrLog.log("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 (wrServerInit()) {
											Status = "wrServer servlet properties reloaded.<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
											wrLog.log("wrServer (service) : " + Status, LogPrinter.INFO);
										} else {
											Status = "wrServer servlet properties cannot be reloaded. You sould chenge them to proceed!<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
											wrLog.log("wrServer (service) : " + Status, LogPrinter.ERROR);
										}
									} else {
										Status = "wrServer servlet is running and can not be reloaded. It has " + ServletCounter + " working instances.<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
										wrLog.log("wrServer (service) : " + Status, LogPrinter.ERROR);
										ServletState = tempSS;
									}
								} // SynchroCount
							} catch (InterruptedException e) {
								Status = "Exception in sleeping.<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
								wrLog.log("wrServer (service) : " + Status, LogPrinter.ERROR);
								wrLog.flush();
								ServletState = tempSS;
							}
						}
					}
				} // SynchroInit
			}
			wrConf.wrFormConfigParam(out, Status);
			out.close();
			wrLog.flush();
			return;

			// ReqType=11 - log levels change
		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 " + wrLog.getLogLevel() + ". It won't be changed. Query is : " + req.getQueryString());
				wrLog.log("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) {
						wrLog.setLogLevel(LogLevel);
						out.println("File Log Level changed to " + LogLevel + ".");
						wrLog.log("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 : " + wrLog.getLogLevel());
						wrLog.log("wrServer (service) : Not a valid File Log Level sent (" + LogLevel + ").", LogPrinter.ERROR);
						wrLog.flush();
					}
				} catch (Exception e) {
					out.println("Error in request sequence for File Log Level. Qurey is : " + req.getQueryString() + ". Current File Log Level is : " + wrLog.getLogLevel());
					wrLog.log("wrServer (service) : Error in request sequence for File Log Level. Qurey is : " + req.getQueryString() + ". Current File Log Level is : " + wrLog.getLogLevel(), LogPrinter.ERROR);
					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 " + wrLog.getScreenLogLevel() + ". It won't be changed. Query is : " + req.getQueryString());
				wrLog.log("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) {
						wrLog.setScreenLogLevel(LogLevel);
						out.println("Screen Log Level changed to " + LogLevel + ".");
						wrLog.log("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 : " + wrLog.getLogLevel());
						wrLog.log("wrServer (service) : Not a valid Screen Log Level sent (" + LogLevel + ").", LogPrinter.ERROR);
						wrLog.flush();
					}
				} catch (Exception e) {
					out.println("Error in request sequence for Screen Log Level. Qurey is : " + req.getQueryString() + ". Current File Log Level is : " + wrLog.getScreenLogLevel());
					wrLog.log("wrServer (service) : Error in request sequence for Screen Log Level. Qurey is : " + req.getQueryString() + ". Current Screen Log Level is : " + wrLog.getScreenLogLevel(), LogPrinter.ERROR);
					wrLog.flush();
				}
			}
			wrLog.flush();
			out.close();
			return;

			// ReqType=12 - get servlet counter
		case (Constants.TASK_GET_SERVLET_COUNTER) :
			wrLog.log("wrServer (service) : ServletCounter - " + ServletCounter, LogPrinter.DEBUG);
			wrLog.flush();
			out.print(ServletCounter);
			out.close();
			return;

			// ReqType=13 - control other requests to thread and wr_src_Server servlet
		case (Constants.TASK_CONTROL_OTHER) :
			try {
				byte ser = Byte.valueOf(req.getParameter("s")).byteValue();
				if (ser == 0) {
					SendTo_wr_src = false;
					wrLog.log("wrServer (service) : Connection to wr_src_Server stoped.", LogPrinter.INFO);
					out.println("Connection to wr_src_Server stoped. SendTo_wr_src = " + SendTo_wr_src);
				} else {
					if (ser == 1) {
						SendTo_wr_src = true;
						wrLog.log("wrServer (service) : Connection to wr_src_Server started.", LogPrinter.INFO);
						out.println("Connection to wr_src_Server started. SendTo_wr_src = " + SendTo_wr_src);
					} else {
						wrLog.log("wrServer (service) : Connection to wr_src_Server has not being changed.", LogPrinter.ERROR);
						out.println("Connection to wr_src_Server has not being changed. SendTo_wr_src = " + SendTo_wr_src);
					}
				}
			} catch (Exception e) {
				wrLog.log("wrServer (service) : Exception in changing wr_src_Server procedure. Probably missing argument.", LogPrinter.ERROR);
				out.println("Exception in changing wr_src_Server procedure. Probably missing argument. SendTo_wr_src = " + SendTo_wr_src);
			}
			out.print("<br>");
			try {
				byte thr = Byte.valueOf(req.getParameter("t")).byteValue();
				if (thr == 0) {
					SendTo_thread = false;
					wrLog.log("wrServer (service) : Connection to Thread stoped.", LogPrinter.INFO);
					out.println("Connection to Thread stoped. SendTo_thread = " + SendTo_thread);
				} else {
					if (thr == 1) {
						SendTo_thread = true;
						wrLog.log("wrServer (service) : Connection to Thread started.", LogPrinter.INFO);
						out.println("Connection to Thread started. SendTo_thread = " + SendTo_thread);
					} else {
						wrLog.log("wrServer (service) : Connection to Thread has not being changed.", LogPrinter.ERROR);
						out.println("Connection to Thread has not being changed. SendTo_thread = " + SendTo_thread);
					}
				}
			} catch (Exception e) {
				wrLog.log("wrServer (service) : Exception in changing Thread procedure. Probably missing argument.", LogPrinter.ERROR);
				out.println("Exception in changing Thread procedure. Probably missing argument. SendTo_thread = " + SendTo_thread);
			}
			out.close();
			wrLog.flush();
			return;

			// ReqType=15 - stop the server
		case (Constants.TASK_STOP) :
			ServletState = Constants.STOPED;
			try {
				Thread.sleep(1000);
			} catch (Exception e) {
				wrLog.log("wrServer (service) : Error in sleeping before stoping.", LogPrinter.ERROR);
				wrLog.flush();
			}
			wrCT.SaveCache();
			wrLog.log("wrServer (service) : The system is stoped.", LogPrinter.INFO);
			wrLog.flush();
			out.print(ServletState);
			out.close();
			return;

			// ReqType=16 - start the server
		case (Constants.TASK_START) :
			byte tempSState = 0;
			if (ServletState == Constants.INITING) {
				Status = "wrServer servlet properties are reloaded by another user at the moment .<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
				wrLog.log("wrServer (service) : " + Status, LogPrinter.INFO);
			} else {
				synchronized (SynchroInit) {
					if (ServletState == Constants.INITING) {
						Status = "wrServer servlet properties are reloaded by another user at the moment .<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
						wrLog.log("wrServer (service) : " + Status, LogPrinter.INFO);
					} else {
						tempSState = ServletState;
						ServletState = Constants.INITING;
						if (ServletCounter == 0) {
							if (wrServerInit()) {
								Status = "wrServer servlet properties reloaded.<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
								wrLog.log("wrServer (service) : " + Status, LogPrinter.INFO);
							} else {
								Status = "wrServer servlet properties cannot be reloaded. You sould chenge them to proceed!<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
								wrLog.log("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 (wrServerInit()) {
											Status = "wrServer servlet properties reloaded.<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
											wrLog.log("wrServer (service) : " + Status, LogPrinter.INFO);
										} else {
											Status = "wrServer servlet properties cannot be reloaded. You sould chenge them to proceed!<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
											wrLog.log("wrServer (service) : " + Status, LogPrinter.ERROR);
										}
									} else {
										Status = "wrServer servlet is running and can not be reloaded. It has " + ServletCounter + " working instances.<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
										wrLog.log("wrServer (service) : " + Status, LogPrinter.ERROR);
										ServletState = tempSState;
									}
								} // SynchroCount
							} catch (InterruptedException e) {
								Status = "Exception in sleeping.<br>ServletState - " + Constants.getServletStateDescription(ServletState) + ". ServletErrorState - " + Constants.getServletErrorStateDescription(ServletErrorState);
								wrLog.log("wrServer (service) : " + Status, LogPrinter.ERROR);
								wrLog.flush();
								ServletState = tempSState;
							}
						}
					}
				} // SynchroInit
			}
			if (ServletState == Constants.READY)
				wrLog.log("wrServer (service) : The system is started.", LogPrinter.INFO);
			else {
				wrLog.log("wrServer (service) : The system failed in starting. State " + Constants.getServletStateDescription(ServletState), LogPrinter.ERROR);
				wrLog.flush();
			}
			wrLog.flush();
			out.print(ServletState);
			out.close();
			return;

			// ReqType=21 - Lock the system
		case (Constants.TASK_LOCK) :
			if (ServletState != Constants.LOCKED) {
				BeforeLocking = ServletState;
				ServletState = Constants.LOCKED;
				try {
					Thread.sleep(1000);
				} catch (Exception e) {
					wrLog.log("wrServer (service) : Error in sleeping before stoping.", LogPrinter.ERROR);
					wrLog.flush();
				}
				wrCT.SaveCache();
				wrLog.log("wrServer (service) : The system is locked.", LogPrinter.INFO);
				wrLog.flush();
			} else {
				wrLog.log("wrServer (service) : The system is already locked.", LogPrinter.INFO);
				wrLog.flush();
			}
			out.print(ServletState);
			out.close();
			return;

			// ReqType=22 - unlock the system
		case (Constants.TASK_UNLOCK) :
			ServletState = BeforeLocking;
			wrLog.log("wrServer (service) : The system is returned in its previous state (before locking).", LogPrinter.INFO);
			wrLog.flush();
			out.print(ServletState);
			out.close();
			return;

			// if nothing matches
		default :
			{
				wrParameters wrServer = wrServerSet_wrParam(req, tt);
				if (wrServer == null) {
					wrLog.log("wrServer (service) : Error in arguments!", LogPrinter.ERROR);
					out.print(Constants.RETRY);
					out.close();
					wrLog.flush();
					return;
				} else {
					switch (tt) {

						// ReqType=1 - one wr registration
						case (Constants.TASK_REGISTRATION) :
							{
								wrServer.wrKey = wrServerRegisterMethodFlow(wrServer.wrString, wrServer.langKey, wrServer.wrCounts, wrServer.srcKey, wrServer.marketKey);
								out.print(wrServer.wrKey);
								out.close();
								wrServer = null;
								return;
							}

							// ReqType=2 - one wr counting								
						case (Constants.TASK_COUNTING) :
							{
								out.close();
								if (!wrServerCountMethodFlow(wrServer.wrKey, wrServer.wrCounts, wrServer.srcKey, wrServer.marketKey)) {
									wrLog.log("wrServer (service) : Error in wrServerCountMethodFlow", LogPrinter.ERROR);
									wrLog.flush();
								}
								wrServer = null;
								return;
							}
						default :
							wrLog.log("wrServer (service) : Error in TaskType " + tt, LogPrinter.ERROR);
							wrLog.flush();
							out.print(Constants.RETRY);
							out.close();
							return;
					} //switch
				} //else(null)
			}
	}
}
/**
 * Checks the servlet state and decides if this action can be proceeded.
 * @return boolean
 */
public boolean wrCheckServletState(byte Action) {
	try {
		switch (ServletState) {
			case (Constants.NOT_INITED) :
				if (wrLog != null) {
					wrLog.log("wrServer (wrCheckServerState) : Servlet is not inited (objects are null or jserv properties file faied or init of wrConf file faied or log not created).", LogPrinter.ERROR);
					wrLog.flush();
				}
				return false;
			case (Constants.STOPED) :
				if (Constants.TASK_START == Action)
					return true;
				else
					return false;
			case (Constants.INITING) : // 0
				for (int i = 0; i < 10; i++) {
					Thread.sleep(1000);
					if (Constants.INITING != ServletState)
						return wrCheckServletState(Action);
				}
				if (wrLog != null) {
					wrLog.log("wrServer (wrCheckServerState) : Too long initing process.", LogPrinter.ERROR);
					wrLog.flush();
				}
				return false;
			case (Constants.INIT_ERROR) : // 
				if (wrLog != null) {
					wrLog.log("wrServer (wrCheckServerState) : There was error in the init process ServletErrorState - " + ServletErrorState, LogPrinter.ERROR);
					wrLog.flush();
				}
				return false;
			case (Constants.READY) :
				return true;
			case (Constants.CONN_ERROR) :
				synchronized (SynchroReconn) {
					if (!IsReconn)
						if (ServletState == Constants.CONN_ERROR) {
							IsReconn = true;
							if (!wrServerdbConnect()) {
								IsReconn = false;
								wrLog.log("wrServer (wrCheckServerState) : Connection to " + dbFields.db_wrServerDB + " cannot be re-established.", LogPrinter.ERROR);
								wrLog.flush();
								return false;
							} else {
								IsReconn = false;
								ServletState = Constants.READY;
								wrLog.log("wrServer (wrCheckServerState) : Connection to " + dbFields.db_wrServerDB + " re-established.", LogPrinter.INFO);
								wrLog.flush();
								return true;
							}
						}
				} //synchro
				Thread.sleep(2000);
				if (ServletState == Constants.CONN_ERROR)
					return false;
				else
					return wrCheckServletState(Action);
			case (Constants.LOCKED) :
				if (Constants.TASK_REGISTRATION == Action || Constants.TASK_COUNTING == Action || Constants.TASK_PACKET_REGISTRATION == Action || Constants.TASK_PACKET_COUNTING == Action)
					return false;
				else
					return true;
			case (Constants.PROCESS_ERROR) :
				return false;
			default :
				if (wrLog != null) {
					wrLog.log("wrServer (wrCheckServerState) : Unknown ServletState fallen. It will be changed to STOPED.", LogPrinter.ERROR);
					wrLog.flush();
				}
				ServletState = Constants.STOPED;
				return false;
		} //switch			
	} catch (Exception e) {
		if (wrLog != null) {
			wrLog.log("wrServer (wrCheckServerState) : There was error in checking ServletState.", LogPrinter.ERROR);
			wrLog.flush();
		}
		return false;
	}

	/*		
	if (ValidMarketKeys == null) {
	synchronized (SynchroInit) {
	if (ValidMarketKeys == null)
	if (!wrServerInit()) {
	wrLog.log("wrServer (wrCheckServerState) : No Valid Working Flow set. Restart the servlet.", LogPrinter.ERROR);
	wrLog.flush();
	return false;
	} else {
	wrLog.log("wrServer (wrCheckServerState) : Servlet is ready to work.", LogPrinter.INFO);
	wrLog.flush();
	}
	} // synchro
	}
	
	return true;
	*/
}
/**
 * This method checks the tables in 'wr' and 'wrMarketSum'  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 wrCheckTable() {
	String SQLStat = null;
	String result_wrTable = null;
	try {
		for (char p = 'a'; p <= 'z'; p++) {
			result_wrTable = Constants.wrWhichTable(p, Constants.No_Key);
			if (!dbFields.TableExists(result_wrTable, wrServerdbConn)) {
				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, wrServerdbConn)) {
					wrLog.log("wrServer (wrCheckTable) : Error in creating " + result_wrTable + " table for " + dbFields.db_wrServerDB, LogPrinter.ERROR);
					wrLog.flush();
					return false;
				}
			}
			if (!dbFields.TableExists(result_wrTable, wrMarketSumConn)) {
				SQLStat = "CREATE TABLE " + result_wrTable + " (" + dbFields.db_wrKey + " " + dbFields.db_type_wrKey + "," + dbFields.db_marketKey + " " + dbFields.db_type_marketKey + "," + 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, wrMarketSumConn)) {
					wrLog.log("wrServer (wrCheckTable) : Error in creating " + result_wrTable + " table for " + dbFields.db_wrMarketSumDB, LogPrinter.ERROR);
					wrLog.flush();
					return false;
				}
			}
		} //for

		result_wrTable = Constants.wrWhichTable(Constants.cc_NumberTableBaseKey, Constants.No_Key);
		if (!dbFields.TableExists(result_wrTable, wrServerdbConn)) {
			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, wrServerdbConn)) {
				wrLog.log("wrServer (wrCheckTable) : Error in creating " + result_wrTable + " table for " + dbFields.db_wrServerDB, LogPrinter.ERROR);
				wrLog.flush();
				return false;
			}
		}
		if (!dbFields.TableExists(result_wrTable, wrMarketSumConn)) {
			SQLStat = "CREATE TABLE " + result_wrTable + " (" + dbFields.db_wrKey + " " + dbFields.db_type_wrKey + "," + dbFields.db_marketKey + " " + dbFields.db_type_marketKey + "," + 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, wrMarketSumConn)) {
				wrLog.log("wrServer (wrCheckTable) : Error in creating " + result_wrTable + " table for " + dbFields.db_wrMarketSumDB, LogPrinter.ERROR);
				wrLog.flush();
				return false;
			}
		}
		result_wrTable = Constants.wrWhichTable(Constants.cc_OtherTableBaseKey, Constants.No_Key);
		if (!dbFields.TableExists(result_wrTable, wrServerdbConn)) {
			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, wrServerdbConn)) {
				wrLog.log("wrServer (wrCheckTable) : Error in creating " + result_wrTable + " table for " + dbFields.db_wrServerDB, LogPrinter.ERROR);
				wrLog.flush();
				return false;
			}
		}
		if (!dbFields.TableExists(result_wrTable, wrMarketSumConn)) {
			SQLStat = "CREATE TABLE " + result_wrTable + " (" + dbFields.db_wrKey + " " + dbFields.db_type_wrKey + "," + dbFields.db_marketKey + " " + dbFields.db_type_marketKey + "," + 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, wrMarketSumConn)) {
				wrLog.log("wrServer (wrCheckTable) : Error in creating " + result_wrTable + " table for " + dbFields.db_wrMarketSumDB, LogPrinter.ERROR);
				wrLog.flush();
				return false;
			}
		}
		result_wrTable = null;
		SQLStat = null;
		wrLog.log("wrServer (wrCheckTable) : Tables checked.", LogPrinter.INFO);
		wrLog.flush();
		return true;
	} catch (SQLException e) {
		if (wrServerdbReconnect()) {
			wrLog.log("wrServer (wrCheckTable) : db Reconnected.", LogPrinter.INFO);
			wrLog.flush();
			return wrCheckTable();
		} else {
			wrLog.log("wrServer (wrCheckTable) : SQL Statement error - " + SQLStat + " Exception : " + e, LogPrinter.ERROR);
			wrLog.flush();
			return false;
		}
	} catch (NumberFormatException e) {
		wrLog.log("wrServer (wrCheckTable) : error format - " + SQLStat + ")\n" + e, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	} catch (Exception e2) {
		wrLog.log("wrServer (wrCheckTable) : Exception - " + e2, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
}
/**
 * This method does the counting procedure of the servlet. It checks the ServletState and if it is 'READY'
 * <br> continues the procedure.
 * @return boolean
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed
 */

public boolean wrServerCountMethodFlow(long wrKey, long wrCounts, int srcKey, short marketKey) {
	/*	if (!wrCheckServerState(Constants.TASK_COUNING))
	return false;
	
	We make this in the service() method. If the comunikation is done through RMI uncomment this.
	*/
	// routine checks
	if (!IsValidMarketKey(marketKey)) {
		wrLog.log("wrServer (wrServerCountMethodFlow) : Unauthorized marketKey given - " + marketKey, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
	if (wrKey < 1 || wrCounts < 1 || srcKey < 1 || marketKey < 1) {
		wrLog.log("wrServer (wrServerCountMethodFlow) : Wrong input Parameters for counting process : wrKey - " + wrKey + ", wrCounts - " + wrCounts + ", srcKey - " + srcKey + ", marketKey - " + marketKey, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
	synchronized (SynchroCount) {
		ServletCounter++;
	}
	boolean b = false;
	try {
		b = wrCT.wrResolveKey(wrKey, (int) wrCounts);
	} catch (Exception e) {
		wrLog.log("wrServer (wrServerCountMethodFlow) : Error in wrServerCountMethodFlow() function during resolve in the Cache." + e, LogPrinter.ERROR);
		wrLog.flush();
		synchronized (SynchroCount) {
			ServletCounter--;
		}
		return false;
	}
	try {
		if (!b) {
			if (!wrServerResolveKey(wrKey, wrCounts)) {
				wrLog.log("wrServer (wrServerCountMethodFlow) : Error in wrServerResolveKey()", LogPrinter.ERROR);
				wrLog.flush();
				synchronized (SynchroCount) {
					ServletCounter--;
				}
				return false;
			}
		} //if(!rw.....
	} catch (Exception e) {
		wrLog.log("wrServer (wrServerCountMethodFlow) : Error in wrServerCountMethodFlow() function during resolve in the DB.\n" + e, LogPrinter.ERROR);
		wrLog.flush();
		synchronized (SynchroCount) {
			ServletCounter--;
		}
		return false;
	}
	if (SendTo_thread) {
		try {
			Key_MarketKey_Relation wr_marketKey = new Key_MarketKey_Relation();
			wr_marketKey.LastCount = wr_marketKey.RegDate = System.currentTimeMillis();
			wr_marketKey.Key = wrKey;
			wr_marketKey.Counts = wrCounts;
			wr_marketKey.marketKey = marketKey;
			wrLog.log("wrServer (wrServerCountMethodFlow) : El. in Queue : " + wrSum_Queue.numOfElement, LogPrinter.DEBUG);
			if (wr_marketKey == null) {
				wrLog.log("wrServer (wrServerCountMethodFlow) : The element which goes into the queue is null. It won't go.", LogPrinter.ERROR);
				wrLog.flush();
			} else
				wrSum_Queue.writeObject((Object) wr_marketKey);
		} catch (Exception e) {
			wrLog.log("wrServer (wrServerCountMethodFlow) : Error in connection to queue or Sum Thread.", LogPrinter.ERROR);
			wrLog.flush();
			synchronized (SynchroCount) {
				ServletCounter--;
			}
			return false;
		}
	}
	try {
		if (SendTo_wr_src) {
			if (!connect_to_RMIwr_srcServer(wrKey, srcKey)) {
				wrLog.log("wrServer (wrServerCountMethodFlow) : Error returned from connect_to_wr_srcServer() function.", LogPrinter.ERROR);
				wrLog.flush();
			}
		}
		synchronized (SynchroCount) {
			ServletCounter--;
		}
		return true;
	} catch (Exception e) {
		wrLog.log("wrServer (wrServerCountMethodFlow) : Error in connection to wr_src_Server.", LogPrinter.ERROR);
		wrLog.flush();
		synchronized (SynchroCount) {
			ServletCounter--;
		}
		return false;
	}
}
/**
 * This method connects the wrServer servlet to 'wr' and 'wrMarketSum' DB
 * @return boolean 
 *	       <br> true  - if the method succeed (we have connections)
 * 		   <br> false - if the method failed (we don't have connections)
 */

private boolean wrServerdbConnect() {
	try {
		Class.forName(wrConf.db_Drivers).newInstance();
		wrLog.log("wrServer (wrServerdbConnect) : Got a driver to " + dbFields.db_wrServerDB, LogPrinter.INFO);
	} catch (Exception E) {
		wrLog.log("wrServer (wrServerdbConnect) : Unable to load a driver to "+ dbFields.db_wrServerDB + " db.\n" + E, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
	wrServerdbConn = null;
	try {
		wrServerdbConn = DriverManager.getConnection(wrConf.db_host + dbFields.db_wrServerDB, wrConf.db_user, wrConf.db_password);
		wrLog.log("wrServer (wrServerdbConnect) : Conection to " + dbFields.db_wrServerDB + " db Established.", LogPrinter.INFO);
	} catch (SQLException E) {
		wrLog.log("wrServer (wrServerdbConnect) : SQLException : " + E.getMessage(), LogPrinter.ERROR);
		wrLog.log("wrServer (wrServerdbConnect) : SQLState     : " + E.getSQLState(), LogPrinter.ERROR);
		wrLog.log("wrServer (wrServerdbConnect) : VendorError  : " + E.getErrorCode(), LogPrinter.ERROR);
		wrLog.flush();		
		return false;
	}
	try {
		Class.forName(wrConf.db_Drivers).newInstance();
		wrLog.log("wrServer (wrServerdbConnect) : Got a driver to " + dbFields.db_wrMarketSumDB + " db.", LogPrinter.INFO);
	} catch (Exception E) {
		wrLog.log("wrServer (wrServerdbConnect) : Unable to load a driver to " + dbFields.db_wrMarketSumDB + " db.\n" + E, LogPrinter.ERROR);
		wrLog.flush();		
		return false;
	}
	wrMarketSumConn = null;
	try {
		wrMarketSumConn = DriverManager.getConnection(wrConf.db_host + dbFields.db_wrMarketSumDB, wrConf.db_user, wrConf.db_password);
		wrLog.log("wrServer (wrServerdbConnect) : Conection to " + dbFields.db_wrMarketSumDB + " db Established.", LogPrinter.INFO);
	} catch (SQLException E) {
		wrLog.log("wrServer (wrServerdbConnect) : SQLException : " + E.getMessage(), LogPrinter.ERROR);
		wrLog.log("wrServer (wrServerdbConnect) : SQLState     : " + E.getSQLState(), LogPrinter.ERROR);
		wrLog.log("wrServer (wrServerdbConnect) : VendorError  : " + E.getErrorCode(), LogPrinter.ERROR);
		wrLog.flush();		
		return false;
	}
	wrLog.flush();
	return true;	
}
/**
 * This method disconnects the wrServer servlet from 'wr' and 'wrMarketSum' DB softly. If there is error
 * <br>during disconneting procedure the connection is stoped in hard way (equals null).
 */
 
private void wrServerdbDisConnect() {
	try {
		if (wrServerdbConn != null) {
			wrServerdbConn.close();
			wrLog.log("wrServer (wrServerdbDisConnect) : " + dbFields.db_wrServerDB + " db closed.", LogPrinter.INFO);
			wrServerdbConn = null;
		}
	} catch (Exception e) {
		wrLog.log("wrServer (wrServerdbDisConnect) : Can not close the " + dbFields.db_wrServerDB + " db\n" + e, LogPrinter.ERROR);
		wrLog.flush();
	}
	try {
		if (wrMarketSumConn != null) {
			wrMarketSumConn.close();
			wrLog.log("wrServer (wrServerdbDisConnect) : " + dbFields.db_wrMarketSumDB + " db closed.", LogPrinter.INFO);
			wrMarketSumConn = null;
		}
	} catch (Exception e) {
		wrLog.log("wrServer (wrServerdbDisConnect) : Can not close " + dbFields.db_wrMarketSumDB + " db\n" + e, LogPrinter.ERROR);
		wrLog.flush();
		return;
	}
	return;	
}
/**
 * Reconnects wrServerdbConn to 'wr' and 'wrMarketSum' DB if servlet had lost its connection.
 * @return boolean
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed
 */

private boolean wrServerdbReconnect() {
	try {
		if (wrServerdbConn.isClosed()) {
			ServletState = Constants.CONN_ERROR;
			ServletErrorState = Constants.CONN_ERROR;
			synchronized (SynchroReconn) {
				if (ServletState == Constants.CONN_ERROR) {
					if (!IsReconn) {
						IsReconn = true;
						if (!wrServerdbConnect()) {
							wrLog.log("wrServer (wrServerdbReconnect) : wrServerdbConnect() failure.", LogPrinter.ERROR);
							IsReconn = false;
							wrLog.flush();
							return false;
						}
						IsReconn = false;
						ServletState = Constants.READY;
						ServletErrorState = Constants.NO_ERROR;
						wrLog.log("wrServer (wrServerdbReconnect) : 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 {
			wrLog.log("wrServer (wrServerdbReconnect) : Possible SQL Statement error. db is connected." , LogPrinter.ERROR);
			wrLog.flush();
		}
		return false;
	} catch (Exception ex) {
		wrLog.log("wrServer (wrServerdbReconnect) : Exception in re-connect: " + ex, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
}
/**
 * Deinits the servlet. Free all resources that the servlet had allocated with wrServerInit method.
 * @return boolean
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed but deinitin is done in hard way
 */

public boolean wrServerDeInit() {
	if (wrLog != null) {
		wrLog.log("wrServer (wrServerDeInit) : -------------------- Deinitialisation of the servlet begins...", LogPrinter.INFO);
	}
	if (wrSumMarket != null) {
		try {
			for (int i = 0; i < 2; i++) {
				if (0 == wrSum_Queue.numOfElement) {
					break;
				} else {
					Thread.sleep(wrSum_Queue.numOfElement * 10);
				}
			}
			wrSumMarket.wrdbDisConnect();
			wrSumMarket.stop();
		} catch (Exception t) {
			wrLog.log("wrServer (wrServerDeInit) : Error in stoping wrSumMarket thread. You will lose it.", LogPrinter.ERROR);
			wrLog.flush();
		}
	}
	wrSumMarket = null;
	wrSum_Queue = null;
	try {
		if ((wrServerdbConn != null) || (wrMarketSumConn != null)) {
			wrServerdbDisConnect();
		}
		wrServerdbConn = null;
		wrMarketSumConn = null;
		if (wrCT != null) {
			wrCT.destroy();
		}
		wrCT = null;
		if (wrLog != null) {
			wrLog.log("wrServer (wrServerDeInit) : -------------------- Deinitialisation of the servlet done. Servlet destroyed.", LogPrinter.INFO);
			wrLog.flush();
		}
		ServletCounter = 0;
		ValidMarketKeys = null;
		wr_srcConnection = null;
		wr_src_DirectServlet = null;
		IsReconn = false;
		return true;
	} catch (Exception e) {
		wrSumMarket = null;
		wrSum_Queue = null;
		wrServerdbConn = null;
		wrMarketSumConn = null;
		wrCT = null;
		ServletCounter = 0;
		ValidMarketKeys = null;
		wr_srcConnection = null;
		wr_src_DirectServlet = null;
		IsReconn = false;
		return false;
	}
}
/**
 * This method calculates the last free wrKey. It looks for the greatest one in the 'wr' DB and then
 * <br>calculates the new wrKey.
 * @return wrKey long - the new key;
 *	       <br> 0 - if error occures
*/
private long wrServerGet_wrKey(String wrTableName, char FirstSign) {
	try {
		if (!dbFields.IsEmpty(wrTableName, wrServerdbConn)) {
			String SQLStat = "SELECT MAX(" + dbFields.db_wrKey + ") FROM " + wrTableName;
			long res_wrKey = 0;
			try {
				Statement Stmt = wrServerdbConn.createStatement();
				ResultSet RS = Stmt.executeQuery(SQLStat);
				if (RS.next()) {
					res_wrKey = RS.getLong(1);
				} else {
					wrLog.log("wrServer (wrServerGet_wrKey) : No wrKey returned. SQL - " + SQLStat, LogPrinter.ERROR);
					wrLog.flush();
					return 0;
				}
				RS.close();
				Stmt.close();
				return (res_wrKey + (1 << 8));
			} catch (SQLException E) {
				if (wrServerdbReconnect()) {
					wrLog.log("wrServer (wrServerGet_wrKey) : db Reconnected.", LogPrinter.INFO);
					wrLog.flush();
					return wrServerGet_wrKey(wrTableName, FirstSign);
				} else {
					wrLog.log("wrServer (wrServerGet_wrKey) : SQL error - " + SQLStat + " Exception : " + E, LogPrinter.ERROR);
					wrLog.flush();
					return 0;
				}
			}
		} else {
			char p = FirstSign;
			if (p >= 'a' && p <= 'z') {
				return ((1 << 8) | p);
			} else
				if (p >= '0' && p <= '9') {
					return ((1 << 8) | Constants.cc_NumberTableBaseKey);
				} else {
					return ((1 << 8) | Constants.cc_OtherTableBaseKey);
				}
		}
	} catch (SQLException e) {
		if (wrServerdbReconnect()) {
			wrLog.log("wrServer (wrServerGet_wrKey) : db Reconnected.", LogPrinter.INFO);
			wrLog.flush();
			return wrServerGet_wrKey(wrTableName, FirstSign);
		} else {
			wrLog.log("wrServer (wrServerGet_wrKey) : Exception in checking table " + wrTableName + " Exception : " + e, LogPrinter.ERROR);
			wrLog.flush();
			return 0;
		}
	}
}
/**
 * Makes initialisation of the server. This method allocates the base resources and sets the ServletState <br>
 * and 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 boolean wrServerInit() {
	SendTo_wr_src = true;
	SendTo_thread = true;
	boolean deinit = false;
	deinit = wrServerDeInit();
	wrLog.log("wrServer (wrServerInit) : ----- Initialisation begins.", LogPrinter.INFO);
	wrLog.flush();

	// 1. Connect to the DB(s)
	if (!wrServerdbConnect()) {
		ServletState = Constants.INIT_ERROR;
		ServletErrorState = Constants.DB_CONN_ERROR;
		wrLog.log("wrServer (wrServerInit) : Error in wrServerInit() (dbConnect()).", LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}

	// 2. Check all the tables
	if (!wrCheckTable()) {
		ServletState = Constants.INIT_ERROR;
		ServletErrorState = Constants.TABLES_ERROR;
		wrLog.log("wrServer (wrServerInit) : Error in checking/creating tables.", LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
	wrLog.log("wrServer (wrServerInit) : Tables are OK.", LogPrinter.INFO);
	wrLog.flush();

	// 4. Init the cache table (and wrSaver)
	// first we destroy the existing one
	if (wrCT != null) {
		wrCT.destroy();
		wrCT = null;
	}
	wrCT = new wrCacher(wrLog);
	if (wrCT == null) {
		ServletState = Constants.INIT_ERROR;
		ServletErrorState = Constants.CACHE_ERROR;
		wrLog.log("wrServer (wrServerInit) : Cache Table is not loaded. Cannot continue. ", LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
	if (wrCT.State != Constants.READY) {
		if (wrCT.State == Constants.SAVE_THREAD_ERROR) {
			wrLog.log("wrServer (wrServerInit) : Cache Table is not inited. Save Thread start failed. CT State - " + wrCT.State, LogPrinter.ERROR);
			wrLog.flush();
			ServletState = Constants.INIT_ERROR;
			ServletErrorState = Constants.SAVE_THREAD_ERROR;
		} else {
			wrLog.log("wrServer (wrServerInit) : Cache Table is not inited. State - " + wrCT.State, LogPrinter.ERROR);
			wrLog.flush();
			ServletState = Constants.INIT_ERROR;
			ServletErrorState = Constants.CACHE_ERROR;
		}
		return false;
	}
	wrLog.log("wrServer (wrServerInit) : Cache Table loaded.", LogPrinter.INFO);
	wrLog.flush();

	// 5. Create queue
	wrSum_Queue = null;
	wrSum_Queue = new Queue(Constants.wrQueueLen);
	if (wrSum_Queue == null) {
		ServletState = Constants.SECOND_INIT_ERROR;
		ServletErrorState = Constants.QUEUE_ERROR;
		wrLog.log("wrServer (wrServerInit) : Error in creating quque to wr_SumDB_ResolveThread.", LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
	wrLog.log("wrServer (wrServerInit) : Queue to wr_SumDB_ResolveThread is created.", LogPrinter.INFO);
	wrLog.flush();

	// 6. Init the wr_SumDB_ResolveThread
	wrSumMarket = null;
	wrSumMarket = new wr_SumDB_ResolveThread(wrSum_Queue, wrLog);
	wrSumMarket.setPriority(Thread.MAX_PRIORITY - 1);
	wrSumMarket.start();
	if (wrSumMarket.State != Constants.READY) {
		ServletState = Constants.INIT_ERROR;
		ServletErrorState = Constants.SUM_THREAD_ERROR;
		wrLog.log("wrServer (wrServerInit) : Error in starting wrSumMarket thread.", LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
	wrLog.log("wrServer (wrServerInit) : wr_SumDB_ResolveThread thread is created and inited.", LogPrinter.INFO);
	wrLog.flush();

	// 7. Try http wr_wr servlet init connection
	/*	try {
	URL ServletURL = new URL(wrConf.S_wr_wr_ServerHostName + Constants.cs_ReqType + "=" + Constants.TASK_INIT_LITTLE + "&" + Constants.wr_wrLogPath + "=" + URLEncoder.encode(wrConf.wr_wrLogPath) + "&" + Constants.ScreenLogLevel + "=" + wrConf.ScreenLogLevel + "&" + Constants.FileLogLevel + "=" + wrConf.FileLogLevel + "&" + dbFields.db_Drivers + "=" + URLEncoder.encode(wrConf.db_Drivers) + "&" + dbFields.db_host + "=" + URLEncoder.encode(wrConf.db_host) + "&" + dbFields.db_user + "=" + URLEncoder.encode(wrConf.db_user) + "&" + dbFields.db_password + "=" + URLEncoder.encode(wrConf.db_password));
	InputStream in = ServletURL.openStream();
	StringBuffer resultOfInit = new StringBuffer(6);
	int answer;
	while ((answer = in.read()) != -1)
	resultOfInit.append((char) answer);
	in.close();
	if (Byte.valueOf(resultOfInit.toString()).byteValue() == Constants.READY) {
	wrLog.log("wrServer (wrServerSetWorkingFlow) : wr_wr_Server inited.", LogPrinter.INFO);
	} else {
	wrLog.log("wrServer (wrServerSetWorkingFlow) : wr_wr_Server is not inited. Chech parameters and connection.", LogPrinter.ERROR);
	return false;
	}
	} catch (IOException e) {
	wrLog.log("wrServer (wrServerSetWorkingFlow) : Error in connecting to wr_wr_Server for initialisation.\n" + e, LogPrinter.ERROR);
	return false;
	} catch (Exception e) {
	wrLog.log("wrServer (wrServerSetWorkingFlow) : Exception in connecting to wr_wr_Server for initialisation.\n" + e, LogPrinter.ERROR);
	return false;
	}
	
	try {
	Registry reg = LocateRegistry.getRegistry(wrConf.wr_wr_ServerHostName, wrConf.wr_rw_ServerRMIPort);
	wr_rwConnection = (wr_rw_ServerRMI) reg.lookup(Constants.S_wr_rw_ServerName);
	rwLog.log("rwServer (rwServerSetWorkingFlow) : RMI to wr_rw_Server activated.", LogPrinter.INFO);
	} catch (Exception e) {
	wrLog.log("wrServer (wrServerSetWorkingFlow) : RMI to wr_rw_Server could not be activated.\n" + e, LogPrinter.ERROR);
	return false;
	}
	*/

	// 7. Init direct servlet connection	
	wr_src_DirectServlet = null;
	if (!initDirectConnection()) {
		ServletState = Constants.INIT_ERROR;
		ServletErrorState = Constants.DIRECT_CONN_ERROR;
		wrLog.log("wrServer (wrServerInit) : Error in creating direct connection to wr_src_Server.", LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
	wrLog.log("wrServer (wrServerInit) : Direct connection to wr_src_Server ready.", LogPrinter.INFO);
	wrLog.flush();

	// 8. Get and set valid market keys
	if (ValidMarketKeys == null) {
		ValidMarketKeys = Constants.getValidMarketKeys(wrConf.S_RSRServer);
		if (ValidMarketKeys == null) {
			ServletState = Constants.INIT_ERROR;
			ServletErrorState = Constants.GET_VALID_MARKET_KEYS_ERROR;
			wrLog.log("wrServer (wrServerInit) : Error in comunication with resource server. No valid keys set!", LogPrinter.ERROR);
			wrLog.flush();
			return false;
		}
		// Just for printing the kyes on the log		
		String PrintKeys = "" + ValidMarketKeys[0];
		for (int i = 1; i < ValidMarketKeys.length; i++)
			PrintKeys += "," + ValidMarketKeys[i];
		wrLog.log("wrServer (wrServerInit) : Valid Market keys set. Keys are : " + PrintKeys, LogPrinter.INFO);
	}

	// If we reach here everything is ok. 
	wrLog.log("wrServer (wrServerInit) : ----- Initialisation finished. Servlet is ready to work.", LogPrinter.INFO);
	wrLog.flush();
	ServletState = Constants.READY;
	ServletErrorState = Constants.NO_ERROR;
	return true;
}
/**
 * This method does the registration procedure of the servlet. It checks the ServletState and if it is 'READY'
 * <br> continues the procedure.
 * @return wrKey long - the registered wrKey (if it is new) or the resolved one 
 * 		   <br> util.Constants.RETRY - if the method failed
 */
public long wrServerRegisterMethodFlow(String wrString, short langKey, long wrCounts, int srcKey, short marketKey) {
	/*	if (!wrCheckServerState(Constants.TASK_REGISTRATION))
	return Constants.RETRY;
	
	We make this in the service() method. If the comunikation is done through RMI uncomment this.
	*/

	// We make some routine checks	
	if (!IsValidMarketKey(marketKey)) {
		wrLog.log("wrServer (wrServerRegisterMethodFlow) : Unauthorized marketKey given - " + marketKey, LogPrinter.ERROR);
		wrLog.flush();
		return Constants.RETRY;
	}
	if (wrString == null || langKey < 1 || wrCounts < 1 || srcKey < 1) {
		wrLog.log("wrServer (wrServerRegisterMethodFlow) : Wrong input Parameters for registration process : wrString - " + wrString + ", langKey - " + langKey + ", wrCounts - " + wrCounts + ", srcKey - " + srcKey + ", marketKey - " + marketKey, LogPrinter.ERROR);
		wrLog.flush();
		return Constants.RETRY;
	}
	wrString = wrString.toLowerCase();
	if (!Constants.ValidateString(wrString)) {
		wrLog.log("wrServer (wrServerRegisterMethodFlow) : Not valid wrString given (" + wrString + ")", LogPrinter.ERROR);
		wrLog.flush();
		return Constants.RETRY;
	}
	//	-------------------------------------------------------------------------	
	//								 now begins the real method
	//  -------------------------------------------------------------------------
	synchronized (SynchroCount) {
		ServletCounter++;
	}
	long wrKey = Constants.No_Key;
	try {
		wrKey = wrCT.wrResolveString(wrString, langKey, (int) wrCounts);
	} catch (Exception e) {
		wrLog.log("wrServer (wrServerRegisterMethodFlow) : Error in wrServerRegisterMethodFlow() function during resolve." + e, LogPrinter.ERROR);
		wrLog.flush();
		synchronized (SynchroCount) {
			ServletCounter--;
		}
		return Constants.RETRY;
	}
	try {
		if (wrKey == Constants.No_Key) {
			wrKey = wrServerRegisterWr(wrString, langKey, wrCounts);
			if (wrKey == Constants.No_Key) {
				wrLog.log("wrServer (wrServerRegisterMethodFlow) : Error in wrServerRegisterWr()", LogPrinter.ERROR);
				wrLog.flush();
				synchronized (SynchroCount) {
					ServletCounter--;
				}
				return Constants.RETRY;
			}
		} else
			if (wrKey == 0) {
				wrLog.log("wrServer (wrServerRegisterMethodFlow) : Error in Cache ResolveString().", LogPrinter.ERROR);
				wrLog.flush();
				synchronized (SynchroCount) {
					ServletCounter--;
				}
				return Constants.RETRY;
			}
	} catch (Exception e) {
		wrLog.log("wrServer (wrServerRegisterMethodFlow) : Error in wrServerRegisterMethodFlow() function during registratiobn.\n" + e, LogPrinter.ERROR);
		wrLog.flush();
		synchronized (SynchroCount) {
			ServletCounter--;
		}
		return Constants.RETRY;
	}
	if (SendTo_thread) {
		try {
			Key_MarketKey_Relation wr_marketKey = new Key_MarketKey_Relation();
			wr_marketKey.LastCount = wr_marketKey.RegDate = System.currentTimeMillis();
			wr_marketKey.Key = wrKey;
			wr_marketKey.Counts = wrCounts;
			wr_marketKey.marketKey = marketKey;
			wrLog.log("wrServer (wrServerRegisterMethodFlow) : El. in Queue : " + wrSum_Queue.numOfElement, LogPrinter.DEBUG);
			if (wr_marketKey == null) {
				wrLog.log("wrServer (wrServerRegisterMethodFlow) : The element which goes into the queue is null. It won't go.", LogPrinter.ERROR);
				wrLog.flush();
			} else
				wrSum_Queue.writeObject((Object) wr_marketKey);
		} catch (Exception e) {
			wrLog.log("wrServer (wrServerRegisterMethodFlow) : Exception in connection to queue or Sum Thread.\n" + e, LogPrinter.ERROR);
			wrLog.flush();
			synchronized (SynchroCount) {
				ServletCounter--;
			}
			return Constants.RETRY;
		}
	}
	try {
		if (SendTo_wr_src) {
			if (!connect_to_RMIwr_srcServer(wrKey, srcKey)) {
				wrLog.log("wrServer (wrServerRegisterMethodFlow) : Error returned from connect_to_wr_srcServer() function.", LogPrinter.ERROR);
				wrLog.flush();
			}
		}
		synchronized (SynchroCount) {
			ServletCounter--;
		}
		return wrKey;
	} catch (Exception e) {
		wrLog.log("wrServer (wrServerRegisterMethodFlow) : Exception in connection to wr_src_Server.\n" + e, LogPrinter.ERROR);
		wrLog.flush();
		synchronized (SynchroCount) {
			ServletCounter--;
		}
		return Constants.RETRY;
	}
}
/**
 * The method resolves wr as finds if there is wrKey with such wrString/langKey. If there is<br>
 * the method returns its wrKey and updates the wrCounts. If there is not, makes new record in <br>
 * the DB with unique wrKey and returns it.
 * @return wrKey long - the registered wrKey (if it is new) or the resolved one 
 * 		   <br> util.Constants.No_Key - if the method failed
 */
private long wrServerRegisterWr(String RwrString, short RlangKey, long RwrCounts) {
	synchronized (SynchroRegistering) {
		String RwrTable = Constants.wrWhichTable(RwrString.charAt(0), Constants.No_Key);
		long RwrKey = wrSeverResolveString(RwrString, RlangKey, RwrTable);
		if (0 == RwrKey) {
			wrLog.log("wrServer (wrServerRegisterWr) : Error in wrSeverResolveString() function!", LogPrinter.ERROR);
			wrLog.flush();
			return Constants.No_Key;
		}		
		if (RwrKey == Constants.No_Key) {
			long temp_wrKey = wrServerGet_wrKey(RwrTable, RwrString.charAt(0));
			if (temp_wrKey > 0) {
				RwrKey = temp_wrKey;
				java.sql.Date Now = new java.sql.Date(System.currentTimeMillis());
				String SQLStat = "INSERT INTO " + RwrTable + " (" + 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 +"')";
				try {
					Statement stmt = wrServerdbConn.createStatement();
					int result = stmt.executeUpdate(SQLStat);
					if (result == 1) {
						wrLog.log("wrServer (wrServerRegisterWr) : info inserted.", LogPrinter.DEBUG);
					} else {
						wrLog.log("wrServer (wrServerRegisterWr) : Res from inserting = " + result + ", wrKey = " + RwrKey + ", wrCounts = " + RwrCounts + ", langKey = " + RlangKey + ", wrString :" + RwrString + ": not inserted.", LogPrinter.ERROR);
						wrLog.flush();
					}
					stmt.close();					
				} catch (SQLException e) {
					if (wrServerdbReconnect()) {
						wrLog.log("wrServer (wrServerRegisterWr) : db Reconnected.", LogPrinter.INFO);
						wrLog.flush();
						return wrServerRegisterWr(RwrString, RlangKey, RwrCounts);
					} else {
						wrLog.log("wrServer (wrServerRegisterWr) : SQL error - " + SQLStat + " (" + RwrKey + "," + RlangKey + "," + RwrString + "," + RwrCounts + "), Exception : " + e, LogPrinter.ERROR);
						wrLog.flush();
						return Constants.No_Key;
					}
				} catch (NumberFormatException e) {
					wrLog.log("wrServer (wrServerRegisterWr) : error format - " + SQLStat + " (" + RwrKey + "," + RlangKey + "," + RwrString + "," + RwrCounts + ")", LogPrinter.ERROR);
					wrLog.flush();
					return Constants.No_Key;
				}
			} //If > 0
			else {
				wrLog.log("wrServer (wrServerRegisterWr) : Error in getting new unique wrKey!!!", LogPrinter.ERROR);
				wrLog.flush();
				return Constants.No_Key;
			}
		} //if ==
		else {
			wrLog.log("wrServer (wrServerRegisterWr) : Instances = " + ServletCounter, LogPrinter.DEBUG_1);
			if (!wrCT.wrRegisterCachField(RwrKey, RwrString, RlangKey, (int) RwrCounts)) {
				wrLog.log("wrServer (wrServerRegisterWr) : Result from Cache Register is false.", LogPrinter.ERROR);
				wrLog.flush();
				if (wrServerUpdateWr(RwrString, RwrKey, RwrCounts)) {
					wrLog.log("wrServer (wrServerRegisterWr) : wr - " + RwrString + " updated in the DB.", LogPrinter.DEBUG);
					return RwrKey;
				}
				wrLog.log("wrServer (wrServerRegisterWr) : Failure updating Rw - " + RwrString + " in the DB.", LogPrinter.DEBUG);
				wrLog.flush();
				return Constants.No_Key;
			}
		}
		return RwrKey;
	} //synchro
}
/**
 * The method search for wr with wrKey in 'wr' DB. If there is thet it is loaded in the cache 
 * <br>or updated in the 'wr' DB (if the cache registration failed). 
 * @return boolean
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed 
 */

private boolean wrServerResolveKey(long RwrKey, long RwrCounts) {
	String wrTable = Constants.wrWhichTable(' ', RwrKey);
	String SQLStat = "SELECT " + dbFields.db_wrString + "," + dbFields.db_langKey + " FROM " + wrTable + " WHERE " + dbFields.db_wrKey + " = " + String.valueOf(RwrKey);
	String RwrString = null;
	short RlangKey = 0;
	try {
		Statement Stmt = wrServerdbConn.createStatement();
		ResultSet RS = Stmt.executeQuery(SQLStat);
		if (RS.next()) {
			RwrString = RS.getString(1);
			RlangKey = RS.getShort(2);
			while (RS.next()) {
				wrLog.log("wrServer (wrServerResolveKey) : INFO DUBLICATED (never will be used): wrKey = " + RwrKey + ", langKey = " + RS.getString(2) + ", wrString : " + RS.getShort(1) + ":", LogPrinter.ERROR);
				wrLog.flush();
			}
		}
		RS.close();
		Stmt.close();
	} catch (SQLException e) {
		if (wrServerdbReconnect()) {
			wrLog.log("wrServer (wrServerResolveKey) : db Reconnected.", LogPrinter.INFO);
			wrLog.flush();
			return wrServerResolveKey(RwrKey, RwrCounts);
		} else {
			wrLog.log("wrServer (wrServerResolveKey) : SQL error - " + SQLStat + " Exception : " + e, LogPrinter.ERROR);
			wrLog.flush();
			return false;
		}
	} catch (NumberFormatException e) {
		wrLog.log("wrServer (wrServerResolveKey) : error format - " + SQLStat, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
	if (RwrString == null || RlangKey < 1) {
		wrLog.log("wrServer (wrServerResolveKey) : Given wrKey(" + RwrKey + ") from market_wrServer does not exists in the DB and will not be counted.", LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
	wrLog.log("wrServer (wrServerResolveKey) : wrServerResolveKey found for wrKey = " + RwrKey + " | " + RwrString + " | " + RlangKey, LogPrinter.DEBUG);
	wrLog.log("wrServer (wrServerResolveKey) : Instances = " + ServletCounter, LogPrinter.DEBUG_1);
	if (!wrCT.wrRegisterCachField(RwrKey, RwrString, RlangKey, (int) RwrCounts)) {
		wrLog.log("wrServer (wrServerResolveKey) : Result from Cache Register is false.", LogPrinter.ERROR);
		wrLog.flush();
		if (wrServerUpdateWr(RwrString, RwrKey, RwrCounts)) {
			wrLog.log("wrServer (wrServerResolveKey) : wr - " + RwrString + " updated in the DB.", LogPrinter.DEBUG);
			return true;
		}
		wrLog.log("wrServer (wrServerResolveKey) : Failure updating Rw - " + RwrString + " in the DB.", LogPrinter.DEBUG);
		wrLog.flush();
		return false;
	}
	return true;
}
/**
 * Sets all wr parameters (in a wrParameters structure) send throught http flow 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 wrParameters wrServerSet_wrParam(HttpServletRequest req, byte rt) {
	String temp = null;
	wrParameters wrServer = new wrParameters();
	switch (rt) {
		case (Constants.TASK_REGISTRATION) :
			try {
				temp = req.getParameter(Constants.cs_WR_STRING);
				if (!Constants.ValidateString(temp)) {
					wrLog.log("wrServer (wrServerSet_wrParam) : Error on wrString!(" + temp + ")", LogPrinter.ERROR);
					wrLog.flush();
					return null;
				} else
					wrServer.wrString = temp.toLowerCase().trim();
				temp = req.getParameter(Constants.cs_LANG_KEY);
				if (Short.valueOf(temp).shortValue() < 1) {
					wrLog.log("wrServer (wrServerSet_wrParam) : langKey should be greater than 0 (" + temp + ")", LogPrinter.ERROR);
					wrLog.flush();					
					return null;
				} else
					wrServer.langKey = Short.valueOf(temp).shortValue();
			} catch (Exception t) {
				wrLog.log("wrServer (wrServerSet_wrParam) : Wrong Paramerter (" + temp + ") : wrString - " + wrServer.wrString + ", langKey - " + wrServer.langKey + "\n" + t, LogPrinter.ERROR);
				wrLog.flush();				
				return null;
			}
			break;
		case (Constants.TASK_COUNTING) :
			try {
				temp = req.getParameter(Constants.cs_WR_KEY);
				if (Long.valueOf(temp).longValue() < 1) {
					wrLog.log("wrServer (wrServerSet_wrParam) : wrKey should be greater than 0 (" + temp + ")", LogPrinter.ERROR);
					wrLog.flush();
					return null;
				} else
					wrServer.wrKey = Long.valueOf(temp).longValue();
			} catch (Exception t) {
				wrLog.log("wrServer (wrServerSet_wrParam) : Wrong Paramerter (" + temp + ") : wrString - " + wrServer.wrString + ", langKey - " + wrServer.langKey + "\n" + t, LogPrinter.ERROR);
				wrLog.flush();				
				return null;
			}
			break;
		default :
			wrLog.log("wrServer (wrServerSet_wrParam) : wrServer (rwServerSet_rwParam) : Wrong Operation (" + rt + ") :\n", LogPrinter.ERROR);
			wrLog.flush();			
			return null;
	}
	try {
		temp = req.getParameter(Constants.cs_WR_COUNTS);
		if (Long.valueOf(temp).longValue() < 1) {
			wrLog.log("wrServer (wrServerSet_wrParam) : wrCounts should be greater than 0 (" + temp + ")", LogPrinter.ERROR);
			wrLog.flush();			
			return null;
		} else
			wrServer.wrCounts = Long.valueOf(temp).longValue();
		temp = req.getParameter(Constants.cs_SRC_KEY);
		if (Integer.valueOf(temp).intValue() < 1) {
			wrLog.log("wrServer (wrServerSet_wrParam) : srcKey should be greater than 0 (" + temp + ")", LogPrinter.ERROR);
			wrLog.flush();			
			return null;
		} else
			wrServer.srcKey = Integer.valueOf(temp).intValue();
		temp = req.getParameter(Constants.cs_MARKET_KEY);
		wrServer.marketKey = Short.valueOf(temp).shortValue();
	} catch (Exception t) {
		wrLog.log("wrServer (wrServerSet_wrParam) : Wrong Paramerter (" + temp + ") : wrCounts - " + wrServer.wrCounts + ", srcKey - " + wrServer.wrKey + ", marketKey - " + wrServer.marketKey + "\n" + t, LogPrinter.ERROR);
		wrLog.flush();		
		return null;
	}
	return wrServer;
}
/**
 * Updates the parameters in the 'wr' DB. The method is called when a registration in the cache had failed.
 * @return boolean
 *	       <br> true  - if the method succeed
 * 		   <br> false - if the method failed 
 */

private boolean wrServerUpdateWr(String wrString, long wrKey, long wrCounts) {
	String SQLStat = null;
	try {
		SQLStat = "UPDATE " + Constants.wrWhichTable(wrString.charAt(0), Constants.No_Key) + " 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 (wrServerdbConn == null)
			throw new SQLException();
		Statement stmt = wrServerdbConn.createStatement();
		int result = stmt.executeUpdate(SQLStat);
		stmt.close();
		if (result == 1) {
			wrLog.log("wrServer (wrServerUpdateWr) : wrString = " + wrString + " updated in the DB.", LogPrinter.DEBUG);
		} else {
			if (result > 1) {
				wrLog.log("wrServer (wrServerUpdateWr) : Res from updating = " + result + ", wrKey = " + wrKey + ", wrCounts = " + wrCounts + ", wrString :" + wrString + ": is DUBLICATED.", LogPrinter.ERROR);
			} else {
				wrLog.log("wrServer (wrServerUpdateWr) : Res from updating = " + result + ", wrKey = " + wrKey + ", wrCounts = " + wrCounts + ", wrString :" + wrString + ": not updated.", LogPrinter.ERROR);
				wrLog.flush();
				return false;
			}
			wrLog.flush();
		}
		return true;
	} catch (SQLException e) {
		if (wrServerdbReconnect()) {
			wrLog.log("wrServer (wrServerUpdateWr) : db Reconnected.", LogPrinter.INFO);
			wrLog.flush();
			return wrServerUpdateWr(wrString, wrKey, wrCounts);
		} else {
			wrLog.log("wrServer (wrServerUpdateWr) : SQL error - " + SQLStat + " Exception : " + e, LogPrinter.ERROR);
			wrLog.flush();
			return false;
		}
	} catch (NumberFormatException e) {
		wrLog.log("wrServer (wrServerUpdateWr) : error format - " + SQLStat + " (" + wrKey + "," + wrString + ", " + wrCounts + ")\n" + e, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	} catch (Exception e) {
		wrLog.log("wrServer (wrServerUpdateWr) : Exception - " + SQLStat + "\n" + e, LogPrinter.ERROR);
		wrLog.flush();
		return false;
	}
}
/**
 * The method checks if a wr with wrString/langKey exists in 'wr' DB. 
 * @return wrKey long - the found wrKey
 *		<br> util.Constants.No_Key - if there isn't such or a error had occured
 */
 
private long wrSeverResolveString(String pwrString, short plangKey, String pwrTable) {
	long res_wrKey = Constants.No_Key;
	String SQLStat = "SELECT " + dbFields.db_wrKey + " FROM " + pwrTable + " WHERE " + dbFields.db_wrString + " = " + Constants.DBString(pwrString) + " AND " + dbFields.db_langKey + " = " + String.valueOf(plangKey);
	try {
		Statement Stmt = wrServerdbConn.createStatement();
		ResultSet RS = Stmt.executeQuery(SQLStat);
		if (RS.next())
			res_wrKey = RS.getLong(1);
		while (RS.next()) {
			wrLog.log("wrServer (wrServerResolveString) : INFO DUBLICATED (never will be used): wrKey = " + RS.getLong(1) + ", langKey = " + plangKey + ", wrString : " + pwrString + ":", LogPrinter.ERROR);
			wrLog.flush();
		}
		RS.close();
		Stmt.close();
		wrLog.log("wrServer (wrSeverResolveString) : ResolveString returns : " + res_wrKey, LogPrinter.DEBUG);
		return res_wrKey;		
	} catch (SQLException E) {
		if (wrServerdbReconnect()) {
			wrLog.log("wrServer (wrSeverResolveString) : db Reconnected.", LogPrinter.INFO);
			wrLog.flush();
			return wrSeverResolveString(pwrString, plangKey, pwrTable);
		} else {
			wrLog.log("wrServer (wrSeverResolveString) : SQL error - " + SQLStat + " Exception : " + E, LogPrinter.ERROR);
			wrLog.flush();
			return 0;
		}
	} catch (NumberFormatException e) {
		wrLog.log("wrServer (wrSeverResolveString) : error format - " + SQLStat + " (" + plangKey + "," + pwrString + "," + pwrTable + ")\n" + e, LogPrinter.ERROR);
		wrLog.flush();
		return 0;
	}
}
}

