-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
317 lines (286 loc) · 10.4 KB
/
main.py
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
#
# Copyright 2012-2013 Ontology Engineering Group, Universidad Politecnica de Madrid, Spain
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @author Ahmad Alobaid
#
import traceback
import os
import xml.etree.ElementTree as ET
# import rdfxml
import argparse
import requests
from OntologyGraph import OntologyGraph
VERBOSE = False
def get_oops_pitfalls(ontology_dir):
try:
f = open(ontology_dir, 'r')
ont_file_content = f.read()
f.close()
except:
f = open(ontology_dir, 'r', encoding='utf-8')
ont_file_content = f.read()
f.close()
url = "http://oops.linkeddata.es/rest"
xml_content = """
<?xml version="1.0" encoding="UTF-8"?>
<OOPSRequest>
<OntologyUrl></OntologyUrl>
<OntologyContent>%s</OntologyContent>
<Pitfalls>2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 19, 20, 21, 22, 24, 25, 25, 26, 27, 28, 29</Pitfalls>
<OutputFormat>RDF/XML</OutputFormat>
</OOPSRequest>
""" % (ont_file_content)
headers = {'Content-Type': 'application/xml',
'Connection': 'Keep-Alive',
'Content-Length': str(len(xml_content)),
'Accept-Charset': 'utf-8'
}
oops_reply = requests.post(url, data=xml_content.encode('utf-8'), headers=headers)
oops_reply = oops_reply.text
if VERBOSE:
print("oops_reply: ")
print(oops_reply)
if 'http://www.oeg-upm.net/oops/unexpected_error' in oops_reply:
raise Exception("unexpected error in OOPS webservice")
if oops_reply[:50] == '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">':
if '<title>502 Proxy Error</title>' in oops_reply:
raise Exception('Ontology is too big for OOPS')
else:
raise Exception('Generic error from OOPS')
pitfalls = parse_oops_issues(oops_reply)
return pitfalls
def create_report(pitfalls, ontology_dir):
ont_graph = OntologyGraph(ontology_dir)
panels = []
for i, p in enumerate(pitfalls):
p["id"] = i
panel = get_panel(p)
panels.append(panel)
base_dir = os.path.dirname(os.path.realpath(__file__))
if VERBOSE:
print("base_dir: %s" % base_dir)
print("panels: ")
print(panels)
try:
f = open(os.path.join(base_dir, "report.html"))
html = f.read()
f.close()
except:
f = open(os.path.join(base_dir, "report.html"), encoding='utf-8')
html = f.read()
f.close()
report = html % (
ont_graph.get_uri(), ont_graph.get_title(), ont_graph.get_uri(), ont_graph.get_title(), ont_graph.get_uri(),
ont_graph.get_uri(), ont_graph.get_version(), "".join(panels))
return report
def create_md_report(pitfalls, ontology_dir):
ont_graph = OntologyGraph(ontology_dir)
panels = []
for i, p in enumerate(pitfalls):
p["id"] = i
panel = get_md_panel(p)
panels.append(panel)
base_dir = os.path.dirname(os.path.realpath(__file__))
if VERBOSE:
print("base_dir: %s" % base_dir)
print("panels: ")
print(panels)
try:
f = open(os.path.join(base_dir, "report.md"))
html = f.read()
f.close()
except:
f = open(os.path.join(base_dir, "report.md"), encoding='utf-8')
html = f.read()
f.close()
report = html % (
ont_graph.get_title(), "".join(panels))
return report
def save_report(report, output_dir):
# maybe we can add some kind of options of the output file name
# file_name = ontology_dir.split(os.sep)[-1]
# file_name+= ".html"
file_name = "oops.html"
if VERBOSE:
print("save_report> output filename: %s" % file_name)
print("save_report> output dir: %s" % output_dir)
if os.path.exists(output_dir):
print("save_report> exists: "+output_dir)
else:
print("save_report> does not exists: " + output_dir)
try:
f = open(os.path.join(output_dir, file_name), 'w')
f.write(report)
except:
f = open(os.path.join(output_dir, file_name), 'w', encoding='utf-8')
f.write(report)
f.close()
def save_md_report(report, output_dir):
# maybe we can add some kind of options of the output file name
# file_name = ontology_dir.split(os.sep)[-1]
# file_name+= ".html"
file_name = "oops.md"
if VERBOSE:
print("output filename: %s" % file_name)
print("output dir: %s" % output_dir)
try:
f = open(os.path.join(output_dir, file_name), 'w')
f.write(report)
except:
f = open(os.path.join(output_dir, file_name), 'w', encoding='utf-8')
f.write(report)
f.close()
def parse_oops_issues(oops_rdf):
"""
To parse the oops_rdf response
:param oops_rdf: rdfxml OOPS! reply
:return: list of pitalls, each as a dict
"""
root = ET.fromstring(oops_rdf)
pitfalls = []
for child in root:
pitf = get_desc(child)
if pitf is not None:
pitfalls.append(pitf)
if VERBOSE:
print("number of pitfalls: %d" % len(pitfalls))
print(pitfalls)
return pitfalls
def get_desc(desc_xml):
"""
From XML child to dict
:param desc_xml:
:return:
"""
has_code = ""
has_name = ""
has_desc = ""
has_importance = ""
has_num_aff = ""
affected_elements = []
for att in desc_xml:
if att.tag == '{http://oops.linkeddata.es/def#}hasAffectedElement':
affected_elements.append(att.text)
elif att.tag == '{http://oops.linkeddata.es/def#}hasImportanceLevel':
has_importance = att.text
elif att.tag == '{http://oops.linkeddata.es/def#}hasName':
has_name = att.text
elif att.tag == '{http://oops.linkeddata.es/def#}hasNumberAffectedElements':
has_num_aff = att.text
elif att.tag == '{http://oops.linkeddata.es/def#}hasDescription':
has_desc = att.text
elif att.tag == '{http://oops.linkeddata.es/def#}hasCode':
has_code = att.text
desc = {
'code': has_code,
'name': has_name,
'description': has_desc,
'importance': has_importance,
'num_of_affected_elements': has_num_aff,
'affected_elements': affected_elements
}
if has_code == '':
return None
return desc
def get_panel(pitfall):
"""
:param pitfall: as a dict
:return: html of a single pitfall
"""
# print("In get panel")
if VERBOSE:
print("\n\n========================================\npitfall: ")
print(pitfall)
labels = {
"Minor": "label-minor",
"Important": "label-warning",
"Critical": "label-danger"
}
# print("pitfall: ")
# print(pitfall)
if "SUGGESTION" in pitfall["code"]:
pitfall["name"] = pitfall["code"].replace("SUGGESTION: ", "")
pitfall["importance"] = "Minor"
label_key = pitfall["importance"]
# label_key = str(pitfall["importance"]).replace('"','')
return """
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#collapse%d">
%s. %s<span style="float: right;">%s cases detected. <span class="label %s">%s</span></span></a>
</h4>
</div>
<div id="collapse%d" class="panel-collapse collapse">
<div class="panel-body">
<p>%s</p>
</div>
</div>
</div>
""" % (pitfall["id"], pitfall["code"], pitfall["name"], pitfall["num_of_affected_elements"],
labels[label_key], pitfall["importance"], pitfall["id"], pitfall["description"])
def get_md_panel(pitfall):
"""
:param pitfall: as a dict
:return: html of a single pitfall
"""
# print("In get panel")
if VERBOSE:
print("\n\n========================================\npitfall: ")
print(pitfall)
labels = {
"Minor": "https://raw.githubusercontent.com/OnToology/oops-report/master/sample/minor.png",
"Important": "https://raw.githubusercontent.com/OnToology/oops-report/master/sample/important.png",
"Critical": "https://raw.githubusercontent.com/OnToology/oops-report/master/sample/critical.png"
}
if "SUGGESTION" in pitfall["code"]:
pitfall["name"] = pitfall["code"].replace("SUGGESTION: ", "")
pitfall["importance"] = "Minor"
label_key = pitfall["importance"]
# label_key = str(pitfall["importance"]).replace('"','')
return """
#### %s. %s <img src="%s" height="15px"> (%s cases detected).
*%s*
""" % (pitfall["code"], pitfall["name"], labels[label_key], pitfall["num_of_affected_elements"], pitfall["description"].strip())
def workflow(output_dir, ontology_dir):
pitfalls = get_oops_pitfalls(ontology_dir=ontology_dir)
report = create_report(pitfalls, ontology_dir)
save_report(report=report, output_dir=output_dir)
md_report = create_md_report(pitfalls, ontology_dir)
save_md_report(md_report, output_dir)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Generate a nice HTML from')
parser.add_argument('--outputdir', help='the output directory')
parser.add_argument('--ontologydir', help='the local directory to the ontology')
parser.add_argument('--verbose', help='the local directory to the ontology')
args = parser.parse_args()
try:
if args.verbose:
if args.verbose.lower() in ('yes', 'true', 't', 'y', '1'):
VERBOSE = True
if not args.outputdir:
print("ERROR: missing --outputdir")
elif not args.ontologydir:
print("ERROR: missing --ontologydir")
else:
if VERBOSE:
print("output_dir: <%s>" % args.outputdir)
print("ontology_dir: <%s>" % args.ontologydir)
workflow(output_dir=args.outputdir, ontology_dir=args.ontologydir)
print("report is generated successfully")
except Exception as e:
print("exception in generating oops error: %s" % str(e))
if VERBOSE:
traceback.print_exc()