001/*
002 * The contents of this file are subject to the terms of the Common Development and
003 * Distribution License (the License). You may not use this file except in compliance with the
004 * License.
005 *
006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
007 * specific language governing permission and limitations under the License.
008 *
009 * When distributing Covered Software, include this CDDL Header Notice in each file and include
010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
011 * Header, with the fields enclosed by brackets [] replaced by your own identifying
012 * information: "Portions copyright [year] [name of copyright owner]".
013 *
014 * Copyright 2015-2016 ForgeRock AS.
015 */
016package org.forgerock.audit.events.handlers.writers;
017
018import java.io.IOException;
019import java.io.OutputStream;
020import java.io.PrintWriter;
021
022/**
023 * A TextWriter provides a character-based stream which can be queried for number of bytes written.
024 */
025public interface TextWriter {
026    /**
027     * Writes some text to the output stream.
028     *
029     * @param text
030     *            The text to write
031     * @throws IOException
032     *             If a problem occurs.
033     */
034    void write(String text) throws IOException;
035
036    /**
037     * Flushes any buffered contents of the output stream.
038     *
039     * @throws IOException
040     *             If a problem occurs.
041     */
042    void flush() throws IOException;
043
044    /**
045     * Releases any resources held by the writer.
046     */
047    void shutdown();
048
049    /**
050     * Retrieves the number of bytes written by this writer.
051     *
052     * @return the number of bytes written by this writer.
053     */
054    long getBytesWritten();
055
056    /**
057     * A TextWriter implementation which writes to a given output stream.
058     */
059    public class Stream implements TextWriter {
060        private final MeteredStream stream;
061        private final PrintWriter writer;
062
063        /**
064         * Creates a new text writer that will write to the provided output stream.
065         *
066         * @param outputStream
067         *            The output stream to which
068         */
069        public Stream(OutputStream outputStream) {
070            stream = new MeteredStream(outputStream, 0);
071            writer = new PrintWriter(stream, true);
072        }
073
074        @Override
075        public void write(String text) {
076            writer.print(text);
077        }
078
079        @Override
080        public void flush() {
081            writer.flush();
082        }
083
084        @Override
085        public void shutdown() {
086            writer.close();
087        }
088
089        @Override
090        public long getBytesWritten() {
091            return stream.getBytesWritten();
092        }
093    }
094}