/*****************************************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ****************************************************************************************/
package gov.va.med.esr.messaging.xml;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.core.io.ClassPathResource;

/**
 * ClassPathURIResolver created on Nov 8, 2006
 * 
 * @author DNS   LEV
 */
public class ClassPathURIResolver implements URIResolver {

   /**
    * An instance of logger 
    */
   private Logger logger = Logger.getLogger( getClass() );
   
   /**
    * A default constructor
    */
   public ClassPathURIResolver() {
      super();
   }

   /**
    * Called by the processor when it encounters an xsl:include, xsl:import, or document()
    * function.
    * 
    * @param href An href attribute, which may be relative or absolute.
    * @param base The base URI in effect when the href attribute was encountered.
    * @return A Source object, or null if the href cannot be resolved, and the processor
    *         should try to resolve the URI itself.
    * @throws TransformerException if an error occurs when trying to resolve the URI.
    */
   public Source resolve(String href, String base) throws TransformerException {
      
      if( logger.isDebugEnabled() ) {
         logger.debug( "Resolve system Id: " + href );
      }
      StreamSource stream = null;
      if( href != null && href.indexOf( "edb" ) != -1 ) {
    	  InputStream istream = null;
         try {
            ClassPathResource resource = new ClassPathResource( href );
            istream = resource.getInputStream();
            stream = new StreamSource( new BufferedInputStream(istream) );
         }
         catch( IOException e ) {
            throw new TransformerException( "Failed to translate a path of " + href );
         } finally {
        	/* Reverted Fortify resource leak finding change.
        	  Input stream need to be open throughout the WLS server's life cycle.
 			if (istream != null) {
				IOUtils.closeQuietly(istream);
			}     
			*/   	 
         }
         
      }
      return stream;
   }
}