Repository navigation
Expand file tree
/
Copy pathStringObservable.java
More file actions
614 lines (563 loc) · 22.8 KB
/
Copy pathStringObservable.java
File metadata and controls
614 lines (563 loc) · 22.8 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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
/**
* Copyright 2014 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 rx.Observable;
import rx.Observable.Operator;
import rx.Producer;
import rx.Subscriber;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.internal.operators.OnSubscribeInputStream;
import rx.internal.operators.OnSubscribeInputStreamToLines;
import rx.internal.operators.OnSubscribeReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
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.concurrent.Callable;
import java.util.regex.Pattern;
public class StringObservable {
/**
* Reads bytes from a source {@link InputStream} and outputs {@link Observable} of
* {@code byte[]}s. Supports backpressure.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.from.png" alt="">
*
* @param i
* Source {@link InputStream}
* @return the Observable containing read byte arrays from the input
*/
public static Observable<byte[]> from(final InputStream i) {
return from(i, 8 * 1024);
}
/**
* Func0 that allows throwing an {@link IOException}s commonly thrown during IO operations.
* @see StringObservable#using(UnsafeFunc0, Func1)
*
* @param <R>
*/
public static interface UnsafeFunc0<R> extends Callable<R> {
public R call() throws Exception;
}
/**
* Helps in creating an Observable that automatically calls {@link Closeable#close()} on completion, error or unsubscribe.
*
* <pre>
* StringObservable.using(() -> new FileReader(file), (reader) -> StringObservable.from(reader))
* </pre>
*
* @param resourceFactory
* Generates a new {@link Closeable} resource for each new subscription to the returned Observable
* @param observableFactory
* Converts the {@link Closeable} resource into a {@link Observable} with {@link #from(InputStream)} or {@link #from(Reader)}
* @return
* An {@link Observable} that automatically closes the resource when done.
*/
public static <R, S extends Closeable> Observable<R> using(final UnsafeFunc0<S> resourceFactory,
final Func1<S, Observable<R>> observableFactory) {
return Observable.using(new Func0<S>() {
@Override
public S call() {
try {
return resourceFactory.call();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}, observableFactory, new Action1<S>() {
@Override
public void call(S resource) {
try {
resource.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}, true);
}
/**
* Reads bytes from a source {@link InputStream} and outputs {@link Observable} of
* {@code byte[]}s. Supports backpressure.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.from.png" alt="">
*
* @param is
* Source {@link InputStream}
* @param size
* internal buffer size
* @return the Observable containing read byte arrays from the input
*/
public static Observable<byte[]> from(final InputStream is, final int size) {
return Observable.create(new OnSubscribeInputStream(is, size));
}
/**
* Reads characters from a source {@link Reader} and outputs {@link Observable} of
* {@link String}s. Supports backpressure.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.from.png" alt="">
*
* @param i
* Source {@link Reader}
* @return the Observable of Strings read from the source
*/
public static Observable<String> from(final Reader i) {
return from(i, 8 * 1024);
}
/**
* Reads characters from a source {@link Reader} and outputs {@link Observable} of
* {@link String}s. Supports backpressure.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.from.png" alt="">
*
* @param i
* Source {@link Reader}
* @param size
* internal buffer size
* @return the Observable of Strings read from the source
*/
public static Observable<String> from(final Reader reader, final int size) {
return Observable.create(new OnSubscribeReader(reader, size));
}
/**
* Reads lines from a source {@link InputStream} and outputs {@link Observable} of {@code String}s. Supports backpressure.
*
* @param is
* Source {@link InputStream}
* @param ch
* Charset to be used to read the source {@link InputStream}
* @return the Observable containing the split lines of the source
*/
public static Observable<String> byLine(InputStream is, Charset ch) {
return Observable.create(new OnSubscribeInputStreamToLines(is, ch));
}
/**
* Decodes a stream of multibyte chunks into a stream of strings that works on infinite streams
* and where handles when a multibyte character spans two chunks.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.decode.png" alt="">
*
* @param src
* @param charsetName
* @return the Observable returning a stream of decoded strings
*/
public static Observable<String> decode(Observable<byte[]> src, String charsetName) {
return decode(src, Charset.forName(charsetName));
}
/**
* Decodes a stream of multibyte chunks into a stream of strings that works on infinite streams
* and where handles when a multibyte character spans two chunks.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.decode.png" alt="">
*
* @param src
* @param charset
* @return the Observable returning a stream of decoded strings
*/
public static Observable<String> decode(Observable<byte[]> src, Charset charset) {
return decode(src, charset.newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE));
}
/**
* Decodes a stream of multibyte chunks into a stream of strings that works on infinite streams
* and handles when a multibyte character spans two chunks.
* This method allows for more control over how malformed and unmappable characters are handled.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.decode.png" alt="">
*
* @param src
* @param charsetDecoder
* @return the Observable returning a stream of decoded strings
*/
public static Observable<String> decode(final Observable<byte[]> src, final CharsetDecoder charsetDecoder) {
return src.lift(new Operator<String, byte[]>() {
@Override
public Subscriber<? super byte[]> call(final Subscriber<? super String> o) {
return new Subscriber<byte[]>(o) {
private ByteBuffer leftOver = null;
@Override
public void onCompleted() {
if (process(null, leftOver, true))
o.onCompleted();
}
@Override
public void onError(Throwable e) {
if (process(null, leftOver, true))
o.onError(e);
}
@Override
public void onNext(byte[] bytes) {
process(bytes, leftOver, false);
}
public boolean process(byte[] next, ByteBuffer last, boolean endOfInput) {
if (o.isUnsubscribed())
return false;
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) {
o.onError(e);
return false;
}
}
if (bb.remaining() > 0) {
leftOver = bb;
}
else {
leftOver = null;
}
String string = cb.toString();
if (!string.isEmpty())
o.onNext(string);
return true;
}
};
}
});
}
/**
* Encodes a possibly infinite stream of strings into an Observable of byte arrays.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.encode.png" alt="">
*
* @param src
* @param charsetName
* @return the Observable with a stream of encoded byte arrays
*/
public static Observable<byte[]> encode(Observable<String> src, String charsetName) {
return encode(src, Charset.forName(charsetName));
}
/**
* Encodes a possibly infinite stream of strings into an Observable of byte arrays.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.encode.png" alt="">
*
* @param src
* @param charset
* @return the Observable with a stream of encoded byte arrays
*/
public static Observable<byte[]> encode(Observable<String> src, Charset charset) {
return encode(src, charset.newEncoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE));
}
/**
* Encodes a possibly infinite stream of strings into an Observable of byte arrays.
* This method allows for more control over how malformed and unmappable characters are handled.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.encode.png" alt="">
*
* @param src
* @param charsetEncoder
* @return the Observable with a stream of encoded byte arrays
*/
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.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.stringConcat.png" alt="">
*
* @param src
* @return the Observable returing all strings concatenated as a single string
*/
public static Observable<String> stringConcat(Observable<String> src) {
return toString(src.reduce(new StringBuilder(), new Func2<StringBuilder, String, StringBuilder>() {
@Override
public StringBuilder call(StringBuilder a, String b) {
return a.append(b);
}
}));
}
/**
* Maps {@link Observable}<{@link Object}> to {@link Observable}<{@link String}> by using {@link String#valueOf(Object)}
* @param src
* @return An {@link Observable} of only {@link String}s.
*/
public static Observable<String> toString(Observable<?> src) {
return src.map(new Func1<Object, String>() {
@Override
public String call(Object obj) {
return String.valueOf(obj);
}
});
}
/**
* Rechunks the strings based on a regex pattern and works on infinite stream.
*
* <pre>
* split(["boo:an", "d:foo"], ":") --> ["boo", "and", "foo"]
* split(["boo:an", "d:foo"], "o") --> ["b", "", ":and:f", "", ""]
* </pre>
*
* See {@link Pattern}
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.split.png" alt="">
*
* @param src
* the source that should be use for the split
* @param regex
* a string that build regular expression modifier
* @return the Observable streaming the split values
*/
public static Observable<String> split(final Observable<String> src, String regex) {
Pattern pattern = Pattern.compile(regex);
return StringObservable.split(src,pattern);
}
/**
* Rechunks the strings based on a regex pattern and works on infinite stream.
*
* <pre>
* split(["boo:an", "d:foo"], ":") --> ["boo", "and", "foo"]
* split(["boo:an", "d:foo"], "o") --> ["b", "", ":and:f", "", ""]
* </pre>
*
* See {@link Pattern}
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.split.png" alt="">
*
* @param src
* the source that should be use for the split
* @param pattern
* pre compiled regular expression pattern for the split functionality
* @return the Observable streaming the split values
*/
public static Observable<String> split(final Observable<String> src, final Pattern pattern) {
return src.lift(new Operator<String, String>() {
@Override
public Subscriber<? super String> call(final Subscriber<? super String> o) {
return new Subscriber<String>(o) {
private String leftOver = null;
@Override
public void onCompleted() {
if (leftOver!=null)
output(leftOver);
if (!o.isUnsubscribed())
o.onCompleted();
}
@Override
public void onError(Throwable e) {
if (leftOver!=null)
output(leftOver);
if (!o.isUnsubscribed())
o.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--)
if (!o.isUnsubscribed())
o.onNext("");
if (!o.isUnsubscribed())
o.onNext(part);
}
}
};
}
});
}
/**
* Concatenates the sequence of values by adding a separator
* between them and emitting the result once the source completes.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.join.png" alt="">
* <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 Observable<String> join(final Observable<String> source, final CharSequence separator) {
return source.lift(new Operator<String, String>() {
@Override
public Subscriber<String> call(final Subscriber<? super String> child) {
final JoinParentSubscriber parent = new JoinParentSubscriber(child, separator);
child.add(parent);
child.setProducer(new Producer() {
@Override
public void request(long n) {
if (n > 0) {
parent.requestAll();
}
}});
return parent;
}
});
}
private static final class JoinParentSubscriber extends Subscriber<String> {
private final Subscriber<? super String> child;
private final CharSequence separator;
private boolean mayAddSeparator;
private StringBuilder b = new StringBuilder();
JoinParentSubscriber(Subscriber<? super String> child, CharSequence separator) {
this.child = child;
this.separator = separator;
}
void requestAll() {
request(Long.MAX_VALUE);
}
@Override
public void onStart() {
request(0);
}
@Override
public void onCompleted() {
String str = b.toString();
b = null;
if (!child.isUnsubscribed())
child.onNext(str);
if (!child.isUnsubscribed())
child.onCompleted();
}
@Override
public void onError(Throwable e) {
b = null;
if (!child.isUnsubscribed())
child.onError(e);
}
@Override
public void onNext(String t) {
if (mayAddSeparator) {
b.append(separator);
}
mayAddSeparator = true;
b.append(t);
}
}
/**
* Splits the {@link Observable} of Strings by lines and numbers them (zero based index)
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.byLine.png" alt="">
*
* @param source
* @return the Observable conaining the split lines of the source
*/
public static Observable<String> byLine(Observable<String> source) {
return split(source, System.getProperty("line.separator"));
}
/**
* Converts a String into an Observable that emits the chars in the String.
* <p>
* <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/from.png" alt="">
*
* @param str
* the source String
* @return an Observable that emits each char in the source String
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#from">RxJava wiki: from</a>
*/
public static Observable<String> byCharacter(Observable<String> source) {
return source.lift(new Operator<String, String>() {
@Override
public Subscriber<? super String> call(final Subscriber<? super String> subscriber) {
return new Subscriber<String>(subscriber) {
@Override
public void onCompleted() {
subscriber.onCompleted();
}
@Override
public void onError(Throwable e) {
subscriber.onError(e);
}
@Override
public void onNext(String str) {
for (char c : str.toCharArray()) {
subscriber.onNext(Character.toString(c));
}
}
};
}
});
}
}