-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathRuleEngine.cs
110 lines (99 loc) · 3.34 KB
/
RuleEngine.cs
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
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;
using JavaToCSharp.Configuration;
using System.Configuration;
using JavaToCSharp.Rules;
namespace JavaToCSharp
{
public class RuleEngine
{
List<Rule> rules = new List<Rule>();
public void AddRule(Rule rule)
{
rules.Add(rule);
}
/// <summary>
/// Loads the rules.
/// </summary>
public void LoadRules()
{
//load from app.config
J2CSSection config =
ConfigurationManager.GetSection(
"J2CS") as J2CSSection;
foreach (RuleSection rs in config.Rules)
{
EquivalentRule r = new EquivalentRule(rs.Name);
r.Pattern = rs.Pattern;
r.Replacement = rs.Replacement;
//Console.WriteLine(r.ToString());
AddRule(r);
}
//load from assembly
Assembly asm = Assembly.GetExecutingAssembly();
string nameSpace = "JavaToCSharp.Rules";
foreach (Type type in asm.GetTypes())
{
if (type.Namespace == nameSpace && !type.IsAbstract && type.Name != "EquivalentRule")
AddRule(Activator.CreateInstance(type) as Rule);
}
}
protected static void Log(string message)
{
Console.WriteLine(message);
}
protected static void LogTip(string message)
{
Console.WriteLine(message);
}
protected void LogExecute(string ruleName,int iRowNumber)
{
Log(string.Format("[Line {0}] {1}", iRowNumber, ruleName));
}
//protected void LogFind(string strOrigin, int iRowNumber)
//{
// Log(string.Format("[{0}]", this.RuleName));
// Log(string.Format("(Line: {0}): {1}", iRowNumber, strOrigin.Trim().Replace("\r", "")));
//}
//protected void LogAttention(string strOrigin, int iRowNumber)
//{
// LogTip(string.Format("[{0}]", this.RuleName));
// LogTip(string.Format("(Line: {0}): {1}", iRowNumber, strOrigin.Trim().Replace("\r", "")));
//}
public void Run(string path)
{
//read from file
if (!File.Exists(path))
{
Console.WriteLine("File not found");
return;
}
StreamReader sr = new StreamReader(path, true);
string strOrigin = sr.ReadToEnd();
sr.Close();
//run rules
StringBuilder sb = new StringBuilder();
string[] arrInput = strOrigin.Split(new char[] { '\n' });
for (int i = 0; i < arrInput.Length; i++)
{
string tmp = arrInput[i].Replace("\r", "");
int ruleNum = i + 1;
foreach (Rule rule in rules)
{
if (rule.Execute(tmp, out tmp, ruleNum))
{
LogExecute(rule.RuleName, ruleNum);
}
}
sb.AppendLine(tmp);
}
//save result to file
StreamWriter sw = new StreamWriter(path, false);
sw.Write(sb.ToString());
sw.Close();
}
}
}