-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
493 lines (423 loc) · 14.4 KB
/
Program.cs
File metadata and controls
493 lines (423 loc) · 14.4 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
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Serialization;
using CorpusExplorer.Sdk.Ecosystem;
using CorpusExplorer.Sdk.Ecosystem.Model;
using CorpusExplorer.Sdk.Helper;
using CorpusExplorer.Sdk.Model.Cache;
using CorpusExplorer.Sdk.Model.Extension;
using CorpusExplorer.Sdk.Utils.DataTableWriter;
using CorpusExplorer.Sdk.Utils.DataTableWriter.Abstract;
using CorpusExplorer.Terminal.Console.Helper;
using CorpusExplorer.Terminal.Console.Properties;
#if Featherweight
#else
using CorpusExplorer.Terminal.Console.Web;
#endif
using CorpusExplorer.Terminal.Console.Xml.Model;
using CorpusExplorer.Terminal.Console.Xml.Processor;
namespace CorpusExplorer.Terminal.Console
{
public class Program
{
// private static readonly Dictionary<string, IAction> _actions = new Dictionary<string, IAction>();
private static readonly string _appPath =
Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "cec.exe");
private static AbstractTableWriter _writer = new TsvTableWriter();
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
try
{
var dll = args.Name.Substring(0, args.Name.IndexOf(",", StringComparison.Ordinal)) + ".dll";
var path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
@"CorpusExplorer\App",
dll);
return !File.Exists(path) ? null : Assembly.LoadFrom(path);
}
catch
{
return null;
}
}
private static void DebugScript(string[] args)
{
var path = args[0].Replace("DEBUG:", "").Replace("\"", "");
if (ProcessXmlScript(path))
return;
var lines = File.ReadAllLines(path, Configuration.Encoding);
System.Console.WriteLine(Resources.ExecuteScript, path);
for (var i = 0; i < lines.Length; i++)
try
{
var line = lines[i];
System.Console.Write($"[{i + 1:D3}/{lines.Length:D3}] {line}");
StartProcessCec(line);
System.Console.WriteLine(Resources.PointPointPointOk);
}
catch (Exception ex)
{
System.Console.WriteLine(ex.Message);
System.Console.WriteLine(ex.StackTrace);
}
}
private class PInfo
{
public DateTime DateTimeStart { get; set; }
public DateTime DateTimeLoad { get; set; }
public double SizeAppInRam { get; set; }
public double SizeCorpusInRam { get; set; }
public double SizeMaxRamUse { get; set; }
public void Print()
{
var end = DateTime.Now;
System.Console.WriteLine($"RAM (app): {SizeAppInRam / 1024 / 1024}");
System.Console.WriteLine($"Load corpus: {(DateTimeLoad - DateTimeStart).Milliseconds}ms");
System.Console.WriteLine($"RAM (corpus): {SizeCorpusInRam / 1024 / 1024} MB");
System.Console.WriteLine($"Execute action: {(end - DateTimeLoad).Milliseconds}ms");
System.Console.WriteLine($"RAM (all): {SizeMaxRamUse / 1024 / 1024} MB");
}
}
private static PInfo _pInfo = null;
private static void Execute(string[] args)
{
if (args == null || args.Length == 0)
{
PrintHelp(true);
return;
}
// --> Start of dev-relevant arguments
if (args.Length > 0 && args[0] == "/PINFO")
{
var tmp = args.ToList();
tmp.RemoveAt(0);
args = tmp.ToArray();
_pInfo = new PInfo
{
DateTimeStart = DateTime.Now,
SizeAppInRam = GC.GetTotalMemory(false)
};
}
if (args.Length > 0 && args[0] == "/WAIT")
{
System.Console.WriteLine("...PRESS ENTER TO CONTINUE...");
System.Console.ReadLine();
var tmp = args.ToList();
tmp.RemoveAt(0);
args = tmp.ToArray();
}
if (args.Length == 1 && args[0] == "--github")
{
PrintDocs();
return;
}
// <-- End of dev-relevant arguments
if (args.Length > 0 && args[0] == "/WAIT")
{
System.Console.WriteLine("...PRESS ENTER TO CONTINUE...");
System.Console.ReadLine();
var tmp = args.ToList();
tmp.RemoveAt(0);
args = tmp.ToArray();
}
if (args[0].StartsWith("F:") || args[0].StartsWith("FNT:"))
{
_writer = Configuration.GetTableWriter(args[0]);
var list = new List<string>(args);
list.RemoveAt(0);
args = list.ToArray();
}
if (args[0].StartsWith("PORT:") || args[0].StartsWith("IP:"))
{
ExecuteWebservice(args);
return;
}
if (args[0].StartsWith("FILE:"))
{
ExecuteSkript(args);
return;
}
if (args[0].StartsWith("DEBUG:"))
{
System.Console.WriteLine("CEC DEBUG-WAIT [PRESS -ENTER- TO CONTINUE]");
System.Console.ReadLine();
DebugScript(args);
return;
}
if (args[0].ToLowerInvariant() == "shell")
{
ExecuteShell();
_writer.Destroy();
return;
}
if (args.Length == 1 && File.Exists(args[0]))
{
args[0] = "FILE:" + args[0];
ExecuteSkript(args);
return;
}
if (args.Length == 1 && args[0] == "--session")
{
SessionMode();
return;
}
ExecuteDirect(args);
_writer.Destroy();
}
private static void SessionMode()
{
var stream = System.Console.OpenStandardInput();
var reader = new StreamReader(stream, Encoding.UTF8);
var xml = reader.ReadToEnd();
reader.Close();
stream.Close();
session session;
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
var serializer = new XmlSerializer(typeof(session));
session = (session)serializer.Deserialize(ms);
}
try
{
XmlScriptProcessor.ExecuteSession(session);
}
catch (Exception ex)
{
XmlScriptProcessor.LogError(ex);
}
}
private static void Wait(string cmd)
{
var process = Process.GetProcessById(int.Parse(cmd.Replace("WAIT:", "")));
System.Console.WriteLine($"WAIT 4: {process.Id} - {process.ProcessName}");
process.WaitForExit();
}
private static void PrintDocs()
{
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
PrintHelp(false);
System.Console.WriteLine("---");
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
PrintHelp(false);
}
private static void ExecuteWebservice(string[] args)
{
ConsoleHelper.PrintHeader();
var ip = "127.0.0.1";
var port = 2312;
var file = "";
var timeout = 120;
foreach (var arg in args)
{
if (arg.StartsWith("IP:"))
ip = arg.Replace("IP:", "");
else if (arg.StartsWith("PORT:"))
port = int.Parse(arg.Replace("PORT:", ""));
else if (arg.StartsWith("TIMEOUT:"))
timeout = int.Parse(arg.Replace("TIMEOUT:", ""));
else
file = arg;
}
#if Featherweight
#else
if (file.Contains("#"))
{
var ws = new WebService(_writer, ip, port, file, timeout);
ws.Run();
}
else
{
var ws = new WebService(_writer, ip, port, file, timeout);
ws.Run();
}
#endif
}
private static void ExecuteDirect(string[] args)
{
var task = args[1].ToLowerInvariant();
var action = Configuration.GetConsoleAction(task);
if (action == null)
return;
var corpus = args[0] == "NULL" ? CorpusNullHelper.Corpus : CorpusLoadHelper.LoadCorpus(args[0]);
var selection = corpus?.ToSelection();
if (selection == null)
return;
if(_pInfo != null)
{
_pInfo.DateTimeLoad = DateTime.Now;
_pInfo.SizeCorpusInRam = GC.GetTotalMemory(false);
}
var temp = args.ToList();
temp.RemoveAt(0); // CorpusFile (no longer needed)
temp.RemoveAt(0); // Action (no longer needed)
action.Execute(selection, temp.ToArray(), _writer);
if (_pInfo != null)
{
_pInfo.SizeMaxRamUse = GC.GetTotalMemory(false);
_pInfo.Print();
}
}
private static void ExecuteShell()
{
ConsoleHelper.PrintHeader();
System.Console.WriteLine(Resources.BaseHelp);
System.Console.WriteLine();
var history = new List<string>();
while (true)
{
System.Console.Write("cec.exe ");
var command = System.Console.ReadLine();
if (command == null)
continue;
switch (command)
{
case "quit":
case "exit":
return;
case "help":
PrintHelp(true);
break;
default:
if (command.StartsWith("SAVE:"))
{
File.WriteAllLines(command.Replace("SAVE:", ""), history.ToArray());
}
else
{
history.Add(command);
StartProcessCec(command);
}
break;
}
}
}
private static void ExecuteSkript(string[] args)
{
var path = args[0].Replace("FILE:", "").Replace("\"", "");
if (ProcessXmlScript(path))
return;
var lines = File.ReadAllLines(path, Configuration.Encoding);
foreach (var line in lines)
StartProcessCec(line);
}
private static void Main(string[] args)
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
CorpusExplorerEcosystem.Initialize(new CacheStrategyDisableCaching());
System.Console.InputEncoding = System.Console.OutputEncoding = Configuration.Encoding;
CultureInfo.DefaultThreadCurrentCulture = Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Execute(args);
}
private static void PrintHelp(bool clear)
{
ConsoleHelper.PrintHeader(clear);
System.Console.WriteLine(Resources.HelpModes);
System.Console.WriteLine(Resources.HelpImportHeader);
var importer = Configuration.AddonImporters.GetReflectedTypeNameList("Importer");
foreach (var x in importer) System.Console.WriteLine(Resources.HelpImportPattern, x);
System.Console.WriteLine(Resources.HelpImportExample);
var scraper = Configuration.AddonScrapers.GetReflectedTypeNameList("Scraper");
System.Console.WriteLine(Resources.HelpAnnotateHeader);
foreach (var x in scraper)
System.Console.WriteLine(Resources.HelpAnnotatePattern, x);
System.Console.WriteLine(Resources.HelpAnnotateNote);
var tagger = Configuration.AddonTaggers.GetReflectedTypeNameList(""); // ignore hier nicht, da Tagger wie in TreeTagger Namensbestandteil ist. Ignore nur bei Namenssuche.
System.Console.WriteLine(Resources.HelpAnnotateTaggerHeader);
foreach (var x in tagger)
{
System.Console.Write(Resources.HelpAnnotateTaggerPattern, x);
System.Console.WriteLine(Resources.HelpAnnotateTaggerLanguagePattern, string.Join(", ", Configuration.AddonTaggers.GetReflectedType(x, "Tagger").LanguagesAvailabel));
}
System.Console.WriteLine(Resources.HelpAnnotateExample);
System.Console.WriteLine(Resources.HelpOutputHeader);
var exporter = Configuration.AddonExporters.GetReflectedTypeNameList("Exporter");
foreach (var x in exporter)
System.Console.WriteLine(Resources.HelpOutputPattern, x);
System.Console.WriteLine(Resources.HelpOutputExample);
System.Console.WriteLine(Resources.HelpQueryClusterSyntax);
System.Console.WriteLine(Resources.HelpActionHeader);
foreach (var action in Configuration.AddonConsoleActions.OrderBy(x => x.Action))
System.Console.WriteLine(Resources.HelpActionPattern, action.Description);
System.Console.WriteLine(Resources.HelpActionExample);
System.Console.WriteLine(Resources.HelpScripting);
System.Console.WriteLine(Resources.HelpFormatHeader);
foreach (var x in Configuration.AddonTableWriter.OrderBy(x => x.Value.WriteTid))
System.Console.WriteLine($"{x.Value.TableWriterTag} - {x.Value.Description}");
System.Console.WriteLine(Resources.HelpFormatFooter);
}
private static bool ProcessXmlScript(string path)
{
try
{
Task.Run(MyGcCollect);
XmlScriptProcessor.Process(path);
return true;
}
catch
{
return false;
}
}
private static async Task MyGcCollect()
{
while (true)
{
await Task.Delay(TimeSpan.FromMinutes(5));
Task.Run(GC.Collect);
}
}
private static string[] _separator = { " > " };
private static void StartProcessCec(string argument)
{
if (string.IsNullOrEmpty(argument))
return;
if (argument.StartsWith("#"))
{
System.Console.WriteLine(argument);
return;
}
if (argument.Contains(" > "))
{
var split = argument.Split(_separator, StringSplitOptions.None).ToList();
argument = split[0];
var process = Process.Start(new ProcessStartInfo
{
Arguments = !argument.StartsWith("F:") ? $"{_writer.TableWriterTag} {argument}" : argument,
CreateNoWindow = true,
FileName = _appPath,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardOutput = true,
StandardOutputEncoding = Configuration.Encoding,
UseShellExecute = false
});
var res = process?.StandardOutput.ReadToEnd();
process?.WaitForExit();
File.WriteAllText(split[1], res, Configuration.Encoding);
}
else
{
var process = Process.Start(new ProcessStartInfo
{
Arguments = !argument.StartsWith("F:") ? $"{_writer.TableWriterTag} {argument}" : argument,
CreateNoWindow = true,
FileName = _appPath,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardOutput = true,
StandardOutputEncoding = Configuration.Encoding,
UseShellExecute = false
});
var res = process?.StandardOutput.ReadToEnd();
process?.WaitForExit();
System.Console.Out.Write(res);
}
}
}
}