summaryrefslogtreecommitdiff
path: root/Tizen.Applications.DataControl/Tizen.Applications.DataControl/MatrixCursor.cs
blob: c0d804726dccd16cb208d5dc40218ad4cf11417a (plain)
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
/*
 * Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved
 *
 * 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.IO;
using System.Text;
using System.Collections.Generic;
using System.Threading;

namespace Tizen.Applications.DataControl
{
    /// <summary>
    /// Represents MatrixCursor class for DataControl provider's matrix cursor.
    /// </summary>
    public class MatrixCursor : IDisposable, ICursor
    {
        private const string LogTag = "Tizen.Applications.DataControl";
        private FileStream _fs;
        private bool _disposed = false;
        private string _cursorPath;
        private long _rowCount = 0;
        private long _rowCountPosition = 0;
        private int _currentRowIndex = 0;
        private IList<long> _rowFieldOffset = new List<long>();
        private string[] _columnNames;
        private ColumnType[] _columnTypes;
        private const int ColumnTypeNull = 5;

        private byte[] GetValue(int index)
        {
            byte[] int_tmp = new byte[sizeof(int)];
            byte[] ret_array;
            ColumnType type;
            int size, read_len;

            MoveToColumn(index);

            read_len = _fs.Read(int_tmp, 0, int_tmp.Length);
            if (read_len != int_tmp.Length)
            {
                ErrorFactory.ThrowException(ResultType.IoError, true, "Column Type " + index.ToString());
            }

            type = (ColumnType)BitConverter.ToInt32(int_tmp, 0);

            if (type != _columnTypes[index])
            {
                if ((int)type == ColumnTypeNull &&
                    (_columnTypes[index] == ColumnType.ColumnTypeBlob || _columnTypes[index] == ColumnType.ColumnTypeString))
                {
                    return null; /* null type */
                }

                ErrorFactory.ThrowException(ResultType.IoError, true, "Type mismatch " + index.ToString());
            }

            read_len = _fs.Read(int_tmp, 0, int_tmp.Length);
            if (read_len != int_tmp.Length)
            {
                ErrorFactory.ThrowException(ResultType.IoError, true, "Column size " + index.ToString());
            }

            size = BitConverter.ToInt32(int_tmp, 0);

            if (size < 0)
            {
                ErrorFactory.ThrowException(ResultType.IoError, true, "Invalid data size " + index.ToString());
            }

            ret_array = new byte[size];
            read_len = _fs.Read(ret_array, 0, ret_array.Length);
            if (read_len != ret_array.Length)
            {
                ErrorFactory.ThrowException(ResultType.IoError, true, "Column value size " + index.ToString());
                return null;
            }

            return ret_array;
        }

        private void MoveToColumn(int ColumnIndex)
        {
            int i, tmp_position;
            byte[] int_tmp = new byte[sizeof(int)];
            int read_len;
            long seek_len;

            seek_len = _fs.Seek(_rowFieldOffset[_currentRowIndex], SeekOrigin.Begin);
            if (seek_len != _rowFieldOffset[_currentRowIndex])
            {
                ErrorFactory.ThrowException(ResultType.IoError, true, "Row index " + _currentRowIndex.ToString());
            }

            for (i = 0; i < ColumnIndex; i++)
            {
                /* type(int) size(int) value */
                switch (_columnTypes[i])
                {
                    case ColumnType.ColumnTypeInt:
                        tmp_position = sizeof(int) * 2 + sizeof(Int64);
                        _fs.Seek(tmp_position, SeekOrigin.Current);
                        break;
                    case ColumnType.ColumnTypeDouble:
                        tmp_position = sizeof(int) * 2 + sizeof(double);
                        _fs.Seek(tmp_position, SeekOrigin.Current);
                        break;
                    case ColumnType.ColumnTypeString:
                        tmp_position = sizeof(int);
                        _fs.Seek(tmp_position, SeekOrigin.Current);
                        read_len = _fs.Read(int_tmp, 0, int_tmp.Length);
                        if (read_len != int_tmp.Length)
                        {
                            ErrorFactory.ThrowException(ResultType.IoError, true, "Column Index " + ColumnIndex.ToString());
                        }

                        tmp_position = BitConverter.ToInt32(int_tmp, 0);

                        if (tmp_position > 0)
                        {
                            _fs.Seek(tmp_position, SeekOrigin.Current);
                        }

                        break;
                    case ColumnType.ColumnTypeBlob:
                        tmp_position = sizeof(int);
                        _fs.Seek(tmp_position, SeekOrigin.Current);

                        read_len = _fs.Read(int_tmp, 0, int_tmp.Length);
                        if (read_len != int_tmp.Length)
                        {
                            ErrorFactory.ThrowException(ResultType.IoError, true, "Column Index " + ColumnIndex.ToString());
                        }

                        tmp_position = BitConverter.ToInt32(int_tmp, 0);

                        if (tmp_position > 0)
                        {
                            _fs.Seek(tmp_position, SeekOrigin.Current);
                        }

                        break;
                }
            }

        }

        internal FileStream GetFileStream()
        {
            return _fs;
        }

        /// <summary>
        /// Gets column count of MatrixCursor.
        /// </summary>
        public int GetColumnCount()
        {
            return _columnTypes.Length;
        }

        /// <summary>
        /// Returns the column type at the given zero-based column index.
        /// </summary>
        /// <param name="index">Target column index</param>
        /// <exception cref="ArgumentException">Thrown in case of Invalid parmaeter.</exception>
        public ColumnType GetColumnType(int index)
        {
            if (index < 0 || index >= _columnTypes.Length)
            {
                ErrorFactory.ThrowException(ResultType.InvalidParamer, false);
            }

            return _columnTypes[index];
        }

        /// <summary>
        /// Returns the column name at the given zero-based column index.
        /// </summary>
        /// <param name="index">Target column index</param>
        /// <exception cref="ArgumentException">Thrown in case of Invalid parmaeter.</exception>
        public string GetColumnName(int index)
        {
            if (index < 0 || index >= _columnTypes.Length)
            {
                ErrorFactory.ThrowException(ResultType.InvalidParamer, false);
            }

            return _columnNames[index];
        }

        /// <summary>
        /// Gets MatrixCursor's row count.
        /// </summary>
        public long GetRowCount()
        {
            return _rowCount;
        }

        /// <summary>
        /// Move the MatrixCursor to the next row.
        /// </summary>
        public bool Next()
        {
            if (_currentRowIndex >= _rowCount - 1)
            {
                return false;
            }

            _currentRowIndex++;
            return true;
        }

        /// <summary>
        /// Move the MatrixCursor to the previous row.
        /// </summary>
        public bool Prev()
        {
            if (_currentRowIndex <= 0)
            {
                return false;
            }

            _currentRowIndex--;
            return true;
        }

        /// <summary>
        /// Move the MatrixCursor to the first row.
        /// </summary>
        public bool Reset()
        {
            _currentRowIndex = 0;
            return true;
        }

        /// <summary>
        /// Returns the value of the requested column as a int.
        /// </summary>
        /// <exception cref="ArgumentException">Thrown in case of Invalid parmaeter.</exception>
        public int GetIntValue(int index)
        {
            int ret;
            byte[] byte_array;

            if (index < 0 || index >= _columnTypes.Length)
            {
                ErrorFactory.ThrowException(ResultType.InvalidParamer, false);
            }

            byte_array = GetValue(index);
            if (byte_array == null)
            {
                ErrorFactory.ThrowException(ResultType.InvalidParamer, false);
            }
            ret = BitConverter.ToInt32(byte_array, 0);

            return ret;
        }

        /// <summary>
        /// Returns the value of the requested column as a int64.
        /// </summary>
        /// <exception cref="ArgumentException">Thrown in case of Invalid parmaeter.</exception>
        public Int64 GetInt64Value(int index)
        {
            Int64 ret;
            byte[] byte_array;

            if (index < 0 || index >= _columnTypes.Length)
            {
                ErrorFactory.ThrowException(ResultType.InvalidParamer, false);
            }

            byte_array = GetValue(index);
            if (byte_array == null)
            {
                ErrorFactory.ThrowException(ResultType.InvalidParamer, false);
            }
            ret = BitConverter.ToInt64(byte_array, 0);

            return ret;
        }

        /// <summary>
        /// Returns the value of the requested column as a double.
        /// </summary>
        /// <exception cref="ArgumentException">Thrown in case of Invalid parmaeter.</exception>
        public double GetDoubleValue(int index)
        {
            double ret;
            byte[] byte_array;

            if (index < 0 || index >= _columnTypes.Length)
            {
                ErrorFactory.ThrowException(ResultType.InvalidParamer, false);
            }

            byte_array = GetValue(index);
            if (byte_array == null)
            {
                ErrorFactory.ThrowException(ResultType.InvalidParamer, false);
            }
            ret = BitConverter.ToDouble(byte_array, 0);

            return ret;
        }

        /// <summary>
        /// Returns the value of the requested column as a string.
        /// </summary>
        /// <exception cref="ArgumentException">Thrown in case of Invalid parmaeter.</exception>
        public string GetStringValue(int index)
        {
            string ret;
            byte[] byte_array;

            if (index < 0 || index >= _columnTypes.Length)
            {
                ErrorFactory.ThrowException(ResultType.InvalidParamer, false);
            }

            byte_array = GetValue(index);

            if (byte_array == null)
            {
                return null;
            }

            ret = Encoding.UTF8.GetString(byte_array);
            return ret;

        }

        /// <summary>
        /// Returns the value of the requested column as a blob.
        /// </summary>
        /// <exception cref="ArgumentException">Thrown in case of Invalid parmaeter.</exception>
        public byte[] GetBlobValue(int index)
        {
            byte[] byte_array;

            if (index < 0 || index >= _columnTypes.Length)
            {
                ErrorFactory.ThrowException(ResultType.InvalidParamer, false);
            }

            byte_array = GetValue(index);
            return byte_array;
        }

        private static class FileManager
        {
            private static readonly string DATACONTROL_DIRECTORY = "/tmp/";
            private static Dictionary<int, int> fileTable = new Dictionary<int, int>();
            public static string OpenFileStream(int threadID)
            {
                string path;
                int index;

                if (threadID < 0)
                {
                    Log.Error(LogTag, "threadID is " + threadID.ToString());
                    return null;
                }

                if (fileTable.ContainsKey(threadID) == false)
                {
                    fileTable.Add(threadID, 0);
                }

                index = fileTable[threadID];
                index++;
                fileTable[threadID] = index;

                path = DATACONTROL_DIRECTORY + Application.Current.ApplicationInfo.ApplicationId + "_"+Application.Current.ApplicationInfo.ProcessId.ToString() + "_" + threadID.ToString() + "_" + index.ToString();

                return path;
            }
        }

        /// <summary>
        /// Initializes MatrixCursor class with columnNames and columnTypes.
        /// </summary>
        /// <param name="columnNames">MatrixCursor's column name list</param>
        /// <param name="columnTypes">MatrixCursor's column type list</param>
        /// <exception cref="ArgumentException">Thrown in case of Invalid parmaeter.</exception>
        ///  <exception cref="InvalidOperationException">Thrown in case of any internal error.</exception>
        public MatrixCursor(string[] columnNames, ColumnType[] columnTypes)
        {
            byte[] byte_tmp, length_tmp, string_tmp;
            int i, total_len_of_column_names = 0;

            if (columnNames == null || columnTypes == null ||
                (columnNames.Length != columnTypes.Length) || columnNames.Length < 1)
            {
                ErrorFactory.ThrowException(ResultType.InvalidParamer, false);
            }

            for (i = 0; i < columnNames.Length; i++)
            {
                if (string.IsNullOrEmpty(columnNames[i]))
                {
                    ErrorFactory.ThrowException(ResultType.InvalidParamer, false, "columnNames index " + i.ToString());
                }
            }

            for (i = 0; i < columnTypes.Length; i++)
            {
                if ( columnTypes[i] < ColumnType.ColumnTypeInt || columnTypes[i] > ColumnType.ColumnTypeBlob)
                {
                    ErrorFactory.ThrowException(ResultType.InvalidParamer, false, "columnTypes index" + i.ToString());
                }
            }

            _columnNames = columnNames;
            _columnTypes = columnTypes;

            _cursorPath = FileManager.OpenFileStream(Thread.CurrentThread.ManagedThreadId);
            if (_cursorPath == null)
            {
                Log.Error(LogTag, "Unable to create a cursor file : " + _cursorPath);
                ErrorFactory.ThrowException(ResultType.IoError, true);
            }

            _fs = new FileStream(_cursorPath, FileMode.Create);
            /* column count */
            byte_tmp = BitConverter.GetBytes(columnNames.Length);
            _fs.Write(byte_tmp, 0, byte_tmp.Length);

            /* column type */
            for (i = 0; i < columnTypes.Length; i++)
            {
                byte_tmp = BitConverter.GetBytes((int)_columnTypes[i]);
                _fs.Write(byte_tmp, 0, byte_tmp.Length);
            }

            /* column name */
            for (i = 0; i < columnTypes.Length; i++)
            {
                string_tmp = Encoding.UTF8.GetBytes(columnNames[i]);
                byte_tmp = new byte[string_tmp.Length + 1];/*insert null */

                string_tmp.CopyTo(byte_tmp, 0);

                length_tmp = BitConverter.GetBytes(byte_tmp.Length);
                total_len_of_column_names += length_tmp.Length;

                _fs.Write(length_tmp, 0, length_tmp.Length);
                _fs.Write(byte_tmp, 0, byte_tmp.Length);
            }

            /* total length of column names */
            byte_tmp = BitConverter.GetBytes(total_len_of_column_names);
            _fs.Write(byte_tmp, 0, byte_tmp.Length);

            _rowCountPosition = _fs.Position;
            /* row count */
            byte_tmp = BitConverter.GetBytes(_rowCount);
            _fs.Write(byte_tmp, 0, byte_tmp.Length);
            _fs.Flush();
        }

        internal MatrixCursor()
        {
            _columnNames = new string[0];
            _columnTypes = new ColumnType[0];
            _fs = null;
            _cursorPath = null;
        }

        /// <summary>
        /// Adds a new row to the end with the given column values.
        /// </summary>
        /// <param name="columnValues">New column values</param>
        /// <exception cref="ArgumentException">Thrown in case of Invalid parmaeter.</exception>
        public void AddRow(object[] columnValues)
        {
            int i, size = 0;
            byte[] type_array, length_array, value_array = null, string_array, byte_tmp;

            if (columnValues == null || columnValues.Length <= 0 || columnValues.Length != _columnTypes.Length)
            {
                ErrorFactory.ThrowException(ResultType.InvalidParamer, false);
            }

            using (MemoryStream ms = new MemoryStream())
            {
                for (i = 0; i < _columnTypes.Length; i++)
                {
                    type_array = BitConverter.GetBytes((int)_columnTypes[i]);
                    switch (_columnTypes[i])
                    {
                        case ColumnType.ColumnTypeInt:
                            if (!(columnValues[i] is Int64) && !(columnValues[i] is Int32))
                            {
                                ErrorFactory.ThrowException(ResultType.InvalidParamer, false, "Type mismatch :Index "  + i.ToString());
                            }

                            value_array = BitConverter.GetBytes(Convert.ToUInt64(columnValues[i]));
                            size = value_array.Length;
                            break;
                        case ColumnType.ColumnTypeDouble:
                            if (!(columnValues[i] is Double))
                            {
                                ErrorFactory.ThrowException(ResultType.InvalidParamer, false, "Type mismatch :Index " + i.ToString());
                            }

                            value_array = BitConverter.GetBytes(Convert.ToDouble(columnValues[i]));
                            size = value_array.Length;
                            break;
                        case ColumnType.ColumnTypeString:
                            if (columnValues[i] == null)
                            {
                                type_array = BitConverter.GetBytes(ColumnTypeNull);
                                size = 0;
                                break;
                            }

                            if (!(columnValues[i] is string))
                            {
                                ErrorFactory.ThrowException(ResultType.InvalidParamer, false, "Type mismatch :Index " + i.ToString());
                            }

                            string_array = Encoding.UTF8.GetBytes(Convert.ToString(columnValues[i]));
                            value_array = new byte[string_array.Length + 1];/*insert null */
                            string_array.CopyTo(value_array, 0);
                            size = value_array.Length;
                            break;

                        case ColumnType.ColumnTypeBlob:
                            if (columnValues[i] == null)
                            {
                                type_array = BitConverter.GetBytes(ColumnTypeNull);
                                size = 0;
                                break;
                            }

                            if (!(columnValues[i] is byte[]))
                            {
                                ErrorFactory.ThrowException(ResultType.InvalidParamer, false, "Type mismatch :Index " + i.ToString());
                            }

                            value_array = (byte[])columnValues[i];
                            size = value_array.Length;
                            break;
                    }

                    ms.Write(type_array, 0, type_array.Length);

                    length_array = BitConverter.GetBytes(size);
                    ms.Write(length_array, 0, length_array.Length);
                    if (size > 0)
                    {
                        ms.Write(value_array, 0, value_array.Length);
                    }
                }

                /* update row count */
                _rowCount++;
                byte_tmp = BitConverter.GetBytes(_rowCount);
                _fs.Seek(_rowCountPosition, SeekOrigin.Begin);
                _fs.Write(byte_tmp, 0, byte_tmp.Length);

                _fs.Seek(0, SeekOrigin.End);

                _rowFieldOffset.Add(_fs.Position);
                ms.WriteTo(_fs);/* row data */
                _fs.Flush();

                Log.Debug(LogTag, "_fs pos = " + _fs.Position.ToString());
                Log.Debug(LogTag, "_fs len = " + _fs.Length.ToString());
            }
        }

        /// <summary>
        /// Releases all resources used by the MatrixCursor class.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (!string.IsNullOrEmpty(_cursorPath))
                {
                    FileInfo fi = new FileInfo(_cursorPath);

                    if (_fs != null)
                    {
                        _fs.Dispose();
                    }

                    if (fi.Exists)
                    {
                        fi.Delete();
                    }
                }

                _disposed = true;
            }

            if (disposing)
            {
                GC.SuppressFinalize(this);
            }
        }

        ~MatrixCursor()
        {
            Dispose(false);
        }
    }
}