    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *     https://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.configuration2.resolver;
    018
    019import java.io.IOException;
    020import java.io.InputStream;
    021import java.net.URL;
    022import java.net.URLConnection;
    023import java.util.HashMap;
    024import java.util.Map;
    025
    026import org.xml.sax.EntityResolver;
    027import org.xml.sax.InputSource;
    028import org.xml.sax.SAXException;
    029
    030/**
    031 * The DefaultEntityResolver used by XML Configurations.
    032 *
    033 * @since 1.7
    034 */
    035public class DefaultEntityResolver implements EntityResolver, EntityRegistry {
    036
    037    /** Stores a map with the registered public IDs. */
    038    private final Map<String, URL> registeredEntities = new HashMap<>();
    039
    040    /**
    041     * Constructs a new instance.
    042     */
    043    public DefaultEntityResolver() {
    044        // empty
    045    }
    046
    047    /**
    048     * Gets a map with the entity IDs that have been registered using the {@code registerEntityId()} method.
    049     *
    050     * @return a map with the registered entity IDs
    051     */
    052    @Override
    053    public Map<String, URL> getRegisteredEntities() {
    054        return registeredEntities;
    055    }
    056
    057    /**
    058     * <p>
    059     * Registers the specified URL for the specified public identifier.
    060     * </p>
    061     * <p>
    062     * This implementation maps {@code PUBLICID}'s to URLs (from which the resource will be loaded). A common use case for
    063     * this method is to register local URLs (possibly computed at runtime by a class loader) for DTDs and Schemas. This
    064     * allows the performance advantage of using a local version without having to ensure every {@code SYSTEM} URI on every
    065     * processed XML document is local. This implementation provides only basic functionality. If more sophisticated
    066     * features are required, either calling {@code XMLConfiguration.setDocumentBuilder(DocumentBuilder)} to set a custom
    067     * {@code DocumentBuilder} (which also can be initialized with a custom {@code EntityResolver}) or creating a custom
    068     * entity resolver and registering it with the XMLConfiguration is recommended.
    069     * </p>
    070     *
    071     * @param publicId Public identifier of the Entity to be resolved
    072     * @param entityURL The URL to use for reading this Entity
    073     * @throws IllegalArgumentException if the public ID is undefined
    074     */
    075    @Override
    076    public void registerEntityId(final String publicId, final URL entityURL) {
    077        if (publicId == null) {
    078            throw new IllegalArgumentException("Public ID must not be null!");
    079        }
    080        getRegisteredEntities().put(publicId, entityURL);
    081    }
    082
    083    /**
    084     * Resolves the requested external entity. This is the default implementation of the {@code EntityResolver} interface.
    085     * It checks the passed in public ID against the registered entity IDs and uses a local URL if possible.
    086     *
    087     * @param publicId the public identifier of the entity being referenced
    088     * @param systemId the system identifier of the entity being referenced
    089     * @return an input source for the specified entity
    090     * @throws org.xml.sax.SAXException if a parsing exception occurs
    091     */
    092    @SuppressWarnings("resource") // The stream is managed by the InputSource returned by this method.
    093    @Override
    094    public InputSource resolveEntity(final String publicId, final String systemId) throws SAXException {
    095        // Has this system identifier been registered?
    096        URL entityURL = null;
    097        if (publicId != null) {
    098            entityURL = getRegisteredEntities().get(publicId);
    099        }
    100
    101        if (entityURL != null) {
    102            // Obtain an InputSource for this URL. This code is based on the
    103            // createInputSourceFromURL() method of Commons Digester.
    104            try {
    105                final URLConnection connection = entityURL.openConnection();
    106                connection.setUseCaches(false);
    107                final InputStream stream = connection.getInputStream();
    108                final InputSource source = new InputSource(stream);
    109                source.setSystemId(entityURL.toExternalForm());
    110                return source;
    111            } catch (final IOException e) {
    112                throw new SAXException(e);
    113            }
    114        }
    115        // default processing behavior
    116        return null;
    117    }
    118}