Bug 3866: Support for Restconf HTTP Patch
[netconf.git] / opendaylight / restconf / sal-rest-connector / src / main / java / org / opendaylight / netconf / sal / rest / impl / XmlToPATCHBodyReader.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.netconf.sal.rest.impl;
10
11 import com.google.common.collect.ImmutableList;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.Type;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.List;
19 import javax.ws.rs.Consumes;
20 import javax.ws.rs.WebApplicationException;
21 import javax.ws.rs.core.MediaType;
22 import javax.ws.rs.core.MultivaluedMap;
23 import javax.ws.rs.ext.MessageBodyReader;
24 import javax.ws.rs.ext.Provider;
25 import javax.xml.parsers.DocumentBuilder;
26 import javax.xml.parsers.DocumentBuilderFactory;
27 import javax.xml.parsers.ParserConfigurationException;
28 import org.opendaylight.netconf.sal.restconf.impl.PATCHEntity;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
33 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
34 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.w3c.dom.Document;
39 import org.w3c.dom.Element;
40 import org.w3c.dom.NodeList;
41 import org.opendaylight.netconf.sal.rest.api.Draft02.MediaTypes;
42 import org.opendaylight.netconf.sal.rest.api.RestconfService;
43 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
44 import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
45 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
46 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
47 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
48 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
49 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
50 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
51 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
52
53 @Provider
54 @Consumes({MediaTypes.PATCH + RestconfService.XML})
55 public class XmlToPATCHBodyReader extends AbstractIdentifierAwareJaxRsProvider implements
56         MessageBodyReader<PATCHContext> {
57
58     private final static Logger LOG = LoggerFactory.getLogger(XmlToPATCHBodyReader.class);
59     private static final DocumentBuilderFactory BUILDERFACTORY;
60
61     static {
62         final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
63         try {
64             factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
65             factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
66             factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
67             factory.setXIncludeAware(false);
68             factory.setExpandEntityReferences(false);
69         } catch (final ParserConfigurationException e) {
70             throw new ExceptionInInitializerError(e);
71         }
72         factory.setNamespaceAware(true);
73         factory.setCoalescing(true);
74         factory.setIgnoringElementContentWhitespace(true);
75         factory.setIgnoringComments(true);
76         BUILDERFACTORY = factory;
77     }
78
79     @Override
80     public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
81         return true;
82     }
83
84     @Override
85     public PATCHContext readFrom(Class<PATCHContext> type, Type genericType, Annotation[] annotations, MediaType
86             mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException,
87             WebApplicationException {
88
89         try {
90             final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
91
92             if (entityStream.available() < 1) {
93                 // represent empty nopayload input
94                 return new PATCHContext(path, null, null);
95             }
96
97             final DocumentBuilder dBuilder;
98             try {
99                 dBuilder = BUILDERFACTORY.newDocumentBuilder();
100             } catch (final ParserConfigurationException e) {
101                 throw new IllegalStateException("Failed to parse XML document", e);
102             }
103             final Document doc = dBuilder.parse(entityStream);
104
105             return parse(path, doc);
106         } catch (final RestconfDocumentedException e) {
107             throw e;
108         } catch (final Exception e) {
109             LOG.debug("Error parsing xml input", e);
110
111             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
112                     ErrorTag.MALFORMED_MESSAGE);
113         }
114     }
115
116     private PATCHContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc) {
117         final List<PATCHEntity> resultCollection = new ArrayList<>();
118         final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
119         final NodeList editNodes = doc.getElementsByTagName("edit");
120         final DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
121         final DomToNormalizedNodeParserFactory parserFactory =
122                 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER,
123                         pathContext.getSchemaContext());
124
125         for (int i = 0; i < editNodes.getLength(); i++) {
126             Element element = (Element) editNodes.item(i);
127             final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
128             final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
129             final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
130             DataSchemaNode targetNode = ((DataNodeContainer)(pathContext.getSchemaNode())).getDataChildByName
131                     (target.replace("/", ""));
132             if (targetNode == null) {
133                 LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
134                 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
135                         ErrorTag.MALFORMED_MESSAGE);
136             } else {
137                 final YangInstanceIdentifier targetII = pathContext.getInstanceIdentifier().node(targetNode.getQName());
138                 final NodeList valueNodes = element.getElementsByTagName("value").item(0).getChildNodes();
139                 Element value = null;
140                 for (int j = 0; j < valueNodes.getLength(); j++) {
141                     if (valueNodes.item(j) instanceof Element) {
142                         value = (Element) valueNodes.item(j);
143                         break;
144                     }
145                 }
146                 NormalizedNode<?, ?> parsed = null;
147                 if (schemaNode instanceof ContainerSchemaNode) {
148                     parsed = parserFactory.getContainerNodeParser().parse(Collections.singletonList(value),
149                             (ContainerSchemaNode) targetNode);
150                 } else if (schemaNode instanceof ListSchemaNode) {
151                     NormalizedNode<?, ?> parsedValue = parserFactory.getMapEntryNodeParser().parse(Collections
152                             .singletonList(value), (ListSchemaNode) targetNode);
153                     parsed = ImmutableNodes.mapNodeBuilder().withNodeIdentifier(new NodeIdentifier
154                             (targetNode.getQName())).withChild((MapEntryNode) parsedValue).build();
155                 }
156
157                 resultCollection.add(new PATCHEntity(editId, operation, targetII, parsed));
158             }
159         }
160
161         return new PATCHContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
162     }
163 }