ulysseskao
2016-05-01 8f5c8891aba521570fa63c4baf616e3a3c8d9526
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
using System;
using System.Collections;
using System.Data.OracleClient;
using NLog;
using TRACEROBJECTLib;
 
namespace CCSTrace.CCS.EventAI
{
    public class TraceSubject
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
 
        private string _mDbConnectionString;
        private static bool _isNewCase;
        private static ArrayList _mLinkList;                                // store the switch of the new case path
        private static TraceEngine _mTEngine;
        private static Hashtable _mTreeMap;                             // store the switch of the old case path
        private static int _sFsc;
        private static int _sUfid;
        private readonly ArrayList _mTmp = new ArrayList();
        private NetworkContext _mPContext;
 
        private readonly OracleConnection _connectionTpc;
        private readonly OracleTransaction _transaction;
 
        public TraceSubject(OracleConnection conn, OracleTransaction trx, string traceConnectionString)
        {
            _connectionTpc = conn;
            _transaction = trx;
            _mDbConnectionString = traceConnectionString;
 
            try
            {
                if (_mTEngine == null)
                {
                    _mTEngine = new TraceEngine();
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex, ex.Message);
                throw ex;
            }
        }
 
        public void DiscardEngine()
        {
            _mTEngine = null;
        }
 
        public ArrayList GetNewResult()
        {
            return _mLinkList;
        }
 
        public Hashtable GetOldResult()
        {
            return _mTreeMap;
        }
 
