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
618 lines (567 loc) · 22.3 KB
/
StringObservable.java
File metadata and controls
618 lines (567 loc) · 22.3 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
615
616
617
618
/**
* 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.OnSubscribe;
import rx.Observable.Operator;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.functions.Func2;
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.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
public class StringObservable {
/**
* Reads from the bytes from a source {@link InputStream} and outputs {@link Observable} of
* {@code byte[]}s
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/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);
}
private static class CloseableResource<S extends Closeable> implements Subscription {
private final AtomicBoolean unsubscribed = new AtomicBoolean();
private S closable;
public CloseableResource(S closeable) {
this.closable = closeable;
}
@Override
public void unsubscribe() {
if (unsubscribed.compareAndSet(false, true)) {
try {
closable.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@Override
public boolean isUnsubscribed() {
return unsubscribed.get();
}
}
/**
* Func0 that allows throwing an {@link IOException}s commonly thrown during IO operations.
* @see StringObservable#from(UnsafeFunc0, UnsafeFunc1)
*
* @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
*/
public static <R, S extends Closeable> Observable<R> using(final UnsafeFunc0<S> resourceFactory,
final Func1<S, Observable<R>> observableFactory) {
return Observable.using(new Func0<CloseableResource<S>>() {
@Override
public CloseableResource<S> call() {
try {
return new CloseableResource<S>(resourceFactory.call());
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}, new Func1<CloseableResource<S>, Observable<R>>() {
@Override
public Observable<R> call(CloseableResource<S> t1) {
return observableFactory.call(t1.closable);
}
});
}
/**
* Reads from the bytes from a source {@link InputStream} and outputs {@link Observable} of
* {@code byte[]}s
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/St.from.png" alt="">
*
* @param i
* 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 i, final int size) {
return Observable.create(new OnSubscribe<byte[]>() {
@Override
public void call(Subscriber<? super byte[]> o) {
byte[] buffer = new byte[size];
try {
if (o.isUnsubscribed())
return;
int n = i.read(buffer);
while (n != -1 && !o.isUnsubscribed()) {
o.onNext(Arrays.copyOf(buffer, n));
if (!o.isUnsubscribed())
n = i.read(buffer);
}
} catch (IOException e) {
o.onError(e);
}
if (o.isUnsubscribed())
return;
o.onCompleted();
}
});
}
/**
* Reads from the characters from a source {@link Reader} and outputs {@link Observable} of
* {@link String}s
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/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 from the characters from a source {@link Reader} and outputs {@link Observable} of
* {@link String}s
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/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 i, final int size) {
return Observable.create(new OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> o) {
char[] buffer = new char[size];
try {
if (o.isUnsubscribed())
return;
int n = 0;
n = i.read(buffer);
while (n != -1 && !o.isUnsubscribed()) {
o.onNext(new String(buffer, 0, n));
n = i.read(buffer);
}
} catch (IOException e) {
o.onError(e);
}
if (o.isUnsubscribed())
return;
o.onCompleted();
}
});
}
/**
* 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.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/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 the 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/Netflix/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 the multibyte chunks into a stream of strings that works on infinite streams
* and where it 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/Netflix/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 possible infinite stream of strings into a Observable of byte arrays.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/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 possible infinite stream of strings into a Observable of byte arrays.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/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 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.
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/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/Netflix/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
*/
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/Netflix/RxJava/images/rx-operators/St.split.png" alt="">
*
* @param src
* @param regex
* @return the Observable streaming the split values
*/
public static Observable<String> split(final Observable<String> src, String regex) {
final Pattern pattern = Pattern.compile(regex);
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() {
output(leftOver);
if (!o.isUnsubscribed())
o.onCompleted();
}
@Override
public void onError(Throwable e) {
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/Netflix/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> o) {
return new Subscriber<String>(o) {
boolean mayAddSeparator;
StringBuilder b = new StringBuilder();
@Override
public void onCompleted() {
String str = b.toString();
b = null;
if (!o.isUnsubscribed())
o.onNext(str);
if (!o.isUnsubscribed())
o.onCompleted();
}
@Override
public void onError(Throwable e) {
b = null;
if (!o.isUnsubscribed())
o.onError(e);
}
@Override
public void onNext(String t) {
if (mayAddSeparator) {
b.append(separator);
}
mayAddSeparator = true;
b.append(t);
}
};
}
});
}
public final static class Line {
private final int number;
private final String text;
public Line(int number, String text) {
this.number = number;
this.text = text;
}
public int getNumber() {
return number;
}
public String getText() {
return text;
}
@Override
public int hashCode() {
int result = 31 + number;
result = 31 * result + (text == null ? 0 : text.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Line))
return false;
Line other = (Line) obj;
if (number != other.number)
return false;
if (other.text == text)
return true;
if (text == null)
return false;
return text.equals(other.text);
}
@Override
public String toString() {
return number + ":" + text;
}
}
/**
* Splits the {@link Observable} of Strings by lines and numbers them (zero based index)
* <p>
* <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/St.byLine.png" alt="">
*
* @param source
* @return the Observable conaining the split lines of the source
*/
public static Observable<Line> byLine(Observable<String> source) {
return split(source, System.getProperty("line.separator")).map(new Func1<String, Line>() {
int lineNumber = 0;
@Override
public Line call(String text) {
return new Line(lineNumber++, text);
}
});
}
}