#region Apache Notice /***************************************************************************** * $Revision$ * $LastChangedDate$ * $LastChangedBy$ * * iBATIS.NET Data Mapper * Copyright (C) 2006/2005 - The Apache Software Foundation * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion #region Using using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization.Formatters.Binary; using System.Xml.Serialization; using IBatisNet.Common.Exceptions; using IBatisNet.Common.Logging; using IBatisNet.Common.Utilities; using IBatisNet.DataMapper.Exceptions; using IBatisNet.DataMapper.MappedStatements; #endregion namespace IBatisNet.DataMapper.Configuration.Cache { /// /// Summary description for CacheModel. /// [Serializable] [XmlRoot("cacheModel", Namespace="http://ibatis.apache.org/mapping")] public class CacheModel { #region Fields private static IDictionary _lockMap = new HybridDictionary(); [NonSerialized] private static readonly ILog _logger = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType ); /// /// This is used to represent null objects that are returned from the cache so /// that they can be cached, too. /// [NonSerialized] public readonly static object NULL_OBJECT = new Object(); /// /// Constant to turn off periodic cache flushes /// [NonSerialized] public const long NO_FLUSH_INTERVAL = -99999; [NonSerialized] private object _statLock = new Object(); [NonSerialized] private int _requests = 0; [NonSerialized] private int _hits = 0; [NonSerialized] private string _id = string.Empty; [NonSerialized] private ICacheController _controller = null; [NonSerialized] private FlushInterval _flushInterval = null; [NonSerialized] private long _lastFlush = 0; [NonSerialized] private HybridDictionary _properties = new HybridDictionary(); [NonSerialized] private string _implementation = string.Empty; [NonSerialized] private bool _isReadOnly = true; [NonSerialized] private bool _isSerializable = false; #endregion #region Properties /// /// Identifier used to identify the CacheModel amongst the others. /// [XmlAttribute("id")] public string Id { get { return _id; } set { if ((value == null) || (value.Length < 1)) throw new ArgumentNullException("The id attribute is mandatory in a cacheModel tag."); _id = value; } } /// /// Cache controller implementation name. /// [XmlAttribute("implementation")] public string Implementation { get { return _implementation; } set { if ((value == null) || (value.Length < 1)) throw new ArgumentNullException("The implementation attribute is mandatory in a cacheModel tag."); _implementation = value; } } /// /// Set the cache controller /// public ICacheController CacheController { set{ _controller =value; } } /// /// Set or get the flushInterval (in Ticks) /// [XmlElement("flushInterval",typeof(FlushInterval))] public FlushInterval FlushInterval { get { return _flushInterval; } set { _flushInterval = value; } } /// /// Specifie how the cache content should be returned. /// If true a deep copy is returned. /// /// /// Combinaison /// IsReadOnly=true/IsSerializable=false : Returned instance of cached object /// IsReadOnly=false/IsSerializable=true : Returned coopy of cached object /// public bool IsSerializable { get { return _isSerializable; } set { _isSerializable = value; } } /// /// Determines if the cache will be used as a read-only cache. /// Tells the cache model that is allowed to pass back a reference to the object /// existing in the cache. /// /// /// The IsReadOnly properties works in conjonction with the IsSerializable propertie. /// public bool IsReadOnly { get { return _isReadOnly; } set { _isReadOnly = value; } } #endregion #region Constructor (s) / Destructor /// /// Constructor /// public CacheModel() { _lastFlush = DateTime.Now.Ticks; } #endregion #region Methods /// /// /// public void Initialize() { // Initialize FlushInterval _flushInterval.Initialize(); try { if (_implementation == null) { throw new DataMapperException ("Error instantiating cache controller for cache named '"+_id+"'. Cause: The class for name '"+_implementation+"' could not be found."); } // Build the CacheController Type type = TypeUtils.ResolveType(_implementation); object[] arguments = new object[0]; _controller = (ICacheController)Activator.CreateInstance(type, arguments); } catch (Exception e) { throw new ConfigurationException("Error instantiating cache controller for cache named '"+_id+". Cause: " + e.Message, e); } //------------ configure Controller--------------------- try { _controller.Configure(_properties); } catch (Exception e) { throw new ConfigurationException ("Error configuring controller named '"+_id+"'. Cause: " + e.Message, e); } } /// /// Event listener /// /// A MappedStatement on which we listen ExecuteEventArgs event. public void RegisterTriggerStatement(IMappedStatement mappedStatement) { mappedStatement.Execute +=new ExecuteEventHandler(FlushHandler); } /// /// FlushHandler which clear the cache /// /// /// private void FlushHandler(object sender, ExecuteEventArgs e) { if (_logger.IsDebugEnabled) { _logger.Debug("Flush cacheModel named "+_id+" for statement '"+e.StatementName+"'"); } Flush(); } /// /// Clears all elements from the cache. /// public void Flush() { _lastFlush = DateTime.Now.Ticks; _controller.Flush(); } /// /// Adds an item with the specified key and value into cached data. /// Gets a cached object with the specified key. /// /// The cached object or null /// /// A side effect of this method is that is may clear the cache /// if it has not been cleared in the flushInterval. /// public object this [CacheKey key] { get { lock(this) { if (_lastFlush != NO_FLUSH_INTERVAL && (DateTime.Now.Ticks - _lastFlush > _flushInterval.Interval)) { Flush(); } } object value = null; lock (GetLock(key)) { value = _controller[key]; } if(_isSerializable && !_isReadOnly && (value != NULL_OBJECT && value != null)) { try { MemoryStream stream = new MemoryStream((byte[]) value); stream.Position = 0; BinaryFormatter formatter = new BinaryFormatter(); value = formatter.Deserialize( stream ); } catch(Exception ex) { throw new IBatisNetException("Error caching serializable object. Be sure you're not attempting to use " + "a serialized cache for an object that may be taking advantage of lazy loading. Cause: "+ex.Message, ex); } } lock(_statLock) { _requests++; if (value != null) { _hits++; } } if (_logger.IsDebugEnabled) { if (value != null) { _logger.Debug(String.Format("Retrieved cached object '{0}' using key '{1}' ", value, key)); } else { _logger.Debug(String.Format("Cache miss using key '{0}' ", key)); } } return value; } set { if (null == value) {value = NULL_OBJECT;} if(_isSerializable && !_isReadOnly && value != NULL_OBJECT) { try { MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, value); value = stream.ToArray(); } catch(Exception ex) { throw new IBatisNetException("Error caching serializable object. Cause: "+ex.Message, ex); } } _controller[key] = value; if (_logger.IsDebugEnabled) { _logger.Debug(String.Format("Cache object '{0}' using key '{1}' ", value, key)); } } } /// /// /// public double HitRatio { get { if (_requests!=0) { return (double)_hits/(double)_requests; } else { return 0; } } } /// /// Add a property /// /// The name of the property /// The value of the property public void AddProperty(string name, string value) { _properties.Add(name, value); } #endregion /// /// /// /// /// [MethodImpl(MethodImplOptions.Synchronized)] public object GetLock(CacheKey key) { int controllerId = HashCodeProvider.GetIdentityHashCode(_controller); int keyHash = key.GetHashCode(); int lockKey = 29 * controllerId + keyHash; object lok =_lockMap[lockKey]; if (lok == null) { lok = lockKey; //might as well use the same object _lockMap[lockKey] = lok; } return lok; } } }