jtulach@312: package org.apidesign.exceptions.trycatchredo.usage; jtulach@312: jtulach@312: import org.apidesign.exceptions.trycatchredo.api.UserQuestionException; jtulach@312: import java.io.ByteArrayOutputStream; jtulach@312: import java.io.IOException; jtulach@312: import java.io.OutputStream; jtulach@312: import javax.swing.JOptionPane; jtulach@312: jtulach@314: // BEGIN: trycatchredo.stream jtulach@312: public final class QueryStream extends OutputStream { jtulach@312: private ByteArrayOutputStream arr = new ByteArrayOutputStream(); jtulach@312: /** this field can be manipulated by the QueryException */ jtulach@312: Boolean reverse; jtulach@312: jtulach@312: @Override jtulach@314: public synchronized void write(byte[] b, int off, int len) jtulach@314: throws IOException { jtulach@312: if (reverse == null) { jtulach@312: throw new QueryException(); jtulach@312: } jtulach@312: arr.write(b, off, len); jtulach@312: } jtulach@312: jtulach@312: @Override jtulach@312: public synchronized void write(int b) throws IOException { jtulach@312: if (reverse == null) { jtulach@312: throw new QueryException(); jtulach@312: } jtulach@312: arr.write(b); jtulach@312: } jtulach@312: jtulach@312: @Override jtulach@312: public String toString() { jtulach@312: if (reverse == null) { jtulach@312: return "Reverse question was not answered yet!"; jtulach@312: } jtulach@312: if (reverse) { jtulach@312: StringBuilder sb = new StringBuilder(); jtulach@312: sb.append(arr.toString()); jtulach@312: sb.reverse(); jtulach@312: return sb.toString(); jtulach@312: } jtulach@312: return arr.toString(); jtulach@312: } jtulach@312: jtulach@312: private class QueryException extends UserQuestionException { jtulach@312: jtulach@312: @Override jtulach@312: public JOptionPane getQuestionPane() { jtulach@312: JOptionPane p = new JOptionPane("Store in reverse way?"); jtulach@312: p.setOptionType(JOptionPane.YES_NO_CANCEL_OPTION); jtulach@312: return p; jtulach@312: } jtulach@312: jtulach@312: @Override jtulach@312: public void confirm(Object option) { jtulach@312: if (option.equals(JOptionPane.YES_OPTION)) { jtulach@312: reverse = Boolean.TRUE; jtulach@312: return; jtulach@312: } jtulach@312: if (option.equals(JOptionPane.NO_OPTION)) { jtulach@312: reverse = Boolean.FALSE; jtulach@312: return; jtulach@312: } jtulach@312: } jtulach@312: } jtulach@312: } jtulach@314: // END: trycatchredo.stream