/*
* Copyright 2007-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.impalaframework.module.builder;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.impalaframework.exception.ConfigurationException;
import org.impalaframework.xml.SimpleSaxErrorHandler;
import org.springframework.beans.factory.xml.DefaultDocumentLoader;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.util.Assert;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class XmlModulelDefinitionDocumentLoader {
private static final Log logger = LogFactory.getLog(XmlModulelDefinitionDocumentLoader.class);
Document loadDocument(Resource resource) {
Assert.notNull(resource);
EncodedResource encodedResource = new EncodedResource(resource, "UTF-8");
InputStream inputStream = null;
try {
// this will throw an IOException if the stream cannot be opened
inputStream = encodedResource.getResource().getInputStream();
}
catch (IOException e) {
throw new ConfigurationException(
"Could not load module definition, as unable to obtain input stream for resource "
+ encodedResource.getResource(), e);
}
Document document = null;
DefaultDocumentLoader loader = new DefaultDocumentLoader();
try {
InputSource inputSource = new InputSource(inputStream);
inputSource.setEncoding(encodedResource.getEncoding());
document = loader.loadDocument(inputSource, null, new SimpleSaxErrorHandler(logger),
XmlBeanDefinitionReader.VALIDATION_NONE, false);
}
catch (Exception e) {
throw new ConfigurationException("Unable to load XML module definition document from resource "
+ encodedResource.getResource(), e);
}
finally {
try {
if (inputStream != null)
inputStream.close();
}
catch (IOException e) {
}
}
return document;
}
}