samples/trycatchredo/src/org/apidesign/exceptions/trycatchredo/usage/QueryStream.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 03 Apr 2020 16:32:36 +0200
changeset 416 9ed8788a1a4e
parent 312 0678c9589013
permissions -rw-r--r--
Using HTTPS to download the libraries
     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 // BEGIN: trycatchredo.stream
    10 public final class QueryStream extends OutputStream {
    11     private ByteArrayOutputStream arr = new ByteArrayOutputStream();
    12     /** this field can be manipulated by the QueryException */
    13     Boolean reverse;
    14 
    15     @Override
    16     public synchronized void write(byte[] b, int off, int len)
    17     throws IOException {
    18         if (reverse == null) {
    19             throw new QueryException();
    20         }
    21         arr.write(b, off, len);
    22     }
    23 
    24     @Override
    25     public synchronized void write(int b) throws IOException {
    26         if (reverse == null) {
    27             throw new QueryException();
    28         }
    29         arr.write(b);
    30     }
    31 
    32     @Override
    33     public String toString() {
    34         if (reverse == null) {
    35             return "Reverse question was not answered yet!";
    36         }
    37         if (reverse) {
    38             StringBuilder sb = new StringBuilder();
    39             sb.append(arr.toString());
    40             sb.reverse();
    41             return sb.toString();
    42         }
    43         return arr.toString();
    44     }
    45 
    46     private class QueryException extends UserQuestionException {
    47 
    48         @Override
    49         public JOptionPane getQuestionPane() {
    50             JOptionPane p = new JOptionPane("Store in reverse way?");
    51             p.setOptionType(JOptionPane.YES_NO_CANCEL_OPTION);
    52             return p;
    53         }
    54 
    55         @Override
    56         public void confirm(Object option) {
    57             if (option.equals(JOptionPane.YES_OPTION)) {
    58                 reverse = Boolean.TRUE;
    59                 return;
    60             }
    61             if (option.equals(JOptionPane.NO_OPTION)) {
    62                 reverse = Boolean.FALSE;
    63                 return;
    64             }
    65         }
    66     }
    67 }
    68 // END: trycatchredo.stream