All Downloads are FREE. Search and download functionalities are using the official Maven repository.

Alachisoft.NCache.Common.AppUtil Maven / Gradle / Ivy

package Alachisoft.NCache.Common;

import com.alachisoft.ncache.runtime.exceptions.ConfigurationException;
import com.alachisoft.ncache.runtime.util.HelperFxn;
import com.alachisoft.ncache.runtime.util.NCDateTime;
import com.alachisoft.ncache.runtime.util.TimeSpan;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import static tangible.DotNetToJavaStringHelper.isNullOrEmpty;

/**
 * Utility class to help with common tasks.
 */
public class AppUtil {
//	private static boolean isRunningAsWow64 = false;
//	private static String installDir = null;
////C# TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java:
////#if MONO
//	public final static String DeployedAssemblyDir = "deploy/";
////#else
    public final static int MAX_BUCKETS = 1000;
    public final static String DeployedAssemblyDir = "deploy" + File.separator;
////#endif
//	private static int s_logLevel = 7;
//	private static String javaLibDir = null;
//	static {
////C# TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java:
////#if !MONO
//		isRunningAsWow64 = Win32.InternalCheckIsWow64();
////#else
//		//@UH
////#endif
//		installDir = GetInstallDir();
//
//		javaLibDir = GetJavaLibDir();
//		DeployedAssemblyDir = installDir + DeployedAssemblyDir;
//		String logLevel = System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.EventLogLevel"];
//
//		if (logLevel != null && !logLevel.equals("")) {
//			logLevel = logLevel.toLowerCase();
////C# TO JAVA CONVERTER NOTE: The following 'switch' operated on a string member and was converted to Java 'if-else' logic:
////			switch (logLevel)
////ORIGINAL LINE: case "error":
//			if (logLevel.equals("error")) {
//			s_logLevel = 1;
//
//			}
////ORIGINAL LINE: case "warning":
//			else if (logLevel.equals("warning")) {
//			s_logLevel = 3;
//
//			}
////ORIGINAL LINE: case "all":
//			else if (logLevel.equals("all")) {
//			s_logLevel = 7;
//			}
//		}
//	}
//
//	public static boolean getIsRunningAsWow64() {
//		return isRunningAsWow64;
//	}
//
    //
////        /// 
////        /// Retrieve all the values from a section, or only those that are specified in keyList
////        /// Automatically caters for wow64/win32.
////        /// 
////        /// ">Section from which key is to be read.
////        /// Hashtable that will contain the key/values retrieved
////        /// list of keys that are to be retrieved. This list will be used in
////        /// case of WOW64
////        /// number of keys retrieved
////        public static int GetAppSettings(string section, Hashtable values, ArrayList keyList)
////        {
////            if (values == null) values = new Hashtable();
/////#if WOW64
////            if (keyList != null)
////            {
////                foreach (string val in keyList)
////                {
////                    values[val] = RegHelper.GetRegValue(section, val);
////                }
////            }
/////#else
////            RegHelper.GetRegValues(RegHelper.ROOT_KEY + section, values);
/////#endif
////            return values.Count;
////        }
//
//	/**
//	 Get decrypted value from section.
//	 Automatically caters for wow64/win32.
//
//	 @param section ">Section from which key is to be read.
//	 @param key key
//	 @return value retrieved
//	*/
//	public static String GetDecryptedAppSetting(String section, String key) {
/////#if WOW64
////            return RegHelper.DecryptedValue(GetAppSetting(section, key));
/////#else
////            return (string)RegHelper.GetDecryptedRegValue(RegHelper.ROOT_KEY + section, key);
/////#endif
////C# TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java:
////#if !NCWOW64
//		section = RegHelper.ROOT_KEY + section;
////#endif
//		return (String)RegHelper.GetDecryptedRegValue(section, key, 0);
//	}
//
//	/**
//	 Write the value to the NCache registry key.
//	 Automatically caters for wow64/win32.
//
//	 @param section ">Section from which key is to be read.
//	 @param key Name of the value to be write.
//	 @param value New value of key
//	*/
//	public static void SetAppSetting(String section, String key, String value, short prodId) {
/////#if WOW64
////            StringBuilder sbSection = new StringBuilder(section);
////            StringBuilder sbKey = new StringBuilder(key);
////            StringBuilder sbNewVal = new StringBuilder(value);
////            NCLicenseDll.SetRegVal(sbSection, sbKey, sbNewVal);
/////#else
////            RegHelper.SetRegValue(section, key, value,prodId);
/////#endif
////C# TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java:
////#if !NCWOW64
//		section = RegHelper.ROOT_KEY + section;
////#endif
//		RegHelper.SetRegValue(section, key, value, prodId);
//	}
//
//	/**
//	 Write the value to the NCache registry key after encrypting it.
//	 Automatically caters for wow64/win32.
//
//	 @param section ">Section from which key is to be read.
//	 @param key Name of the value to be write.
//	 @param value New value of key
//	*/
//	public static void SetEncryptedAppSetting(String section, String key, String value) {
/////#if WOW64
////            SetAppSetting(section, key, RegHelper.EncryptedValue(value));
/////#else
////            RegHelper.SetEncryptedRegValue(RegHelper.ROOT_KEY + section, key, value);
/////#endif
////C# TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java:
////#if !NCWOW64
//		section = RegHelper.ROOT_KEY + section;
////#endif
//		RegHelper.SetEncryptedRegValue(section, key, value);
//	}
//
//	/**
//	 Check if the section has preceeding \. If not then append one
//
//	 @param section Section
//	 @return Checked and completed section
//	*/
//	private static String CompleteSection(String section) {
//		return section.startsWith("\\") ? section : "\\" + section;
//	}
//
//	/**
//	 Gets the install directory of NCache.
//	 Returns null if registry key does not exist.
//	*/
//	public static String getInstallDir() {
//		return installDir;
//	}
//
//
//	private static String GetJavaLibDir() {
//		return AppUtil.getInstallDir() + "Java\\Lib\\";
//	}
//	public static String getJavaLibDir() {
//		return javaLibDir;
//	}
//	/**
//	 Writes an error, warning, information, success audit, or failure audit
//	 entry with the given message text to the event log.
//
//	 @param msg The string to write to the event log.
//	 @param type One of the EventLogEntryType values.
//	*/
//	public static void LogEvent(String source, String msg, EventLogEntryType type, short category, int eventId) {
//		try {
//			int level = (int)type;
//			if ((level & s_logLevel) == level) {
////C# TO JAVA CONVERTER NOTE: The following 'using' block is replaced by its Java equivalent:
////				using (EventLog ncLog = new EventLog("Application"))
//				EventLog ncLog = new EventLog("Application");
//				try {
//					ncLog.Source = source;
//					ncLog.WriteEntry(msg, type, eventId);
//				} finally {
//					ncLog.dispose();
//				}
//			}
//		} catch (RuntimeException e) {
//		}
//	}
//
//
//	/**
//	 Writes an error, warning, information, success audit, or failure audit
//	 entry with the given message text to the event log.
//
//	 @param msg The string to write to the event log.
//	 @param type One of the EventLogEntryType values.
//	*/
//	public static void LogEvent(String msg, EventLogEntryType type) {
//		if (type == EventLogEntryType.Information) {
//			LogEvent("NCache", msg, type, EventCategories.Information, EventID.GeneralInformation);
//		} else {
//			LogEvent("NCache", msg, type, EventCategories.Warning, EventID.GeneralError);
//		}
//	}
//
//	/**
//	 Returns lg(Log2) of a number.
//
//	 @param val
//	 @return
//	*/
////C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java:
////ORIGINAL LINE: public static byte Lg(int val)
//	public static byte Lg(int val) {
////C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java:
////ORIGINAL LINE: byte i = 0;
//		byte i = 0;
//		while (val > 1) {
//			val >>= 1;
//			i++;
//		}
//		return i;
//	}
//
//	/**
//	 Store all date time values as a difference to this time
//	*/
//	//private static DateTime START_DT = new DateTime(2004, 12, 31).ToUniversalTime();
    private static java.util.Date START_DT;//; = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime();
//
//
//	/**
//	 Reads the value/data pair from the NCache registry key.
//	 Automatically caters for wow64/win32.
//
//	 @param key Name of the value to be read.
//	 @return Data of the value.
//	*/

