/********************************************************************
 * 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 org.apache.log4j.Logger;
import org.springframework.core.io.ClassPathResource;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import org.apache.commons.io.IOUtils;

/**
 * ClassPathEntityResolver created on Dec 5, 2006
 * @author DNS   LEV
 */
public class ClassPathEntityResolver implements EntityResolver {

   /**
    * An instance of logger 
    */
   private Logger logger = Logger.getLogger( getClass() );
   
   /**
    * A default constructor
    */
   public ClassPathEntityResolver() {
      super();
   }
 
   /**
    * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String)
    */
   public InputSource resolveEntity( String publicId, String systemId ) 
      throws SAXException, IOException {

      if( logger.isDebugEnabled() ) {
         logger.debug( "Resolve system Id: " + systemId );
      }
      InputSource source = null;
      int pos = -1;
      if( systemId != null && (pos = systemId.indexOf( "edb" )) != -1 ) {
         // Ignore a file:// and only get a path starting from edb.
         // For instance edb/messaging/hl7/xsd/messages/vista/inbound/ORUZ07.xsd
         String path = systemId.substring( pos );
         
         ClassPathResource resource = new ClassPathResource( path );
         InputStream istream = null;
         try {
        	 istream = resource.getInputStream();
        	 source = new InputSource( new BufferedInputStream(istream));
         } 
         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 source;
   }
}