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 *
029 * @since 2.0
030 */
031public class BrokenOutputStream extends OutputStream {
032
033    /**
034     * The exception that is thrown by all methods of this class.
035     */
036    private final IOException exception;
037
038    /**
039     * Creates a new stream that always throws the given exception.
040     *
041     * @param exception the exception to be thrown
042     */
043    public BrokenOutputStream(final IOException exception) {
044        this.exception = exception;
045    }
046
047    /**
048     * Creates a new stream that always throws an {@link IOException}
049     */
050    public BrokenOutputStream() {
051        this(new IOException("Broken output stream"));
052    }
053
054    /**
055     * Throws the configured exception.
056     *
057     * @param b ignored
058     * @throws IOException always thrown
059     */
060    @Override
061    public void write(final int b) throws IOException {
062        throw exception;
063    }
064
065    /**
066     * Throws the configured exception.
067     *
068     * @throws IOException always thrown
069     */
070    @Override
071    public void flush() throws IOException {
072        throw exception;
073    }
074
075    /**
076     * Throws the configured exception.
077     *
078     * @throws IOException always thrown
079     */
080    @Override
081    public void close() throws IOException {
082        throw exception;
083    }
084
085}