/*
 * Copyright (c) eHealth
 */
package be.ehealth.technicalconnector.service.etee.impl;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;

import be.ehealth.technicalconnector.service.etee.CryptoFactory;
import be.ehealth.technicalconnector.utils.ConnectorIOUtils;
import be.fgov.ehealth.etee.crypto.policies.OCSPOption;
import be.fgov.ehealth.technicalconnector.tests.junit.rule.SessionRule;


/**
 * Integration test for {@link OcspRevocationStatusChecker}
 * 
 * @author EHP
 */
public class ConnectorRevocationStatusCheckerIntegrationTest {

    @ClassRule
    public static SessionRule rule = SessionRule.withInactiveSession().build();

    @Before
    public void before() throws Exception {
        KeyStore store = (KeyStore) CryptoFactory.getOCSPOptions().get(OCSPOption.TRUST_STORE);
        store.setCertificateEntry("ca", generate("/etee/government2011.ca.cer"));
        store.setCertificateEntry("ca2", generate("/etee/belgium.root.cer"));
        CryptoFactory.getOCSPOptions().put(OCSPOption.TRUST_STORE, store);
    }

    @After
    public void after() throws Exception {
        KeyStore store = (KeyStore) CryptoFactory.getOCSPOptions().get(OCSPOption.TRUST_STORE);
        store.deleteEntry("ca");
        store.deleteEntry("ca2");
        CryptoFactory.getOCSPOptions().put(OCSPOption.TRUST_STORE, store);
    }


    /**
     * Tests RevocationStatusChecker on a CA
     */
    @Test
    public void testWithCertificate() throws Exception {

        ConnectorRevocationStatusChecker checker = new ConnectorRevocationStatusChecker();
        boolean isRevoked = checker.isRevoked(generate("/etee/www.ehealth.fgov.be.cer"));
        Assert.assertFalse(isRevoked);
    }

    @Test
    public void testWithSelfSignedCertificate() throws Exception {
        ConnectorRevocationStatusChecker checker = new ConnectorRevocationStatusChecker();
        boolean isRevoked = checker.isRevoked(generate("/etee/tsl.ehealth.fgov.be.cer"));
        Assert.assertFalse(isRevoked);
    }

    public static X509Certificate generate(String location) throws Exception {
        InputStream is = null;
        try {
            is = ConnectorIOUtils.getResourceAsStream(location);
            return (java.security.cert.X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is);
        } finally {
            ConnectorIOUtils.closeQuietly(is);
        }
    }
}
