/*
 *  Name:    $Id: XMLUtil.java,v 1.5 2010/03/23 11:22:10 t724w Exp $
 *
 *  Copyright 2009 Bundesamt für Informatik und Telekommunikation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ch.admin.bit.edec.dsig.util;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.xpath.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * Simple Helper Methods which were useful when you work with DOM
 *
 * @author t724w (mru)
 */
public class XMLUtil {

  /**
   * Private constructor to hide implicit public one.
   */
  private XMLUtil() {
  }

  public static Document read(String inputFile) throws SAXException, IOException, ParserConfigurationException {
    return read(new FileInputStream(inputFile));
  }

  public static Document read(InputStream inputStream) throws SAXException, IOException, ParserConfigurationException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL xsdUrl = XMLUtil.class.getResource("/xsd/edec_evv_root.xsd");
    Schema schema = schemaFactory.newSchema(xsdUrl);

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    builderFactory.setSchema(schema);

    try {
      DocumentBuilder builder = builderFactory.newDocumentBuilder();
      return builder.parse(inputStream);
    }
    finally {
      try {
        inputStream.close();
      }
      catch (IOException ex) {
        // ignore IO exception
      }
    }
  }

  public static Node extractX509Token(Document xmldoc) throws XPathExpressionException {
    // create XPath object which has own NamespaceContext
    XPath xpath = XPathFactory.newInstance().newXPath();
    // with a custom NamespaceContext we can use Namespaces in our XPath query
    NamespaceContext nsc = new NamespaceContextImpl();
    xpath.setNamespaceContext(nsc);

    // extract x509 Token --> xml element wsse:BinarySecurityToken
    XPathExpression expr = xpath.compile("//wsse:Security/wsse:BinarySecurityToken");
    return (Node) expr.evaluate(xmldoc, XPathConstants.NODE);
  }

  public static Node extractDSignature(Document xmldoc) throws XPathExpressionException {
    // create XPath object which has own NamespaceContext
    XPath xpath = XPathFactory.newInstance().newXPath();
    // with a custom NamespaceContext we can use Namespaces in our XPath query
    NamespaceContext nsc = new NamespaceContextImpl();
    xpath.setNamespaceContext(nsc);

    XPathExpression expr = xpath.compile("//wsse:Security/ds:Signature");
    return (Node) expr.evaluate(xmldoc, XPathConstants.NODE);
  }

  public static Node extractTimeStamp(Document xmldoc) throws XPathExpressionException {
    // create XPath object which has own NamespaceContext
    XPath xpath = XPathFactory.newInstance().newXPath();
    // with a custom NamespaceContext we can use Namespaces in our XPath query
    NamespaceContext nsc = new NamespaceContextImpl();
    xpath.setNamespaceContext(nsc);

    XPathExpression expr = xpath.compile("//wsse:Security/wsu:Timestamp/wsu:Created");
    return (Node) expr.evaluate(xmldoc, XPathConstants.NODE);
  }

  public static Node extractDocumentInformation(Document xmldoc) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("//*[local-name()='documentInformation']");
    return (Node) expr.evaluate(xmldoc, XPathConstants.NODE);
  }

  public static Node extractTraderDeclarationNumber(Document xmldoc) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("//*[local-name()='traderDeclarationNumber']");
    return (Node) expr.evaluate(xmldoc, XPathConstants.NODE);
  }

  public static Node extractTraderReference(Document xmldoc) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("//*[local-name()='traderReference']");
    return (Node) expr.evaluate(xmldoc, XPathConstants.NODE);
  }

  public static NodeList extractDeclaratTIN(Document xmldoc) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("//*[local-name()='traderIdentificationNumber']");
    return (NodeList) expr.evaluate(xmldoc, XPathConstants.NODESET);
  }

}
