package market.market_util;

import java.io.*;
import java.net.*;
/**
 * This class contains all constants needed by market_wrServer and market_rwServer 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_SYSTEM_SERVLET_STATE = "8"; // equals to util.Constants.cs_GET_SERVLET_STATE;
 	public final static String cs_INIT = "init";	
// 	public final static String cs_GET_CONF = "get";
 	public final static String cs_ConfSaveValue = "value"; 		
	public final static String cs_GET_MARKET_KEY = "GetMarketKey";
	public final static String cs_GET_ALL_MARKET_KEYS = "10";
	public final static String cs_PACKET_REGISTRATION = "18";
	public final static String cs_PACKET_COUNTING = "19";
	public final static String cs_SPEED_COUNTING = "20";	
	
/** 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 = 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 SYSTEM_CONN_ERROR = 32;
	public final static byte GET_MARKET_KEY_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; // Shoul always be 0
 	public final static byte No_Key = -1; // Shoul always be -1
 	public final static byte Zero_Key = 0;
 	public final static byte No_MarketKey = -1; // Shoul always be -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";

/** Other constants */	
	public final static char ca_SQL_Escape_Chars[] = {'\0','\n','\t','\r','\b','\'','\"','\\','%','_'};
	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 = '#';  // This must be always sign diferent from number or letter
	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";
	public final static String rwServerName = "rwServer";
	public final static String wrServerName = "wrServer";
	public final static String cfg_String_for_jserv_conf = "cfgPath";
	public final static String ScreenLogLevel = "SLL";
	public final static String FileLogLevel = "FLL";

/** A constant used in this class methods */
	public final static byte cb_wrCheck_Count = 10;


/** 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();
	}
}
/**
 * The method gets the marketKey from S_wrProcessorHostName place. 
 * @return MarketKey int - the returned market key.
 					<br>0 - if error occures.
 					<br>Constants.No_MarketKey - no market key set
 */
public static int getMarketKey(String S_wrProcessorHostName) {
	int mKey = No_MarketKey;
	StringBuffer ret_marketKey = new StringBuffer(8);
	try {
		URL ServletURL = new URL(S_wrProcessorHostName + Constants.cs_ReqType + "=" + Constants.cs_GET_MARKET_KEY);
		InputStream in = ServletURL.openStream();
		int b;
		while ((b = in.read()) != -1)
			ret_marketKey.append((char) b);
		mKey = Integer.valueOf(ret_marketKey.toString()).intValue();
	} catch (IOException e) {
		return 0;
	}
	return mKey;
}
/**
 * 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 (CACHE_ERROR) :
			return "Cache Error";
		case (SAVE_THREAD_ERROR) :
			return "Save Thread Error";
		case (GET_MARKET_KEY_ERROR) :
			return "Get Valid Market Key Error";
		case (SYSTEM_CONN_ERROR) :
			return "Error with connection to the system or the system is not in READY state.";
		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";
	}
}
/**
 * Finds in which table is/to be/ strored the info for specific rw.
 * @return TableName String - always returnes table name
*/

public static String market_rwWhichTable(char p, int MK) {
	StringBuffer result_rwTable = new StringBuffer("rw_");
	result_rwTable.append(String.valueOf(MK));
	result_rwTable.append('_');
	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();
}
/**
 * Finds in which table is/to be/ strored the info for specific wr.
 * @return TableName String - always returnes table name
*/

public static String market_wrWhichTable(char p, int MK) {
	StringBuffer result_wrTable = new StringBuffer("wr_");
	result_wrTable.append(String.valueOf(MK));
	result_wrTable.append('_');
	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();
}
/**
 * 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;
	}
}
}

