-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathParserFactory.cs
More file actions
94 lines (79 loc) · 2.32 KB
/
ParserFactory.cs
File metadata and controls
94 lines (79 loc) · 2.32 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
using System;
using System.Collections.Generic;
using System.Reflection;
using KitchenPC.Context;
using KitchenPC.Recipes;
namespace KitchenPC.Parser
{
public interface IParser
{
NLP.Parser NlpParser { get; set; }
ParserResult Parse(Uri page);
}
public class ParserAttribute : Attribute
{
public string Domain { get; private set; }
public ParserAttribute(string domain)
{
Domain = domain;
}
}
public class ParserResult
{
public enum Status { Success, UnknownIngredient, MissingData, BadData }
public Status Result { get; private set; }
public IEnumerable<String> UnknownIngredients { get; set; }
public Recipe Recipe { get; private set; }
public ParserResult(Status result)
{
Result = result;
}
public ParserResult(Recipe recipe)
{
Result = Status.Success;
Recipe = recipe;
}
}
public static class ParserFactory
{
private static IKPCContext context;
private static Dictionary<String, Type> parserMap;
private static Type defaultParser;
public static void Initialize(IKPCContext context, Assembly assembly, Type defaultParser)
{
ParserFactory.context = context;
parserMap = new Dictionary<string, Type>();
ParserFactory.defaultParser = defaultParser;
var types = assembly.GetTypes();
foreach (var t in types)
{
var att = t.GetCustomAttributes(typeof(ParserAttribute), false);
foreach(var a in att)
{
var domain = ((ParserAttribute)a).Domain.Trim().ToLower();
if (parserMap.ContainsKey(domain))
{
throw new DuplicateParser(domain);
}
parserMap.Add(domain, t);
}
}
}
public static IParser GetParser(string uri)
{
return GetParser(new Uri(uri));
}
public static IParser GetParser(Uri uri)
{
Type t;
if (!parserMap.TryGetValue(uri.Host.ToLower(), out t))
{
t = defaultParser;
}
var constructor = t.GetConstructor(new Type[0]);
var p = constructor.Invoke(null) as IParser;
p.NlpParser = context.Parser;
return p;
}
}
}