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.juneau.rest.util;
018
019import java.io.*;
020
021import org.apache.juneau.encoders.*;
022
023import jakarta.servlet.*;
024
025/**
026 * A wrapped {@link ServletOutputStream} with an added <c>finish()</c> method.
027 *
028 * <h5 class='section'>See Also:</h5><ul>
029 * </ul>
030 */
031public class FinishableServletOutputStream extends ServletOutputStream implements Finishable {
032
033   final OutputStream os;
034   final ServletOutputStream sos;
035   final Finishable f;
036
037   /**
038    * Constructor.
039    *
040    * @param os The wrapped output stream.
041    */
042   public FinishableServletOutputStream(OutputStream os) {
043      this.os = os;
044      this.sos = (os instanceof ServletOutputStream ? (ServletOutputStream)os : null);
045      this.f = (os instanceof Finishable ? (Finishable)os : null);
046   }
047
048   @Override /* OutputStream */
049   public final void write(byte[] b, int off, int len) throws IOException {
050      os.write(b, off, len);
051   }
052
053   @Override /* OutputStream */
054   public final void write(int b) throws IOException {
055      os.write(b);
056   }
057
058   @Override /* OutputStream */
059   public final void flush() throws IOException {
060      os.flush();
061   }
062
063   @Override /* OutputStream */
064   public final void close() throws IOException {
065      os.close();
066   }
067
068   @Override /* ServletOutputStream */
069   public boolean isReady() {
070      return sos == null ? true : sos.isReady();
071   }
072
073   @Override /* ServletOutputStream */
074   public void setWriteListener(WriteListener arg0) {
075      if (sos != null)
076         sos.setWriteListener(arg0);
077   }
078
079   /**
080    * Calls {@link Finishable#finish()} on the underlying output stream.
081    *
082    * <p>
083    * A no-op if the underlying output stream does not implement the {@link Finishable} interface.
084    */
085   @Override /* Finishable */
086   public void finish() throws IOException {
087      if (f != null)
088         f.finish();
089   }
090}