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 *     http://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 * @since 1.7
033 */
034public class DefaultEntityResolver implements EntityResolver, EntityRegistry
035{
036    /** Stores a map with the registered public IDs.*/
037    private final Map<String, URL> registeredEntities = new HashMap<>();
038
039    /**
040     * <p>
041     * Registers the specified URL for the specified public identifier.
042     * </p>
043     * <p>
044     * This implementation maps {@code PUBLICID}'s to URLs (from which
045     * the resource will be loaded). A common use case for this method is to
046     * register local URLs (possibly computed at runtime by a class loader) for
047     * DTDs and Schemas. This allows the performance advantage of using a local
048     * version without having to ensure every {@code SYSTEM} URI on every
049     * processed XML document is local. This implementation provides only basic
050     * functionality. If more sophisticated features are required, either calling
051     * {@code XMLConfiguration.setDocumentBuilder(DocumentBuilder)} to set a custom
052     * {@code DocumentBuilder} (which also can be initialized with a
053     * custom {@code EntityResolver}) or creating a custom entity resolver
054     * and registering it with the XMLConfiguration is recommended.
055     * </p>
056     *
057     * @param publicId Public identifier of the Entity to be resolved
058     * @param entityURL The URL to use for reading this Entity
059     * @throws IllegalArgumentException if the public ID is undefined
060     */
061    @Override
062    public void registerEntityId(final String publicId, final URL entityURL)
063    {
064        if (publicId == null)
065        {
066            throw new IllegalArgumentException("Public ID must not be null!");
067        }
068        getRegisteredEntities().put(publicId, entityURL);
069    }
070
071    /**
072     * Resolves the requested external entity. This is the default
073     * implementation of the {@code EntityResolver} interface. It checks
074     * the passed in public ID against the registered entity IDs and uses a
075     * local URL if possible.
076     *
077     * @param publicId the public identifier of the entity being referenced
078     * @param systemId the system identifier of the entity being referenced
079     * @return an input source for the specified entity
080     * @throws org.xml.sax.SAXException if a parsing exception occurs
081     */
082    @SuppressWarnings("resource") // The stream is managed by the InputSource returned by this method.
083    @Override
084    public InputSource resolveEntity(final String publicId, final String systemId)
085            throws SAXException
086    {
087        // Has this system identifier been registered?
088        URL entityURL = null;
089        if (publicId != null)
090        {
091            entityURL = getRegisteredEntities().get(publicId);
092        }
093
094        if (entityURL != null)
095        {
096            // Obtain an InputSource for this URL. This code is based on the
097            // createInputSourceFromURL() method of Commons Digester.
098            try
099            {
100                final URLConnection connection = entityURL.openConnection();
101                connection.setUseCaches(false);
102                final InputStream stream = connection.getInputStream();
103                final InputSource source = new InputSource(stream);
104                source.setSystemId(entityURL.toExternalForm());
105                return source;
106            }
107            catch (final IOException e)
108            {
109                throw new SAXException(e);
110            }
111        }
112        // default processing behavior
113        return null;
114    }
115
116    /**
117     * Returns a map with the entity IDs that have been registered using the
118     * {@code registerEntityId()} method.
119     *
120     * @return a map with the registered entity IDs
121     */
122    @Override
123    public Map<String, URL> getRegisteredEntities()
124    {
125        return registeredEntities;
126    }
127}