1. /*
  2. * Copyright 2002-2004 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. package org.springframework.beans.factory.xml;
  17. import java.io.IOException;
  18. import org.apache.commons.logging.Log;
  19. import org.apache.commons.logging.LogFactory;
  20. import org.xml.sax.EntityResolver;
  21. import org.xml.sax.InputSource;
  22. import org.springframework.core.io.ClassPathResource;
  23. import org.springframework.core.io.Resource;
  24. /**
  25. * EntityResolver implementation for the Spring beans DTD,
  26. * to load the DTD from the Spring classpath resp. JAR file.
  27. *
  28. * <p>Fetches "spring-beans.dtd" from the classpath resource
  29. * "/org/springframework/beans/factory/xml/spring-beans.dtd",
  30. * no matter if specified as some local URL or as
  31. * "http://www.springframework.org/dtd/spring-beans.dtd".
  32. *
  33. * @author Juergen Hoeller
  34. * @since 04.06.2003
  35. */
  36. public class BeansDtdResolver implements EntityResolver {
  37. private static final String DTD_NAME = "spring-beans";
  38. private static final String SEARCH_PACKAGE = "/org/springframework/beans/factory/xml/";
  39. protected final Log logger = LogFactory.getLog(getClass());
  40. public InputSource resolveEntity(String publicId, String systemId) throws IOException {
  41. logger.debug("Trying to resolve XML entity with public ID [" + publicId +
  42. "] and system ID [" + systemId + "]");
  43. if (systemId != null && systemId.indexOf(DTD_NAME) > systemId.lastIndexOf("/")) {
  44. String dtdFile = systemId.substring(systemId.indexOf(DTD_NAME));
  45. logger.debug("Trying to locate [" + dtdFile + "] under [" + SEARCH_PACKAGE + "]");
  46. try {
  47. Resource resource = new ClassPathResource(SEARCH_PACKAGE + dtdFile, getClass());
  48. InputSource source = new InputSource(resource.getInputStream());
  49. source.setPublicId(publicId);
  50. source.setSystemId(systemId);
  51. logger.debug("Found beans DTD [" + systemId + "] in classpath");
  52. return source;
  53. }
  54. catch (IOException ex) {
  55. logger.debug("Could not resolve beans DTD [" + systemId + "]: not found in classpath", ex);
  56. }
  57. }
  58. // use the default behaviour -> download from website or wherever
  59. return null;
  60. }
  61. }