samples/delegatingwriterfinal/src-test1.0/api/usage/CryptoWriter.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:53:07 +0200
changeset 67 b029a28df444
permissions -rw-r--r--
As the purpose of buffer is to "buffer", let's modify our example to delegate to appendable methods directly only if the appendable is too big
     1 
     2 package api.usage;
     3 
     4 import api.Writer;
     5 import java.io.IOException;
     6 
     7 
     8 /** Writer alters each char from 'A' to 'Z' range with next one just like
     9  * old Romans did.
    10  *
    11  * @author Jaroslav Tulach
    12  */
    13 public class CryptoWriter implements Writer.Impl {
    14     private Writer out;
    15     
    16     private CryptoWriter(Writer out) {
    17         this.out = out;
    18     }
    19     
    20     
    21     public static Writer create(Writer out) {
    22         return Writer.create(new CryptoWriter(out));
    23     }
    24     
    25     @Override
    26     public void write(char[] cbuf, int off, int len) throws IOException {
    27         char[] arr = new char[len];
    28         for (int i = 0; i < len; i++) {
    29             arr[i] = convertChar(cbuf[off + i]);
    30         }
    31         out.write(arr, 0, len);
    32     }
    33 
    34     @Override
    35     public void write(String str, int off, int len) throws IOException {
    36         StringBuffer sb = new StringBuffer();
    37         for (int i = 0; i < len; i++) {
    38             sb.append(convertChar(str.charAt(off + i)));
    39         }
    40         out.write(sb.toString(), 0, len);
    41     }
    42 
    43     private char convertChar(int c) {
    44         if (c == 'Z') {
    45             return 'A';
    46         }
    47         if (c == 'z') {
    48             return 'a';
    49         }
    50         return (char)(c + 1);
    51     }
    52 
    53     public void close() throws IOException {
    54         out.close();
    55     }
    56 
    57     public void flush() throws IOException {
    58         out.flush();
    59     }
    60 }