001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.io.output;
018
019import java.io.IOException;
020import java.io.OutputStream;
021
022/**
023 * Broken output stream. This stream always throws an {@link IOException} from
024 * all {@link OutputStream} methods.
025 * <p>
026 * This class is mostly useful for testing error handling in code that uses an
027 * output stream.
028 * </p>
029 *
030 * @since 2.0
031 */
032public class BrokenOutputStream extends OutputStream {
033
034    /**
035     * The exception that is thrown by all methods of this class.
036     */
037    private final IOException exception;
038
039    /**
040     * Creates a new stream that always throws the given exception.
041     *
042     * @param exception the exception to be thrown
043     */
044    public BrokenOutputStream(final IOException exception) {
045        this.exception = exception;
046    }
047
048    /**
049     * Creates a new stream that always throws an {@link IOException}
050     */
051    public BrokenOutputStream() {
052        this(new IOException("Broken output stream"));
053    }
054
055    /**
056     * Throws the configured exception.
057     *
058     * @param b ignored
059     * @throws IOException always thrown
060     */
061    @Override
062    public void write(final int b) throws IOException {
063        throw exception;
064    }
065
066    /**
067     * Throws the configured exception.
068     *
069     * @throws IOException always thrown
070     */
071    @Override
072    public void flush() throws IOException {
073        throw exception;
074    }
075
076    /**
077     * Throws the configured exception.
078     *
079     * @throws IOException always thrown
080     */
081    @Override
082    public void close() throws IOException {
083        throw exception;
084    }
085
086}