2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.util.test;
10 import static java.util.Objects.requireNonNull;
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;
23 public final class XmlFileLoader {
24 private XmlFileLoader() {
28 public static NetconfMessage xmlFileToNetconfMessage(final String fileName) throws IOException, SAXException,
29 ParserConfigurationException {
30 return new NetconfMessage(xmlFileToDocument(fileName));
33 public static Element xmlFileToElement(final String fileName) throws IOException, SAXException,
34 ParserConfigurationException {
35 return xmlFileToDocument(fileName).getDocumentElement();
38 public static String xmlFileToString(final String fileName) throws IOException, SAXException,
39 ParserConfigurationException {
40 return XmlUtil.toString(xmlFileToDocument(fileName));
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);
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() {
57 public InputStream openStream() {
58 return resourceAsStream;
60 }.asCharSource(StandardCharsets.UTF_8).read();
65 public static InputStream getResourceAsStream(final String fileName) {
66 return XmlFileLoader.class.getClassLoader().getResourceAsStream(fileName);