View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.configuration2.resolver;
18  
19  import java.io.IOException;
20  import java.io.InputStream;
21  import java.net.URL;
22  import java.net.URLConnection;
23  import java.util.HashMap;
24  import java.util.Map;
25  
26  import org.xml.sax.EntityResolver;
27  import org.xml.sax.InputSource;
28  import org.xml.sax.SAXException;
29  
30  /**
31   * The DefaultEntityResolver used by XML Configurations.
32   *
33   * @since 1.7
34   */
35  public class DefaultEntityResolver implements EntityResolver, EntityRegistry {
36      /** Stores a map with the registered public IDs. */
37      private final Map<String, URL> registeredEntities = new HashMap<>();
38  
39      /**
40       * Constructs a new instance.
41       */
42      public DefaultEntityResolver() {
43          // empty
44      }
45  
46      /**
47       * Gets a map with the entity IDs that have been registered using the {@code registerEntityId()} method.
48       *
49       * @return a map with the registered entity IDs
50       */
51      @Override
52      public Map<String, URL> getRegisteredEntities() {
53          return registeredEntities;
54      }
55  
56      /**
57       * <p>
58       * Registers the specified URL for the specified public identifier.
59       * </p>
60       * <p>
61       * This implementation maps {@code PUBLICID}'s to URLs (from which the resource will be loaded). A common use case for
62       * this method is to register local URLs (possibly computed at runtime by a class loader) for DTDs and Schemas. This
63       * allows the performance advantage of using a local version without having to ensure every {@code SYSTEM} URI on every
64       * processed XML document is local. This implementation provides only basic functionality. If more sophisticated
65       * features are required, either calling {@code XMLConfiguration.setDocumentBuilder(DocumentBuilder)} to set a custom
66       * {@code DocumentBuilder} (which also can be initialized with a custom {@code EntityResolver}) or creating a custom
67       * entity resolver and registering it with the XMLConfiguration is recommended.
68       * </p>
69       *
70       * @param publicId Public identifier of the Entity to be resolved
71       * @param entityURL The URL to use for reading this Entity
72       * @throws IllegalArgumentException if the public ID is undefined
73       */
74      @Override
75      public void registerEntityId(final String publicId, final URL entityURL) {
76          if (publicId == null) {
77              throw new IllegalArgumentException("Public ID must not be null!");
78          }
79          getRegisteredEntities().put(publicId, entityURL);
80      }
81  
82      /**
83       * Resolves the requested external entity. This is the default implementation of the {@code EntityResolver} interface.
84       * It checks the passed in public ID against the registered entity IDs and uses a local URL if possible.
85       *
86       * @param publicId the public identifier of the entity being referenced
87       * @param systemId the system identifier of the entity being referenced
88       * @return an input source for the specified entity
89       * @throws org.xml.sax.SAXException if a parsing exception occurs
90       */
91      @SuppressWarnings("resource") // The stream is managed by the InputSource returned by this method.
92      @Override
93      public InputSource resolveEntity(final String publicId, final String systemId) throws SAXException {
94          // Has this system identifier been registered?
95          URL entityURL = null;
96          if (publicId != null) {
97              entityURL = getRegisteredEntities().get(publicId);
98          }
99  
100         if (entityURL != null) {
101             // Obtain an InputSource for this URL. This code is based on the
102             // createInputSourceFromURL() method of Commons Digester.
103             try {
104                 final URLConnection connection = entityURL.openConnection();
105                 connection.setUseCaches(false);
106                 final InputStream stream = connection.getInputStream();
107                 final InputSource source = new InputSource(stream);
108                 source.setSystemId(entityURL.toExternalForm());
109                 return source;
110             } catch (final IOException e) {
111                 throw new SAXException(e);
112             }
113         }
114         // default processing behavior
115         return null;
116     }
117 }