wojilu /wojilu/Data/Cache/MemoryDB.cs

Language C# Lines 497
MD5 Hash 6fc82113464d8c8c6a0d56518fd5a15c Estimated Cost $8,838 (why?)
Repository https://bitbucket.org/kingshine/wojilu.git View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
/*
 * Copyright 2010 www.wojilu.com
 * 
 * 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.
 */

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Web;

using wojilu.ORM;
using wojilu.Serialization;
using wojilu.Web;

namespace wojilu.Data {

    internal class MemoryDB {

        private static readonly ILog logger = LogManager.GetLogger( typeof( MemoryDB ) );

        private static IDictionary objectList = Hashtable.Synchronized( new Hashtable() );
        private static IDictionary indexList = Hashtable.Synchronized( new Hashtable() );

        public static IDictionary GetObjectsMap() {
            return objectList;
        }

        public static IDictionary GetIndexMap() {
            return indexList;
        }


        private static Object objLock = new object();

        private static Object chkLock = new object();


        private static IList GetObjectsByName( Type t ) {

            if (isCheckFileDB( t )) {

                lock (chkLock) {

                    if (isCheckFileDB( t )) {

                        loadDataFromFile( t );
                        _hasCheckedFileDB[t] = true;

                    }

                }

            }
            return (objectList[t.FullName] as IList);
        }

        private static Hashtable _hasCheckedFileDB = new Hashtable();

        private static Boolean isCheckFileDB( Type t ) {
            if (_hasCheckedFileDB[t] == null) return true;
            return false;
        }


        private static void loadDataFromFile( Type t ) {
            if (wojilu.IO.File.Exists( getCachePath( t ) )) {
                IList list = getListWithIndex( wojilu.IO.File.Read( getCachePath( t ) ), t );
                objectList[t.FullName] = list;
            }
            else {
                objectList[t.FullName] = new ArrayList();
            }
        }

        private static IList getListWithIndex( String jsonString, Type t ) {

            IList list = new ArrayList();

            if (strUtil.IsNullOrEmpty( jsonString )) return list;

            List<object> lists = JsonParser.Parse( jsonString ) as List<object>;

            foreach (Dictionary<String, object> map in lists) {

                CacheObject obj = JSON.setValueToObject( t, map ) as CacheObject;
                int index = list.Add( obj );
                addIdIndex( t.FullName, obj.Id, index );
                makeIndexByInsert( obj );
            }

            return list;
        }

        private static void Serialize( Type t ) {
            Serialize( t, GetObjectsByName( t ) );
        }

        private static void Serialize( Type t, IList list ) {
            String target = SimpleJsonString.ConvertList( list );
            if (strUtil.IsNullOrEmpty( target )) return;

            String absolutePath = getCachePath( t );
            lock (objLock) {
                wojilu.IO.File.Write( absolutePath, target );
            }
        }

        private static void UpdateObjects( String key, IList list ) {
            objectList[key] = list;
        }

        //------------------------------------------------------------------------------

        internal static CacheObject FindById( Type t, int id ) {

            IList list = GetObjectsByName( t );
            if (list.Count > 0) {
                int objIndex = getIndex( t.FullName, id );
                if (objIndex >= 0 && objIndex < list.Count) {
                    return list[objIndex] as CacheObject;
                }
            }
            return null;
        }

        internal static IList FindBy( Type t, String propertyName, Object val ) {

            String propertyKey = getPropertyKey( t.FullName, propertyName );
            NameValueCollection valueCollection = getValueCollection( propertyKey );

            String ids = valueCollection[val.ToString()];
            if (strUtil.IsNullOrEmpty( ids )) return new ArrayList();

            IList results = new ArrayList();
            String[] arrItem = ids.Split( ',' );
            foreach (String strId in arrItem) {
                int id = cvt.ToInt( strId );
                if (id < 0) continue;
                CacheObject obj = FindById( t, id );
                if (obj != null) results.Add( obj );
            }
            return results;
        }

        internal static IList FindAll( Type t ) {
            return new ArrayList( GetObjectsByName( t ) );
        }

        internal static void Insert( CacheObject obj ) {

            Type t = obj.GetType();
            String _typeFullName = t.FullName;

            IList list = FindAll( t );
            obj.Id = getNextId( list );

            int index = list.Add( obj );

            addIdIndex( _typeFullName, obj.Id, index );
            UpdateObjects( _typeFullName, list );

            makeIndexByInsert( obj );

            if (isInMemory( t )) return;

            Serialize( t );
        }

