translator.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. from collections import defaultdict
  2. from flask import request
  3. from rdflib.term import URIRef
  4. from lakesuperior.dictionaries.namespaces import ns_collection as nsc
  5. from lakesuperior.store_layouts.rdf.base_rdf_layout import BaseRdfLayout
  6. class Translator:
  7. '''
  8. Utility class to perform translations of strings and their wrappers.
  9. All static methods.
  10. '''
  11. @staticmethod
  12. def camelcase(word):
  13. '''
  14. Convert a string with underscores with a camel-cased one.
  15. Ripped from https://stackoverflow.com/a/6425628
  16. '''
  17. return ''.join(x.capitalize() or '_' for x in word.split('_'))
  18. @staticmethod
  19. def uuid_to_uri(uuid):
  20. '''Convert a UUID to a URI.
  21. @return URIRef
  22. '''
  23. return URIRef('{}rest/{}'.format(request.host_url, uuid))
  24. @staticmethod
  25. def localize_string(s):
  26. '''Convert URIs into URNs in a string using the application base URI.
  27. @param string s Input string.
  28. @return string
  29. '''
  30. return s.replace(
  31. request.host_url + 'rest/',
  32. str(nsc['fcres'])
  33. )
  34. @staticmethod
  35. def globalize_string(s):
  36. '''Convert URNs into URIs in a string using the application base URI.
  37. @param string s Input string.
  38. @return string
  39. '''
  40. return s.replace(
  41. str(nsc['fcres']),
  42. request.host_url + 'rest/'
  43. )
  44. @staticmethod
  45. def globalize_term(urn):
  46. '''
  47. Convert an URN into an URI using the application base URI.
  48. @param rdflib.term.URIRef urn Input URN.
  49. @return rdflib.term.URIRef
  50. '''
  51. if urn == BaseRdfLayout.ROOT_NODE_URN:
  52. urn = nsc['fcres']
  53. return URIRef(Translator.globalize_string(str(urn)))
  54. @staticmethod
  55. def globalize_graph(g):
  56. '''
  57. Globalize a graph.
  58. '''
  59. from lakesuperior.model.ldpr import Ldpr
  60. q = '''
  61. CONSTRUCT {{ ?s ?p ?o . }} WHERE {{
  62. {{
  63. ?s ?p ?o .
  64. FILTER (
  65. STRSTARTS(str(?s), "{0}")
  66. ||
  67. STRSTARTS(str(?o), "{0}")
  68. ||
  69. STRSTARTS(str(?s), "{1}")
  70. ||
  71. STRSTARTS(str(?o), "{1}")
  72. ) .
  73. }}
  74. }}'''.format(nsc['fcres'], BaseRdfLayout.ROOT_NODE_URN)
  75. flt_g = g.query(q)
  76. for t in flt_g:
  77. global_s = Translator.globalize_term(t[0])
  78. global_o = Translator.globalize_term(t[2]) \
  79. if isinstance(t[2], URIRef) \
  80. else t[2]
  81. g.remove(t)
  82. g.add((global_s, t[1], global_o))
  83. return g
  84. @staticmethod
  85. def globalize_rsrc(rsrc):
  86. '''
  87. Globalize a resource.
  88. '''
  89. g = rsrc.graph
  90. urn = rsrc.identifier
  91. global_g = Translator.globalize_graph(g)
  92. global_uri = Translator.globalize_term(urn)
  93. return global_g.resource(global_uri)
  94. @staticmethod
  95. def parse_rfc7240(h_str):
  96. '''
  97. Parse `Prefer` header as per https://tools.ietf.org/html/rfc7240
  98. The `cgi.parse_header` standard method does not work with all possible
  99. use cases for this header.
  100. @param h_str (string) The header(s) as a comma-separated list of Prefer
  101. statements, excluding the `Prefer: ` token.
  102. '''
  103. parsed_hdr = defaultdict(dict)
  104. # Split up headers by comma
  105. hdr_list = [ x.strip() for x in h_str.split(',') ]
  106. for hdr in hdr_list:
  107. parsed_pref = defaultdict(dict)
  108. # Split up tokens by semicolon
  109. token_list = [ token.strip() for token in hdr.split(';') ]
  110. prefer_token = token_list.pop(0).split('=')
  111. prefer_name = prefer_token[0]
  112. # If preference has a '=', it has a value, else none.
  113. if len(prefer_token)>1:
  114. parsed_pref['value'] = prefer_token[1].strip('"')
  115. for param_token in token_list:
  116. # If the token list had a ';' the preference has a parameter.
  117. print('Param token: {}'.format(param_token))
  118. param_parts = [ prm.strip().strip('"') \
  119. for prm in param_token.split('=') ]
  120. param_value = param_parts[1] if len(param_parts) > 1 else None
  121. parsed_pref['parameters'][param_parts[0]] = param_value
  122. parsed_hdr[prefer_name] = parsed_pref
  123. return parsed_hdr