001/*
002 *   Copyright 2020 Vonage
003 *
004 *   Licensed under the Apache License, Version 2.0 (the "License");
005 *   you may not use this file except in compliance with the License.
006 *   You may obtain a copy of the License at
007 *
008 *        http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *   Unless required by applicable law or agreed to in writing, software
011 *   distributed under the License is distributed on an "AS IS" BASIS,
012 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *   See the License for the specific language governing permissions and
014 *   limitations under the License.
015 */
016package com.vonage.client.legacyutils;
017
018import com.vonage.client.VonageResponseParseException;
019import org.w3c.dom.Document;
020import org.w3c.dom.Node;
021import org.xml.sax.InputSource;
022import org.xml.sax.SAXException;
023
024import javax.xml.parsers.DocumentBuilder;
025import java.io.IOException;
026import java.io.StringReader;
027
028public class XmlUtil {
029
030    public static String stringValue(Node node) {
031        return node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
032    }
033
034    public static int intValue(Node node) throws VonageResponseParseException {
035        String str = stringValue(node);
036        if (str != null) {
037            return Integer.parseInt(str, 10);
038        } else {
039            throw new VonageResponseParseException("Null or empty value provided for numeric value: " + node.getNodeName());
040        }
041    }
042
043    public static Document parseXmlString(final DocumentBuilder documentBuilder,
044                                          final String response) throws VonageResponseParseException {
045        try {
046            return documentBuilder.parse(new InputSource(new StringReader(response)));
047        } catch (SAXException se) {
048            throw new VonageResponseParseException("XML parse failure", se);
049        } catch (IOException ioe) {
050            // Should never happen:
051            throw new VonageResponseParseException("IOException while parsing response XML!", ioe);
052        }
053    }
054}