KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > martiansoftware > nailgun > NGOutputStream


1 /*
2
3   Copyright 2004, Martian Software, Inc.
4
5   Licensed under the Apache License, Version 2.0 (the "License");
6   you may not use this file except in compliance with the License.
7   You may obtain a copy of the License at
8
9   http://www.apache.org/licenses/LICENSE-2.0
10
11   Unless required by applicable law or agreed to in writing, software
12   distributed under the License is distributed on an "AS IS" BASIS,
13   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   See the License for the specific language governing permissions and
15   limitations under the License.
16
17 */

18
19 package com.martiansoftware.nailgun;
20
21 import java.io.IOException JavaDoc;
22
23 /**
24  * Wraps an OutputStream to send writes in NailGun chunks. Because
25  * multiple NGOutputStreams wrap the same OutputStream (that is,
26  * the OutputStream obtained from the Socket connection with
27  * the client), writes are synchronized on the underlying OutputStream.
28  * If this were not the case, write interleaving could completely
29  * break the NailGun protocol.
30  *
31  * @author <a HREF="http://www.martiansoftware.com/contact.html">Marty Lamb</a>
32  */

33 class NGOutputStream extends java.io.FilterOutputStream JavaDoc {
34
35     private byte[] header;
36     
37     /**
38      * Creates a new NGOutputStream wrapping the specified
39      * OutputStream and using the specified Nailgun chunk code.
40      * @param out the OutputStream to wrap
41      * @param code the NailGun chunk code associated with this
42      * stream (i.e., '1' for stdout, '2' for stderr).
43      */

44     public NGOutputStream(java.io.OutputStream JavaDoc out, char code) {
45         super(out);
46         header = new byte[5];
47         header[4] = (byte) code;
48     }
49     
50     /**
51      * @see java.io.OutputStream.write(byte[])
52      */

53     public void write(byte[] b) throws IOException JavaDoc {
54         write(b, 0, b.length);
55     }
56     
57     /**
58      * @see java.io.OutputStream.write(int)
59      */

60     public void write(int b) throws IOException JavaDoc {
61         byte[] b2 = {(byte) b};
62         write(b2, 0, 1);
63     }
64     
65     /**
66      * @see java.io.OutputStream.write(byte[],int,int)
67      */

68     public void write(byte[] b, int offset, int len) throws IOException JavaDoc {
69         LongUtils.toArray(len, header, 0);
70         synchronized(out) {
71             out.write(header, 0, 5);
72             out.write(b, offset, len);
73         }
74         out.flush();
75     }
76 }
77
Popular Tags