    static {
        try {
            int x = 0;
//           Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
//        cal.setTime(new java.util.Date(2004, 11, 31, 0, 0, 0));
//        START_DT = cal.getTime();
            NCDateTime time = new NCDateTime(2004, 11, 30, 0, 0, 0, 0);
            START_DT = time.getLocalizedDate();

            int y = 0;
        } catch (Exception e) {
            //System.err.println(e.getCause() + " " + e.getMessage());
        }
    }
//
//
//
//	/**
//	 Reads the value/data pair from the NCache registry key.
//	 Automatically caters for wow64/win32.
//
//	 @param section Section from which key is to be read.
//	 @param key Name of the value to be read.
//	 @return Data of the value.
//	*/

    public static String getInstallDir() {
        String installPath = ServicePropValues.INSTALLDIR_DIR;
        if (installPath != null && !installPath.equals("")) {
            return installPath;
        }

        String path = ServicePropValues.getTGHome();//GetAppSetting("InstallDir");
        if (path == null || path.length() == 0) {
            return null;
        }
        return path;
    }

    public static String GetAppSetting(String key) {
        return GetAppSetting("", key);
    }

    public static String GetAppSetting(String section, String key) {
///#if WOW64
//                StringBuilder regVal = new StringBuilder();
//                StringBuilder sbSection = new StringBuilder(section);
//                StringBuilder sbKey = new StringBuilder(key);
//                StringBuilder sbDefaultVal = new StringBuilder("");
//                NCLicenseDll.GetRegVal(regVal, sbSection, sbKey, sbDefaultVal);
//                return regVal.ToString();
///#else
//            return (string)RegHelper.GetRegValue(RegHelper.ROOT_KEY + section, key);
///#endif

//		if (!getIsRunningAsWow64()) {
//			section = RegHelper.ROOT_KEY + section;
//		}

//		Object tempVal = RegHelper.GetRegValue(section, key, 0);
//		if (!(tempVal instanceof String)) {
//			return String.valueOf(tempVal);
//		}

        //Basit: Get properties
        return "";
//		return (String)tempVal;
    }

