1
2
3
4
5
6
7
8
9
10
11 package org.eclipse.jgit.transport;
12
13 import java.io.IOException;
14 import java.io.OutputStream;
15 import java.text.MessageFormat;
16
17 import org.eclipse.jgit.internal.JGitText;
18
19
20
21
22
23
24
25
26
27 public class SideBandOutputStream extends OutputStream {
28
29 public static final int CH_DATA = SideBandInputStream.CH_DATA;
30
31
32 public static final int CH_PROGRESS = SideBandInputStream.CH_PROGRESS;
33
34
35 public static final int CH_ERROR = SideBandInputStream.CH_ERROR;
36
37
38 public static final int SMALL_BUF = 1000;
39
40
41 public static final int MAX_BUF = 65520;
42
43 static final int HDR_SIZE = 5;
44
45 private final OutputStream out;
46
47 private final byte[] buffer;
48
49
50
51
52
53
54
55 private int cnt;
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72 public SideBandOutputStream(int chan, int sz, OutputStream os) {
73 if (chan <= 0 || chan > 255)
74 throw new IllegalArgumentException(MessageFormat.format(
75 JGitText.get().channelMustBeInRange1_255,
76 Integer.valueOf(chan)));
77 if (sz <= HDR_SIZE)
78 throw new IllegalArgumentException(MessageFormat.format(
79 JGitText.get().packetSizeMustBeAtLeast,
80 Integer.valueOf(sz), Integer.valueOf(HDR_SIZE)));
81 else if (MAX_BUF < sz)
82 throw new IllegalArgumentException(MessageFormat.format(
83 JGitText.get().packetSizeMustBeAtMost, Integer.valueOf(sz),
84 Integer.valueOf(MAX_BUF)));
85
86 out = os;
87 buffer = new byte[sz];
88 buffer[4] = (byte) chan;
89 cnt = HDR_SIZE;
90 }
91
92 void flushBuffer() throws IOException {
93 if (HDR_SIZE < cnt)
94 writeBuffer();
95 }
96
97
98 @Override
99 public void flush() throws IOException {
100 flushBuffer();
101 out.flush();
102 }
103
104
105 @Override
106 public void write(byte[] b, int off, int len) throws IOException {
107 while (0 < len) {
108 int capacity = buffer.length - cnt;
109 if (cnt == HDR_SIZE && capacity < len) {
110
111
112 PacketLineOut.formatLength(buffer, buffer.length);
113 out.write(buffer, 0, HDR_SIZE);
114 out.write(b, off, capacity);
115 off += capacity;
116 len -= capacity;
117
118 } else {
119 if (capacity == 0)
120 writeBuffer();
121
122 int n = Math.min(len, capacity);
123 System.arraycopy(b, off, buffer, cnt, n);
124 cnt += n;
125 off += n;
126 len -= n;
127 }
128 }
129 }
130
131
132 @Override
133 public void write(int b) throws IOException {
134 if (cnt == buffer.length)
135 writeBuffer();
136 buffer[cnt++] = (byte) b;
137 }
138
139 private void writeBuffer() throws IOException {
140 PacketLineOut.formatLength(buffer, cnt);
141 out.write(buffer, 0, cnt);
142 cnt = HDR_SIZE;
143 }
144 }