-
Notifications
You must be signed in to change notification settings - Fork 4
/
classification_scheme.js
195 lines (173 loc) · 6.44 KB
/
classification_scheme.js
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
/**
* classification_scheme.js
*
* Manages Classification Scheme loading and checking
*/
import { readFile, readFileSync } from "fs";
import chalk from "chalk";
import { AvlTree } from "@datastructures-js/binary-search-tree";
import { parseXmlString } from "libxmljs2";
import fetchS from "sync-fetch";
import { dvb } from "./DVB_definitions.js";
import handleErrors from "./fetch_err_handler.js";
import { hasChild } from "./schema_checks.js";
import { isHTTPURL } from "./pattern_checks.js";
export const CS_URI_DELIMITER = ":";
/**
* Constructs a linear list of terms from a heirarical clssification schemes which are read from an XML document and parsed by libxmljs
*
* @param {String} CSuri the classification scheme domian
* @param {Object} term the classification scheme term that may include nested subterms
* @param {boolean} leafNodesOnly flag to indicate if only the leaf <term> values are to be loaded
*/
function addCSTerm(vals, CSuri, term, leafNodesOnly = false) {
if (term.type() != "element") return;
if (term.name() == dvb.e_Term) {
if (!leafNodesOnly || (leafNodesOnly && !hasChild(term, dvb.e_Term))) if (term.attr(dvb.a_termID)) vals.push(`${CSuri}${CS_URI_DELIMITER}${term.attr(dvb.a_termID).value()}`);
let st = 0,
subTerm;
while ((subTerm = term.child(st++)) != null) addCSTerm(vals, CSuri, subTerm, leafNodesOnly);
}
}
/**
* load the hierarical values from an XML classification scheme document into a linear list
*
* @param {String} xmlCS the XML document of the classification scheme
* @param {boolean} leafNodesOnly flag to indicate if only the leaf <term> values are to be loaded
* @returns {Object} values parsed from the classification scheme in .vals and uri of classification scheme in .uri
*/
function loadClassificationScheme(xmlCS, leafNodesOnly = false) {
let rc = { uri: null, vals: [] };
if (!xmlCS) return rc;
const CSnamespace = xmlCS.root().attr(dvb.a_uri);
if (!CSnamespace) return rc;
rc.uri = CSnamespace.value();
let t = 0,
term;
while ((term = xmlCS.root().child(t++)) != null) addCSTerm(rc.vals, rc.uri, term, leafNodesOnly);
return rc;
}
export default class ClassificationScheme {
#values;
#schemes;
#leafsOnly;
constructor() {
this.#values = new AvlTree();
this.#schemes = [];
this.#leafsOnly = false;
loadClassificationScheme.bind(this);
}
count() {
return this.#values.count();
}
empty() {
this.#values.clear();
this.#schemes = [];
}
insertValue(key, value = true) {
if (key != "") this.#values.insert(key, value);
}
valuesRange() {
return this.#leafsOnly ? "-only leaf nodes are used from the CS" : "all nodes in the CS are used";
}
/**
* read a classification scheme from a URL and load its hierarical values into a linear list
*
* @param {String} csURL URL to the classification scheme
*/
#loadFromURL(csURL, async = true) {
const isHTTPurl = isHTTPURL(csURL);
console.log(chalk.yellow(`${isHTTPurl ? "" : "--> NOT "}retrieving CS (${this.#leafsOnly ? "leaf" : "all"} nodes) from ${csURL} via fetch()`));
if (!isHTTPurl) return;
if (async)
fetch(csURL)
.then(handleErrors)
.then((response) => response.text())
.then((strXML) => loadClassificationScheme(parseXmlString(strXML), this.#leafsOnly))
.then((res) => {
res.vals.forEach((e) => {
this.insertValue(e, true);
});
this.#schemes.push(res.uri);
})
.catch((error) => console.log(chalk.red(`error (${error}) retrieving ${csURL}`)));
else {
let resp = null;
try {
resp = fetchS(csURL);
} catch (error) {
console.log(chalk.red(error.message));
}
if (resp) {
if (resp.ok) {
let CStext = loadClassificationScheme(parseXmlString(resp.text()), this.#leafsOnly);
CStext.vals.forEach((e) => {
this.insertValue(e, true);
});
this.#schemes.push(CStext.uri);
} else console.log(chalk.red(`error (${resp.status}:${resp.statusText}) handling ${ref}`));
}
}
}
/**
* read a classification scheme from a local file and load its hierarical values into a linear list
*
* @param {String} classificationScheme the filename of the classification scheme
*/
#loadFromFile(classificationScheme, async = true) {
console.log(chalk.yellow(`reading CS (${this.#leafsOnly ? "leaf" : "all"} nodes) from ${classificationScheme}`));
if (async)
readFile(classificationScheme, { encoding: "utf-8" }, (err, data) => {
if (!err) {
let res = loadClassificationScheme(parseXmlString(data.replace(/(\r\n|\n|\r|\t)/gm, "")), this.#leafsOnly);
res.vals.forEach((e) => {
this.insertValue(e, true);
});
this.#schemes.push(res.uri);
} else console.log(chalk.red(err));
});
else {
let buff = readFileSync(classificationScheme, { encoding: "utf-8" });
let data = buff.toString();
let res = loadClassificationScheme(parseXmlString(data.replace(/(\r\n|\n|\r|\t)/gm, "")), this.#leafsOnly);
res.vals.forEach((e) => {
this.insertValue(e, true);
});
this.#schemes.push(res.uri);
}
}
loadCS(options, async = true) {
if (!options) options = {};
if (!Object.prototype.hasOwnProperty.call(options, "leafNodesOnly")) options.leafNodesOnly = false;
this.#leafsOnly = options.leafNodesOnly;
if (options.file) this.#loadFromFile(options.file, async);
if (options.files) options.files.forEach((file) => this.#loadFromFile(file, async));
if (options.url) this.#loadFromURL(options.url, async);
if (options.urls) options.urls.forEach((url) => this.#loadFromURL(url, async));
}
/**
* determines if the value is in the classification scheme
*
* @param {String} value The value to check for existance
* @returns {boolean} true if value is in the classification scheme
*/
isIn(value) {
return this.#values.has(value);
}
/**
* determines if the scheme used by the provided term is included
* @param {String} term The term whose scheme should bechecked
* @returns {boolean}
*/
hasScheme(term) {
const pos = term.lastIndexOf(CS_URI_DELIMITER);
if (pos == -1) return false;
return this.#schemes.includes(term.slice(0, pos));
}
showMe(prefix = "") {
console.log(`in showme("${prefix}"), count=${this.#values.count()}`);
this.#values.traverseInOrder((node) => {
if (prefix == "" || node.getValue().beginsWith(prefix)) console.log(node.getValue());
});
}
}