KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensymphony > module > sitemesh > util > OutputConverter


1 package com.opensymphony.module.sitemesh.util;
2
3 import java.io.*;
4
5 /**
6  * A converter from one character type to another
7  * <p>
8  * This class is not threadsafe
9  */

10 public class OutputConverter
11 {
12     /**
13      * Resin versions 2.1.12 and previously have encoding problems for internationalisation.
14      * <p>
15      * This is fixed in Resin 2.1.13. Once 2.1.13 is used more widely, this parameter (and class) can be removed.
16      */

17     public static final String JavaDoc WORK_AROUND_RESIN_I18N_BUG = "sitemesh.resin.i18n.workaround";
18
19     public static Writer getWriter(Writer out)
20     {
21         if ("true".equalsIgnoreCase(System.getProperty(WORK_AROUND_RESIN_I18N_BUG)))
22             return new ResinWriter(out);
23         else
24             return out;
25     }
26
27     public static String JavaDoc convert(String JavaDoc inputString) throws IOException
28     {
29         if ("true".equalsIgnoreCase(System.getProperty(WORK_AROUND_RESIN_I18N_BUG)))
30         {
31             StringWriter sr = new StringWriter();
32             resinConvert(inputString, sr);
33             return sr.getBuffer().toString();
34         }
35         else
36             return inputString;
37     }
38
39     /**
40      * To get internationalised characters to work on Resin, some conversions need to take place.
41      */

42     static class ResinWriter extends Writer
43     {
44         private final Writer target;
45         private final CharArrayWriter buffer = new CharArrayWriter();
46
47         public ResinWriter(Writer target)
48         {
49             this.target = target;
50         }
51
52         public void close() throws IOException
53         {
54             flush();
55         }
56
57         public void flush() throws IOException
58         {
59             resinConvert(buffer.toString(), target);
60             buffer.reset();
61         }
62
63         public void write(char cbuf[], int off, int len) throws IOException
64         {
65             buffer.write(cbuf, off, len);
66             flush();
67         }
68     }
69
70     private static void resinConvert(String JavaDoc inputString, Writer writer) throws IOException
71     {
72         //does this need to be made configurable? Or are these two always correct?
73
InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(inputString.getBytes("UTF-8")), "ISO-8859-1");
74         int i;
75         while ((i = reader.read()) != -1)
76         {
77             writer.write(i);
78         }
79         writer.flush();
80     }
81
82 }
83
Popular Tags