5f901c8c18f3b887b933c509e4ead4178f9df6d0
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / sal / restconf / impl / RestconfImpl.xtend
1 package org.opendaylight.controller.sal.restconf.impl
2
3 import java.util.ArrayList
4 import java.util.HashMap
5 import java.util.List
6 import java.util.Set
7 import javax.ws.rs.core.Response
8 import org.opendaylight.controller.md.sal.common.api.TransactionStatus
9 import org.opendaylight.controller.sal.rest.api.RestconfService
10 import org.opendaylight.yangtools.yang.common.QName
11 import org.opendaylight.yangtools.yang.data.api.CompositeNode
12 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
13 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdentifierBuilder
14 import org.opendaylight.yangtools.yang.data.api.Node
15 import org.opendaylight.yangtools.yang.data.impl.NodeFactory
16 import org.opendaylight.yangtools.yang.model.api.ChoiceNode
17 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
18 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
19 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
20 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode
21 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode
22 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
23 import org.opendaylight.yangtools.yang.model.api.Module
24 import org.opendaylight.yangtools.yang.model.api.TypeDefinition
25 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition
26
27 import static javax.ws.rs.core.Response.Status.*
28
29 class RestconfImpl implements RestconfService {
30
31     val static RestconfImpl INSTANCE = new RestconfImpl
32
33     @Property
34     BrokerFacade broker
35
36     @Property
37     extension ControllerContext controllerContext
38
39     private new() {
40         if (INSTANCE !== null) {
41             throw new IllegalStateException("Already instantiated");
42         }
43     }
44
45     static def getInstance() {
46         return INSTANCE
47     }
48
49     override readAllData() {
50 //        return broker.readOperationalData("".toInstanceIdentifier.getInstanceIdentifier);
51         throw new UnsupportedOperationException("Reading all data is currently not supported.")
52     }
53
54     override getModules() {
55         throw new UnsupportedOperationException("TODO: auto-generated method stub")
56     }
57
58     override getRoot() {
59         return null;
60     }
61
62     override invokeRpc(String identifier, CompositeNode payload) {
63         val rpc = identifier.rpcDefinition
64         if (rpc === null) {
65             throw new ResponseException(NOT_FOUND, "RPC does not exist.");
66         }
67         val value = normalizeNode(payload, rpc.input, null)
68         val List<Node<?>> input = new ArrayList
69         input.add(value)
70         val rpcRequest = NodeFactory.createMutableCompositeNode(rpc.QName, null, input, null, null)
71         val rpcResult = broker.invokeRpc(rpc.QName, rpcRequest);
72         if (!rpcResult.successful) {
73             throw new ResponseException(INTERNAL_SERVER_ERROR, "Operation failed")
74         }
75         if (rpcResult.result === null) {
76             return null
77         }
78         return new StructuredData(rpcResult.result, rpc.output)
79     }
80
81     override readData(String identifier) {
82         val instanceIdentifierWithSchemaNode = identifier.resolveInstanceIdentifier
83         val data = broker.readOperationalData(instanceIdentifierWithSchemaNode.getInstanceIdentifier);
84         return new StructuredData(data, instanceIdentifierWithSchemaNode.schemaNode)
85     }
86
87     override readConfigurationData(String identifier) {
88         val instanceIdentifierWithSchemaNode = identifier.resolveInstanceIdentifier
89         val data = broker.readConfigurationData(instanceIdentifierWithSchemaNode.getInstanceIdentifier);
90         return new StructuredData(data, instanceIdentifierWithSchemaNode.schemaNode)
91     }
92
93     override readOperationalData(String identifier) {
94         val instanceIdentifierWithSchemaNode = identifier.resolveInstanceIdentifier
95         val data = broker.readOperationalData(instanceIdentifierWithSchemaNode.getInstanceIdentifier);
96         return new StructuredData(data, instanceIdentifierWithSchemaNode.schemaNode)
97     }
98
99     override updateConfigurationDataLegacy(String identifier, CompositeNode payload) {
100         updateConfigurationData(identifier, payload);
101     }
102
103     override updateConfigurationData(String identifier, CompositeNode payload) {
104         val identifierWithSchemaNode = identifier.resolveInstanceIdentifier
105         val value = normalizeNode(payload, identifierWithSchemaNode.schemaNode, identifierWithSchemaNode.mountPoint)
106         val status = broker.commitConfigurationDataPut(identifierWithSchemaNode.instanceIdentifier, value).get();
107         switch status.result {
108             case TransactionStatus.COMMITED: Response.status(OK).build
109             default: Response.status(INTERNAL_SERVER_ERROR).build
110         }
111     }
112
113     override createConfigurationDataLegacy(String identifier, CompositeNode payload) {
114         createConfigurationData(identifier, payload);
115     }
116
117     override createConfigurationData(String identifier, CompositeNode payload) {
118         val uncompleteIdentifierWithSchemaNode = identifier.resolveInstanceIdentifier
119         var schemaNode = (uncompleteIdentifierWithSchemaNode.schemaNode as DataNodeContainer).getSchemaChildNode(payload)
120         if (schemaNode === null) {
121             schemaNode = payload.findModule(uncompleteIdentifierWithSchemaNode.instanceIdentifier)?.getSchemaChildNode(payload)
122         }
123         val value = normalizeNode(payload, schemaNode, uncompleteIdentifierWithSchemaNode.instanceIdentifier)
124         val completeIdentifierWithSchemaNode = uncompleteIdentifierWithSchemaNode.addLastIdentifierFromData(value, schemaNode)
125         val status = broker.commitConfigurationDataPost(completeIdentifierWithSchemaNode.instanceIdentifier, value)?.get();
126         if (status === null) {
127             return Response.status(ACCEPTED).build
128         }
129         switch status.result {
130             case TransactionStatus.COMMITED: Response.status(NO_CONTENT).build
131             default: Response.status(INTERNAL_SERVER_ERROR).build
132         }
133     }
134     
135     override createConfigurationData(CompositeNode payload) {
136         val schemaNode = payload.findModule(null)?.getSchemaChildNode(payload)
137         val value = normalizeNode(payload, schemaNode, null)
138         val identifierWithSchemaNode = addLastIdentifierFromData(null, value, schemaNode)
139         val status = broker.commitConfigurationDataPost(identifierWithSchemaNode.instanceIdentifier, value)?.get();
140         if (status === null) {
141             return Response.status(ACCEPTED).build
142         }
143         switch status.result {
144             case TransactionStatus.COMMITED: Response.status(NO_CONTENT).build
145             default: Response.status(INTERNAL_SERVER_ERROR).build
146         }
147     }
148
149     private def InstanceIdWithSchemaNode resolveInstanceIdentifier(String identifier) {
150         val identifierWithSchemaNode = identifier.toInstanceIdentifier
151         if (identifierWithSchemaNode === null) {
152             throw new ResponseException(BAD_REQUEST, "URI has bad format");
153         }
154         return identifierWithSchemaNode
155     }
156
157     private def dispatch Module findModule(CompositeNode data, InstanceIdentifier partialPath) {
158         if (partialPath !== null && !partialPath.path.empty) {
159             return data.nodeType.namespace.findModuleByNamespace(partialPath)
160         } else {
161             return data.nodeType.namespace.findModuleByNamespace
162         }
163     }
164
165     private def dispatch Module findModule(CompositeNodeWrapper data, InstanceIdentifier partialPath) {
166         var Module module = null;
167         if (partialPath !== null && !partialPath.path.empty) {
168             module = data.namespace.findModuleByNamespace(partialPath) // namespace from XML
169             if (module === null) {
170                 module = data.namespace.toString.findModuleByName(partialPath) // namespace (module name) from JSON
171             }
172         } else {
173             module = data.namespace.findModuleByNamespace // namespace from XML
174             if (module === null) {
175                 module = data.namespace.toString.findModuleByName // namespace (module name) from JSON
176             }
177         }
178         return module
179     }
180     
181     private def dispatch DataSchemaNode getSchemaChildNode(DataNodeContainer parentSchemaNode, CompositeNode data) {
182         return parentSchemaNode?.getDataChildByName(data.nodeType.localName)
183     }
184     
185     private def dispatch DataSchemaNode getSchemaChildNode(DataNodeContainer parentSchemaNode, CompositeNodeWrapper data) {
186         return parentSchemaNode?.getDataChildByName(data.localName)
187     }
188
189     private def InstanceIdWithSchemaNode addLastIdentifierFromData(InstanceIdWithSchemaNode identifierWithSchemaNode, CompositeNode data, DataSchemaNode schemaOfData) {
190         val iiOriginal = identifierWithSchemaNode?.instanceIdentifier
191         var  InstanceIdentifierBuilder iiBuilder = null
192         if (iiOriginal === null) { 
193             iiBuilder = InstanceIdentifier.builder
194         } else {
195             iiBuilder = InstanceIdentifier.builder(iiOriginal)
196         }
197
198         if (schemaOfData instanceof ListSchemaNode) {
199             iiBuilder.nodeWithKey(schemaOfData.QName, (schemaOfData as ListSchemaNode).resolveKeysFromData(data))
200         } else {
201             iiBuilder.node(schemaOfData.QName)
202         }
203         return new InstanceIdWithSchemaNode(iiBuilder.toInstance, schemaOfData, identifierWithSchemaNode?.mountPoint)
204     }
205
206     private def resolveKeysFromData(ListSchemaNode listNode, CompositeNode dataNode) {
207         val keyValues = new HashMap<QName, Object>();
208         for (key : listNode.keyDefinition) {
209             val dataNodeKeyValueObject = dataNode.getSimpleNodesByName(key.localName)?.head?.value
210             if (dataNodeKeyValueObject === null) {
211                 throw new ResponseException(BAD_REQUEST, "List " + dataNode.nodeType.localName + " does not contain key: " + key.localName)
212             }
213             keyValues.put(key, dataNodeKeyValueObject);
214         }
215         return keyValues
216     }
217
218     private def CompositeNode normalizeNode(CompositeNode node, DataSchemaNode schema, InstanceIdentifier mountPoint) {
219         if (schema !== null && !schema.containerOrList) {
220             throw new ResponseException(BAD_REQUEST, "Root element has to be container or list yang datatype.");
221         }
222         if (node instanceof CompositeNodeWrapper) {
223             if ((node  as CompositeNodeWrapper).changeAllowed) {
224                 normalizeNode(node as CompositeNodeWrapper, schema, null, mountPoint)
225             }
226             return (node as CompositeNodeWrapper).unwrap()
227         }
228         return node
229     }
230
231     private def isContainerOrList(DataSchemaNode schemaNode) {
232         return (schemaNode instanceof ContainerSchemaNode) || (schemaNode instanceof ListSchemaNode)
233     }
234
235     private def void normalizeNode(NodeWrapper<?> nodeBuilder, DataSchemaNode schema, QName previousAugment,
236         InstanceIdentifier mountPoint) {
237         if (schema === null) {
238             throw new ResponseException(BAD_REQUEST,
239                 "Data has bad format\n" + nodeBuilder.localName + " does not exist in yang schema.");
240         }
241         var validQName = schema.QName
242         var currentAugment = previousAugment;
243         if (schema.augmenting) {
244             currentAugment = schema.QName
245         } else if (previousAugment !== null && schema.QName.namespace !== previousAugment.namespace) {
246             validQName = QName.create(currentAugment, schema.QName.localName);
247         }
248         var moduleName = controllerContext.findModuleNameByNamespace(validQName.namespace);
249         if (moduleName === null && mountPoint !== null && !mountPoint.path.empty) {
250             moduleName = controllerContext.findModuleByNamespace(validQName.namespace, mountPoint)?.name
251         }
252         if (nodeBuilder.namespace === null || nodeBuilder.namespace == validQName.namespace ||
253             nodeBuilder.namespace.toString == moduleName) {
254             nodeBuilder.qname = validQName
255         } else {
256             throw new ResponseException(BAD_REQUEST,
257                 "Data has bad format.\nIf data is in XML format then namespace for " + nodeBuilder.localName +
258                     " should be " + schema.QName.namespace + ".\nIf data is in Json format then module name for " +
259                     nodeBuilder.localName + " should be " + moduleName + ".");
260         }
261
262         if (nodeBuilder instanceof CompositeNodeWrapper) {
263             val List<NodeWrapper<?>> children = (nodeBuilder as CompositeNodeWrapper).getValues
264             for (child : children) {
265                 normalizeNode(child,
266                     findFirstSchemaByLocalName(child.localName, (schema as DataNodeContainer).childNodes),
267                     currentAugment, mountPoint)
268             }
269             if(schema instanceof ListSchemaNode) {
270                 val listKeys = (schema as ListSchemaNode).keyDefinition
271                 for (listKey : listKeys) {
272                     var foundKey = false
273                     for (child : children) {
274                         if (child.unwrap.nodeType.localName == listKey.localName) {
275                             foundKey = true;
276                         }
277                     }
278                     if (!foundKey) {
279                         throw new ResponseException(BAD_REQUEST,
280                             "Missing key \"" + listKey.localName + "\" of list \"" + schema.QName.localName + "\"")
281                     }
282                 }
283             }
284         } else if (nodeBuilder instanceof SimpleNodeWrapper) {
285             val simpleNode = (nodeBuilder as SimpleNodeWrapper)
286             val value = simpleNode.value
287             var inputValue = value;
288             
289             if (schema.typeDefinition instanceof IdentityrefTypeDefinition) {
290                 if (value instanceof String) {
291                     inputValue = new IdentityValuesDTO(validQName.namespace.toString, value as String, null)
292                 } // else value is instance of ValuesDTO
293             }
294             
295             val outputValue = RestCodec.from(schema.typeDefinition)?.deserialize(inputValue);
296             simpleNode.setValue(outputValue)
297         } else if (nodeBuilder instanceof EmptyNodeWrapper) {
298             val emptyNodeBuilder = nodeBuilder as EmptyNodeWrapper
299             if (schema instanceof LeafSchemaNode) {
300                 emptyNodeBuilder.setComposite(false);
301             } else if (schema instanceof ContainerSchemaNode) {
302
303                 // FIXME: Add presence check
304                 emptyNodeBuilder.setComposite(true);
305             }
306         }
307     }
308
309     private def dispatch TypeDefinition<?> typeDefinition(LeafSchemaNode node) {
310         var baseType = node.type
311         while (baseType.baseType !== null) {
312             baseType = baseType.baseType;
313         }
314         baseType
315     }
316
317     private def dispatch TypeDefinition<?> typeDefinition(LeafListSchemaNode node) {
318         var TypeDefinition<?> baseType = node.type
319         while (baseType.baseType !== null) {
320             baseType = baseType.baseType;
321         }
322         baseType
323     }
324
325     private def DataSchemaNode findFirstSchemaByLocalName(String localName, Set<DataSchemaNode> schemas) {
326         for (schema : schemas) {
327             if (schema instanceof ChoiceNode) {
328                 for (caze : (schema as ChoiceNode).cases) {
329                     val result = findFirstSchemaByLocalName(localName, caze.childNodes)
330                     if (result !== null) {
331                         return result
332                     }
333                 }
334             } else {
335                 val result = schemas.findFirst[n|n.QName.localName.equals(localName)]
336                 if (result !== null) {
337                     return result;
338
339                 }
340             }
341         }
342         return null
343     }
344
345 }