Use Object.requireNonNull
[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 com.google.common.io.ByteSource;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.nio.charset.StandardCharsets;
16 import javax.xml.parsers.ParserConfigurationException;
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
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 resourceAsStream = XmlFileLoader.class.getClassLoader().getResourceAsStream(fileName)) {
46             requireNonNull(resourceAsStream, fileName);
47             final Document doc = XmlUtil.readXmlToDocument(resourceAsStream);
48             return doc;
49         }
50     }
51
52     public static String fileToString(final String fileName) throws IOException {
53         try (InputStream resourceAsStream = XmlFileLoader.class.getClassLoader().getResourceAsStream(fileName)) {
54             requireNonNull(resourceAsStream);
55             return new ByteSource() {
56                 @Override
57                 public InputStream openStream() {
58                     return resourceAsStream;
59                 }
60             }.asCharSource(StandardCharsets.UTF_8).read();
61
62         }
63     }
64
65     public static InputStream getResourceAsStream(final String fileName) {
66         return XmlFileLoader.class.getClassLoader().getResourceAsStream(fileName);
67     }
68 }