        // for EOS(only get the reverse tree)
        public void StartTrace(int startFsc, int startUfid, bool mIsNew)
        {
            _sFsc = startFsc;
            _sUfid = startUfid;
            _isNewCase = mIsNew;
            _mTreeMap = new Hashtable();
            _mLinkList = new ArrayList();
 
            try
            {
                SetReverseTree(Trace(true));
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message);
                throw;
            }
        }
 
        private bool GetSwitchOn(int ufid)
        {
            var sqlStmt = "SELECT M.OSTATUS as OSTATUS FROM (SELECT UFID,OSTATUS FROM BASEDB.CONNECTIVITY WHERE FSC = 114) M,"
                             + "BASEDB.SWITCH S WHERE M.UFID = S.UFID AND S.NSTATUS <> 0 AND M.UFID = " + ufid;
 
            OracleCommand command = null;
            OracleDataReader reader = null;
 
            try
            {
                command = new OracleCommand(sqlStmt, _connectionTpc, _transaction);
                reader = command.ExecuteReader();
 
                if (reader.Read())
                {
                    if (Convert.ToInt32(reader["OSTATUS"]) == 1)
                        return true;
                }
                reader.Close();
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message);
            }
            finally
            {
                command?.Dispose();
 
                reader?.Close();
            }
            return false;
        }
 
        private bool GetJumperOn(int ufid)
        {
            var sqlStmt = "SELECT OSTATUS FROM BASEDB.CONNECTIVITY WHERE FSC = 109 AND UFID = " + ufid;
 
            OracleCommand command = null;
            OracleDataReader reader = null;
 
            try
            {
                command = new OracleCommand(sqlStmt, _connectionTpc, _transaction);
                reader = command.ExecuteReader();
 
                if (reader.Read())
                {
                    if (Convert.ToInt32(reader["OSTATUS"]) == 1)
                        return true;
                }
                reader.Close();
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message);
            }
            finally
            {
                command?.Dispose();
 
                reader?.Close();
            }
            return false;
        }
 
        private readonly Hashtable _traceCounts = new Hashtable();
 
        private void SetReverseTree(ResultTree tree)
        {
            int i = 0;
            TreeIterator iti = null;
            bool ostatus = true;
 
            if (tree != null)
            {
                i = 0;
                iti = tree.CreateTreeIterator();
                bool isNotEnd = true;
 
                while (isNotEnd)
                {
                    if (GetTraceCount(iti.Value.ClassID, iti.Value.ObjectID) > 5)
                        throw new TraceLoopException("追蹤產生迴圈狀況。(Fsc,Ufid) = (" + iti.Value.ClassID + "," + iti.Value.ObjectID + ")");
                    else
                        AddTraceCount(iti.Value.ClassID, iti.Value.ObjectID);
 
                    while (iti.IsLeaf == 0)
                    {
                        TreeNode node = iti.Value;
 
                        if ((node.ClassID == 114) || (node.ClassID == 108) || (node.ClassID == 109))
                        {
                            Equipment equip = new Equipment(node.ClassID, node.ObjectID);
 
                            if (_isNewCase)
                                _mLinkList.Add(equip);
                            else
                            {
                                _mTreeMap.Add(node.ObjectID, equip);
                                _mTmp.Add(equip);
                            }
                            i++;
 
                            /*                            if (getTraceCount(node.ClassID, node.ObjectID) > 2)
                                                            throw new Exception("追蹤產生迴圈狀況。(Fsc,Ufid) = (" + node.ClassID + "," + node.ObjectID + ")");
                                                        else
                                                            AddTraceCount(node.ClassID, node.ObjectID);
                            */
                        }
 
                        Console.WriteLine(node.ClassID + "----->" + node.ObjectID);
                        Logger.Info(node.ClassID + "----->" + node.ObjectID);
 
                        iti.MoveDescent((short)0);
                    }
 
                    // 當從breaker出來的導線不只一條時,breaker可能會不被add(因為breaker是leaf但其parent的DescentCount > 1,所以被忽略)
                    /*
                     * if ( ((com.origo.TraceModel.ITreeNode)iti.get_Value()).get_ClassID() == EOS.GlobalVariable.Breaker ) {
                     * com.origo.TraceModel.ITreeNode node = iti.get_Value(); Equipment Equip = new Equipment(node.get_ClassID(),node.get_ObjectID()); if (
                     * IsNewCase ) m_LinkList.add(i,Equip); else { m_TreeMap.put(new Integer(node.get_ObjectID()),Equip); m_Tmp.add(Equip); }
                     * System.out.println(node.get_ClassID() + "----->" + node.get_ObjectID()); System.out.println("Trace Finish...."); i++; break; }
                     */
 
                    if ((iti.Value).ClassID == GlobalVariable.Breaker)
                    {
                        TreeNode node = iti.Value;
                        Equipment equip = new Equipment(node.ClassID, node.ObjectID);
 
                        if (_isNewCase)
                            _mLinkList.Add(equip);
                        else
                        {
                            _mTreeMap.Add(node.ObjectID, equip);
                            _mTmp.Add(equip);
                        }
                        i++;    //後面直接就FINISH,所以就不用判斷tracecount
 
                        Logger.Info(node.ClassID + "----->" + node.ObjectID);
                        Logger.Info("Trace Finish....");
                        break;
                    }
                    // 當追蹤到被切開的開關且該上一層設備只有該開關一個child)
                    else if (iti.Value.ClassID == GlobalVariable.Switch || iti.Value.ClassID == GlobalVariable.Jumper)
                    {
                        TreeNode node = iti.Value;
                        iti.MoveAscent();
 
                        Equipment equip = new Equipment(node.ClassID, node.ObjectID);
 
                        if (IsEndEquip(equip))
                        {
                            if (_isNewCase)
                                _mLinkList.Add(equip);
                            else
                            {
                                _mTreeMap.Add(node.ObjectID, equip);
                                _mTmp.Add(equip);
                            }
                            i++;    //後面直接就FINISH,所以就不用判斷tracecount
 
                            Logger.Info(node.ClassID + "----->" + node.ObjectID);
                            Logger.Info("Trace Finish....");
                            break;
                        }
 
                        //switch (node.ClassID)
                        //{
                        //  case 114:
                        //    ostatus = getSwitchOn(node.ObjectID);
                        //    break;
                        //  case 109:
                        //    ostatus = getJumperOn(node.ObjectID);
                        //    break;
                        //}
 
                        //if (!ostatus && (iti.DescentCount == 1)) {
                        //    Equipment Equip = new Equipment(node.ClassID, node.ObjectID);
 
                        //    if (IsNewCase)
                        //          m_LinkList.Add(Equip);
                        //    else {
                        //        m_TreeMap.Add(node.ObjectID, Equip);
                        //        m_Tmp.Add(Equip);
                        //    }
                        //    i++;
 
                        //    Console.WriteLine(node.ClassID + "----->" + node.ObjectID);
                        //    _Plogger.Info(node.ClassID + "----->" + node.ObjectID);
                        //    Console.WriteLine("Trace Finish....");
                        //    _Plogger.Info("Trace Finish....");
                        //    break;
                        //}
                    }
                    else
                    {
                        TreeNode node = iti.Value;
                        iti.MoveAscent();
 
                        if (iti.DescentCount == 1)
                            throw new Exception("追蹤到非開關類斷開之設備(Fsc = " + node.ClassID + ",Ufid = " + node.ObjectID);
                    }
 
                    for (int j = 1; j < iti.DescentCount; j++)
                    {
                        iti.MoveDescent((short)j);
 
                        if (iti.IsLeaf == 1)
                        {
                            TreeNode node = iti.Value;
                            Equipment equip = new Equipment(node.ClassID, node.ObjectID);
 
                            switch (node.ClassID)
                            {
                                case 108:
                                    if (_isNewCase)
                                        _mLinkList.Add(equip);
                                    else
                                    {
                                        _mTreeMap.Add(node.ObjectID, equip);
                                        _mTmp.Add(equip);
                                    }
 
                                    Logger.Info(node.ClassID + "----->" + node.ObjectID);
                                    i++;
 
                                    /*                                if (getTraceCount(node.ClassID, node.ObjectID) > 2)
                                                                        throw new Exception("追蹤產生迴圈狀況。(Fsc,Ufid) = (" + node.ClassID + "," + node.ObjectID + ")");
                                                                    else
                                                                        AddTraceCount(node.ClassID, node.ObjectID);
                                    */
                                    break;
 
                                case 109:
                                case 114:
                                    switch (node.ClassID)
                                    {
                                        case 114:
                                            ostatus = GetSwitchOn(node.ObjectID);
                                            break;
 
                                        case 109:
                                            ostatus = GetJumperOn(node.ObjectID);
                                            break;
                                    }
 
                                    // Only for switch because the breaker only has one node to descent
                                    if (!ostatus)
                                    {
                                        if (_isNewCase)
                                            _mLinkList.Add(equip);
                                        else
                                        {
                                            _mTreeMap.Add(node.ObjectID, equip);
                                            _mTmp.Add(equip);
                                        }
 
                                        Logger.Info(node.ClassID + "----->" + node.ObjectID);
                                        i++;
 
                                        /*                                    if (getTraceCount(node.ClassID, node.ObjectID) > 2)
                                                                                throw new Exception("追蹤產生迴圈狀況。(Fsc,Ufid) = (" + node.ClassID + "," + node.ObjectID + ")");
                                                                            else
                                                                                AddTraceCount(node.ClassID, node.ObjectID);
                                        */
                                    }
                                    break;
 
                                default:
                                    break;
                            } // switch
 
                            iti.MoveAscent();
                            isNotEnd = false;
                        }
                        else
                        {
                            isNotEnd = true;
                            break;
                        }
                    } // for
                } // while
                Logger.Info("Tree Node Count = " + i);
            }
            else
            {
                Logger.Info("Tree is null");
                throw new Exception("無法追蹤到任何設備,可能是該用戶所在變壓器設備連結性有問題。");
            }
        }
 
        private ResultTree Trace(bool reverse)
        {
            ResultTree tree = null;
 
            try
            {
                ConfigTrace();
                Logger.Info("configTrace OK.");
            }
            catch (Exception e)
            {
                Logger.Error(e.Message);
                Console.WriteLine(e.StackTrace);
                return tree;
            }
 
            try
            {
                tree = ModeTrace(reverse);
            }
            catch (Exception e)
            {
                Logger.Error(e.Message);
                Console.WriteLine(e.StackTrace);
            }
 
            return tree;
        }
 
        private void ConfigTrace()
        {
            if (_mDbConnectionString == null)
            {
                _mDbConnectionString = "basedb/basedb000@nntpc";
            }
            try
            {
                if (_mPContext == null) _mPContext = _mTEngine.teoCreateContext();
 
                if (_mPContext.IsConnected == 0)
                {
                    _mPContext.Connect("", _mDbConnectionString);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex, ex.Message);
            }
        }
 
        private ResultTree ModeTrace(bool reverse)
        {
            TravelContext tContext = new TravelContext();
            TravelStartCriterion sCriterion = new TravelStartCriterion();
            TravelTerminateCriterion eCriterion = new TravelTerminateCriterion();
 
            sCriterion.ClsID = (short)_sFsc;
            sCriterion.ObjID = _sUfid;
 
            if (reverse) // 反向上追
            {
                sCriterion.StartMode = (TRAVELSTARTCRITERIONTYPE)(Convert.ToInt32(TRAVELSTARTCRITERIONTYPE.TRAVELBYNEGDIR) + Convert.ToInt32(TRAVELSTARTCRITERIONTYPE.TRAVELWITHFOLLOW));
 
                eCriterion.ClsID = (short)GlobalVariable.Breaker;
                eCriterion.EndMode = TRAVELTERMCRITERIONTYPE.TRAVELTOTHISCLASS;
            }
            else // 順向追蹤
            {
                sCriterion.StartMode = TRAVELSTARTCRITERIONTYPE.TRAVELBYCURDIR;
 
                eCriterion.EndMode = TRAVELTERMCRITERIONTYPE.TRAVELTOTHISCLASS;
            }
 
            tContext.addCriterion(sCriterion);
            tContext.addCriterion(eCriterion);
 
            _mPContext.ResetContext();
 
            Logger.Info("Set ModeTrace OK.");
            ResultTreeBuilder trBuilder = _mPContext.CreateTreeBuilder();
            if (!trBuilder.constructResultTree(tContext, TRAVELTHREADMODE.CONMODE_SYNCHRONOUS)) { return null; }
            Logger.Info("ConstructResultTree OK.");
            ResultTree result = trBuilder.ResultTree;
 
            Logger.Info("getResultTree OK.");
            return result;
        }
 
        //判斷是否為最終設備(逆向追到已經無child的設備時,檢查該設備是否為最終設備(查驗該設備的同層設備,是否仍有可繼續逆向追蹤的設備,若無,則該設備為最終設備
        private bool IsEndEquip(Equipment selfEquip)
        {
            string sqlStmt;
            OracleCommand command = null;
            OracleDataReader reader = null;
            long nValue = 0;
 
            sqlStmt = "SELECT DIR,OSTATUS,N1,N2 FROM BASEDB.CONNECTIVITY WHERE FSC = " + selfEquip.Fsc+ " AND UFID = " + selfEquip.Ufid;
 
            try
            {
                command = new OracleCommand(sqlStmt, _connectionTpc, _transaction);
                reader = command.ExecuteReader();
 
                if (reader.Read())
                {
                    if (Convert.ToInt32(reader["OSTATUS"]) == 1)  //如果設備本身為非切開的設備,那應該繼續往逆向追
                        return false;
                    else
                    {
                        if (Convert.ToInt32(reader["DIR"]) == 3)    //順向無電 N1-->N2,所以逆向的上游N值抓N2
                            nValue = Convert.ToInt32(reader["N2"]);
                        else
                            nValue = Convert.ToInt32(reader["N1"]);
                    }
                }
                reader.Close();
 
                sqlStmt = "SELECT FSC,UFID,DIR,OSTATUS,N1,N2 FROM BASEDB.CONNECTIVITY WHERE N1 <> N2 AND ( N1 = " + nValue + " OR N2 = " + nValue + ")";
                command.CommandText = sqlStmt;
 
                reader = command.ExecuteReader();
 
                while (reader.Read())
                {
                    if (Convert.ToInt32(reader["FSC"]) == selfEquip.Fsc&& Convert.ToInt32(reader["UFID"]) == selfEquip.Ufid)
                        continue;
 
                    if (Convert.ToInt32(reader["OSTATUS"]) == 0)    //切開的設備不可能為逆向的上游
                        continue;
 
                    if (Convert.ToInt32(reader["N1"]) == nValue)
                    {
                        switch (Convert.ToInt32(reader["DIR"]))
                        {
                            case 1:
                            case 3:
                                break;
 
                            case 2:
                            case 4:
                                return false; //如果逆向的上游連接點為N1,一定要N2-->N1才可能還有需要逆向追蹤設備
                            case 99:
                                break;  //未供電設備不可能是逆向上游
                        }
                    }
                    else if (Convert.ToInt32(reader["N2"]) == nValue)
                    {
                        switch (Convert.ToInt32(reader["DIR"]))
                        {
                            case 1:
                            case 3:
                                return false;  //如果逆向的上游連接點為N2,一定要N1-->N2才可能還有需要逆向追蹤設備
                            case 2:
                            case 4:
                                break;
 
                            case 99:
                                return false;   //未供電設備不可能是逆向上游
                        }
                    }
                }
                reader.Close();
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message);
                return false;
            }
            finally
            {
                if (command != null)
                    command.Dispose();
 
                if (reader != null)
                    reader.Close();
            }
 
            return true;
        }
 
        private int GetTraceCount(int fsc, int ufid)
        {
            if (_traceCounts.ContainsKey(fsc + "|" + ufid))
                return int.Parse(_traceCounts[fsc + "|" + ufid].ToString());
            else
                return 0;
        }
 
        private void AddTraceCount(int fsc, int ufid)
        {
            int count = 1;
 
            if (_traceCounts.ContainsKey(fsc + "|" + ufid))
            {
                count = int.Parse(_traceCounts[fsc + "|" + ufid].ToString());
                count++;
                _traceCounts.Remove(fsc + "|" + ufid);
            }
 
            _traceCounts.Add(fsc + "|" + ufid, count.ToString());
        }
    }
 
    public class TraceLoopException : Exception
    {
        public TraceLoopException(string message) : base(message)
        {
        }
    }
}