Move SendErrorExceptionUtil
[netconf.git] / netconf / netconf-util / src / test / java / org / opendaylight / netconf / util / test / XmlFileLoader.java
1 /*
2  * Copyright (c) 2013 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.util.test;
9
10 import static java.util.Objects.requireNonNull;
11
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.nio.charset.StandardCharsets;
15 import javax.xml.parsers.ParserConfigurationException;
16 import org.eclipse.jdt.annotation.NonNull;
17 import org.opendaylight.netconf.api.NetconfMessage;
18 import org.opendaylight.netconf.api.xml.XmlUtil;
19 import org.w3c.dom.Document;
20 import org.w3c.dom.Element;
21 import org.xml.sax.SAXException;
22
23 public final class XmlFileLoader {
24     private XmlFileLoader() {
25         // Hidden on purpose
26     }
27
28     public static NetconfMessage xmlFileToNetconfMessage(final String fileName) throws IOException, SAXException,
29             ParserConfigurationException {
30         return new NetconfMessage(xmlFileToDocument(fileName));
31     }
32
33     public static Element xmlFileToElement(final String fileName) throws IOException, SAXException,
34             ParserConfigurationException {
35         return xmlFileToDocument(fileName).getDocumentElement();
36     }
37
38     public static String xmlFileToString(final String fileName) throws IOException, SAXException,
39             ParserConfigurationException {
40         return XmlUtil.toString(xmlFileToDocument(fileName));
41     }
42
43     public static Document xmlFileToDocument(final String fileName) throws IOException, SAXException,
44             ParserConfigurationException {
45         try (InputStream resource = getResourceAsStream(fileName)) {
46             return XmlUtil.readXmlToDocument(resource);
47         }
48     }
49
50     public static String fileToString(final String fileName) throws IOException {
51         try (InputStream resource = getResourceAsStream(fileName)) {
52             return new String(resource.readAllBytes(), StandardCharsets.UTF_8);
53         }
54     }
55
56     public static @NonNull InputStream getResourceAsStream(final String fileName) {
57         final String resourceName = requireNonNull(fileName);
58         return requireNonNull(XmlFileLoader.class.getClassLoader().getResourceAsStream(resourceName), resourceName);
59     }
60 }