Completed
Pull Request — master (#270)
by
unknown
04:06
created

XmlExporter   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 215
Duplicated Lines 18.6 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 40
loc 215
rs 10
wmc 27

16 Methods

Rating   Name   Duplication   Size   Complexity  
A add_etree_method() 0 2 1
A add_etree_variable_type() 0 2 1
A add_etree_datatype() 0 2 1
A add_etree_object_type() 20 20 1
A write_xml() 0 14 2
D node_to_etree() 0 26 8
A _add_namespace_uri_els() 0 3 1
A build_etree() 0 19 2
A dump_etree() 0 7 1
A _add_alias_els() 0 9 2
A __init__() 0 5 1
B add_etree_variable() 0 39 1
A _add_ref_els() 0 12 2
A add_etree_reference() 0 2 1
A _get_node() 0 3 1
A add_etree_object() 20 20 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
"""
2
from a list of nodes in the address space, build an XML file
3
format is the one from opc-ua specification
4
"""
5
import logging
6
import xml.etree.ElementTree as Et
7
8
from opcua import ua
9
from opcua.ua import object_ids as o_ids  # FIXME needed because the reverse look up isn't part of ObjectIds Class
10
11
12
class XmlExporter(object):
13
14
    def __init__(self, server, node_set_attrs):
15
        self.logger = logging.getLogger(__name__)
16
        self.etree = Et.ElementTree(Et.Element('UANodeSet', node_set_attrs))
17
        self.server = server
18
        self.aliases = {}
19
20
    def build_etree(self, node_list):
21
        """
22
        Create an XML etree object from a list of nodes
23
        Args:
24
            node_list: list of Node objects for export
25
26
        Returns:
27
        """
28
        self.logger.info('Building XML etree')
29
30
        # add all namespace uris to the XML etree
31
        self._add_namespace_uri_els()  # TODO not done yet
32
33
        # add all nodes in the list to the XML etree
34
        for node in node_list:
35
            self.node_to_etree(node)
36
37
        # add all required aliases to the XML etree; must be done after nodes are added
38
        self._add_alias_els()
39
40
    def write_xml(self, xmlpath):
41
        """
42
        Write the XML etree in the exporter object to a file
43
        Args:
44
            xmlpath: string representing the path/file name
45
46
        Returns:
47
        """
48
        # try to write the XML etree to a file
49
        self.logger.info('Exporting XML file to %s', xmlpath)
50
        try:
51
            self.etree.write(xmlpath, short_empty_elements=False)
52
        except TypeError as e:  # TODO where to find which exceptions etree.write() raises?
53
            self.logger.error("Error writing XML to file: ", e)
54
55
    def dump_etree(self):
56
        """
57
        Dump etree to console for debugging
58
        Returns:
59
        """
60
        self.logger.info('Dumping XML etree to console')
61
        Et.dump(self.etree)
62
63
    def node_to_etree(self, node):
64
        """
65
        Add the necessary XML sub elements to the etree for exporting the node
66
        Args:
67
            node: Node object which will be added to XML etree
68
69
        Returns:
70
        """
71
        node_class = node.get_node_class()
72
73
        if node_class is ua.NodeClass.Object:
74
            self.add_etree_object(node)
75
        elif node_class is ua.NodeClass.ObjectType:
76
            self.add_etree_object_type(node)
77
        elif node_class is ua.NodeClass.Variable:
78
            self.add_etree_variable(node)
79
        elif node_class is ua.NodeClass.VariableType:
80
            self.add_etree_variable_type(node)
81
        elif node_class is ua.NodeClass.RefernceType:
82
            self.add_etree_reference(node)
83
        elif node_class is ua.NodeClass.DataType:
84
            self.add_etree_datatype(node)
85
        elif node_class is ua.NodeClass.Method:
86
            self.add_etree_method(node)
87
        else:
88
            self.logger.info("Exporting node class not implemented: %s ", node_class)
89
90
    def _get_node(self, obj):
91
        # TODO not sure if this is required for exporter, check on functionality
92
        pass
93
94
        # ORIGINAL CODE FROM IMPORTER
95
        # node = ua.AddNodesItem()
96
        # node.RequestedNewNodeId = ua.NodeId.from_string(obj.nodeid)
97
        # node.BrowseName = ua.QualifiedName.from_string(obj.browsename)
98
        # node.NodeClass = getattr(ua.NodeClass, obj.nodetype[2:])
99
        # if obj.parent:
100
        #     node.ParentNodeId = ua.NodeId.from_string(obj.parent)
101
        # if obj.parentlink:
102
        #     node.ReferenceTypeId = self.to_nodeid(obj.parentlink)
103
        # if obj.typedef:
104
        #     node.TypeDefinition = ua.NodeId.from_string(obj.typedef)
105
        # return node
106
107 View Code Duplication
    def add_etree_object(self, obj):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
108
        """
109
        Add a UA object element to the XML etree
110
        """
111
        browsename = obj.get_browse_name().to_string()
112
        nodeid = obj.nodeid.to_string()
113
114
        displayname = obj.get_display_name().Text.decode(encoding='UTF8')
115
116
        refs = obj.get_references()
117
118
        obj_el = Et.SubElement(self.etree.getroot(),
119
                               'UAObject',
120
                               BrowseName=browsename,
121
                               NodeId=nodeid)
122
123
        disp_el = Et.SubElement(obj_el, 'DisplayName', )
124
        disp_el.text = displayname
125
126
        self._add_ref_els(obj_el, refs)
127
128 View Code Duplication
    def add_etree_object_type(self, obj):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
129
        """
130
        Add a UA object type element to the XML etree
131
        """
132
        browsename = obj.get_browse_name().to_string()
133
        nodeid = obj.nodeid.to_string()
134
135
        displayname = obj.get_display_name().Text.decode(encoding='UTF8')
136
137
        refs = obj.get_references()
138
139
        obj_el = Et.SubElement(self.etree.getroot(),
140
                               'UAObject',
141
                               BrowseName=browsename,
142
                               NodeId=nodeid)
143
144
        disp_el = Et.SubElement(obj_el, 'DisplayName', )
145
        disp_el.text = displayname
146
147
        self._add_ref_els(obj_el, refs)
148
149
    def add_etree_variable(self, obj):
150
        """
151
        Add a UA variable element to the XML etree
152
        """
153
        browsename = obj.get_browse_name().to_string()
154
        datatype = o_ids.ObjectIdNames[obj.get_data_type().Identifier]
155
        datatype_nodeid = obj.get_data_type().to_string()
156
        nodeid = obj.nodeid.to_string()
157
        parent = obj.get_parent().nodeid.to_string()
158
        acccesslevel = str(obj.get_attribute(ua.AttributeIds.AccessLevel).Value.Value)
159
        useraccesslevel = str(obj.get_attribute(ua.AttributeIds.UserAccessLevel).Value.Value)
160
161
        displayname = obj.get_display_name().Text.decode(encoding='UTF8')
162
163
        value = str(obj.get_value())
164
165
        refs = obj.get_references()
166
167
        var_el = Et.SubElement(self.etree.getroot(),
168
                               'UAVariable',
169
                               BrowseName=browsename,
170
                               DataType=datatype,
171
                               NodeId=nodeid,
172
                               ParentNodeId=parent,
173
                               AccessLevel=acccesslevel,
174
                               UserAccessLevel=useraccesslevel)
175
176
        disp_el = Et.SubElement(var_el, 'DisplayName', )
177
        disp_el.text = displayname
178
179
        self._add_ref_els(var_el, refs)
180
181
        val_el = Et.SubElement(var_el, 'Value')
182
183
        valx_el = Et.SubElement(val_el, 'uax:' + datatype)
184
        valx_el.text = value
185
186
        # add any references that get used to aliases dict; this gets handled later
187
        self.aliases[datatype] = datatype_nodeid
188
189
    def add_etree_variable_type(self, obj):
190
        pass
191
192
    def add_etree_method(self, obj):
193
        pass
194
195
    def add_etree_reference(self, obj):
196
        pass
197
198
    def add_etree_datatype(self, obj):
199
        pass
200
201
    def _add_namespace_uri_els(self):
202
        # TODO name space uris should be exported
203
        pass
204
205
    def _add_alias_els(self):
206
207
        aliases_el = Et.Element('Aliases')
208
209
        for k, v in self.aliases.items():
210
            ref_el = Et.SubElement(aliases_el, 'Alias', Alias=k)
211
            ref_el.text = v
212
213
        self.etree.getroot().insert(0, aliases_el)
214
215
    def _add_ref_els(self, parent_el, refs):
216
        refs_el = Et.SubElement(parent_el, 'References')
217
218
        for ref in refs:
219
            ref_name = o_ids.ObjectIdNames[ref.ReferenceTypeId.Identifier]
220
            ref_forward = str(ref.IsForward)
221
            ref_nodeid = ref.NodeId.to_string()
222
            ref_el = Et.SubElement(refs_el, 'Reference', IsForward=ref_forward, ReferenceType=ref_name)
223
            ref_el.text = ref_nodeid
224
225
            # add any references that gets used to aliases dict; this gets handled later
226
            self.aliases[ref_name] = ref_nodeid
227