001/*
002 *  Copyright 2010, 2011 Christopher Pheby
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 *      http://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 */
016package org.jadira.bindings.core.loader;
017
018import java.io.IOException;
019import java.io.InputStream;
020
021import org.xml.sax.EntityResolver;
022import org.xml.sax.InputSource;
023import org.xml.sax.SAXException;
024
025/**
026 * A SAX entity resolving capable of resolving files from the classpath when
027 * prefixed with the custom 'classpath:/' URL scheme
028 */
029public class BindingXmlEntityResolver implements EntityResolver {
030
031        private static final String CLASSPATH_SCHEME = "classpath:/";
032
033        public InputSource resolveEntity(String publicId, String systemId)
034                        throws SAXException, IOException {
035
036                if (systemId.startsWith(CLASSPATH_SCHEME)) {
037                        String filename = systemId.substring(CLASSPATH_SCHEME.length());
038                        InputStream stream = Thread.currentThread().getContextClassLoader()
039                                        .getResourceAsStream(filename);
040                        return new InputSource(stream);
041                } else {
042                        return null;
043                }
044        }
045}