1 package com.genimen.djeneric.web.util; 2 3 import java.io.BufferedReader ; 4 import java.io.InputStream ; 5 import java.io.InputStreamReader ; 6 import java.io.UnsupportedEncodingException ; 7 8 import javax.xml.transform.Source ; 9 import javax.xml.transform.TransformerException ; 10 import javax.xml.transform.URIResolver ; 11 import javax.xml.transform.stream.StreamSource ; 12 13 import com.genimen.djeneric.util.DjLogger; 14 15 public class DjenericXslUriResolver implements URIResolver 16 { 17 private static final String CLASSPATH_PROTOCOL = "classpath:"; 18 19 public DjenericXslUriResolver() 20 { 21 } 22 23 public Source resolve(String fileName, String base) throws TransformerException 24 { 25 if (base == null || base.indexOf("/") == -1) base = CLASSPATH_PROTOCOL; 26 27 if (base.toLowerCase().endsWith(".xsl") || base.toLowerCase().endsWith(".xslt") 28 || base.toLowerCase().endsWith(".xml")) 29 { 30 base = base.replace('\\', '/'); 31 int idx = base.lastIndexOf("/"); 32 if (idx != -1) base = base.substring(0, idx + 1); 33 } 34 35 if (!base.endsWith("/")) base += "/"; 36 37 fileName = fileName.replace('\\', '/'); 38 39 String subPath = ""; 40 int idx = fileName.lastIndexOf("/"); 41 if (idx != -1) 42 { 43 subPath = fileName.substring(0, idx + 1); 44 fileName = fileName.substring(idx + 1); 45 } 46 47 String basePath = base + subPath; 48 String absPath = basePath + fileName; 49 50 String actualName = absPath.substring(CLASSPATH_PROTOCOL.length()); 51 InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(actualName); 52 if (is == null) 53 { 54 is = getClass().getResourceAsStream(actualName); 55 if (is == null) throw new TransformerException ("Stylesheet " + actualName + " not found (" + absPath + ")"); 56 } 57 58 StreamSource ss; 59 try 60 { 61 ss = new StreamSource (new BufferedReader (new InputStreamReader (is, "UTF-8"))); 62 } 63 catch (UnsupportedEncodingException e) 64 { 65 DjLogger.log(e); 66 ss = new StreamSource (new BufferedReader (new InputStreamReader (is))); 67 } 68 ss.setPublicId(absPath); 69 ss.setSystemId(absPath); 70 return ss; 71 } 72 } | Popular Tags |