View Javadoc

1   /*
2    * Copyright 2006 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.xml.sax.InputSource;
24  
25  import org.springframework.core.io.Resource;
26  
27  /**
28   * Convenient utility methods for dealing with SAX.
29   *
30   * @author Arjen Poutsma
31   * @since 1.0.0
32   */
33  public abstract class SaxUtils {
34  
35      /**
36       * Creates a SAX <code>InputSource</code> from the given resource. Sets the system identifier to the resource's
37       * <code>URL</code>, if available.
38       *
39       * @param resource the resource
40       * @return the input source created from the resource
41       * @throws IOException if an I/O exception occurs
42       * @see InputSource#setSystemId(String)
43       * @see #getSystemId(org.springframework.core.io.Resource)
44       */
45      public static InputSource createInputSource(Resource resource) throws IOException {
46          InputSource inputSource = new InputSource(resource.getInputStream());
47          inputSource.setSystemId(getSystemId(resource));
48          return inputSource;
49      }
50  
51      /** Retrieves the URL from the given resource as System ID. Returns <code>null</code> if it cannot be opened. */
52      public static String getSystemId(Resource resource) {
53          try {
54              return new URI(resource.getURL().toExternalForm()).toString();
55          }
56          catch (IOException e) {
57              return null;
58          }
59          catch (URISyntaxException e) {
60              return null;
61          }
62      }
63  
64  }