    //
//	/**
//	 Convert DateTime to integer taking 31-12-2004 as base
//	 and removing millisecond information
//
//	 @param dt
//	 @return
//	*/
    public static int DiffSeconds(java.util.Date dt) throws IllegalArgumentException {
        //dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond, DateTimeKind.Utc);

//        NCDateTime ncd = new NCDateTime(dt);
//        ncd.getSeconds();

//        TimeZone utc = TimeZone.getTimeZone("UTC");
//        Calendar c = Calendar.getInstance(utc);
//        c.clear();
//        c.set(Calendar.MILLISECOND, 0);
//        c.setTime((Date) dt);
//        //long ticks = ((date.getTime() + TimeZone.getDefault().getRawOffset()) * 10000) + DIFF;
//        NCDateTime ncdt = null;
//        ncdt = new NCDateTime(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), c.get(Calendar.SECOND), c.get(Calendar.MILLISECOND));

        //NCDateTime date = null;
//        NCDateTime start_ncd = null;
//        start_ncd = new NCDateTime(START_DT);
        //date = new NCDateTime(dt);
//        Date utcDate=date.getLocalizedDate();
        //Basit: UnitTest this
//        TimeSpan timeInterval=TimeSpan.Subtract(utcDate, START_DT);

        long utcTicks=0;
        try {
            utcTicks=(new NCDateTime(NCDateTime.getUTCDate(dt))).getTicks();
        } catch (ParseException e) {
            utcTicks=HelperFxn.getUTCTicks(dt);
        }
        long timespan =  utcTicks- new NCDateTime(START_DT).getTicks();

//        int interval=(int)timeInterval.getTotalSeconds();
        int interval = (int) new TimeSpan(timespan).getTotalSeconds();
        //int interval = utcDate.getSeconds() - start_ncd.getSeconds();
        //int interval = date.getSeconds() - start_ncd.getSeconds();
        return interval;
    }
    //without converting date in UTC

    public static int fixedExpDiffSeconds(java.util.Date dt) throws IllegalArgumentException {
        long timespan = new NCDateTime(dt).getTicks() - new NCDateTime(START_DT).getTicks();
        int interval = (int) new TimeSpan(timespan).getTotalSeconds();
        return interval;
    }

    public static int DiffMilliseconds(java.util.Date dt) throws IllegalArgumentException {
        //dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond, DateTimeKind.Utc);

        TimeZone utc = TimeZone.getTimeZone("UTC");
        Calendar c = Calendar.getInstance(utc);
        c.clear();
        c.set(Calendar.MILLISECOND, 0);
        c.setTime((Date) dt);
        //long ticks = ((date.getTime() + TimeZone.getDefault().getRawOffset()) * 10000) + DIFF;
        NCDateTime ncdt = null;
        ncdt = new NCDateTime(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), c.get(Calendar.SECOND), c.get(Calendar.MILLISECOND));


        NCDateTime date = null;
        NCDateTime start_ncd = null;
        start_ncd = new NCDateTime(START_DT);
        date = new NCDateTime(dt);

