samples/trycatchredo/src/org/apidesign/exceptions/trycatchredo/usage/QueryStream.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sun, 01 Feb 2009 16:29:46 +0100
changeset 312 0678c9589013
child 314 03a451fc2256
permissions -rw-r--r--
Renaming the project to 'Try Catch Redo'
     1 package org.apidesign.exceptions.trycatchredo.usage;
     2 
     3 import org.apidesign.exceptions.trycatchredo.api.UserQuestionException;
     4 import java.io.ByteArrayOutputStream;
     5 import java.io.IOException;
     6 import java.io.OutputStream;
     7 import javax.swing.JOptionPane;
     8 
     9 public final class QueryStream extends OutputStream {
    10     private ByteArrayOutputStream arr = new ByteArrayOutputStream();
    11     /** this field can be manipulated by the QueryException */
    12     Boolean reverse;
    13 
    14     @Override
    15     public synchronized void write(byte[] b, int off, int len) throws IOException {
    16         if (reverse == null) {
    17             throw new QueryException();
    18         }
    19         arr.write(b, off, len);
    20     }
    21 
    22     @Override
    23     public synchronized void write(int b) throws IOException {
    24         if (reverse == null) {
    25             throw new QueryException();
    26         }
    27         arr.write(b);
    28     }
    29 
    30     @Override
    31     public String toString() {
    32         if (reverse == null) {
    33             return "Reverse question was not answered yet!";
    34         }
    35         if (reverse) {
    36             StringBuilder sb = new StringBuilder();
    37             sb.append(arr.toString());
    38             sb.reverse();
    39             return sb.toString();
    40         }
    41         return arr.toString();
    42     }
    43 
    44     private class QueryException extends UserQuestionException {
    45 
    46         @Override
    47         public JOptionPane getQuestionPane() {
    48             JOptionPane p = new JOptionPane("Store in reverse way?");
    49             p.setOptionType(JOptionPane.YES_NO_CANCEL_OPTION);
    50             return p;
    51         }
    52 
    53         @Override
    54         public void confirm(Object option) {
    55             if (option.equals(JOptionPane.YES_OPTION)) {
    56                 reverse = Boolean.TRUE;
    57                 return;
    58             }
    59             if (option.equals(JOptionPane.NO_OPTION)) {
    60                 reverse = Boolean.FALSE;
    61                 return;
    62             }
    63         }
    64     }
    65 }