        internal static void InsertByIndex( CacheObject obj, String propertyName, Object pValue ) {

            Type t = obj.GetType();
            String _typeFullName = t.FullName;

            IList list = FindAll( t );
            obj.Id = getNextId( list );
            int index = list.Add( obj );

            addIdIndex( _typeFullName, obj.Id, index );
            UpdateObjects( _typeFullName, list );

            makeIndexByInsert( obj, propertyName, pValue );

            if (isInMemory( t )) return;

            Serialize( t );
        }

        internal static void InsertByIndex( CacheObject obj, Dictionary<String, Object> dic ) {

            Type t = obj.GetType();
            String _typeFullName = t.FullName;

            IList list = FindAll( t );
            obj.Id = getNextId( list );
            int index = list.Add( obj );

            addIdIndex( _typeFullName, obj.Id, index );
            UpdateObjects( _typeFullName, list );

            foreach (KeyValuePair<String, Object> kv in dic) {
                makeIndexByInsert( obj, kv.Key, kv.Value );
            }

            if (isInMemory( t )) return;

            Serialize( t );
        }

        internal static Result Update( CacheObject obj ) {

            Type t = obj.GetType();

            makeIndexByUpdate( obj );

            if (isInMemory( t )) return new Result();

            try {
                Serialize( t );
                return new Result();
            }
            catch (Exception ex) {
                throw ex;
            }
        }

        internal static Result updateByIndex( CacheObject obj, Dictionary<String, Object> dic ) {

            Type t = obj.GetType();

            makeIndexByUpdate( obj );

            if (isInMemory( t )) return new Result();

            try {
                Serialize( t );
                return new Result();
            }
            catch (Exception ex) {
                throw ex;
            }
        }

        internal static void Delete( CacheObject obj ) {

            Type t = obj.GetType();
            String _typeFullName = t.FullName;

            makeIndexByDelete( obj );

            IList list = FindAll( t );
            list.Remove( obj );
            UpdateObjects( _typeFullName, list );

            deleteIdIndex( _typeFullName, obj.Id );

            if (isInMemory( t )) return;

            Serialize( t, list );
        }

        private static int getNextId( IList list ) {
            if (list.Count == 0) return 1;
            CacheObject preObject = list[list.Count - 1] as CacheObject;
            return preObject.Id + 1;
        }

        private static Boolean isInMemory( Type t ) {
            return rft.GetAttribute( t, typeof( NotSaveAttribute ) ) != null;
        }

        //----------------------------------------------------------------------------------------------

        private static Object objIndexLock = new object();
        private static Object objIndexLockInsert = new object();
        private static Object objIndexLockUpdate = new object();
        private static Object objIndexLockDelete = new object();

        private static void makeIndexByInsert( CacheObject cacheObject, String propertyName, Object pValue ) {
            if (cacheObject == null || pValue == null) return;
            Type t = cacheObject.GetType();
            String propertyKey = getPropertyKey( t.FullName, propertyName );
            lock (objIndexLock) {
                NameValueCollection valueCollection = getValueCollection( propertyKey );
                valueCollection.Add( pValue.ToString(), cacheObject.Id.ToString() );
                indexList[propertyKey] = valueCollection;
            }
        }

        private static void makeIndexByInsert( CacheObject cacheObject ) {
            if (cacheObject == null) return;
            Type t = cacheObject.GetType();
            PropertyInfo[] properties = getProperties( t );
            foreach (PropertyInfo p in properties) {

                String propertyKey = getPropertyKey( t.FullName, p.Name );
                lock (objIndexLockInsert) {
                    NameValueCollection valueCollection = getValueCollection( propertyKey );
                    addNewValueMap( valueCollection, cacheObject, p );
                }
            }
        }

        private static void makeIndexByUpdate( CacheObject cacheObject ) {
            if (cacheObject == null) return;
            Type t = cacheObject.GetType();
            PropertyInfo[] properties = getProperties( t );
            foreach (PropertyInfo p in properties) {

                String propertyKey = getPropertyKey( t.FullName, p.Name );

                lock (objIndexLockUpdate) {
                    NameValueCollection valueCollection = getValueCollection( propertyKey );
                    deleteOldValueIdMap( valueCollection, cacheObject.Id );
                    addNewValueMap( valueCollection, cacheObject, p );
                }

            }
        }

        private static void makeIndexByUpdate( CacheObject cacheObject, String propertyName, Object pValue ) {
            if (cacheObject == null || pValue == null) return;
            Type t = cacheObject.GetType();

            String propertyKey = getPropertyKey( t.FullName, propertyName );

            lock (objIndexLockUpdate) {

                NameValueCollection valueCollection = getValueCollection( propertyKey );
                deleteOldValueIdMap( valueCollection, cacheObject.Id );
                valueCollection.Add( pValue.ToString(), cacheObject.Id.ToString() );
                indexList[propertyKey] = valueCollection;

            }
        }

