KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > genimen > djeneric > web > util > DjenericXslUriResolver


1 package com.genimen.djeneric.web.util;
2
3 import java.io.BufferedReader JavaDoc;
4 import java.io.InputStream JavaDoc;
5 import java.io.InputStreamReader JavaDoc;
6 import java.io.UnsupportedEncodingException JavaDoc;
7
8 import javax.xml.transform.Source JavaDoc;
9 import javax.xml.transform.TransformerException JavaDoc;
10 import javax.xml.transform.URIResolver JavaDoc;
11 import javax.xml.transform.stream.StreamSource JavaDoc;
12
13 import com.genimen.djeneric.util.DjLogger;
14
15 public class DjenericXslUriResolver implements URIResolver JavaDoc
16 {
17   private static final String JavaDoc CLASSPATH_PROTOCOL = "classpath:";
18
19   public DjenericXslUriResolver()
20   {
21   }
22
23   public Source JavaDoc resolve(String JavaDoc fileName, String JavaDoc base) throws TransformerException JavaDoc
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 JavaDoc 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 JavaDoc basePath = base + subPath;
48     String JavaDoc absPath = basePath + fileName;
49
50     String JavaDoc actualName = absPath.substring(CLASSPATH_PROTOCOL.length());
51     InputStream JavaDoc is = Thread.currentThread().getContextClassLoader().getResourceAsStream(actualName);
52     if (is == null)
53     {
54       is = getClass().getResourceAsStream(actualName);
55       if (is == null) throw new TransformerException JavaDoc("Stylesheet " + actualName + " not found (" + absPath + ")");
56     }
57
58     StreamSource JavaDoc ss;
59     try
60     {
61       ss = new StreamSource JavaDoc(new BufferedReader JavaDoc(new InputStreamReader JavaDoc(is, "UTF-8")));
62     }
63     catch (UnsupportedEncodingException JavaDoc e)
64     {
65       DjLogger.log(e);
66       ss = new StreamSource JavaDoc(new BufferedReader JavaDoc(new InputStreamReader JavaDoc(is)));
67     }
68     ss.setPublicId(absPath);
69     ss.setSystemId(absPath);
70     return ss;
71   }
72 }
Popular Tags