From 950022469aa23da97b4e477b3c8f312ccaa856c9 Mon Sep 17 00:00:00 2001 From: servilla Date: Fri, 15 Jun 2018 21:59:15 -0600 Subject: [PATCH] Add initial project files --- .gitignore | 107 ++++++++++++ LICENSE | 201 +++++++++++++++++++++ README.md | 2 + src/metapype/eml2_1_1/__init__.py | 24 +++ src/metapype/eml2_1_1/exceptions.py | 28 +++ src/metapype/eml2_1_1/export.py | 59 +++++++ src/metapype/eml2_1_1/harness.py | 125 +++++++++++++ src/metapype/eml2_1_1/rules.py | 260 ++++++++++++++++++++++++++++ src/metapype/eml2_1_1/validate.py | 46 +++++ src/metapype/model/__init__.py | 22 +++ src/metapype/model/io.py | 106 ++++++++++++ src/metapype/model/node.py | 96 ++++++++++ src/metapype/model/views.py | 39 +++++ src/metapype/setup.py | 34 ++++ 14 files changed, 1149 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 src/metapype/eml2_1_1/__init__.py create mode 100644 src/metapype/eml2_1_1/exceptions.py create mode 100644 src/metapype/eml2_1_1/export.py create mode 100644 src/metapype/eml2_1_1/harness.py create mode 100644 src/metapype/eml2_1_1/rules.py create mode 100644 src/metapype/eml2_1_1/validate.py create mode 100644 src/metapype/model/__init__.py create mode 100644 src/metapype/model/io.py create mode 100644 src/metapype/model/node.py create mode 100644 src/metapype/model/views.py create mode 100644 src/metapype/setup.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a93dd78 --- /dev/null +++ b/.gitignore @@ -0,0 +1,107 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +# Jetbrains IDEA artifacts +.idea \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..526be76 --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# Metapype Lite +A light weight metadata generator for the Ecological Metadata Language diff --git a/src/metapype/eml2_1_1/__init__.py b/src/metapype/eml2_1_1/__init__.py new file mode 100644 index 0000000..e2ed9e3 --- /dev/null +++ b/src/metapype/eml2_1_1/__init__.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""":Mod: __init__.py + +:Synopsis: + +:Author: + servilla + +:Created: + 6/6/18 +""" +import daiquiri + +logger = daiquiri.getLogger('__init__.py: ' + __name__) + + +def main(): + return 0 + + +if __name__ == "__main__": + main() diff --git a/src/metapype/eml2_1_1/exceptions.py b/src/metapype/eml2_1_1/exceptions.py new file mode 100644 index 0000000..6fe86c0 --- /dev/null +++ b/src/metapype/eml2_1_1/exceptions.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""":Mod: exceptions + +:Synopsis: + +:Author: + servilla + +:Created: + 6/5/18 +""" +import daiquiri + +logger = daiquiri.getLogger('exceptions: ' + __name__) + + +class MPLRuleError(Exception): + pass + + +def main(): + return 0 + + +if __name__ == "__main__": + main() diff --git a/src/metapype/eml2_1_1/export.py b/src/metapype/eml2_1_1/export.py new file mode 100644 index 0000000..d298d21 --- /dev/null +++ b/src/metapype/eml2_1_1/export.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""":Mod: export + +:Synopsis: + +:Author: + servilla + +:Created: + 6/12/18 +""" +import daiquiri + +logger = daiquiri.getLogger('export: ' + __name__) + +space = ' ' + +def to_xml(node, level=0): + xml='' + boiler = 'xmlns:eml="eml://ecoinformatics.org/eml-2.1.1" ' + \ + 'xmlns:stmml="http://www.xml-cml.org/schema/stmml-1.1" ' + \ + 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' + \ + 'xsi:schemaLocation="eml://ecoinformatics.org/eml-2.1.1 ' + \ + 'http://nis.lternet.edu/schemas/EML/eml-2.1.1/eml.xsd"' + type = node.rank + attributes = '' + for attribute in node.attributes: + attributes += ' {0}="{1}"'.format(attribute, node.attributes[attribute]) + if level == 0: + indent = '' + if type == 'eml': + type = node.rank + ':' + node.rank + attributes += ' ' + boiler + else: + indent = space * level + open_tag = '<'+ type + attributes + '>' + xml += indent + open_tag + '\n' + if node.content is not None: + xml += indent + space + node.content + '\n' + for child in node.children: + xml += to_xml(child, level + 1) + close_tag = '' + + if level == 0: + xml += indent + close_tag + else: + xml += indent + close_tag + '\n' + + return xml + + +def main(): + return 0 + + +if __name__ == "__main__": + main() diff --git a/src/metapype/eml2_1_1/harness.py b/src/metapype/eml2_1_1/harness.py new file mode 100644 index 0000000..9908b67 --- /dev/null +++ b/src/metapype/eml2_1_1/harness.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""":Mod: harness + +:Synopsis: + +:Author: + servilla + +:Created: + 6/5/18 +""" +import json + +import daiquiri + +from metapype.eml2_1_1.exceptions import MPLRuleError +import metapype.eml2_1_1.export +import metapype.eml2_1_1.validate as validate +from metapype.model.node import Node +from metapype.model import io +from metapype.model import views + + +logger = daiquiri.getLogger('harness: ' + __name__) + + +def main(): + # Create root EML node, with attributes + eml = Node('eml') + eml.add_attribute('packageId', 'edi.1001.1') + eml.add_attribute('system', 'http://metapypelite.edirepository.org') + + # Create access control node with approrpiate permissionsc + access = Node('access', parent=eml) + access.add_attribute('authSystem', 'https://pasta.edirepository.org/authentication') + access.add_attribute('order', 'allowFirst') + allow = Node('allow', parent=access) + principal = Node('principal', parent=allow, content='uid=chase,o=EDI,dc=edirepository,dc=org') + allow.add_child(principal) + permission = Node('permission', parent=allow, content='changePermission') + allow.add_child(permission) + access.add_child(allow) + allow = Node('allow', parent=access) + principal = Node('principal', parent=allow, content='public') + allow.add_child(principal) + permission = Node('permission', parent=allow, content='read') + allow.add_child(permission) + access.add_child(allow) + deny = Node('deny', parent=access) + access.add_child(deny) + principal = Node('principal', parent=deny, content='public') + deny.add_child(principal) + permission = Node('permission', parent=deny, content='write') + deny.add_child(permission) + eml.add_child(access) + + + # Create dataset node + dataset = Node('dataset') + eml.add_child(dataset) + title = Node('title', parent=dataset, content='This is my title') + dataset.add_child(title) + creator = Node('creator', parent=dataset) + dataset.add_child(creator) + individual_name = Node('individualName', parent=creator) + creator.add_child(individual_name) + given_name = Node('givenName', parent=individual_name, content='Mark') + individual_name.add_child(given_name) + surname = Node('surName', parent=individual_name) + surname.content = 'Servilla' + value = Node('value', parent = surname) + value.content = 'Servilla' + value.add_attribute('xml:lang', 'en') + surname.add_child(value) + individual_name.add_child(surname) + contact = Node('contact', parent=dataset) + dataset.add_child(contact) + contact.add_child(individual_name) + contact = Node('contact', parent=dataset) + individual_name = Node('individualName', parent=contact) + surname = Node('surName', parent=individual_name, content='James') + dataset.add_child(contact) + contact.add_child(individual_name) + individual_name.add_child(surname) + + + # Create additional metadata node + additional_metadata = Node('additionalMetadata', parent=eml) + eml.add_child(additional_metadata) + metadata = Node('metadata', parent=additional_metadata, content='TEST') + additional_metadata.add_child(metadata) + + try: + validate.tree(eml) + except MPLRuleError as e: + logger.error(e) + + json_str = io.to_json(eml) + print(json_str) + with open('test_eml.json', 'w') as f: + f.write(json_str) + + m = json.loads(json_str) + node = io.from_json(m) + + views.graph(node, 0) + + try: + validate.tree(node) + except MPLRuleError as e: + logger.error(e) + + xml = metapype.eml2_1_1.export.to_xml(node) + print(xml) + with open('test_eml.xml', 'w') as f: + f.write(xml) + + + return 0 + + +if __name__ == "__main__": + main() diff --git a/src/metapype/eml2_1_1/rules.py b/src/metapype/eml2_1_1/rules.py new file mode 100644 index 0000000..6b2bf93 --- /dev/null +++ b/src/metapype/eml2_1_1/rules.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""":Mod: rules + +:Synopsis: + +:Author: + servilla + +:Created: + 6/4/18 +""" +import daiquiri + +from metapype.eml2_1_1.exceptions import MPLRuleError +from metapype.model.node import Node + + +logger = daiquiri.getLogger('rules: ' + __name__) + +REQUIRED = True +OPTIONAL = False +INFINITY = None + + +def access_rule(node: Node): + rules = [ + ['allow', 'deny', 1, INFINITY] + ] + process_rules(rules, node) + attributes = { + 'id': OPTIONAL, + 'system': OPTIONAL, + 'scope': OPTIONAL, + 'order': OPTIONAL, + 'authSystem': REQUIRED + } + process_attributes(attributes, node) + if 'order' in node.attributes: + allowed = ['allowFirst', 'denyFirst'] + if node.attributes['order'] not in allowed: + msg = '"{0}:order" attribute must be one of "{1}"'.format(node.rank, allowed) + raise MPLRuleError(msg) + + +def additional_metadata_rule(node: Node): + rules = [ + ['describes', 0, INFINITY], + ['metadata', 1, 1] + ] + process_rules(rules, node) + attributes = { + 'id': OPTIONAL + } + process_attributes(attributes, node) + + +def allow_rule(node: Node): + rules = [ + ['principal', 1, INFINITY], + ['permission', 1, INFINITY] + ] + process_rules(rules, node) + + +def any_name_rule(node: Node): + rules = [ + ['value', 0, INFINITY] + ] + process_rules(rules, node) + attributes = { + 'lang': OPTIONAL + } + process_attributes(attributes, node) + if node.content is not None and type(node.content) is not str: + msg = 'Node "{0}" content should be type string, not "{1}"'.format(node.rank, type(node.content)) + raise MPLRuleError(msg) + if len(node.children) == 0 and node.content is None: + msg = 'Node "{0}" content should not be empty'.format(node.rank) + raise MPLRuleError(msg) + +def dataset_rule(node: Node): + pass + + +def deny_rule(node: Node): + rules = [ + ['principal', 1, INFINITY], + ['permission', 1, INFINITY] + ] + process_rules(rules, node) + + +def eml_rule(node: Node): + rules = [ + ['access', 0, 1], + ['dataset', 'citation', 'software', 'protocol', 1, 1], + ['additionalMetadata', 0, INFINITY] + ] + process_rules(rules, node) + attributes = { + 'packageId': REQUIRED, + 'system': REQUIRED, + 'scope': OPTIONAL, + 'lang': OPTIONAL + } + process_attributes(attributes, node) + + +def individual_name_rule(node: Node): + rules = [ + ['salutation', 0, INFINITY], + ['givenName', 0, INFINITY], + ['surName', 1, 1] + ] + process_rules(rules, node) + + +def metadata_rule(node: Node): + if len(node.children) != 0: + msg = 'Node "{0}" should not have children'.format(node.rank) + raise MPLRuleError(msg) + if type(node.content) is not str: + msg = 'Node "{0}" content should be type string, not "{1}"'.format(node.rank, type(node.content)) + raise MPLRuleError(msg) + + +def permission_rule(node: Node): + if len(node.children) != 0: + msg = 'Node "{0}" should not have children'.format(node.rank) + raise MPLRuleError(msg) + allowed = ['read', 'write', 'changePermission', 'all'] + if node.content not in allowed: + msg = 'Node "{0}" content should be one of "{1}", not "{2}"'.format(node.rank, allowed, node.content) + raise MPLRuleError(msg) + + +def principal_rule(node: Node): + if len(node.children) != 0: + msg = 'Node "{0}" should not have children'.format(node.rank) + raise MPLRuleError(msg) + if type(node.content) is not str: + msg = 'Node content should be type string, not "{0}"'.format(type(node.content)) + raise MPLRuleError(msg) + + +def responsible_party_rule(node: Node): + rules = [ + ['individualName', 'organizationName', 'positionName', 1, INFINITY], + ['address', 0, INFINITY], + ['phone', 0, INFINITY], + ['electronicMailAddress', 0, INFINITY], + ['onlineUrl', 0, INFINITY], + ['userId', 0, INFINITY] + ] + process_rules(rules, node) + attributes = { + 'id': OPTIONAL, + 'system': OPTIONAL, + 'scope': OPTIONAL + } + process_attributes(attributes, node) + + +def title_rule(node: Node): + if node.content is not None and type(node.content) is not str: + msg = 'Node "{0}" content should be type string, not "{1}"'.format(node.rank, type(node.content)) + raise MPLRuleError(msg) + rules = [ + ['value', 0, INFINITY] + ] + process_rules(rules, node) + attributes = { + 'lang': OPTIONAL + } + process_attributes(attributes, node) + + +def value_rule(node: Node): + if node.content is None: + msg = 'Node "{0}" content cannot be empty'.format(node.rank) + raise MPLRuleError(msg) + if type(node.content) is not str: + msg = 'Node "{0}" content should be type string, not "{1}"'.format(node.rank, type(node.content)) + raise MPLRuleError(msg) + attributes = { + 'xml:lang': REQUIRED, + } + process_attributes(attributes, node) + + +def process_rules(rules, node: Node): + i = 0 + max_i = len(node.children) + for rule in rules: + rank = rule[:-2] + min = rule[-2] + max = rule[-1] + cnt = 0 + while i < max_i: + child_rank = node.children[i].rank + if child_rank in rank: + cnt += 1 + if max is not INFINITY and cnt > max: + msg = 'Maximum occurrence of "{0}" exceeded for "{1}"'.format(rank, node.rank) + raise MPLRuleError(msg) + i += 1 + else: break + if cnt < min: + msg = 'Minimum occurrence of "{0}" not met for "{1}"'.format(rank, node.rank) + raise MPLRuleError(msg) + if i < max_i: + child_rank = node.children[i].rank + msg = 'Child "{0}" not allowed for "{1}"'.format(child_rank, node.rank) + raise MPLRuleError(msg) + + +def process_attributes(attributes, node: Node): + for attribute in attributes: + required = attributes[attribute] + if required and attribute not in node.attributes: + msg = '"{0}" is a required attribute of node "{1}"'.format(attribute, node.rank) + raise MPLRuleError(msg) + for attribute in node.attributes: + if attribute not in attributes: + msg = '"{0}" is not a recognized attributes of node "{1}"'.format(attribute, node.rank) + raise MPLRuleError(msg) + + + +rules = { + 'access': access_rule, + 'additionalMetadata': additional_metadata_rule, + 'allow': allow_rule, + 'contact': responsible_party_rule, + 'creator': responsible_party_rule, + 'dataset': dataset_rule, + 'deny': deny_rule, + 'eml': eml_rule, + 'givenName': any_name_rule, + 'individualName': individual_name_rule, + 'metadata': metadata_rule, + 'organizationName': any_name_rule, + 'permission': permission_rule, + 'positionName': any_name_rule, + 'principal': principal_rule, + 'salutation': any_name_rule, + 'surName': any_name_rule, + 'title': title_rule, + 'value': value_rule, +} + + +def main(): + return 0 + + +if __name__ == "__main__": + main() diff --git a/src/metapype/eml2_1_1/validate.py b/src/metapype/eml2_1_1/validate.py new file mode 100644 index 0000000..31e7b49 --- /dev/null +++ b/src/metapype/eml2_1_1/validate.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""":Mod: validate + +:Synopsis: + +:Author: + servilla + +:Created: + 6/5/18 +""" +import daiquiri + +from metapype.eml2_1_1.exceptions import MPLRuleError +from metapype.eml2_1_1.rules import rules +from metapype.model.node import Node + + +logger = daiquiri.getLogger('validate: ' + __name__) + + +def node(node: Node): + if node.rank not in rules: + msg = 'Unknown node rank: {}'.format(node.rank) + raise MPLRuleError(msg) + else: + rules[node.rank](node) + + +def tree(root: Node): + try: + node(root) + except MPLRuleError as e: + logger.error(e) + for child in root.children: + tree(child) + + +def main(): + return 0 + + +if __name__ == "__main__": + main() diff --git a/src/metapype/model/__init__.py b/src/metapype/model/__init__.py new file mode 100644 index 0000000..9e961b6 --- /dev/null +++ b/src/metapype/model/__init__.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""":Mod: __init__.py + +:Synopsis: + +:Author: + servilla + +:Created: + 5/15/18 +""" +import logging + + +def main(): + return 0 + + +if __name__ == "__main__": + main() diff --git a/src/metapype/model/io.py b/src/metapype/model/io.py new file mode 100644 index 0000000..2d24ef0 --- /dev/null +++ b/src/metapype/model/io.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""":Mod: io + +:Synopsis: + +:Author: + servilla + +:Created: + 6/15/18 +""" +import json + +import daiquiri + +from metapype.model.node import Node + + +logger = daiquiri.getLogger('model_io: ' + __name__) +space = ' ' + + +def to_json(node, level=0, comma=''): + json = '' + type = node.rank + if level == 0: + indent = '' + else: + indent = space * level + + open_tag = '{"' + type + '":[\n' + json += indent + open_tag + + attributes = '{"attributes":null},' + if len(node.attributes) > 0: + _ = '{' + ','.join(['"' + key + '":"' + node.attributes[key] + '"' for key in node.attributes]) + '}' + attributes = attributes.replace('null', _) + json += indent + space + attributes + '\n' + + content = '{"content":null},' + if node.content is not None: + _ = '"' + node.content + '"' + content = content.replace('null',_) + json += indent + space + content + '\n' + + children = '{"children":[null]}' + if len(node.children) > 0: + _ = '' + for child in node.children: + newline = '' + if child is node.children[0]: + newline = '\n' + if child is node.children[-1]: + _ += newline + to_json(child, level + 2, comma='') + else: + _ += newline + to_json(child, level + 2, comma=',') + children = children.replace('null]}', _) + json += indent + space + children + json += indent + space + ']}\n' + else: + json += indent + space + children + '\n' + + if level == 0: + close_tag = indent + ']}' + else: + close_tag = indent + ']}' + comma + '\n' + json += close_tag + + return json + + +def from_json(json_node: dict, parent: Node=None) -> Node: + _ = json_node.popitem() + name = _[0] + body = _[1] + node = Node(name) + + if parent is not None: + node.parent = parent + + attributes = body[0]['attributes'] + if attributes is not None: + for attribute in attributes: + node.add_attribute(attribute, attributes[attribute]) + + content = body[1]['content'] + if content is not None: + node.content = content + + children = body[2]['children'] + for child in children: + if child is not None: + child_node = from_json(child, node) + node.add_child(child_node) + + return node + + +def main(): + return 0 + + +if __name__ == "__main__": + main() diff --git a/src/metapype/model/node.py b/src/metapype/model/node.py new file mode 100644 index 0000000..46fd9d0 --- /dev/null +++ b/src/metapype/model/node.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""":Mod: node + +:Synopsis: + +:Author: + servilla + +:Created: + 5/15/18 +""" +import uuid + +import daiquiri + + +logger = daiquiri.getLogger('node.py: ' + __name__) + + +class Node(object): + + def __init__(self, rank: str, parent=None, content: str=None): + self._node_id = uuid.uuid4().hex + self._rank = rank + self._parent = parent + self._content = content + self._attributes = {} # Attribute key/value pairs + self._children = [] # Children node objects in add order + + @property + def node_id(self): + return self._node_id + + @property + def rank(self): + return self._rank + + @property + def parent(self): + return self._parent + + @parent.setter + def parent(self, parent): + self._parent = parent + + @property + def content(self): + return self._content + + @content.setter + def content(self, content): + self._content = content + + @property + def attributes(self): + return self._attributes + + @attributes.setter + def attributes(self, attributes): + self._attributes = attributes + + def add_attribute(self, name, value): + self._attributes[name] = value + + def remove_attribute(self, name): + del self._attributes[name] + + def attribute_value(self, name): + return self._attributes[name] + + def list_attributes(self): + return list(self._attributes.keys()) + + @property + def children(self): + return self._children + + @children.setter + def children(self, children): + self._children = children + + def add_child(self, child): + self._children.append(child) + + def remove_child(self, child): + self._children.remove(child) + + +def main(): + return 0 + + +if __name__ == "__main__": + main() diff --git a/src/metapype/model/views.py b/src/metapype/model/views.py new file mode 100644 index 0000000..4247384 --- /dev/null +++ b/src/metapype/model/views.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""":Mod: views + +:Synopsis: + +:Author: + servilla + +:Created: + 6/4/18 +""" +import daiquiri + +logger = daiquiri.getLogger('views: ' + __name__) + + +def graph(node, level): + indent = ' ' * level + type = node.rank + if node.content is not None: + type += ': {}'.format(node.content) + if len(node.attributes) > 0: + type += ' ' + str(node.attributes) + if level == 0: + print(type) + else: + print(indent + '\u2570\u2500 ' + type) + for child in node.children: + graph(child, level + 1) + + +def main(): + return 0 + + +if __name__ == "__main__": + main() diff --git a/src/metapype/setup.py b/src/metapype/setup.py new file mode 100644 index 0000000..84ee23d --- /dev/null +++ b/src/metapype/setup.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""":Mod: setup.py + +:Synopsis: + +:Author: + servilla + +:Created: + 6/15/18 +""" +import setuptools + +setuptools.setup(name='metapype', + version='0.0.1', + description='Metapype for EML', + author='EDI', + url='https://github.com/PASTAplus/metapype-eml', + license='Apache License, Version 2.0', + packages=setuptools.find_packages(), + include_package_data=True, + exclude_package_data={ + '': ['settings.py, properties.py, config.py'], + }, ) + + +def main(): + return 0 + + +if __name__ == "__main__": + main()