        private static void makeIndexByDelete( CacheObject cacheObject ) {
            if (cacheObject == null) return;
            Type t = cacheObject.GetType();
            PropertyInfo[] properties = getProperties( t );
            foreach (PropertyInfo p in properties) {

                String propertyKey = getPropertyKey( t.FullName, p.Name );
                lock (objIndexLockDelete) {
                    NameValueCollection valueCollection = getValueCollection( propertyKey );
                    deleteOldValueIdMap( valueCollection, cacheObject.Id );
                }
            }
        }

        private static PropertyInfo[] getProperties( Type t ) {
            return t.GetProperties( BindingFlags.Public | BindingFlags.Instance );
        }

        private static NameValueCollection getValueCollection( String propertyKey ) {
            NameValueCollection valueCollection = indexList[propertyKey] as NameValueCollection;
            if (valueCollection == null) valueCollection = new NameValueCollection();
            return valueCollection;
        }

        private static void addNewValueMap( NameValueCollection valueCollection, CacheObject cacheObject, PropertyInfo p ) {

            Attribute attr = rft.GetAttribute( p, typeof( NotSaveAttribute ) );
            if (attr != null) return;

            String propertyKey = getPropertyKey( cacheObject.GetType().FullName, p.Name );

            Object pValue = rft.GetPropertyValue( cacheObject, p.Name );
            if (pValue == null || strUtil.IsNullOrEmpty( pValue.ToString() )) return;

            valueCollection.Add( pValue.ToString(), cacheObject.Id.ToString() );
            indexList[propertyKey] = valueCollection;
        }

        // TODO 优化
        private static void deleteOldValueIdMap( NameValueCollection valueCollection, int oid ) {
            foreach (String key in valueCollection.AllKeys) {

                String val = valueCollection[key];
                String[] arrItem = val.Split( ',' );
                StringBuilder result = new StringBuilder();
                foreach (String strId in arrItem) {
                    int id = cvt.ToInt( strId );
                    if (id == oid) continue;
                    result.Append( strId );
                    result.Append( "," );
                }
                String resultStr = result.ToString();
                if (strUtil.HasText( resultStr ))
                    valueCollection[key] = resultStr.Trim().TrimEnd( ',' );
                else
                    valueCollection.Remove( key );
            }
        }

        private static String getPropertyKey( String typeFullName, String propertyName ) {
            return typeFullName + "_" + propertyName;
        }


        //-------------------------- Id Index --------------------------------

        private static IDictionary GetIdIndexMap( String key ) {
            if (objectList[key] == null) {
                objectList[key] = new Hashtable();
            }
            return (objectList[key] as IDictionary);
        }

        private static void UpdateIdIndexMap( String key, IDictionary map ) {
            objectList[key] = map;
        }

        private static void clearIdIndexMap( String key ) {
            objectList.Remove( key );
        }


        private static void addIdIndex( String typeFullName, int oid, int index ) {
            String key = getIdIndexMapKey( typeFullName );
            IDictionary indexMap = GetIdIndexMap( key );
            indexMap[oid] = index;
            UpdateIdIndexMap( key, indexMap );
        }
        private static void deleteIdIndex( String typeFullName, int oid ) {

            String key = getIdIndexMapKey( typeFullName );

            clearIdIndexMap( key );

            IList results = objectList[typeFullName] as IList;
            foreach (CacheObject obj in results) {
                addIdIndex( typeFullName, obj.Id, results.IndexOf( obj ) );
            }

            IDictionary indexMap = GetIdIndexMap( key );
            UpdateIdIndexMap( key, indexMap );
        }

        private static int getIndex( String typeFullName, int oid ) {
            int result = -1;
            Object objIndex = GetIdIndexMap( getIdIndexMapKey( typeFullName ) )[oid];
            if (objIndex != null) {
                result = (int)objIndex;
            }
            return result;
        }

        private static String getIdIndexMapKey( String typeFullName ) {
            return String.Format( "{0}_oid_index", typeFullName );
        }

        //----------------------------------------------------------

        private static String getCachePath( Type t ) {
            if (SystemInfo.IsWeb == false) {
                return getCacheFileName( t.FullName );
            }
            return getWebCacheFileName( t.FullName );
        }

        private static String getCacheFileName( String name ) {
            return PathHelper.CombineAbs( new String[] {
                AppDomain.CurrentDomain.BaseDirectory,
                cfgHelper.FrameworkRoot,
                "data",
                name + fileExt
            } );
        }

        private static String getWebCacheFileName( String name ) {

            String rpath = strUtil.Join( cfgHelper.FrameworkRoot, "data" );
            rpath = strUtil.Join( rpath, name + fileExt );
            return PathHelper.Map( rpath );
        }

        private static readonly String fileExt = ".config";

    }
}
Back to Top