001/*
002 * Copyright (c) 2011-2017 Nexmo Inc
003 *
004 * Permission is hereby granted, free of charge, to any person obtaining a copy
005 * of this software and associated documentation files (the "Software"), to deal
006 * in the Software without restriction, including without limitation the rights
007 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
008 * copies of the Software, and to permit persons to whom the Software is
009 * furnished to do so, subject to the following conditions:
010 *
011 * The above copyright notice and this permission notice shall be included in
012 * all copies or substantial portions of the Software.
013 *
014 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
015 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
016 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
017 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
018 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
019 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
020 * THE SOFTWARE.
021 */
022package com.nexmo.client.legacyutils;
023
024import com.nexmo.client.NexmoResponseParseException;
025import org.w3c.dom.Document;
026import org.w3c.dom.Node;
027import org.xml.sax.InputSource;
028import org.xml.sax.SAXException;
029
030import javax.xml.parsers.DocumentBuilder;
031import java.io.IOException;
032import java.io.StringReader;
033
034public class XmlUtil {
035
036    public static String stringValue(Node node) {
037        return node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
038    }
039
040    public static int intValue(Node node) throws NexmoResponseParseException {
041        String str = stringValue(node);
042        if (str != null) {
043            return Integer.parseInt(str, 10);
044        } else {
045            throw new NexmoResponseParseException("Null or empty value provided for numeric value: " + node.getNodeName());
046        }
047    }
048
049    public static Document parseXmlString(final DocumentBuilder documentBuilder,
050                                          final String response) throws NexmoResponseParseException {
051        try {
052            return documentBuilder.parse(new InputSource(new StringReader(response)));
053        } catch (SAXException se) {
054            throw new NexmoResponseParseException("XML parse failure", se);
055        } catch (IOException ioe) {
056            // Should never happen:
057            throw new NexmoResponseParseException("IOException while parsing response XML!", ioe);
058        }
059    }
060}