forked from ReactiveX/RxJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringObservable.java
More file actions
325 lines (298 loc) · 11.9 KB
/
StringObservable.java
File metadata and controls
325 lines (298 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx.observables;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.util.Arrays;
import java.util.regex.Pattern;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.Observable.OnSubscribeFunc;
import rx.util.functions.Func1;
import rx.util.functions.Func2;
public class StringObservable {
/**
* Decodes a stream the multibyte chunks into a stream of strings that works on infinite streams and where handles when a multibyte character spans two chunks.
*
* @param src
* @param charsetName
* @return
*/
public static Observable<String> decode(Observable<byte[]> src, String charsetName) {
return decode(src, Charset.forName(charsetName));
}
/**
* Decodes a stream the multibyte chunks into a stream of strings that works on infinite streams and where handles when a multibyte character spans two chunks.
*
* @param src
* @param charset
* @return
*/
public static Observable<String> decode(Observable<byte[]> src, Charset charset) {
return decode(src, charset.newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE));
}
/**
* Decodes a stream the multibyte chunks into a stream of strings that works on infinite streams and where handles when a multibyte character spans two chunks.
* This method allows for more control over how malformed and unmappable characters are handled.
*
* @param src
* @param charsetDecoder
* @return
*/
public static Observable<String> decode(final Observable<byte[]> src, final CharsetDecoder charsetDecoder) {
return Observable.create(new OnSubscribeFunc<String>() {
@Override
public Subscription onSubscribe(final Observer<? super String> observer) {
return src.subscribe(new Observer<byte[]>() {
private ByteBuffer leftOver = null;
@Override
public void onCompleted() {
if (process(null, leftOver, true))
observer.onCompleted();
}
@Override
public void onError(Throwable e) {
if (process(null, leftOver, true))
observer.onError(e);
}
@Override
public void onNext(byte[] bytes) {
process(bytes, leftOver, false);
}
public boolean process(byte[] next, ByteBuffer last, boolean endOfInput) {
ByteBuffer bb;
if (last != null) {
if (next != null) {
// merge leftover in front of the next bytes
bb = ByteBuffer.allocate(last.remaining() + next.length);
bb.put(last);
bb.put(next);
bb.flip();
}
else { // next == null
bb = last;
}
}
else { // last == null
if (next != null) {
bb = ByteBuffer.wrap(next);
}
else { // next == null
return true;
}
}
CharBuffer cb = CharBuffer.allocate((int) (bb.limit() * charsetDecoder.averageCharsPerByte()));
CoderResult cr = charsetDecoder.decode(bb, cb, endOfInput);
cb.flip();
if (cr.isError()) {
try {
cr.throwException();
}
catch (CharacterCodingException e) {
observer.onError(e);
return false;
}
}
if (bb.remaining() > 0) {
leftOver = bb;
}
else {
leftOver = null;
}
String string = cb.toString();
if (!string.isEmpty())
observer.onNext(string);
return true;
}
});
}
});
}
/**
* Encodes a possible infinite stream of strings into a Observable of byte arrays.
*
* @param src
* @param charsetName
* @return
*/
public static Observable<byte[]> encode(Observable<String> src, String charsetName) {
return encode(src, Charset.forName(charsetName));
}
/**
* Encodes a possible infinite stream of strings into a Observable of byte arrays.
*
* @param src
* @param charset
* @return
*/
public static Observable<byte[]> encode(Observable<String> src, Charset charset) {
return encode(src, charset.newEncoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE));
}
/**
* Encodes a possible infinite stream of strings into a Observable of byte arrays.
* This method allows for more control over how malformed and unmappable characters are handled.
*
* @param src
* @param charsetEncoder
* @return
*/
public static Observable<byte[]> encode(Observable<String> src, final CharsetEncoder charsetEncoder) {
return src.map(new Func1<String, byte[]>() {
@Override
public byte[] call(String str) {
CharBuffer cb = CharBuffer.wrap(str);
ByteBuffer bb;
try {
bb = charsetEncoder.encode(cb);
} catch (CharacterCodingException e) {
throw new RuntimeException(e);
}
return Arrays.copyOfRange(bb.array(), bb.position(), bb.limit());
}
});
}
/**
* Gather up all of the strings in to one string to be able to use it as one message. Don't use this on infinite streams.
*
* @param src
* @return
*/
public static Observable<String> stringConcat(Observable<String> src) {
return src.aggregate(new Func2<String, String, String>() {
@Override
public String call(String a, String b) {
return a + b;
}
});
}
/**
* Rechunks the strings based on a regex pattern and works on infinite stream.
*
* resplit(["boo:an", "d:foo"], ":") --> ["boo", "and", "foo"]
* resplit(["boo:an", "d:foo"], "o") --> ["b", "", ":and:f", "", ""]
*
* See {@link Pattern}
*
* @param src
* @param regex
* @return
*/
public static Observable<String> split(final Observable<String> src, String regex) {
final Pattern pattern = Pattern.compile(regex);
return Observable.create(new OnSubscribeFunc<String>() {
@Override
public Subscription onSubscribe(final Observer<? super String> observer) {
return src.subscribe(new Observer<String>() {
private String leftOver = null;
@Override
public void onCompleted() {
output(leftOver);
observer.onCompleted();
}
@Override
public void onError(Throwable e) {
output(leftOver);
observer.onError(e);
}
@Override
public void onNext(String segment) {
String[] parts = pattern.split(segment, -1);
if (leftOver != null)
parts[0] = leftOver + parts[0];
for (int i = 0; i < parts.length - 1; i++) {
String part = parts[i];
output(part);
}
leftOver = parts[parts.length - 1];
}
private int emptyPartCount = 0;
/**
* when limit == 0 trailing empty parts are not emitted.
* @param part
*/
private void output(String part) {
if (part.isEmpty()) {
emptyPartCount++;
}
else {
for(; emptyPartCount>0; emptyPartCount--)
observer.onNext("");
observer.onNext(part);
}
}
});
}
});
}
/**
* Concatenates the sequence of values by adding a separator
* between them and emitting the result once the source completes.
* <p>
* The conversion from the value type to String is performed via
* {@link java.lang.String#valueOf(java.lang.Object)} calls.
* <p>
* For example:
* <pre>
* Observable<Object> source = Observable.from("a", 1, "c");
* Observable<String> result = join(source, ", ");
* </pre>
*
* will yield a single element equal to "a, 1, c".
*
* @param source the source sequence of CharSequence values
* @param separator the separator to a
* @return an Observable which emits a single String value having the concatenated
* values of the source observable with the separator between elements
*/
public static <T> Observable<String> join(final Observable<T> source, final CharSequence separator) {
return Observable.create(new OnSubscribeFunc<String>() {
@Override
public Subscription onSubscribe(final Observer<? super String> t1) {
return source.subscribe(new Observer<T>() {
boolean mayAddSeparator;
StringBuilder b = new StringBuilder();
@Override
public void onNext(T args) {
if (mayAddSeparator) {
b.append(separator);
}
mayAddSeparator = true;
b.append(String.valueOf(args));
}
@Override
public void onError(Throwable e) {
b = null;
t1.onError(e);
}
@Override
public void onCompleted() {
String str = b.toString();
b = null;
t1.onNext(str);
t1.onCompleted();
}
});
}
});
}
}