01: /*
02: * Created on 11-Sep-2006
03: */
04: package uk.org.ponder.htmlutil;
05:
06: import java.io.BufferedReader;
07: import java.io.Reader;
08:
09: import uk.org.ponder.streamutil.ReaderCopier;
10: import uk.org.ponder.streamutil.StreamCloseUtil;
11: import uk.org.ponder.streamutil.write.PrintOutputStream;
12: import uk.org.ponder.util.UniversalRuntimeException;
13: import uk.org.ponder.xml.XMLWriter;
14:
15: /**
16: * @author Antranig Basman (antranig@caret.cam.ac.uk)
17: *
18: */
19: public class TextToHTMLRenderer implements ReaderCopier {
20:
21: /**
22: * Copies text from input to output, converting newlines into XHTML
23: * <br/> elements. The supplied streams WILL be closed!
24: */
25: public void copyReader(Reader r, PrintOutputStream pos) {
26: BufferedReader br = new BufferedReader(r);
27: XMLWriter xmlw = new XMLWriter(pos);
28: try {
29: while (true) {
30: String line = br.readLine();
31:
32: if (line == null)
33: break;
34: xmlw.write(line);
35: // TODO: make some kind of "XMLFilterWriter" architecture if necessary
36: // writeEncodeLinks(xmlw, line);
37: xmlw.writeRaw("<br/>");
38: }
39: } catch (Throwable t) {
40: throw UniversalRuntimeException.accumulate(t,
41: "Error rendering text as HTML");
42: } finally {
43: StreamCloseUtil.closeReader(r);
44: pos.close();
45: }
46: }
47:
48: public static void writeEncodeLinks(XMLWriter xmlw, String line) {
49: int linkpos = line.indexOf("://");
50: if (linkpos == -1) {
51: xmlw.write(line);
52: return;
53: }
54: int backpos = linkpos - 1;
55: for (; backpos >= 0; --backpos) {
56: if (Character.isWhitespace(line.charAt(backpos)))
57: break;
58: }
59: ++backpos;
60: if (backpos == linkpos - 1) { // require non-empty protocol
61: xmlw.write(line);
62: return;
63: }
64:
65: int frontpos = linkpos + 3;
66: for (; frontpos < line.length(); ++frontpos) {
67: if (Character.isWhitespace(line.charAt(backpos)))
68: break;
69: }
70: String url = line.substring(backpos, frontpos);
71: xmlw.write(line.substring(0, backpos));
72: xmlw.writeRaw("<a target=\"_top\" href=\"");
73: xmlw.write(url);
74: xmlw.writeRaw("\">");
75: xmlw.write(url);
76: xmlw.writeRaw("</a>");
77: xmlw.write(line.substring(frontpos));
78: }
79:
80: }
|