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.Charsets;
12 import com.google.common.base.Preconditions;
13 import com.google.common.io.ByteSource;
14 import java.io.IOException;
15 import java.io.InputStream;
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 class XmlFileLoader {
25 public static NetconfMessage xmlFileToNetconfMessage(final String fileName) throws IOException, SAXException,
26 ParserConfigurationException {
27 return new NetconfMessage(xmlFileToDocument(fileName));
30 public static Element xmlFileToElement(final String fileName) throws IOException, SAXException,
31 ParserConfigurationException {
32 return xmlFileToDocument(fileName).getDocumentElement();
35 public static String xmlFileToString(final String fileName) throws IOException, SAXException,
36 ParserConfigurationException {
37 return XmlUtil.toString(xmlFileToDocument(fileName));
40 public static Document xmlFileToDocument(final String fileName) throws IOException, SAXException,
41 ParserConfigurationException {
42 try (InputStream resourceAsStream = XmlFileLoader.class.getClassLoader().getResourceAsStream(fileName)) {
43 Preconditions.checkNotNull(resourceAsStream, fileName);
44 final Document doc = XmlUtil.readXmlToDocument(resourceAsStream);
49 public static String fileToString(final String fileName) throws IOException {
50 try (InputStream resourceAsStream = XmlFileLoader.class.getClassLoader().getResourceAsStream(fileName)) {
51 Preconditions.checkNotNull(resourceAsStream);
52 return new ByteSource() {
54 public InputStream openStream() {
55 return resourceAsStream;
57 }.asCharSource(Charsets.UTF_8).read();
62 public static InputStream getResourceAsStream(final String fileName) {
63 return XmlFileLoader.class.getClassLoader().getResourceAsStream(fileName);