View Javadoc
1   /*
2    * Copyright 2002-2012 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.xml.sax;
18  
19  import java.io.IOException;
20  import java.net.URI;
21  import java.net.URISyntaxException;
22  
23  import org.springframework.core.io.Resource;
24  
25  import org.apache.commons.logging.Log;
26  import org.apache.commons.logging.LogFactory;
27  import org.xml.sax.InputSource;
28  
29  /**
30   * Convenient utility methods for dealing with SAX.
31   *
32   * @author Arjen Poutsma
33   * @since 1.0.0
34   */
35  public abstract class SaxUtils {
36  
37      private static final Log logger = LogFactory.getLog(SaxUtils.class);
38  
39      /**
40       * Creates a SAX <code>InputSource</code> from the given resource. Sets the system identifier to the resource's
41       * <code>URL</code>, if available.
42       *
43       * @param resource the resource
44       * @return the input source created from the resource
45       * @throws IOException if an I/O exception occurs
46       * @see InputSource#setSystemId(String)
47       * @see #getSystemId(org.springframework.core.io.Resource)
48       */
49      public static InputSource createInputSource(Resource resource) throws IOException {
50          InputSource inputSource = new InputSource(resource.getInputStream());
51          inputSource.setSystemId(getSystemId(resource));
52          return inputSource;
53      }
54  
55      /** Retrieves the URL from the given resource as System ID. Returns <code>null</code> if it cannot be opened. */
56      public static String getSystemId(Resource resource) {
57          try {
58              return new URI(resource.getURL().toExternalForm()).toString();
59          }
60          catch (IOException ex) {
61              logger.debug("Could not get System ID from [" + resource + "], ex");
62              return null;
63          }
64          catch (URISyntaxException e) {
65              logger.debug("Could not get System ID from [" + resource + "], ex");
66              return null;
67          }
68      }
69  
70  }