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  
37      /** Stores a map with the registered public IDs. */
38      private final Map<String, URL> registeredEntities = new HashMap<>();
39  
40      /**
41       * Constructs a new instance.
42       */
43      public DefaultEntityResolver() {
44          // empty
45      }
46  
47      /**
48       * Gets a map with the entity IDs that have been registered using the {@code registerEntityId()} method.
49       *
50       * @return a map with the registered entity IDs
51       */
52      @Override
53      public Map<String, URL> getRegisteredEntities() {
54          return registeredEntities;
55      }
56  
57      /**
58       * <p>
59       * Registers the specified URL for the specified public identifier.
60       * </p>
61       * <p>
62       * This implementation maps {@code PUBLICID}'s to URLs (from which the resource will be loaded). A common use case for
63       * this method is to register local URLs (possibly computed at runtime by a class loader) for DTDs and Schemas. This
64       * allows the performance advantage of using a local version without having to ensure every {@code SYSTEM} URI on every
65       * processed XML document is local. This implementation provides only basic functionality. If more sophisticated
66       * features are required, either calling {@code XMLConfiguration.setDocumentBuilder(DocumentBuilder)} to set a custom
67       * {@code DocumentBuilder} (which also can be initialized with a custom {@code EntityResolver}) or creating a custom
68       * entity resolver and registering it with the XMLConfiguration is recommended.
69       * </p>
70       *
71       * @param publicId Public identifier of the Entity to be resolved
72       * @param entityURL The URL to use for reading this Entity
73       * @throws IllegalArgumentException if the public ID is undefined
74       */
75      @Override
76      public void registerEntityId(final String publicId, final URL entityURL) {
77          if (publicId == null) {
78              throw new IllegalArgumentException("Public ID must not be null!");
79          }
80          getRegisteredEntities().put(publicId, entityURL);
81      }
82  
83      /**
84       * Resolves the requested external entity. This is the default implementation of the {@code EntityResolver} interface.
85       * It checks the passed in public ID against the registered entity IDs and uses a local URL if possible.
86       *
87       * @param publicId the public identifier of the entity being referenced
88       * @param systemId the system identifier of the entity being referenced
89       * @return an input source for the specified entity
90       * @throws org.xml.sax.SAXException if a parsing exception occurs
91       */
92      @SuppressWarnings("resource") // The stream is managed by the InputSource returned by this method.
93      @Override
94      public InputSource resolveEntity(final String publicId, final String systemId) throws SAXException {
95          // Has this system identifier been registered?
96          URL entityURL = null;
97          if (publicId != null) {
98              entityURL = getRegisteredEntities().get(publicId);
99          }
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 }