DtdResolver.java

/*
 * Copyright (C) 2021 INRAE AgroClim
 *
 * This file is part of Indicators.
 *
 * Indicators is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Indicators 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indicators. If not, see <http://www.gnu.org/licenses/>.
 */
package fr.inrae.agroclim.indicators.xml;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Objects;

import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import lombok.NonNull;
import lombok.Setter;

/**
 * Resolver for provided DTD.
 *
 * Last changed : $Date$
 *
 * @author $Author$
 * @version $Revision$
 */
public final class DtdResolver implements EntityResolver {

    /**
     * Public ID of doctype ⮕  Resource for the doctype file.
     */
    @Setter
    private Map<String, InputStream> dtds;

    @Override
    public InputSource resolveEntity(@NonNull final String publicId,
            final String systemId) throws SAXException, IOException {
        if (dtds != null && dtds.containsKey(publicId)) {
            final InputStream dtdResource = dtds.get(publicId);
            Objects.requireNonNull(dtdResource, "If DTD Public ID is provided, dtdResource must not be null!");
            return new InputSource(dtdResource);
        }
        return null;
    }
}