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 2006-2008 Sun Microsystems, Inc. 015 * Portions Copyright 2014-2016 ForgeRock AS. 016 */ 017package org.opends.server.loggers; 018 019import java.io.IOException; 020import java.io.OutputStream; 021 022/** 023 * A metered stream is a subclass of OutputStream that 024 * (a) forwards all its output to a target stream 025 * (b) keeps track of how many bytes have been written. 026 */ 027public final class MeteredStream extends OutputStream 028{ 029 OutputStream out; 030 volatile long written; 031 032 /** 033 * Create the stream wrapped around the specified output 034 * stream. 035 * 036 * @param out The target output stream to keep track of. 037 * @param written The number of bytes written to the stream. 038 */ 039 public MeteredStream(OutputStream out, long written) 040 { 041 this.out = out; 042 this.written = written; 043 } 044 045 @Override 046 public void write(int b) throws IOException 047 { 048 out.write(b); 049 written++; 050 } 051 052 @Override 053 public void write(byte buff[]) throws IOException 054 { 055 out.write(buff); 056 written += buff.length; 057 } 058 059 @Override 060 public void write(byte buff[], int off, int len) throws IOException 061 { 062 out.write(buff,off,len); 063 written += len; 064 } 065 066 /** 067 * Flush the output stream which flushes the target output stream. 068 * 069 * @exception IOException if the flush failed. 070 */ 071 @Override 072 public void flush() throws IOException 073 { 074 out.flush(); 075 } 076 077 /** 078 * Close the output stream which closes the target output stream. 079 * 080 * @exception IOException if the close failed. 081 */ 082 @Override 083 public void close() throws IOException 084 { 085 out.close(); 086 } 087 088 /** 089 * Returns the number of bytes written in this stream. 090 * 091 * @return the number of bytes 092 */ 093 public long getBytesWritten() 094 { 095 return written; 096 } 097}