Integrate netconf-mapping-api into netconf-server
[netconf.git] / netconf / mdsal-netconf-connector / src / main / java / org / opendaylight / netconf / mdsal / connector / ops / AbstractConfigOperation.java
1 /*
2  * Copyright (c) 2018 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 package org.opendaylight.netconf.mdsal.connector.ops;
9
10 import static java.nio.charset.StandardCharsets.UTF_8;
11
12 import com.google.common.base.Strings;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.net.MalformedURLException;
16 import java.net.URL;
17 import java.net.URLConnection;
18 import java.net.URLStreamHandler;
19 import java.util.Base64;
20 import java.util.Optional;
21 import org.opendaylight.netconf.api.DocumentedException;
22 import org.opendaylight.netconf.api.xml.XmlElement;
23 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
24 import org.opendaylight.netconf.api.xml.XmlUtil;
25 import org.opendaylight.netconf.server.api.operations.AbstractSingletonNetconfOperation;
26 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
27 import org.opendaylight.yangtools.yang.common.ErrorTag;
28 import org.opendaylight.yangtools.yang.common.ErrorType;
29 import org.w3c.dom.Document;
30 import org.w3c.dom.Element;
31 import org.w3c.dom.NodeList;
32 import org.xml.sax.SAXException;
33
34 abstract class AbstractConfigOperation extends AbstractSingletonNetconfOperation {
35     static final String URL_KEY = "url";
36     static final String CONFIG_KEY = "config";
37     private static final int TIMEOUT_MS = 5000;
38
39     protected AbstractConfigOperation(final String netconfSessionIdForReporting) {
40         super(netconfSessionIdForReporting);
41     }
42
43     protected static NodeList getElementsByTagName(final XmlElement parent, final String key) throws
44         DocumentedException {
45         final Element domParent = parent.getDomElement();
46         final NodeList elementsByTagName;
47
48         if (Strings.isNullOrEmpty(domParent.getPrefix())) {
49             elementsByTagName = domParent.getElementsByTagName(key);
50         } else {
51             elementsByTagName = domParent.getElementsByTagNameNS(parent.getNamespace(), key);
52         }
53
54         return elementsByTagName;
55     }
56
57     static XmlElement getConfigElement(final XmlElement parent) throws DocumentedException {
58         final Optional<XmlElement> configElement = parent.getOnlyChildElementOptionally(CONFIG_KEY);
59         if (configElement.isPresent()) {
60             return configElement.orElseThrow();
61         }
62
63         final XmlElement urlElement = parent.getOnlyChildElementOptionally(URL_KEY)
64             .orElseThrow(() -> new DocumentedException("Invalid RPC, neither <config> not <url> element is present",
65                 ErrorType.PROTOCOL, ErrorTag.MISSING_ELEMENT, ErrorSeverity.ERROR));
66
67         final Document document = getDocumentFromUrl(urlElement.getTextContent());
68         return XmlElement.fromDomElementWithExpected(document.getDocumentElement(), CONFIG_KEY,
69             XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
70     }
71
72     /**
73      * Parses XML Document available at given URL.
74      *
75      * <p>JDK8 supports URL schemes that include http, https, file, and jar, but {@link URLStreamHandler}s for other
76      * protocols (e.g. ftp) may be available.
77      *
78      * @param url URL as defined in RFC 2396
79      * @see URL#URL(String, String, int, String)
80      */
81     private static Document getDocumentFromUrl(final String url) throws DocumentedException {
82         try (InputStream input = openConnection(new URL(url))) {
83             return XmlUtil.readXmlToDocument(input);
84         } catch (MalformedURLException e) {
85             throw new DocumentedException(url + " URL is invalid or unsupported", e,
86                 ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, ErrorSeverity.ERROR);
87         } catch (IOException e) {
88             throw new DocumentedException("Could not open URL " + url, e,
89                 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, ErrorSeverity.ERROR);
90         } catch (SAXException e) {
91             throw new DocumentedException("Could not parse XML at" + url, e,
92                 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, ErrorSeverity.ERROR);
93         }
94     }
95
96     private static InputStream openConnection(final URL url) throws IOException {
97         final URLConnection connection = url.openConnection();
98         connection.setConnectTimeout(TIMEOUT_MS);
99         connection.setReadTimeout(TIMEOUT_MS);
100
101         // Support Basic Authentication scheme, e.g. http://admin:admin@localhost:8000/config.conf
102         if (url.getUserInfo() != null) {
103             String basicAuth = "Basic " + Base64.getUrlEncoder().encodeToString(url.getUserInfo().getBytes(UTF_8));
104             connection.setRequestProperty("Authorization", basicAuth);
105         }
106         return connection.getInputStream();
107     }
108 }