1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.nuiton.jrst;
23
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.net.URL;
29 import javax.xml.parsers.ParserConfigurationException;
30 import javax.xml.parsers.SAXParser;
31 import javax.xml.parsers.SAXParserFactory;
32 import javax.xml.transform.Source;
33 import javax.xml.transform.sax.SAXSource;
34 import org.apache.commons.logging.Log;
35 import org.apache.commons.logging.LogFactory;
36 import org.nuiton.util.FasterCachedResourceResolver;
37 import org.nuiton.util.Resource;
38 import org.xml.sax.EntityResolver;
39 import org.xml.sax.InputSource;
40 import org.xml.sax.SAXException;
41 import org.xml.sax.XMLReader;
42
43
44
45
46
47 public class JRSTResourceResolver extends FasterCachedResourceResolver {
48
49 static private Log log = LogFactory.getLog(JRSTResourceResolver.class);
50
51 protected String xsl;
52
53 public JRSTResourceResolver(String xsl) {
54 this.xsl = xsl;
55 }
56
57 @Override
58 public Source resolve(String href, String base) {
59
60
61 Source resolved = super.resolve(href, base);
62 if (resolved != null) {
63 return resolved;
64 }
65
66
67 if (log.isDebugEnabled()) {
68 log.debug("RESOLVING: href: "+href+" base: "+base);
69 }
70 String xslDir = xsl.substring(0, xsl.lastIndexOf('/') + 1);
71 String resouceFullName = xslDir + href;
72
73 if (log.isDebugEnabled()) {
74 log.debug("RESOLVING: resouceFullName: "+resouceFullName);
75 }
76
77 try {
78 InputStream stream;
79 File file = new File(resouceFullName);
80 if (file.exists()) {
81 stream = new FileInputStream(file);
82 } else {
83 try {
84 stream = Resource.getURL(resouceFullName).openStream();
85 }
86 catch (Exception e) {
87 stream = Resource.getURL("/docbook/common/" + href).openStream();
88 }
89 }
90
91 SAXParserFactory parserFactory = SAXParserFactory.newInstance();
92 SAXParser saxParser = parserFactory.newSAXParser();
93 XMLReader xmlReader = saxParser.getXMLReader();
94 xmlReader.setEntityResolver(new EntityResolver() {
95 @Override
96 public InputSource resolveEntity(String publicId, String systemId)
97 throws SAXException, IOException {
98
99 InputSource source = null;
100
101 String smallSystemId = systemId.substring(systemId.lastIndexOf("/") + 1);
102 URL url = Resource.getURL("/docbook/common/" + smallSystemId);
103 if (url != null) {
104 if (log.isDebugEnabled()) {
105 log.debug("Resolved entity url : " + url);
106 }
107 InputStream stream = url.openStream();
108 source = new InputSource(stream);
109 }
110
111 return source;
112 }
113 });
114 InputSource inSrc = new InputSource(stream);
115 SAXSource saxs = new SAXSource(xmlReader, inSrc);
116 return saxs;
117 } catch (IOException e) {
118 e.printStackTrace();
119 return null;
120 } catch (ParserConfigurationException e) {
121 e.printStackTrace();
122 return null;
123 } catch (SAXException e) {
124 e.printStackTrace();
125 return null;
126 }
127 }
128 }