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; 024 025/** 026 * Convenient utility methods for dealing with SAX. 027 * 028 * @author Arjen Poutsma 029 * @author Juergen Hoeller 030 * @since 3.0 031 */ 032public abstract class SaxResourceUtils { 033 034 /** 035 * Create a SAX {@code InputSource} from the given resource. 036 * <p>Sets the system identifier to the resource's {@code URL}, if available. 037 * @param resource the resource 038 * @return the input source created from the resource 039 * @throws IOException if an I/O exception occurs 040 * @see InputSource#setSystemId(String) 041 * @see #getSystemId(org.springframework.core.io.Resource) 042 */ 043 public static InputSource createInputSource(Resource resource) throws IOException { 044 InputSource inputSource = new InputSource(resource.getInputStream()); 045 inputSource.setSystemId(getSystemId(resource)); 046 return inputSource; 047 } 048 049 /** 050 * Retrieve the URL from the given resource as System ID. 051 * <p>Returns {@code null} if it cannot be opened. 052 */ 053 private static String getSystemId(Resource resource) { 054 try { 055 return resource.getURI().toString(); 056 } 057 catch (IOException ex) { 058 return null; 059 } 060 } 061 062}