001/* 002 * Copyright 2002-2012 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.oxm.support; 018 019import java.io.IOException; 020 021import org.xml.sax.InputSource; 022 023import org.springframework.core.io.Resource; 024import org.springframework.lang.Nullable; 025 026/** 027 * Convenient utility methods for dealing with SAX. 028 * 029 * @author Arjen Poutsma 030 * @author Juergen Hoeller 031 * @since 3.0 032 */ 033public abstract class SaxResourceUtils { 034 035 /** 036 * Create a SAX {@code InputSource} from the given resource. 037 * <p>Sets the system identifier to the resource's {@code URL}, if available. 038 * @param resource the resource 039 * @return the input source created from the resource 040 * @throws IOException if an I/O exception occurs 041 * @see InputSource#setSystemId(String) 042 * @see #getSystemId(org.springframework.core.io.Resource) 043 */ 044 public static InputSource createInputSource(Resource resource) throws IOException { 045 InputSource inputSource = new InputSource(resource.getInputStream()); 046 inputSource.setSystemId(getSystemId(resource)); 047 return inputSource; 048 } 049 050 /** 051 * Retrieve the URL from the given resource as System ID. 052 * <p>Returns {@code null} if it cannot be opened. 053 */ 054 @Nullable 055 private static String getSystemId(Resource resource) { 056 try { 057 return resource.getURI().toString(); 058 } 059 catch (IOException ex) { 060 return null; 061 } 062 } 063 064}