        //Basit: UnitTest this
        int interval = date.getMilliseconds() - start_ncd.getMilliseconds();
        return interval;

//        dt = dt.ToUniversalTime();
//        TimeSpan interval = dt - START_DT;
//        return (int) interval.Milliseconds;
    }

    public static long DiffTicks(java.util.Date dt) throws IllegalArgumentException {
        //dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond, DateTimeKind.Utc);
        //To fix lockexpiration
        return (HelperFxn.getUTCTicks(dt) - new NCDateTime(START_DT).getTicks());
        /*       TimeZone utc = TimeZone.getTimeZone("UTC");
         Calendar c = Calendar.getInstance(utc);
         c.clear();
         c.set(Calendar.MILLISECOND, 0);
         c.setTime((Date) dt);
         //long ticks = ((date.getTime() + TimeZone.getDefault().getRawOffset()) * 10000) + DIFF;
         NCDateTime ncdt = null;
         ncdt = new NCDateTime(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), c.get(Calendar.SECOND), c.get(Calendar.MILLISECOND));


         NCDateTime date = null;
         NCDateTime start_ncd = null;
         start_ncd = new NCDateTime(START_DT);
         date = new NCDateTime(dt);

         //Basit: UnitTest this
         long interval = date.getTicks() - start_ncd.getTicks();
         return interval;
         */

//        dt = dt.ToUniversalTime();
//        TimeSpan interval = dt - START_DT;
//        return interval.Ticks;
    }
//
//	/**
//	 Convert DateTime to integer taking 31-12-2004 as base
//	 and removing millisecond information
//
//	 @param dt
//	 @return
//	*/

    public static java.util.Date GetDateTime(int absoluteTime) {
        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        cal.setTime(START_DT);
        cal.add(Calendar.SECOND, absoluteTime);
////      java.util.Date dt = new java.util.Date(START_DT.Ticks, DateTimeKind.Utc);
//        //return dt.AddSeconds(absoluteTime);
        return cal.getTime();
    }

    public static int hashCode(String str) {
        str= getLocationAffinityKey(str);
        char[] array = str.toCharArray();
        int[] intArray = new int[(int) Math.ceil((double) (array.length) / 2)];

        for (int i = 0, j = 0; i < intArray.length; i++) {
            char[] toInt = new char[2];
            if (j < array.length) {
                toInt[0] = array[j++];
            }
            if (j < array.length) {
                toInt[1] = array[j++];
            }
            intArray[i] = charToInt(toInt);
        }

        int num = 0x15051505;
        int num2 = num;

        for (int i = array.length, j = 0; i > 0; i -= 4, j += 2) {

            num = (((num << 5) + num) + (num >> 0x1b)) ^ intArray[j];
            if (i <= 2) {
                break;
            }
            num2 = (((num2 << 5) + num2) + (num2 >> 0x1b)) ^ intArray[j + 1];
        }
        return (num + (num2 * 0x5d588b65));
    }

    private static int charToInt(char[] array) {
        return (array[0] | (array[1] << 16));
    }

    private static String getLocationAffinityKey(String key)
    {
        int indexStart = key.indexOf('{');
        int indexEnd = key.indexOf('}');
        if (indexStart != -1 && indexEnd != -1 && (indexStart + 1) < indexEnd)
        {
            return key.substring(indexStart + 1, indexEnd);
        }
        return key;
    }

    public static String getLocalServerIp() throws ConfigurationException {
        Node localServerIp = null;
        try {
            String directoryValue = Common.getNCHome();
            String separator = File.separator;
            if (directoryValue != null) {
                if (!directoryValue.endsWith(separator)) {
                    directoryValue = directoryValue.concat(separator);
                }
                directoryValue.replaceFirst(";", "");
                directoryValue = directoryValue.concat("config" + separator + "client.ncconf");
            }
            File hfile = new File(directoryValue);
            if (!hfile.exists()) {
                throw new ConfigurationException("NCHOME not found");
            }
            Document response = null;
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = null;
            builder = builderFactory.newDocumentBuilder();
            response = builder.parse(hfile);
            boolean serverPortFound = false;
            NodeList serverPortNL = response.getElementsByTagName("ncache-server");
            if (serverPortNL != null) {
                Node ncacheServerDetails = serverPortNL.item(0);
                if (ncacheServerDetails == null) {
                    throw new Exception("ncache-server options not found in client.ncconf.");
                }

                NamedNodeMap attributes = ncacheServerDetails.getAttributes();
                localServerIp = attributes.getNamedItem("local-server-ip");
                return localServerIp.getTextContent();
            }
        } catch (Exception e) {
            throw new ConfigurationException("NCHOME not found");
        }
        return null;
    }

    public static boolean isMavenOnlyInstallation()
    {
        boolean isMaven = false;
        String filePath = "";
        String installDirectory = AppUtil.getInstallDir();
        if (isNullOrEmpty(installDirectory))
            isMaven = true;
        else
        {
            String fileDirectory = installDirectory + File.separator + "bin" + File.separator + "service";
            filePath = fileDirectory + File.separator + "Alachisoft.NCache.CacheHost.dll";
            File cacheHostDll = new File(filePath);
            if(!cacheHostDll.exists())
            {
                filePath = fileDirectory + File.separator + "Alachisoft.NCache.CacheHost.exe";
                cacheHostDll = new File(filePath);
                if(!cacheHostDll.exists())
                    isMaven = true;
            }
        }
        return isMaven;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy