samples/trycatchredo/src/org/apidesign/exceptions/trycatchredo/usage/QueryStream.java
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/samples/trycatchredo/src/org/apidesign/exceptions/trycatchredo/usage/QueryStream.java Sun Feb 01 16:29:46 2009 +0100
1.3 @@ -0,0 +1,65 @@
1.4 +package org.apidesign.exceptions.trycatchredo.usage;
1.5 +
1.6 +import org.apidesign.exceptions.trycatchredo.api.UserQuestionException;
1.7 +import java.io.ByteArrayOutputStream;
1.8 +import java.io.IOException;
1.9 +import java.io.OutputStream;
1.10 +import javax.swing.JOptionPane;
1.11 +
1.12 +public final class QueryStream extends OutputStream {
1.13 + private ByteArrayOutputStream arr = new ByteArrayOutputStream();
1.14 + /** this field can be manipulated by the QueryException */
1.15 + Boolean reverse;
1.16 +
1.17 + @Override
1.18 + public synchronized void write(byte[] b, int off, int len) throws IOException {
1.19 + if (reverse == null) {
1.20 + throw new QueryException();
1.21 + }
1.22 + arr.write(b, off, len);
1.23 + }
1.24 +
1.25 + @Override
1.26 + public synchronized void write(int b) throws IOException {
1.27 + if (reverse == null) {
1.28 + throw new QueryException();
1.29 + }
1.30 + arr.write(b);
1.31 + }
1.32 +
1.33 + @Override
1.34 + public String toString() {
1.35 + if (reverse == null) {
1.36 + return "Reverse question was not answered yet!";
1.37 + }
1.38 + if (reverse) {
1.39 + StringBuilder sb = new StringBuilder();
1.40 + sb.append(arr.toString());
1.41 + sb.reverse();
1.42 + return sb.toString();
1.43 + }
1.44 + return arr.toString();
1.45 + }
1.46 +
1.47 + private class QueryException extends UserQuestionException {
1.48 +
1.49 + @Override
1.50 + public JOptionPane getQuestionPane() {
1.51 + JOptionPane p = new JOptionPane("Store in reverse way?");
1.52 + p.setOptionType(JOptionPane.YES_NO_CANCEL_OPTION);
1.53 + return p;
1.54 + }
1.55 +
1.56 + @Override
1.57 + public void confirm(Object option) {
1.58 + if (option.equals(JOptionPane.YES_OPTION)) {
1.59 + reverse = Boolean.TRUE;
1.60 + return;
1.61 + }
1.62 + if (option.equals(JOptionPane.NO_OPTION)) {
1.63 + reverse = Boolean.FALSE;
1.64 + return;
1.65 + }
1.66 + }
1.67 + }
1.68 +}