forked from kendarorg/RepositoryCache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRestAPI.cs
More file actions
301 lines (276 loc) · 10.6 KB
/
RestAPI.cs
File metadata and controls
301 lines (276 loc) · 10.6 KB
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
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace MultiRepositories.Service
{
public class Request
{
public Request()
{
Methods = new List<string>();
}
public List<string> Methods { get; set; }
public string[] Path { get; set; }
}
public abstract class RestAPI
{
private List<Request> _realPaths;
private Func<SerializableRequest, SerializableResponse> _handler;
protected void SetHandler(Func<SerializableRequest, SerializableResponse> handler)
{
_handler = handler;
}
public RestAPI(Func<SerializableRequest, SerializableResponse> handler, params string[] paths)
{
_realPaths = new List<Request>();
Request lastRequest = new Request();
foreach (var path in paths)
{
if (path.StartsWith("*"))
{
lastRequest.Methods.Add(path.Trim('*'));
}
else
{
lastRequest.Path = path.TrimStart('/').Split('/');
_realPaths.Add(lastRequest);
lastRequest = new Request();
}
}
_handler = handler;
}
public void Append(Dictionary<string, string> dic, string key, string data)
{
if (!dic.ContainsKey(key))
{
dic[key] = data;
}
else
{
dic[key] += "/" + data;
}
}
private Dictionary<string, string> BuildPath(string url, string[] realPath)
{
var splittedUrl = url.Trim('/').Split('/');
var data = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
var stars = realPath.Count(a => a.StartsWith("{*"));
if (stars > 1)
{
throw new Exception("Invlid Url");
}
else if (stars == 0)
{
if (splittedUrl.Length != realPath.Length)
{
return null;
}
}
var realIndex = 0;
var splittedIndex = 0;
for (; realIndex < realPath.Length; realIndex++)
{
var mtc = realPath[realIndex];
var spl = splittedUrl[splittedIndex];
var start = mtc.IndexOf("{");
var end = mtc.IndexOf("}");
if (mtc.StartsWith("{*") && mtc.EndsWith("}"))
{
var index = mtc.Substring(2, mtc.Length - 3);
//What is after is useless
if (realIndex == realPath.Length - 1)
{
for (; splittedIndex < splittedUrl.Length; splittedIndex++)
{
Append(data, "*" + index, splittedUrl[splittedIndex]);
}
return data;
}
var limitReal = realPath.Length - 1;
var limitSplit = splittedUrl.Length - 1;
for (; limitReal > realIndex; limitReal--)
{
mtc = realPath[limitReal];
spl = splittedUrl[limitSplit];
start = mtc.IndexOf("{");
end = mtc.IndexOf("}");
if (string.Compare(spl, mtc, true) == 0)
{
limitSplit--;
continue;
}
else if (start >= 0 && end > start)
{
var pre = start > 0 ? mtc.Substring(0, start) : "";
var post = mtc.Substring(end + 1);
if (spl.StartsWith(pre) && spl.EndsWith(post))
{
if (pre.Length > 0)
{
spl = spl.Substring(pre.Length);
mtc = mtc.Substring(pre.Length);
}
if (post.Length > 0)
{
spl = spl.Substring(0, spl.Length - post.Length);
mtc = mtc.Substring(0, mtc.Length - post.Length);
}
if (mtc.IndexOf("#") > 0)
{
if (!AppendMerge(data, mtc.Trim('{', '}'), spl))
{
return null;
}
}
else
{
Append(data, mtc.Trim('{', '}'), spl);
}
limitSplit--;
continue;
}
return null;
}
else if (string.Compare(spl, mtc, true) == 0)
{
limitSplit--;
continue;
}
return null;
}
for (; splittedIndex <= limitSplit; splittedIndex++)
{
spl = splittedUrl[splittedIndex];
Append(data, "*" + index, spl);
}
return data;
}
else if (string.Compare(spl, mtc, true) == 0)
{
splittedIndex++;
continue;
}
else if (start >= 0 && end > start)
{
var pre = start > 0 ? mtc.Substring(0, start) : "";
var post = mtc.Substring(end + 1);
if (spl.StartsWith(pre) && spl.EndsWith(post))
{
if (pre.Length > 0)
{
spl = spl.Substring(pre.Length);
mtc = mtc.Substring(pre.Length);
}
if (post.Length > 0)
{
spl = spl.Substring(0, spl.Length - post.Length);
mtc = mtc.Substring(0, mtc.Length - post.Length);
}
if (mtc.IndexOf("#") > 0)
{
if (!AppendMerge(data, mtc.Trim('{', '}'), spl))
{
return null;
}
}
else
{
Append(data, mtc.Trim('{', '}'), spl);
}
splittedIndex++;
continue;
}
return null;
}
else
{
return null;
}
}
return data;
}
protected static Dictionary<string, Regex> _regexes = new Dictionary<string, Regex>(StringComparer.InvariantCultureIgnoreCase);
//https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html
private bool AppendMerge(Dictionary<string, string> data, string mtc, string spl)
{
var trimmed = mtc.Trim('{', '}');
var sharp = trimmed.IndexOf('#');
var regex = trimmed.Substring(sharp + 1);
if (!_regexes.ContainsKey(regex))
{
_regexes[regex] = new Regex(regex, RegexOptions.CultureInvariant | RegexOptions.Compiled |
RegexOptions.ExplicitCapture);
}
var match = _regexes[regex].Match(spl);
if (!match.Success) return false;
foreach (string groupName in _regexes[regex].GetGroupNames())
{
if (match.Groups[groupName].Success)
{
data[groupName] = match.Groups[groupName].Value;
};
}
return true;
}
public bool CanHandleRequest(String url, string method = null)
{
foreach (var realPath in _realPaths)
{
if (VerifyHttpMethod(method, realPath))
{
var res = BuildPath(url, realPath.Path);
if (res != null) return true;
}
}
return false;
//return OldCanHandleRequest(url);
}
private static bool VerifyHttpMethod(string method, Request realPath)
{
return method == null || realPath.Methods.Count == 0 || realPath.Methods.Any(a => string.Compare(a, method, true) == 0);
}
public SerializableResponse HandleRequest(SerializableRequest request)
{
foreach (var realPath in _realPaths)
{
if (VerifyHttpMethod(request.Method, realPath))
{
var res = BuildPath(request.Url, realPath.Path);
if (res != null)
{
request.PathParams = res;
return _handler(request);
}
}
}
throw new Exception();
//return OldHandleRequest(request);
}
protected SerializableResponse JsonResponse(Object data)
{
var sr = new SerializableResponse
{
ContentType = "application/json"
};
sr.Headers["Date"] = DateTime.Now.ToString("r");
sr.Headers["Last-Modified"] = DateTime.Now.ToString("r");
sr.Content = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
return sr;
}
protected SerializableResponse JsonResponseString(String data)
{
var sr = new SerializableResponse
{
ContentType = "application/json"
};
sr.Headers["Date"] = DateTime.Now.ToString("r");
sr.Headers["Last-Modified"] = DateTime.Now.ToString("r");
sr.Content = Encoding.UTF8.GetBytes(data);
return sr;
}
}
}