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