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 *      https://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.FilterWriter;
020import java.io.IOException;
021import java.io.Writer;
022
023import org.apache.commons.io.IOUtils;
024
025/**
026 * A Proxy stream which acts as expected, that is it passes the method calls on to the proxied stream and doesn't
027 * change which methods are being called. It is an alternative base class to FilterWriter to increase reusability,
028 * because FilterWriter changes the methods being called, such as {@code write(char[]) to write(char[], int, int)}
029 * and {@code write(String) to write(String, int, int)}.
030 */
031public class ProxyWriter extends FilterWriter {
032
033    /**
034     * Constructs a new ProxyWriter.
035     *
036     * @param delegate  the Writer to delegate to.
037     */
038    public ProxyWriter(final Writer delegate) {
039        // the delegate is stored in a protected superclass variable named 'out'
040        super(delegate);
041    }
042
043    /**
044     * Invoked by the write methods after the proxied call has returned
045     * successfully. The number of chars written (1 for the
046     * {@link #write(int)} method, buffer length for {@link #write(char[])},
047     * etc.) is given as an argument.
048     * <p>
049     * Subclasses can override this method to add common post-processing
050     * functionality without having to override all the write methods.
051     * The default implementation does nothing.
052     * </p>
053     *
054     * @param n number of chars written
055     * @throws IOException if the post-processing fails
056     * @since 2.0
057     */
058    @SuppressWarnings("unused") // Possibly thrown from subclasses.
059    protected void afterWrite(final int n) throws IOException {
060        // noop
061    }
062
063    /**
064     * Invokes the delegate's {@code append(char)} method.
065     *
066     * @param c The character to write.
067     * @return this writer.
068     * @throws IOException if an I/O error occurs.
069     * @since 2.0
070     */
071    @Override
072    public Writer append(final char c) throws IOException {
073        try {
074            beforeWrite(1);
075            out.append(c);
076            afterWrite(1);
077        } catch (final IOException e) {
078            handleIOException(e);
079        }
080        return this;
081    }
082
083    /**
084     * Invokes the delegate's {@code append(CharSequence)} method.
085     *
086     * @param csq The character sequence to write.
087     * @return this writer.
088     * @throws IOException if an I/O error occurs.
089     * @since 2.0
090     */
091    @Override
092    public Writer append(final CharSequence csq) throws IOException {
093        try {
094            final int len = IOUtils.length(csq);
095            beforeWrite(len);
096            out.append(csq);
097            afterWrite(len);
098        } catch (final IOException e) {
099            handleIOException(e);
100        }
101        return this;
102    }
103
104    /**
105     * Invokes the delegate's {@code append(CharSequence, int, int)} method.
106     *
107     * @param csq The character sequence to write.
108     * @param start The index of the first character to write.
109     * @param end  The index of the first character to write (exclusive).
110     * @return this writer.
111     * @throws IOException if an I/O error occurs.
112     * @since 2.0
113     */
114    @Override
115    public Writer append(final CharSequence csq, final int start, final int end) throws IOException {
116        try {
117            beforeWrite(end - start);
118            out.append(csq, start, end);
119            afterWrite(end - start);
120        } catch (final IOException e) {
121            handleIOException(e);
122        }
123        return this;
124    }
125
126    /**
127     * Invoked by the write methods before the call is proxied. The number
128     * of chars to be written (1 for the {@link #write(int)} method, buffer
129     * length for {@link #write(char[])}, etc.) is given as an argument.
130     * <p>
131     * Subclasses can override this method to add common pre-processing
132     * functionality without having to override all the write methods.
133     * The default implementation does nothing.
134     * </p>
135     *
136     * @param n number of chars to be written.
137     * @throws IOException if the pre-processing fails.
138     * @since 2.0
139     */
140    @SuppressWarnings("unused") // Possibly thrown from subclasses.
141    protected void beforeWrite(final int n) throws IOException {
142        // noop
143    }
144
145    /**
146     * Invokes the delegate's {@code close()} method.
147     * @throws IOException if an I/O error occurs.
148     */
149    @Override
150    public void close() throws IOException {
151        IOUtils.close(out, this::handleIOException);
152    }
153
154    /**
155     * Invokes the delegate's {@code flush()} method.
156     * @throws IOException if an I/O error occurs.
157     */
158    @Override
159    public void flush() throws IOException {
160        try {
161            out.flush();
162        } catch (final IOException e) {
163            handleIOException(e);
164        }
165    }
166
167    /**
168     * Handles any IOExceptions thrown.
169     * <p>
170     * This method provides a point to implement custom exception
171     * handling. The default behavior is to re-throw the exception.
172     * </p>
173     *
174     * @param e The IOException thrown.
175     * @throws IOException if an I/O error occurs.
176     * @since 2.0
177     */
178    protected void handleIOException(final IOException e) throws IOException {
179        throw e;
180    }
181
182    /**
183     * Invokes the delegate's {@code write(char[])} method.
184     *
185     * @param cbuf the characters to write.
186     * @throws IOException if an I/O error occurs.
187     */
188    @Override
189    public void write(final char[] cbuf) throws IOException {
190        try {
191            final int len = IOUtils.length(cbuf);
192            beforeWrite(len);
193            out.write(cbuf);
194            afterWrite(len);
195        } catch (final IOException e) {
196            handleIOException(e);
197        }
198    }
199
200    /**
201     * Invokes the delegate's {@code write(char[], int, int)} method.
202     *
203     * @param cbuf the characters to write.
204     * @param off The start offset.
205     * @param len The number of characters to write.
206     * @throws IOException if an I/O error occurs.
207     */
208    @Override
209    public void write(final char[] cbuf, final int off, final int len) throws IOException {
210        try {
211            beforeWrite(len);
212            out.write(cbuf, off, len);
213            afterWrite(len);
214        } catch (final IOException e) {
215            handleIOException(e);
216        }
217    }
218
219    /**
220     * Invokes the delegate's {@code write(int)} method.
221     *
222     * @param c the character to write.
223     * @throws IOException if an I/O error occurs.
224     */
225    @Override
226    public void write(final int c) throws IOException {
227        try {
228            beforeWrite(1);
229            out.write(c);
230            afterWrite(1);
231        } catch (final IOException e) {
232            handleIOException(e);
233        }
234    }
235
236    /**
237     * Invokes the delegate's {@code write(String)} method.
238     *
239     * @param str the string to write.
240     * @throws IOException if an I/O error occurs.
241     */
242    @Override
243    public void write(final String str) throws IOException {
244        try {
245            final int len = IOUtils.length(str);
246            beforeWrite(len);
247            out.write(str);
248            afterWrite(len);
249        } catch (final IOException e) {
250            handleIOException(e);
251        }
252    }
253
254    /**
255     * Invokes the delegate's {@code write(String)} method.
256     *
257     * @param str the string to write.
258     * @param off The start offset.
259     * @param len The number of characters to write.
260     * @throws IOException if an I/O error occurs.
261     */
262    @Override
263    public void write(final String str, final int off, final int len) throws IOException {
264        try {
265            beforeWrite(len);
266            out.write(str, off, len);
267            afterWrite(len);
268        } catch (final IOException e) {
269            handleIOException(e);
270        }
271    }
272
273}