/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2008 L.Meckert - laurent.meckert@axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package fr.gouv.finances.cp.xemelios.plugin.signature;

import fr.gouv.finances.cp.utils.Base64;
import fr.gouv.finances.cp.xemelios.common.config.NamespaceModel.StringIterator;
import java.io.StringReader;
import java.io.ByteArrayInputStream;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateFactory;

import java.util.Iterator;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.apache.xml.security.utils.Constants;
//import org.apache.xml.security.utils.XMLUtils;
//import org.apache.xpath.XPathAPI;
import org.w3c.dom.Element;


//import sun.misc.BASE64Decoder;


/**
 *  Classe auxiliaire permettant de récupérer un certificat dans une signature
 *  
 * ((cf utilisation dans LXJNISignatureVerifier.java)
 */
class CertificateExtractor {

    private X509Certificate cert;

    public CertificateExtractor(String signatureAsString) {
        
        try {
            // Create a factory object for creating DOM parsers
            javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);

            // Now use the factory to create a DOM parser (a.k.a. a DocumentBuilder)
            javax.xml.parsers.DocumentBuilder parser = factory.newDocumentBuilder();


            // Parse the string and build a Document tree to represent its content
            System.out.println("SIGNATURE=");
            System.out.println(signatureAsString);
            org.w3c.dom.Document doc = parser.parse(new org.xml.sax.InputSource(new StringReader(signatureAsString)));
            NamespaceContext nscontext;
            Element certElement;

            nscontext = new LocalNSCtx();
            XPathFactory xpf = XPathFactory.newInstance();
            XPath xp = xpf.newXPath();
            xp.setNamespaceContext(nscontext);
            certElement = (Element) xp.evaluate("//ds:X509Certificate[1]", doc, XPathConstants.NODE);
//            certElement = (Element) XPathAPI.selectSingleNode(doc, "//ds:X509Certificate[1]", nscontext);
            if (certElement != null) {
                //BASE64Decoder decoder = new BASE64Decoder();
                byte[] buffer = Base64.decode(certElement.getTextContent());
                //byte[] buffer = decoder.decodeBuffer(certElement.getTextContent());
                CertificateFactory cfactory = CertificateFactory.getInstance("X.509");
                ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
                cert = (X509Certificate) cfactory.generateCertificate(bais);


            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public X509Certificate getCertificate() {


        return cert;


    }
    
    private class LocalNSCtx implements NamespaceContext {
        public LocalNSCtx() { super(); }

        public String getNamespaceURI(String prefix) {
            return Constants.SignatureSpecNS;
        }

        public String getPrefix(String namespaceURI) {
            return "ds";
        }

        public Iterator getPrefixes(String namespaceURI) {
            return new StringIterator("ds");
        }
        
    }
}


