01: /**
02: * $Id: DTDResolver.java,v 1.1 2005/03/21 05:25:46 ru111118 Exp $
03: * Copyright 2004 Sun Microsystems, Inc. All
04: * rights reserved. Use of this product is subject
05: * to license terms. Federal Acquisitions:
06: * Commercial Software -- Government Users
07: * Subject to Standard License Terms and
08: * Conditions.
09: *
10: * Sun, Sun Microsystems, the Sun logo, and Sun ONE
11: * are trademarks or registered trademarks of Sun Microsystems,
12: * Inc. in the United States and other countries.
13: */package com.sun.portal.util;
14:
15: import java.io.Reader;
16: import java.io.BufferedReader;
17: import java.io.StringReader;
18: import java.io.InputStream;
19: import java.io.FileInputStream;
20: import java.io.InputStreamReader;
21: import java.io.IOException;
22: import java.io.FileNotFoundException;
23: import java.net.URL;
24:
25: import org.xml.sax.InputSource;
26: import org.xml.sax.SAXException;
27: import org.xml.sax.SAXParseException;
28: import org.xml.sax.helpers.DefaultHandler;
29:
30: public class DTDResolver extends DefaultHandler {
31:
32: public InputSource resolveEntity(String aPublicID, String aSystemID)
33: throws SAXException {
34:
35: String sysid = aSystemID.trim();
36: if (sysid.toLowerCase().startsWith("jar://")) {
37: String dtdname = sysid.substring(5);
38: String dtdValue = read(dtdname, DTDResolver.class).trim();
39: return new InputSource(new StringReader(dtdValue));
40: }
41:
42: return super .resolveEntity(aPublicID, aSystemID);
43:
44: }
45:
46: public static String read(String fileName, Class cl)
47: throws SAXException {
48:
49: String data = "";
50:
51: try {
52:
53: InputStream in = cl.getResourceAsStream(fileName);
54: //may be absolute file path is given
55: if (in == null) {
56: try {
57: //works well if the user has given absolute path
58: in = new FileInputStream(fileName);
59: } catch (FileNotFoundException e) {
60: //works well if the user has given the relative path to the
61: //location of class file
62: String directoryURL = cl.getProtectionDomain()
63: .getCodeSource().getLocation().toString();
64: String fileURL = directoryURL + fileName;
65: URL url = new URL(fileURL);
66: in = url.openStream();
67: }
68: }
69: data = read(new InputStreamReader(in));
70: in.close();
71: } catch (Exception e) {
72: throw new SAXException("Failed to fetch the DTD", e);
73: }
74: return data;
75: }
76:
77: /**
78: * This method reads the resource from a reader
79: */
80: public static String read(Reader aReader) throws IOException {
81:
82: StringBuffer sb = new StringBuffer();
83: BufferedReader bReader = new BufferedReader(aReader);
84: char[] data = new char[2048];
85:
86: int count = 0;
87: while ((count = bReader.read(data)) != -1) {
88: sb.append(data, 0, count);
89: }
90:
91: bReader.close();
92: aReader.close();
93:
94: return sb.toString();
95: }
96:
97: }
|