/*
 * Decompiled with CFR 0.152.
 */
package org.apache.logging.log4j.core.net.ssl;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import org.apache.logging.log4j.core.net.ssl.StoreConfiguration;
import org.apache.logging.log4j.core.net.ssl.StoreConfigurationException;

public class AbstractKeyStoreConfiguration
extends StoreConfiguration<KeyStore> {
    private final KeyStore keyStore;
    private final String keyStoreType;

    public AbstractKeyStoreConfiguration(String location, String password, String keyStoreType) throws StoreConfigurationException {
        super(location, password);
        this.keyStoreType = keyStoreType == null ? "JKS" : keyStoreType;
        this.keyStore = this.load();
    }

    @Override
    protected KeyStore load() throws StoreConfigurationException {
        FileInputStream fin = null;
        LOGGER.debug("Loading keystore from file with params(location={})", this.getLocation());
        try {
            if (this.getLocation() == null) {
                throw new IOException("The location is null");
            }
            fin = new FileInputStream(this.getLocation());
            KeyStore ks = KeyStore.getInstance(this.keyStoreType);
            ks.load(fin, this.getPasswordAsCharArray());
            LOGGER.debug("Keystore successfully loaded with params(location={})", this.getLocation());
            KeyStore keyStore = ks;
            return keyStore;
        }
        catch (CertificateException e) {
            LOGGER.error("No Provider supports a KeyStoreSpi implementation for the specified type {}", this.keyStoreType);
            throw new StoreConfigurationException(e);
        }
        catch (NoSuchAlgorithmException e) {
            LOGGER.error("The algorithm used to check the integrity of the keystore cannot be found");
            throw new StoreConfigurationException(e);
        }
        catch (KeyStoreException e) {
            LOGGER.error(e);
            throw new StoreConfigurationException(e);
        }
        catch (FileNotFoundException e) {
            LOGGER.error("The keystore file({}) is not found", this.getLocation());
            throw new StoreConfigurationException(e);
        }
        catch (IOException e) {
            LOGGER.error("Something is wrong with the format of the keystore or the given password");
            throw new StoreConfigurationException(e);
        }
        finally {
            try {
                if (fin != null) {
                    fin.close();
                }
            }
            catch (IOException e) {
                LOGGER.debug(e);
            }
        }
    }

    public KeyStore getKeyStore() {
        return this.keyStore;
    }
}
