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