object.vala 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. /********************************************************************
  2. # Copyright 2016-2017 Daniel 'grindhold' Brendle
  3. #
  4. # This file is part of liboparl.
  5. #
  6. # liboparl is free software: you can redistribute it and/or
  7. # modify it under the terms of the GNU Lesser General Public License
  8. # as published by the Free Software Foundation, either
  9. # version 3 of the License, or (at your option) any later
  10. # version.
  11. #
  12. # liboparl is distributed in the hope that it will be
  13. # useful, but WITHOUT ANY WARRANTY; without even the implied
  14. # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  15. # PURPOSE. See the GNU Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public
  18. # License along with liboparl.
  19. # If not, see http://www.gnu.org/licenses/.
  20. *********************************************************************/
  21. namespace OParl {
  22. /**
  23. * This class represents aspects that are common to any
  24. * Object yielded by an OParl endpoint.
  25. */
  26. public abstract class Object : GLib.Object {
  27. public static HashTable<string,string> name_map;
  28. /**
  29. * Contains a unique identifier, the object's URL to be precise.
  30. * This field is ''mandatory'' for any Object
  31. */
  32. public string id {get; protected set; default=null;}
  33. /**
  34. * Contains the original type attribute of an object
  35. */
  36. public string oparl_type { get; protected set; default="invalid type"; }
  37. /**
  38. * Used to contain the name of an object. This field is mandatory
  39. * for most objects.
  40. */
  41. public string name {get; protected set;}
  42. /**
  43. * Contains a short form of the object's name when this is
  44. * convenient. An example may be "Congress" instead of "United
  45. * States Congress"
  46. */
  47. public string? short_name {get; protected set; default=null;}
  48. /**
  49. * Determines which license the data of the object is published
  50. * under.
  51. *
  52. * If license is used in a {@link OParl.System} or an
  53. * {@link OParl.Body} object, it means that all their subordinated
  54. * objects are published under the same license.
  55. * Single objects may override this collective license by specifying
  56. * their own license-property.
  57. * It is ''recommended'' to use one license per {@link OParl.System}
  58. */
  59. public string license {get; protected set;}
  60. /**
  61. * A timestamp that determines when the object has been
  62. * created. This is ''mandatory'' for all objects
  63. */
  64. public GLib.DateTime created {get; protected set;}
  65. /**
  66. * A timestamp that determines when the object has last been changed.
  67. * Servers guarantee that this timestamp is always accurate. For a
  68. * client it's the best way to check for changes in objects.
  69. * It's ''mandatory'' for all objects.
  70. * If an object has been deleted, this timestamp contains the date and
  71. * time of deletion.
  72. */
  73. public GLib.DateTime modified {get; protected set;}
  74. /**
  75. * Contains an array of tags that are meant to ''optionally'' categorize
  76. * the object.
  77. */
  78. public string[] keyword {get; protected set;}
  79. /**
  80. * Represents a hyperlink to this object in the parliamentarian information
  81. * system that feeds the OParl endpoint. This is ''optional'' as not every
  82. * OParl endpoint must have a webbased parliamentarian information system
  83. * behind it.
  84. */
  85. public string web {get; protected set;}
  86. /**
  87. * Determines whether the object has been deleted. ''mandatory''
  88. */
  89. public bool deleted {get; protected set;}
  90. /**
  91. * Vendor Attributes
  92. *
  93. * Vendor attributes allow OParl-providers to deliver additional data
  94. * That has not been standadized in the OParl standard.
  95. */
  96. public HashTable<string, string> vendor_attributes {get; protected set;}
  97. /**
  98. * A reference to the client that made this object.
  99. */
  100. internal Client client;
  101. internal virtual void set_client(Client c) {
  102. this.client = c;
  103. }
  104. internal static void populate_name_map() {
  105. name_map = new HashTable<string,string>(str_hash, str_equal);
  106. name_map.insert("id","id");
  107. name_map.insert("name","name");
  108. name_map.insert("shortName","short_name");
  109. name_map.insert("license","license");
  110. name_map.insert("created","created");
  111. name_map.insert("modified","modified");
  112. name_map.insert("keyword","keyword");
  113. name_map.insert("web","web");
  114. name_map.insert("deleted","deleted");
  115. }
  116. /**
  117. * Triggers {@link OParl.Client.shit_happened} if the client is in non-strict-mode.
  118. * Otherwise it raises the error regularly
  119. */
  120. protected void handle_parse_error(ParsingError e) throws ParsingError {
  121. if (this.client.strict) {
  122. string annotated_message = e.message + _("Error occured in '%s'.").printf(this.id);
  123. e.message = annotated_message;
  124. throw e;
  125. } else {
  126. this.client.shit_happened(new ValidationResult(
  127. ErrorSeverity.ERROR,
  128. e.message,
  129. "",
  130. this.id
  131. ));
  132. }
  133. }
  134. /**
  135. * Verify the validity of a string attribute in an incoimg
  136. * JSON object and write it into the given target if all checks succeed
  137. */
  138. protected void parse_string(Object target, string name, Json.Node item, HashTable<string,string> name_map) throws OParl.ParsingError {
  139. try {
  140. if (item.get_node_type() != Json.NodeType.VALUE) {
  141. throw new ParsingError.EXPECTED_VALUE(_("Attribute '%s' must be a value.").printf(name));
  142. }
  143. if (item.get_value_type() != typeof(string)) {
  144. throw new ParsingError.INVALID_TYPE(_("Attribute '%s' must be a string.").printf(name));
  145. }
  146. target.set(name_map.get(name), item.get_string(),null);
  147. } catch (ParsingError e) {
  148. this.handle_parse_error(e);
  149. }
  150. }
  151. /**
  152. * Verify the validity of an array of string in an incoimg
  153. * JSON object and write it into the given target if all checks succeed
  154. */
  155. protected void parse_array_of_string(Object target, string name, Json.Node item, HashTable<string,string> name_map) throws OParl.ParsingError {
  156. try {
  157. if (item.get_node_type() != Json.NodeType.ARRAY) {
  158. throw new ParsingError.EXPECTED_ARRAY(_("Attribute '%s' must be an array.").printf(name));
  159. }
  160. Json.Array arr = item.get_array();
  161. string[] res = new string[arr.get_length()];
  162. for (int i = 0; i < item.get_array().get_length(); i++ ) {
  163. var element = item.get_array().get_element(i);
  164. if (element.get_node_type() != Json.NodeType.VALUE) {
  165. GLib.warning(_("Omitted array-element in '%s' because it was no Json-Value.").printf(name));
  166. return;
  167. }
  168. if (element.get_value_type() != typeof(string)) {
  169. throw new ParsingError.INVALID_TYPE(_("Arrayelement of '%s' must be a string.").printf(name));
  170. }
  171. res[i] = element.get_string();
  172. }
  173. this.set(name_map.get(name), res);
  174. } catch (ParsingError e) {
  175. this.handle_parse_error(e);
  176. }
  177. }
  178. /**
  179. * Verify the validity of a datetime in an incoimg
  180. * JSON object and write it into the given target if all checks succeed
  181. */
  182. protected void parse_datetime(Object target, string name, Json.Node item, HashTable<string,string> name_map, bool is_date=false) throws OParl.ParsingError {
  183. try {
  184. if (item.get_node_type() != Json.NodeType.VALUE) {
  185. throw new ParsingError.EXPECTED_VALUE(_("Attribute '%s' must be a value.").printf(name));
  186. }
  187. if (item.get_value_type() != typeof(string)) {
  188. throw new ParsingError.INVALID_TYPE(_("Attribute '%s' must be a string.").printf(name));
  189. }
  190. var tv = GLib.TimeVal();
  191. if (is_date) {
  192. tv.from_iso8601(item.get_string()+"T00:00:00+00:00");
  193. } else {
  194. tv.from_iso8601(item.get_string());
  195. }
  196. var dt = new GLib.DateTime.from_timeval_utc(tv);
  197. target.set_property(name_map.get(name), dt);
  198. } catch (ParsingError e) {
  199. this.handle_parse_error(e);
  200. }
  201. }
  202. /**
  203. * Verify the validity of a date in an incoimg
  204. * JSON object and write it into the given target if all checks succeed
  205. */
  206. protected void parse_date(Object target, string name, Json.Node item, HashTable<string,string> name_map) throws OParl.ParsingError {
  207. this.parse_datetime(target, name, item, name_map, true);
  208. }
  209. /**
  210. * Verify the validity of a boolean in an incoimg
  211. * JSON object and write it into the given target if all checks succeed
  212. */
  213. protected void parse_bool(Object target, string name, Json.Node item, HashTable<string,string> name_map) throws OParl.ParsingError {
  214. try {
  215. if (item.get_node_type() != Json.NodeType.VALUE) {
  216. throw new ParsingError.EXPECTED_VALUE(_("Attribute '%s' must be a value.").printf(name));
  217. }
  218. if (item.get_value_type() != typeof(bool)) {
  219. throw new ParsingError.INVALID_TYPE(_("Attribute '%s' must be a boolean.").printf(name));
  220. }
  221. target.set_property(name_map.get(name), item.get_boolean());
  222. } catch (ParsingError e) {
  223. this.handle_parse_error(e);
  224. }
  225. }
  226. protected void parse_int(Object target, string name, Json.Node item, HashTable<string,string> name_map) throws OParl.ParsingError {
  227. try {
  228. if (item.get_node_type() != Json.NodeType.VALUE) {
  229. throw new ParsingError.EXPECTED_VALUE(_("Attribute '%s' must be a value.").printf(name));
  230. }
  231. if (item.get_value_type() != typeof(int64)) {
  232. throw new ParsingError.INVALID_TYPE(_("Attribute '%s' must be an integer.").printf(name));
  233. }
  234. target.set_property(name_map.get(name), item.get_int());
  235. } catch (ParsingError e) {
  236. this.handle_parse_error(e);
  237. }
  238. }
  239. /**
  240. * Verify the validity of a string that represents an external object or
  241. * an external object list. Beware: liboparl does not know anything about
  242. * the validity of URLs. The resolve_url signal hands this over to you at resolve time.
  243. * There you may check the URLs validity with the HTTP library of your choice
  244. * When the check succeed the string will be written into a property with the
  245. * name of the field suffixed with "_url"
  246. */
  247. protected void parse_external(Object target, string name, Json.Node item, HashTable<string,string> name_map) throws OParl.ParsingError {
  248. try {
  249. if (item.get_node_type() != Json.NodeType.VALUE) {
  250. throw new ParsingError.EXPECTED_VALUE(_("Attribute '%s' must be a value.").printf(name));
  251. }
  252. if (item.get_value_type() != typeof(string)) {
  253. throw new ParsingError.INVALID_TYPE(_("Attribute '%s' must be a string.").printf(name));
  254. }
  255. this.set(name_map.get(name)+"_url", item.get_string());
  256. } catch (ParsingError e) {
  257. this.handle_parse_error(e);
  258. }
  259. }
  260. /**
  261. * Parses an array of URLs into a property
  262. */
  263. protected void parse_external_list(Object target, string name, Json.Node item, HashTable<string,string> name_map) throws OParl.ParsingError {
  264. try {
  265. if (item.get_node_type() != Json.NodeType.ARRAY) {
  266. throw new ParsingError.EXPECTED_VALUE(_("Attribute '%s' must be a array.").printf(name));
  267. }
  268. var arr = item.get_array();
  269. var res = new string[arr.get_length()];
  270. for (int i = 0; i < arr.get_length(); i++) {
  271. var element = arr.get_element(i);
  272. if (element.get_node_type() != Json.NodeType.VALUE) {
  273. throw new ParsingError.EXPECTED_VALUE(_("Element of '%s' must be a value.").printf(name));
  274. }
  275. if (element.get_value_type() != typeof(string)) {
  276. throw new ParsingError.INVALID_TYPE(_("Element of '%s' must be a string.").printf(name));
  277. }
  278. res[i] = element.get_string();
  279. }
  280. this.set(name_map.get(name)+"_url", res);
  281. } catch (ParsingError e) {
  282. this.handle_parse_error(e);
  283. }
  284. }
  285. internal virtual void parse(Object target, Json.Node n) throws ParsingError {
  286. // Prepare object
  287. if (n.get_node_type() != Json.NodeType.OBJECT)
  288. throw new ParsingError.EXPECTED_ROOT_OBJECT(_("I need an Object to parse"));
  289. unowned Json.Object o = n.get_object();
  290. // Read in Member values
  291. foreach (unowned string name in o.get_members()) {
  292. unowned Json.Node item = o.get_member(name);
  293. switch(name) {
  294. // Direct Read-in
  295. // - type
  296. case "type":
  297. this.oparl_type = item.get_string();
  298. break;
  299. // - strings
  300. case "id":
  301. case "name":
  302. case "shortName":
  303. case "license":
  304. case "web":
  305. this.parse_string(target, name, item, Object.name_map);
  306. break;
  307. // - string[]
  308. case "keyword":
  309. this.parse_array_of_string(target, name, item, Object.name_map);
  310. break;
  311. // - dates
  312. case "created":
  313. case "modified":
  314. this.parse_datetime(target, name, item, Object.name_map);
  315. break;
  316. // - booleans
  317. case "deleted":
  318. this.parse_bool(target, name, item, Object.name_map);
  319. break;
  320. default:
  321. if (item.get_node_type() == Json.NodeType.VALUE &&
  322. item.get_value_type() == typeof(string) &&
  323. ":" in name) {
  324. if (this.vendor_attributes == null)
  325. this.vendor_attributes = new HashTable<string,string>(str_hash, str_equal);
  326. this.vendor_attributes.set(name, item.get_string());
  327. }
  328. break;
  329. }
  330. }
  331. }
  332. protected List<ValidationResult>? validation_results = null;
  333. /**
  334. * Will yield a detailed report on where
  335. * an Object violates the OParl 1.0 specification.
  336. */
  337. public virtual unowned List<ValidationResult> validate() {
  338. this.validation_results = new List<ValidationResult>();
  339. if (this.id == null) {
  340. this.validation_results.append(new ValidationResult(
  341. ErrorSeverity.ERROR,
  342. _("Invalid 'id'"),
  343. _("The 'id'-field contains no id. The id field must contain a valid"
  344. + "url that can be used to retrieve the object via HTTP."),
  345. _("<id invalid>")
  346. ));
  347. }
  348. if (this.id == "") {
  349. this.validation_results.append(new ValidationResult(
  350. ErrorSeverity.ERROR,
  351. _("Invalid 'id'"),
  352. _("The 'id'-field contains no id. The id field must contain a valid"
  353. + "url that can be used to retrieve the object via HTTP."),
  354. _("<id invalid>")
  355. ));
  356. }
  357. if (this.license == null && (this is System)) {
  358. this.validation_results.append(new ValidationResult(
  359. ErrorSeverity.WARNING,
  360. _("Invalid 'license'"),
  361. _("The 'license'-field does not contain any value. It is recommended to "
  362. + "specify the license for all subordinated objects either in the System"
  363. + " object or in the Body objects"),
  364. this.id
  365. ));
  366. }
  367. if (this.license == null && this is Body) {
  368. System rootsystem = null;
  369. try {
  370. rootsystem = (this as Body).get_system();
  371. } catch (ParsingError e) {
  372. this.validation_results.append(new ValidationResult(
  373. ErrorSeverity.ERROR,
  374. _("Body with no 'system'"),
  375. _("This Body does not have a System."),
  376. this.id
  377. ));
  378. }
  379. if (rootsystem.license == null) {
  380. this.validation_results.append(new ValidationResult(
  381. ErrorSeverity.WARNING,
  382. _("Invalid 'license'"),
  383. _("The 'license'-field does not contain any value. It is recommended to "
  384. + "specify the license for all subordinated objects either in the System"
  385. + " object or in the Body objects"),
  386. this.id
  387. ));
  388. }
  389. }
  390. if (this.license == "") {
  391. this.validation_results.append(new ValidationResult(
  392. ErrorSeverity.ERROR,
  393. _("Invalid 'license'"),
  394. _("The 'license'-field contains an empty string. Please specify a valid "
  395. + "license"),
  396. this.id
  397. ));
  398. }
  399. if (this.license == null && !(this is System || this is Body)) {
  400. Body rootbody = null;
  401. try {
  402. rootbody = this.root_body();
  403. } catch (ParsingError e) {}
  404. System rootsystem = this.root_system(); // root_system already gracefully evaluates to null
  405. if (rootbody == null || rootsystem == null) {
  406. this.validation_results.append(new ValidationResult(
  407. ErrorSeverity.ERROR,
  408. _("Can't resolve root body or root system"),
  409. _("Every object needs to have license information. Typically, most "
  410. + "objects inherit their license from a superordinated Body or "
  411. + "system object of which neither could be resolved in this instance."),
  412. this.id
  413. ));
  414. }
  415. else if (rootbody.license == null && rootsystem.license == null ) {
  416. this.validation_results.append(new ValidationResult(
  417. ErrorSeverity.ERROR,
  418. _("Invalid 'license'"),
  419. _("Neither the superordinated Body nor the superordinated Body "
  420. + "specify a license for this object. Please either add a license "
  421. + "to this object or add one to the containing System or Body"),
  422. this.id
  423. ));
  424. }
  425. }
  426. return this.validation_results;
  427. }
  428. /**
  429. * Each object should implement this method as means to resolve the
  430. * body that this object originates from
  431. */
  432. internal abstract Body? root_body() throws ParsingError;
  433. /**
  434. * Tries to resolve which system this object
  435. * belongs to.
  436. * This method leverages the root_body method
  437. * to get the system.
  438. */
  439. internal virtual System? root_system() {
  440. try {
  441. Body? b = root_body();
  442. return b == null ? null : b.get_system();
  443. } catch (ParsingError e) {
  444. return null;
  445. }
  446. }
  447. /**
  448. * Fetches the object again and overrides the properties by newly
  449. * obtained values
  450. */
  451. public void refresh() throws OParl.ParsingError {
  452. var r = new Resolver(this.client);
  453. Object updated_obj = null;
  454. try {
  455. if (this.id == null) {
  456. throw new ParsingError.EXPECTED_VALUE(_("Expected valid id attribute, encountered: '%s'.").printf(name));
  457. }
  458. updated_obj = r.parse_url(this.id);
  459. if (updated_obj == null) {
  460. throw new ParsingError.EXPECTED_OBJECT(_("Could not parse updated object."));
  461. }
  462. } catch (OParl.ParsingError e) {
  463. this.handle_parse_error(e);
  464. }
  465. Type type = updated_obj.get_type();
  466. if (updated_obj.deleted) {
  467. this.deleted = true;
  468. return;
  469. }
  470. foreach (var property in ((ObjectClass)type.class_ref()).list_properties()) {
  471. if (property.name == "id") continue;
  472. var v = Value(property.value_type);
  473. updated_obj.get_property(property.name, ref v);
  474. if (v.holds(property.value_type)) {
  475. this.set_property(property.name, v);
  476. }
  477. }
  478. }
  479. /**
  480. * Returns a list of all Objects that this Object is connected with
  481. */
  482. public abstract List<OParl.Object> get_neighbors() throws ParsingError;
  483. }
  484. /**
  485. * All OParl.Objects that can be loaded as embedded
  486. * object inherit from this class. They may have fields
  487. * that have been loaded incompletely as defined by the
  488. * spec. This class provides the means to load them
  489. * fully on the fly if needed.
  490. */
  491. public abstract class EmbeddedObject : Object {
  492. /**
  493. * If the object has been loaded as an embedded object
  494. * and thus has some unloaded fields, this property will
  495. * be {{{false}}}
  496. */
  497. public bool fully_loaded { get; protected set; }
  498. /**
  499. * Causes the object to refresh and thus load omitted
  500. * fields
  501. */
  502. public void autoload() throws OParl.ParsingError {
  503. try {
  504. if (!this.fully_loaded) {
  505. this.refresh();
  506. this.fully_loaded = true;
  507. }
  508. } catch (ParsingError e) {
  509. this.handle_parse_error(e);
  510. }
  511. }
  512. }
  513. }