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
9 package org.opendaylight.netconf.util.test;
11 import com.google.common.base.Preconditions;
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.controller.config.util.xml.XmlUtil;
18 import org.opendaylight.netconf.api.NetconfMessage;
19 import org.w3c.dom.Document;
20 import org.w3c.dom.Element;
21 import org.xml.sax.SAXException;
23 public final class XmlFileLoader {
25 private XmlFileLoader() {
29 public static NetconfMessage xmlFileToNetconfMessage(final String fileName) throws IOException, SAXException,
30 ParserConfigurationException {
31 return new NetconfMessage(xmlFileToDocument(fileName));
34 public static Element xmlFileToElement(final String fileName) throws IOException, SAXException,
35 ParserConfigurationException {
36 return xmlFileToDocument(fileName).getDocumentElement();
39 public static String xmlFileToString(final String fileName) throws IOException, SAXException,
40 ParserConfigurationException {
41 return XmlUtil.toString(xmlFileToDocument(fileName));
44 public static Document xmlFileToDocument(final String fileName) throws IOException, SAXException,
45 ParserConfigurationException {
46 try (InputStream resourceAsStream = XmlFileLoader.class.getClassLoader().getResourceAsStream(fileName)) {
47 Preconditions.checkNotNull(resourceAsStream, fileName);
48 final Document doc = XmlUtil.readXmlToDocument(resourceAsStream);
53 public static String fileToString(final String fileName) throws IOException {
54 try (InputStream resourceAsStream = XmlFileLoader.class.getClassLoader().getResourceAsStream(fileName)) {
55 Preconditions.checkNotNull(resourceAsStream);
56 return new ByteSource() {
58 public InputStream openStream() {
59 return resourceAsStream;
61 }.asCharSource(StandardCharsets.UTF_8).read();
66 public static InputStream getResourceAsStream(final String fileName) {
67 return XmlFileLoader.class.getClassLoader().getResourceAsStream(fileName);