samples/delegatingwriterfinal/src-test2.0/api/usage/twodotzero/BufferedWriterOnCDImageTest.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:53:06 +0200
changeset 66 8379bb7c0dff
permissions -rw-r--r--
Tests rewritten to new version, just the Writer version 2.0 does not yet implement Appendable
     1 
     2 package api.usage.twodotzero;
     3 
     4 import api.Writer;
     5 import java.io.IOException;
     6 import java.util.concurrent.atomic.AtomicInteger;
     7 import org.junit.Test;
     8 import static org.junit.Assert.*;
     9 
    10 /** Emulates what goes wrong when one wants to process really large character 
    11  * sequence.
    12  *
    13  * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
    14  */
    15 public class BufferedWriterOnCDImageTest {
    16     
    17     public BufferedWriterOnCDImageTest() {
    18     }
    19 
    20     @Test
    21     public void testBehaviourOfRealBufferInJDKObviouslyThisIsGoingToThrowOutOfMemoryError() throws IOException {
    22         AtomicInteger cnt = new AtomicInteger();
    23         Writer writer = CountingWriter.create(cnt);
    24         CDSequence cdImage = new CDSequence();
    25         Writer bufferedWriter = Writer.createBuffered(writer);
    26         bufferedWriter.append(cdImage);
    27         assertEquals("Correct number of writes delegated", cdImage.length(), cnt.get());
    28     }
    29 
    30 
    31     /** A "lazy" sequence of characters, for example one that can represent
    32      * content of a CD, read it lazily, do not fit all into memory at once.
    33      */
    34     private static final class CDSequence implements CharSequence {
    35         private final int start;
    36         private final int end;
    37         
    38         public CDSequence() {
    39             this(0, 647 * 1024 * 1024);
    40         }
    41 
    42         private CDSequence(int start, int end) {
    43             this.start = start;
    44             this.end = end;
    45         }
    46         
    47         
    48         public int length() {
    49             return end - start;
    50         }
    51 
    52         public char charAt(int index) {
    53             int ch = index % ('Z' - 'A' + 1);
    54             return (char) ('A' + ch);
    55         }
    56 
    57         public CharSequence subSequence(int start, int end) {
    58             return new CDSequence(start, end);
    59         }
    60 
    61         @Override
    62         public String toString() {
    63             char[] arr = new char[length()];
    64             for (int i = 0; i < length(); i++) {
    65                 arr[i] = charAt(i);
    66             }
    67             return new String(arr);
    68         }
    69         
    70         
    71     } // end of CharSequence
    72 }