MockServletInputStream.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */
  20. package org.openspcoop2.protocol.modipa.utils;

  21. import java.io.ByteArrayInputStream;
  22. import java.io.IOException;

  23. import javax.servlet.ReadListener;
  24. import javax.servlet.ServletInputStream;

  25. /**
  26.  * MockServletInputStream semplice stream usato per poter scrivere
  27.  * su un richiesta servlet http
  28.  *
  29.  * @author Tommaso Burlon (tommaso.burlon@link.it)
  30.  * @author $Author$
  31.  * @version $Rev$, $Date$
  32.  */
  33. public class MockServletInputStream extends ServletInputStream {

  34.    
  35.     private ByteArrayInputStream is = new ByteArrayInputStream(new byte[0]);
  36.     private ReadListener cb = null;
  37.    
  38.     public MockServletInputStream() {
  39.         this(new byte[0]);
  40.     }
  41.    
  42.     public MockServletInputStream(byte[] buf) {
  43.         this.is = new ByteArrayInputStream(buf);
  44.     }
  45.    
  46.     @Override
  47.     public boolean isFinished() {
  48.         return this.is.available() > 0;
  49.     }

  50.     @Override
  51.     public boolean isReady() {
  52.         return true;
  53.     }

  54.     @Override
  55.     public void setReadListener(ReadListener arg0) {
  56.         try {
  57.             arg0.onDataAvailable();
  58.         } catch (IOException e) {
  59.             arg0.onError(e);
  60.         }
  61.        
  62.         this.cb = arg0;
  63.     }

  64.     @Override
  65.     public int read() throws IOException {
  66.         int v = this.is.read();
  67.         if (this.isFinished() && this.cb != null)
  68.             this.cb.onAllDataRead();
  69.         return v;
  70.     }

  71. }