View Javadoc
1   /*
2    * Copyright (c) 2014, Dienst Landelijk Gebied - Ministerie van Economische Zaken
3    * 
4    * Gepubliceerd onder de BSD 2-clause licentie, 
5    * zie https://github.com/MinELenI/CBSviewer/blob/master/LICENSE.md voor de volledige licentie.
6    */
7   package nl.mineleni.cbsviewer.servlet;
8   
9   import java.io.IOException;
10  import java.io.OutputStream;
11  import java.util.concurrent.atomic.AtomicBoolean;
12  import java.util.zip.GZIPOutputStream;
13  
14  import javax.servlet.ServletOutputStream;
15  
16  /**
17   * comprimeert de output stream met gzip.
18   * 
19   * @author prinsmc
20   *
21   */
22  public class ServletResponseGZIPOutputStream extends ServletOutputStream {
23  	/** gzip output. */
24  	GZIPOutputStream gzipStream;
25  	/** vlag voor ststus van gzip output stream. */
26  	final AtomicBoolean open = new AtomicBoolean(true);
27  	/** output stream die gecomprimeerd wordt. */
28  	OutputStream output;
29  
30  	/**
31  	 * Instantiates a new servlet response gzip output stream.
32  	 *
33  	 * @param output
34  	 *            the output
35  	 * @throws IOException
36  	 *             Signals that an I/O exception has occurred.
37  	 */
38  	public ServletResponseGZIPOutputStream(OutputStream output)
39  			throws IOException {
40  		this.output = output;
41  		gzipStream = new GZIPOutputStream(output);
42  	}
43  
44  	/*
45  	 * (non-Javadoc)
46  	 * 
47  	 * @see java.io.OutputStream#close()
48  	 */
49  	@Override
50  	public void close() throws IOException {
51  		if (open.compareAndSet(true, false)) {
52  			gzipStream.close();
53  		}
54  	}
55  
56  	/*
57  	 * (non-Javadoc)
58  	 * 
59  	 * @see java.io.OutputStream#flush()
60  	 */
61  	@Override
62  	public void flush() throws IOException {
63  		gzipStream.flush();
64  	}
65  
66  	/*
67  	 * (non-Javadoc)
68  	 * 
69  	 * @see java.io.OutputStream#write(byte[])
70  	 */
71  	@Override
72  	public void write(byte b[]) throws IOException {
73  		write(b, 0, b.length);
74  	}
75  
76  	/*
77  	 * (non-Javadoc)
78  	 * 
79  	 * @see java.io.OutputStream#write(byte[], int, int)
80  	 */
81  	@Override
82  	public void write(byte b[], int off, int len) throws IOException {
83  		if (!open.get()) {
84  			throw new IOException("Stream closed!");
85  		}
86  		gzipStream.write(b, off, len);
87  	}
88  
89  	/*
90  	 * (non-Javadoc)
91  	 * 
92  	 * @see java.io.OutputStream#write(int)
93  	 */
94  	@Override
95  	public void write(int b) throws IOException {
96  		if (!open.get()) {
97  			throw new IOException("Stream closed!");
98  		}
99  		gzipStream.write(b);
100 	}
101 
102 }