package system.util;

import java.io.*;
import java.net.*;
/**
 * This class contains all constants needed by wrServer, rwServer, wr_rw_Server and wr_src_Server<br> servlets
 * @author: Nikolai Rangelov
 */
 
public class Constants 
{
/** All ReqType string that are shared throuh HTTP */
	public final static String cs_ReqType = "ReqType";
 	public final static String cs_REGISTRATION = "1";
	public final static String cs_COUNTING = "2";	
 	public final static String cs_GET_CONFIG = "3";
 	public final static String cs_SAVE_CONFIG = "4";
 	public final static String cs_RELOAD = "5";
 	public final static String cs_INIT_LITTLE = "6";
 	public final static String cs_SECONDARY_INIT = "7";
 	public final static String cs_GET_SERVLET_STATE = "8";
 	public final static String cs_GET_SERVLET_ERROR_STATE = "9";
	public final static String cs_GET_ALL_MARKET_KEYS = "10";
	public final static String cs_CHANGE_LOG_LEVELS = "11";
	public final static String cs_GET_SERVLET_COUNTER = "12";	
	public final static String cs_GET_MARKET_KEY = "GetMarketKey";
	public final static String cs_CONTROL_OTHER = "13";
 	public final static String cs_CLOSE_DIRECT = "14";
 	public final static String cs_STOP = "15";	
 	public final static String cs_START = "16";	
 	public final static String cs_KILL = "17";	 	 	
	public final static String cs_PACKET_REGISTRATION = "18";
	public final static String cs_PACKET_COUNTING = "19";
	public final static String cs_SPEED_COUNTING = "20";
	public final static String cs_LOCK = "21";	
	public final static String cs_UNLOCK = "22";
 	public final static String cs_ConfSaveValue = "value"; 		

/** Servlet Tasks which the servlet does*/		
 	public final static byte TASK_ERROR = 0;
	public final static byte TASK_REGISTRATION = 1;
	public final static byte TASK_COUNTING = 2;
	public final static byte TASK_GET_CONFIG = 3;
	public final static byte TASK_SAVE_CONFIG = 4;
	public final static byte TASK_RELOAD = 5;
 	public final static byte TASK_INIT_LITTLE = 6;
//	public final static byte TASK_SECONDARY_INIT = 7; 	 	
 	public final static byte TASK_GET_SERVLET_STATE = 8;
 	public final static byte TASK_GET_SERVLET_ERROR_STATE = 9;
	public final static byte TASK_GET_ALL_MARKET_KEYS = 10;
	public final static byte TASK_CHANGE_LOG_LEVELS = 11;
	public final static byte TASK_GET_SERVLET_COUNTER = 12;
	public final static byte TASK_CONTROL_OTHER	= 13;
	public final static byte TASK_CLOSE_DIRECT = 14;
	public final static byte TASK_STOP = 15;	
	public final static byte TASK_START = 16;
//	public final static byte TASK_KILL = 17;
	public final static byte TASK_PACKET_REGISTRATION = 18;	
	public final static byte TASK_PACKET_COUNTING = 19;		
	public final static byte TASK_SPEED_COUNTING = 20;
	public final static byte TASK_LOCK = 21;
	public final static byte TASK_UNLOCK = 22;
	
/** SetvletStates in which the servlet can fall */
	public final static byte NOT_INITED = 0;
	public final static byte STOPED = 1;		
	public final static byte INITING = 2;
	public final static byte READY = 3;
	public final static byte INIT_ERROR = 4;
	public final static byte CONN_ERROR = 5;
	public final static byte PROCESS_ERROR = 6;	
	public final static byte LOCKED = 7;
	public final static byte SECOND_INIT_ERROR = 8 ;	// remove it when both init are done
	
/** ServletErrorState in which the servlet can fall */
	public final static byte NO_ERROR = 20;
	public final static byte OBJECT_ERROR = 21;
	public final static byte PROPERTIES_FILE_ERROR = 22;
	public final static byte CONF_FILE_ERROR = 23;	
	public final static byte LOG_ERROR = 24;
	public final static byte DB_CONN_ERROR = 25;
	public final static byte TABLES_ERROR = 26;
	public final static byte RATE_METER_ERROR = 27;
	public final static byte CACHE_ERROR = 28;
	public final static byte SAVE_THREAD_ERROR = 29;
	public final static byte QUEUE_ERROR = 30;
	public final static byte SUM_THREAD_ERROR = 31;
	public final static byte DIRECT_CONN_ERROR = 32;
	public final static byte GET_VALID_MARKET_KEYS_ERROR = 33;		
//	public final static byte INTERCONN_ERROR = 34;
	public final static byte ERROR = 35;
	
/** Some error codes that the servlet or some of its methods returns*/ 		
 	public final static byte RETRY = 0;
 	public final static byte No_Key = -1;
 	public final static byte Zero_Key = 0;
 	public final static byte No_MarketKey = -1;

/** Waiting Times */ 	
 	public final static int Req_Life_Millis = 200;				//millis
 	public final static long Max_Wait_Before_Reload = 20000;   // millis

/** The names of all properties that are used for wr or rw */ 	 
	public final static String cs_LANG_KEY = "langKey";
	public final static String cs_SRC_KEY = "srcKey";	
	public final static String cs_MARKET_KEY = "marketKey";
	public final static String cs_WR_KEY = "wrKey";
 	public final static String cs_WR_COUNTS = "wrCounts";
	public final static String cs_WR_STRING = "wrString";
	public final static String cs_RW_KEY = "rwKey";
	public final static String cs_RW_COUNTS = "rwCounts";
	public final static String cs_RW_STRING = "rwString";
	public final static String S_wr_rw_ServerName = "wr_rw_Server";
	public final static String S_wr_src_ServerName = "wr_src_Server";	
	public final static String cs_FirstSign = "fs";
	public final static String cs_wr_srcServerTable = "wr_src";
	public final static byte cb_wrCheck_Count = 10;	

/** Some specials strings and constants */	
	public final static char ca_SQL_Escape_Chars[] = {'\0','\n','\t','\r','\b','\'','\"','\\','%','_'};
//	public final static byte New_Relation = 1;
//	public final static byte Old_Relation = 0;
	public final static char Separator = '|';
	public final static char Quote = '\"';
	public final static char cc_NumberTableBaseKey = '0'; // This must be always number
	public final static char cc_OtherTableBaseKey = '#';
	public final static String cs_wrBeginTable = "wr_";
	public final static String cs_rwBeginTable = "rw_";
	public final static String cs_EndNumberTable = "numbers";
	public final static String cs_EndSpecialTable = "special";

/** Default value for the lenght of the queue	*/
	public final static short wrQueueLen = 100;
	public final static short rwQueueLen = 100;

/** Parameter's string representation for http initialisation of wr_rw and wr_src Servers*/
	public final static String wr_rwLogPath =  "wr_rwLogPath";
	public final static String wr_srcLogPath = "wr_srcLogPath";
	public final static String ScreenLogLevel = "SLL";
	public final static String FileLogLevel = "FLL";
	public final static String cfg_String_for_jserv_conf = "cfgPath";

/** A Packet comunication parameters */
	public final static char Packet_Delimiter = ',';
	public final static String cs_Packet_Number = "Num";
/**
 * Escapes the qoutes and the escaper character('\').
 * @return String - the escaped string
 *		 <br>null - if the input string is null or empty
 * @param Str java.lang.String - the input string
 */
public final static String DBString(String Str) {
	char escape1 = Constants.Quote;
	char escape2 = '\\';
	if (Str.equals(null) || Str.equals(""))
		return null;
	else {
		StringBuffer Result_string = new StringBuffer();
		Result_string.append(escape1);
		for (int i = 0; i < Str.length(); i++) {
			if (Str.toLowerCase().charAt(i) == escape1 || Str.toLowerCase().charAt(i) == escape2) {
				Result_string.append(escape2);
			}
			Result_string.append(Str.charAt(i));
		}
		Result_string.append(escape1);
		return Result_string.toString();
	}
}
/**
 * This file translate the number of the error to string definition.
 * @return java.lang.String
 * @param ServletErrorState byte
 */
public static String getServletErrorStateDescription(byte ServletErrorState) {
	switch (ServletErrorState) {
		case (NO_ERROR) :
			return "No Error";
		case (OBJECT_ERROR) :
			return "Synchronization Objects Error";
		case (PROPERTIES_FILE_ERROR) :
			return "Jserv Properties File Error";
		case (CONF_FILE_ERROR) :
			return "Configuration File Error";
		case (LOG_ERROR) :
			return "Log File Error";
		case (DB_CONN_ERROR) :
			return "DB Connection Error";
		case (TABLES_ERROR) :
			return "Error During Creating/Checking Tables";
		case (RATE_METER_ERROR) :
			return "Rate Meter Error";
		case (CACHE_ERROR) :
			return "Cache Error";
		case (SAVE_THREAD_ERROR) :
			return "Save Thread Error";
		case (QUEUE_ERROR) :
			return "Queue Error";
		case (SUM_THREAD_ERROR) :
			return "MarketSum Thread Error";
		case (DIRECT_CONN_ERROR) :
			return "Direct Connection Failed";
		case (GET_VALID_MARKET_KEYS_ERROR) :
			return "Get Valid Market Keys Error";
//		case (INTERCONN_ERROR) :
//			return "Inter Serlet Connection Error";
		case (ERROR) :
			return "Error";
		default :
			return "Not a valid ServletState";
	}
}
/**
 * This file translate the number of the Servlet State to string definition.
 * @return java.lang.String
 * @param ServletState byte
 */
 
public static String getServletStateDescription(byte ServletState) {
	switch (ServletState) {
		case (NOT_INITED) :
			return "Not Inited";
		case (STOPED) :
			return "Stoped";
		case (INITING) :
			return "Initing";
		case (READY) :
			return "Ready";
		case (INIT_ERROR) :
			return "Init error";
		case (CONN_ERROR) :
			return "DB connection error";
		case (PROCESS_ERROR) :
			return "Error during working";
		case (LOCKED) :
			return "Locked";
		default :
			return "Not a valid ServletState";
	}
}
/**
 * Resolve the type of the request. Requests are :
 * <br> TASK_REGISTRATION, TASK_COUNTING, TASK_GET_CONFIG, TASK_SAVE_CONFIG, TASK_RELOAD, TASK_INIT_LITTLE,
 * <br> TASK_GET_SERVLET_STATE, TASK_GET_SERVLET_ERROR_STATE, TASK_ERROR, TASK_CONTROL_OTHER, TASK_CHANGE_LOG_LEVELS,
 * <br> TASK_GET_SERVLET_COUNTER, TASK_SPEED_COUNTIN, TASK_PACKET_COUNTING, TASK_PACKET_REGISTRATION,
 * <br> TASK_LOCK, TASK_UNLOCK, TASK_STOP, TASK_START
 * @return byte - the byte equivalent of the request
 * @param sTaskType java.lang.String
 */

public static byte getTask(String sTaskType) {
	if (sTaskType == null)
		return (TASK_ERROR);
	else
		if (sTaskType.equalsIgnoreCase(cs_REGISTRATION))
			return (TASK_REGISTRATION);
		else
			if (sTaskType.equalsIgnoreCase(cs_COUNTING))
				return TASK_COUNTING;
			else
				if (sTaskType.equalsIgnoreCase(cs_GET_CONFIG))
					return TASK_GET_CONFIG;
				else
					if (sTaskType.equalsIgnoreCase(cs_SAVE_CONFIG))
						return TASK_SAVE_CONFIG;
					else
						if (sTaskType.equalsIgnoreCase(cs_RELOAD))
							return TASK_RELOAD;
						else
							if (sTaskType.equalsIgnoreCase(cs_INIT_LITTLE))
								return TASK_INIT_LITTLE;
							else
								if (sTaskType.equalsIgnoreCase(cs_GET_SERVLET_STATE))
									return TASK_GET_SERVLET_STATE;
								else
									if (sTaskType.equalsIgnoreCase(cs_GET_SERVLET_ERROR_STATE))
										return TASK_GET_SERVLET_ERROR_STATE;
									else
										if (sTaskType.equalsIgnoreCase(cs_CONTROL_OTHER))
											return TASK_CONTROL_OTHER;
										else
											if (sTaskType.equalsIgnoreCase(cs_CHANGE_LOG_LEVELS))
												return TASK_CHANGE_LOG_LEVELS;
											else
												if (sTaskType.equalsIgnoreCase(cs_GET_SERVLET_COUNTER))
													return TASK_GET_SERVLET_COUNTER;
												else
													if (sTaskType.equalsIgnoreCase(cs_SPEED_COUNTING))
														return TASK_SPEED_COUNTING;
													else
														if (sTaskType.equalsIgnoreCase(cs_PACKET_COUNTING))
															return TASK_PACKET_COUNTING;
														else
															if (sTaskType.equalsIgnoreCase(cs_PACKET_REGISTRATION))
																return TASK_PACKET_REGISTRATION;
															else
																if (sTaskType.equalsIgnoreCase(cs_LOCK))
																	return TASK_LOCK;
																else
																	if (sTaskType.equalsIgnoreCase(cs_UNLOCK))
																		return TASK_UNLOCK;
																	else
																		if (sTaskType.equalsIgnoreCase(cs_STOP))
																			return TASK_STOP;
																		else
																			if (sTaskType.equalsIgnoreCase(cs_START))
																				return TASK_START;
																			else
																				return TASK_ERROR;
}
/**
 * The method gets all Valid Market Keys from String S_RSRServer place. 
 * @return ValidMarketKeys int[] - the returned market keys.
 					<br>null - if error occures.
 */
public static int[] getValidMarketKeys(String S_RSRServer) {
	String CommString = Constants.cs_ReqType + "=" + Constants.cs_GET_ALL_MARKET_KEYS;
	String marketList = "";
	StreamTokenizer stoken;
	int ValidMarkets[];
	InputStream in;
	try {
		URL ServletURL = new URL(S_RSRServer + CommString);
		in = ServletURL.openStream();
		stoken = new StreamTokenizer(new BufferedReader(new InputStreamReader(in)));
	} catch (IOException e) {
		return null;
	}
	stoken.whitespaceChars((int) Constants.Separator, (int) Constants.Separator);
	try {
		if (stoken.nextToken() != stoken.TT_NUMBER)
			return null;
		int numOfValidMarkets = (int) stoken.nval;
		if (numOfValidMarkets == 0) {
			in.close();
			return null;
		} else {
			ValidMarkets = new int[numOfValidMarkets];
			for (int counter = 0; counter < numOfValidMarkets; counter++) {
				if (stoken.nextToken() != stoken.TT_NUMBER) {
					in.close();
					return null;
				}
				ValidMarkets[counter] = (int) stoken.nval;
			}
			in.close();
			return ValidMarkets;
		}
	} catch (Exception e) {
		return null;
	}
}
/**
 * Finds in which table is/to be/ strored the info for specific rw. It calculates on the FirstSign when the rwKey
 * <br> is Constants.No_Key. Otherwise calculates the table name on the rwKey.
 * @return TableName String - always returnes table name
*/
public static String rwWhichTable(char FirstSign, long rwKey) {
	StringBuffer result_rwTable = new StringBuffer("rw_");
	char p = ' ';
	if (rwKey == No_Key)
		p = FirstSign;
	else
		p = (char) (rwKey % 256);
	if ((p >= 'a') && (p <= 'z'))
		result_rwTable.append(p);
	else
		if (p >= '0' && p <= '9')
			result_rwTable.append(cs_EndNumberTable);
		else
			result_rwTable.append(cs_EndSpecialTable);
	return result_rwTable.toString();
}
/** This function escapes a string using Constants.ca_SQL_Escape_Chars.length[] array.
 * @return str String - escaped string
	 			null - if the string is null or empty ("")
 */
public static String SkipSQL_Escape_Chars(String Str) {
	if (Str.equals(null) || Str.equals(""))
		return null;
	else {
		StringBuffer Result_string = new StringBuffer();
		int i, j;
		for (i = 0; i < Str.length(); i++) {
			for (j = 0; j < Constants.ca_SQL_Escape_Chars.length; j++)
				if (Str.toLowerCase().charAt(i) == Constants.ca_SQL_Escape_Chars[j])
					Result_string.append("\\");
			Result_string.append(Str.charAt(i));
		}
		return Result_string.toString();
	}
}
/**
 * Function	 that check a string whether it is between 32 and 254 ASCII. It checks in the
 * <br>first Constants.cb_wrCheck_Count signs of the string.
 * @return boolean
 *				<br> true - the string is ok
 *				<br> false - the string is not ok
 * @param CheckString java.lang.String
 * @exception java.lang.NullPointerException
 */
public static boolean ValidateString(String CheckString) throws NullPointerException {
	if ((CheckString == null) || CheckString.equals(""))
		return false;
	else {
		String st = CheckString;
		st = st.toLowerCase().trim();
		if (st.length() < Constants.cb_wrCheck_Count)
			for (int i = 0; i < st.length(); i++) {
				if (st.charAt(i) < 32 && st.charAt(i) > 254)
					return false;
			} else
				for (int i = 0; i < Constants.cb_wrCheck_Count; i++) {
					if (st.charAt(i) < 32 && st.charAt(i) > 254)
						return false;
				}
		return true;
	}
}
/**
 * Finds in which table is/to be/ strored the info for specific wr. It calculates on the FirstSign when the wrKey
 * <br> is Constants.No_Key. Otherwise calculates the table name on the wrKey.
 * @return TableName String - always returnes table name
*/
public static String wrWhichTable(char FirstSign, long wrKey) {
	StringBuffer result_wrTable = new StringBuffer("wr_");
	char p = ' ';
	if (wrKey == No_Key)
		p = FirstSign;
	else
		p = (char) (wrKey % 256);
	if ((p >= 'a') && (p <= 'z'))
		result_wrTable.append(p);
	else
		if ((p >= '0') && (p <= '9'))
			result_wrTable.append(cs_EndNumberTable);
		else
			result_wrTable.append(cs_EndSpecialTable);
	return result_wrTable.toString();
}
}

