-
Notifications
You must be signed in to change notification settings - Fork 434
/
IOGroovyMethods.java
1634 lines (1518 loc) · 61.3 KB
/
IOGroovyMethods.java
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.codehaus.groovy.runtime;
import groovy.io.GroovyPrintWriter;
import groovy.lang.Closure;
import groovy.lang.StringWriterIOException;
import groovy.lang.Writable;
import groovy.transform.stc.ClosureParams;
import groovy.transform.stc.FirstParam;
import groovy.transform.stc.FromString;
import groovy.transform.stc.SimpleType;
import org.codehaus.groovy.runtime.callsite.BooleanClosureWrapper;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Arrays;
import java.util.Formatter;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import static org.codehaus.groovy.runtime.DefaultGroovyMethods.callClosureForLine;
/**
* This class defines new groovy methods for Files, URLs, URIs which appear
* on normal JDK classes inside the Groovy environment.
* Static methods are used with the first parameter being the destination class,
* i.e. <code>public static long size(File self)</code>
* provides a <code>size()</code> method for <code>File</code>.
* <p>
* NOTE: While this class contains many 'public' static methods, it is
* primarily regarded as an internal class (its internal package name
* suggests this also). We value backwards compatibility of these
* methods when used within Groovy but value less backwards compatibility
* at the Java method call level. I.e. future versions of Groovy may
* remove or move a method call in this file but would normally
* aim to keep the method available from within Groovy.
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @author Jeremy Rayner
* @author Sam Pullara
* @author Rod Cope
* @author Guillaume Laforge
* @author John Wilson
* @author Hein Meling
* @author Dierk Koenig
* @author Pilho Kim
* @author Marc Guillemot
* @author Russel Winder
* @author bing ran
* @author Jochen Theodorou
* @author Paul King
* @author Michael Baehr
* @author Joachim Baumann
* @author Alex Tkachman
* @author Ted Naleid
* @author Brad Long
* @author Jim Jagielski
* @author Rodolfo Velasco
* @author jeremi Joslin
* @author Hamlet D'Arcy
* @author Cedric Champeau
* @author Tim Yates
* @author Dinko Srkoc
*/
public class IOGroovyMethods extends DefaultGroovyMethodsSupport {
private static final Logger LOG = Logger.getLogger(IOGroovyMethods.class.getName());
/**
* Overloads the leftShift operator for Writer to allow an object to be written
* using Groovy's default representation for the object.
*
* @param self a Writer
* @param value an Object whose default representation will be written to the Writer
* @return the writer on which this operation was invoked
* @throws IOException if an I/O error occurs.
* @since 1.0
*/
public static Writer leftShift(Writer self, Object value) throws IOException {
InvokerHelper.write(self, value);
return self;
}
/**
* Overloads the leftShift operator for Appendable to allow an object to be appended
* using Groovy's default representation for the object.
*
* @param self an Appendable
* @param value an Object whose default representation will be appended to the Appendable
* @return the Appendable on which this operation was invoked
* @throws IOException if an I/O error occurs.
* @since 2.1.0
*/
public static Appendable leftShift(Appendable self, Object value) throws IOException {
InvokerHelper.append(self, value);
return self;
}
/**
* Invokes a Closure that uses a Formatter taking care of resource handling.
* A Formatter is created and passed to the Closure as its argument.
* After the Closure executes, the Formatter is flushed and closed releasing any
* associated resources.
*
* @param self an Appendable
* @param closure a 1-arg Closure which will be called with a Formatter as its argument
* @return the Appendable on which this operation was invoked
* @since 2.1.0
*/
public static Appendable withFormatter(Appendable self, @ClosureParams(value=SimpleType.class, options="java.util.Formatter") Closure closure) {
Formatter formatter = new Formatter(self);
callWithFormatter(closure, formatter);
return self;
}
/**
* Invokes a Closure that uses a Formatter taking care of resource handling.
* A Formatter is created using the given Locale and passed to the Closure as its argument.
* After the Closure executes, the Formatter is flushed and closed releasing any
* associated resources.
*
* @param self an Appendable
* @param locale a Locale used when creating the Formatter
* @param closure a 1-arg Closure which will be called with a Formatter as its argument
* @return the Appendable on which this operation was invoked
* @since 2.1.0
*/
public static Appendable withFormatter(Appendable self, Locale locale, @ClosureParams(value=SimpleType.class, options="java.util.Formatter") Closure closure) {
Formatter formatter = new Formatter(self, locale);
callWithFormatter(closure, formatter);
return self;
}
private static void callWithFormatter(Closure closure, Formatter formatter) {
try {
closure.call(formatter);
} finally {
formatter.flush();
formatter.close();
}
}
/**
* A helper method so that dynamic dispatch of the writer.write(object) method
* will always use the more efficient Writable.writeTo(writer) mechanism if the
* object implements the Writable interface.
*
* @param self a Writer
* @param writable an object implementing the Writable interface
* @throws IOException if an I/O error occurs.
* @since 1.0
*/
public static void write(Writer self, Writable writable) throws IOException {
writable.writeTo(self);
}
/**
* Overloads the leftShift operator to provide an append mechanism to add values to a stream.
*
* @param self an OutputStream
* @param value a value to append
* @return a Writer
* @throws java.io.IOException if an I/O error occurs.
* @since 1.0
*/
public static Writer leftShift(OutputStream self, Object value) throws IOException {
OutputStreamWriter writer = new FlushingStreamWriter(self);
leftShift(writer, value);
return writer;
}
/**
* Overloads the leftShift operator to add objects to an ObjectOutputStream.
*
* @param self an ObjectOutputStream
* @param value an object to write to the stream
* @throws IOException if an I/O error occurs.
* @since 1.5.0
*/
public static void leftShift(ObjectOutputStream self, Object value) throws IOException {
self.writeObject(value);
}
/**
* Pipe an InputStream into an OutputStream for efficient stream copying.
*
* @param self stream on which to write
* @param in stream to read from
* @return the outputstream itself
* @throws IOException if an I/O error occurs.
* @since 1.0
*/
public static OutputStream leftShift(OutputStream self, InputStream in) throws IOException {
byte[] buf = new byte[1024];
while (true) {
int count = in.read(buf, 0, buf.length);
if (count == -1) break;
if (count == 0) {
Thread.yield();
continue;
}
self.write(buf, 0, count);
}
self.flush();
return self;
}
/**
* Overloads the leftShift operator to provide an append mechanism to add bytes to a stream.
*
* @param self an OutputStream
* @param value a value to append
* @return an OutputStream
* @throws IOException if an I/O error occurs.
* @since 1.0
*/
public static OutputStream leftShift(OutputStream self, byte[] value) throws IOException {
self.write(value);
self.flush();
return self;
}
/**
* Create an object output stream for this output stream.
*
* @param outputStream an output stream
* @return an object output stream
* @throws IOException if an IOException occurs.
* @since 1.5.0
*/
public static ObjectOutputStream newObjectOutputStream(OutputStream outputStream) throws IOException {
return new ObjectOutputStream(outputStream);
}
/**
* Create a new ObjectOutputStream for this output stream and then pass it to the
* closure. This method ensures the stream is closed after the closure
* returns.
*
* @param outputStream am output stream
* @param closure a closure
* @return the value returned by the closure
* @throws IOException if an IOException occurs.
* @see #withStream(java.io.OutputStream, groovy.lang.Closure)
* @since 1.5.0
*/
public static <T> T withObjectOutputStream(OutputStream outputStream, @ClosureParams(value=SimpleType.class, options="java.io.ObjectOutputStream") Closure<T> closure) throws IOException {
return withStream(newObjectOutputStream(outputStream), closure);
}
/**
* Create an object input stream for this input stream.
*
* @param inputStream an input stream
* @return an object input stream
* @throws IOException if an IOException occurs.
* @since 1.5.0
*/
public static ObjectInputStream newObjectInputStream(InputStream inputStream) throws IOException {
return new ObjectInputStream(inputStream);
}
/**
* Create an object input stream for this input stream using the given class loader.
*
* @param inputStream an input stream
* @param classLoader the class loader to use when loading the class
* @return an object input stream
* @throws IOException if an IOException occurs.
* @since 1.5.0
*/
public static ObjectInputStream newObjectInputStream(InputStream inputStream, final ClassLoader classLoader) throws IOException {
return new ObjectInputStream(inputStream) {
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
return Class.forName(desc.getName(), true, classLoader);
}
};
}
/**
* Iterates through the given object stream object by object. The
* ObjectInputStream is closed afterwards.
*
* @param ois an ObjectInputStream, closed after the operation
* @param closure a closure
* @throws IOException if an IOException occurs.
* @throws ClassNotFoundException if the class is not found.
* @since 1.0
*/
public static void eachObject(ObjectInputStream ois, Closure closure) throws IOException, ClassNotFoundException {
try {
while (true) {
try {
Object obj = ois.readObject();
// we allow null objects in the object stream
closure.call(obj);
} catch (EOFException e) {
break;
}
}
InputStream temp = ois;
ois = null;
temp.close();
} finally {
closeWithWarning(ois);
}
}
/**
* Create a new ObjectInputStream for this file and pass it to the closure.
* This method ensures the stream is closed after the closure returns.
*
* @param inputStream an input stream
* @param closure a closure
* @return the value returned by the closure
* @throws IOException if an IOException occurs.
* @see #withStream(java.io.InputStream, groovy.lang.Closure)
* @since 1.5.0
*/
public static <T> T withObjectInputStream(InputStream inputStream, @ClosureParams(value=SimpleType.class, options="java.io.ObjectInputStream") Closure<T> closure) throws IOException {
return withStream(newObjectInputStream(inputStream), closure);
}
/**
* Create a new ObjectInputStream for this file and pass it to the closure.
* This method ensures the stream is closed after the closure returns.
*
* @param inputStream an input stream
* @param classLoader the class loader to use when loading the class
* @param closure a closure
* @return the value returned by the closure
* @throws IOException if an IOException occurs.
* @see #withStream(java.io.InputStream, groovy.lang.Closure)
* @since 1.5.0
*/
public static <T> T withObjectInputStream(InputStream inputStream, ClassLoader classLoader, @ClosureParams(value=SimpleType.class, options="java.io.ObjectInputStream") Closure<T> closure) throws IOException {
return withStream(newObjectInputStream(inputStream, classLoader), closure);
}
/**
* Iterates through this stream reading with the provided charset, passing each line to the
* given 1 or 2 arg closure. The stream is closed before this method returns.
*
* @param stream a stream
* @param charset opens the stream with a specified charset
* @param closure a closure (arg 1 is line, optional arg 2 is line number starting at line 1)
* @return the last value returned by the closure
* @throws IOException if an IOException occurs.
* @see #eachLine(java.io.InputStream, java.lang.String, int, groovy.lang.Closure)
* @since 1.5.5
*/
public static <T> T eachLine(InputStream stream, String charset, @ClosureParams(value=FromString.class,options={"String","String,Integer"}) Closure<T> closure) throws IOException {
return eachLine(stream, charset, 1, closure);
}
/**
* Iterates through this stream reading with the provided charset, passing each line to
* the given 1 or 2 arg closure. The stream is closed after this method returns.
*
* @param stream a stream
* @param charset opens the stream with a specified charset
* @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0)
* @param closure a closure (arg 1 is line, optional arg 2 is line number)
* @return the last value returned by the closure
* @throws IOException if an IOException occurs.
* @see #eachLine(java.io.Reader, int, groovy.lang.Closure)
* @since 1.5.7
*/
public static <T> T eachLine(InputStream stream, String charset, int firstLine, @ClosureParams(value=FromString.class,options={"String","String,Integer"}) Closure<T> closure) throws IOException {
return eachLine(new InputStreamReader(stream, charset), firstLine, closure);
}
/**
* Iterates through this stream, passing each line to the given 1 or 2 arg closure.
* The stream is closed before this method returns.
*
* @param stream a stream
* @param closure a closure (arg 1 is line, optional arg 2 is line number starting at line 1)
* @return the last value returned by the closure
* @throws IOException if an IOException occurs.
* @see #eachLine(java.io.InputStream, int, groovy.lang.Closure)
* @since 1.5.6
*/
public static <T> T eachLine(InputStream stream, @ClosureParams(value=FromString.class,options={"String","String,Integer"}) Closure<T> closure) throws IOException {
return eachLine(stream, 1, closure);
}
/**
* Iterates through this stream, passing each line to the given 1 or 2 arg closure.
* The stream is closed before this method returns.
*
* @param stream a stream
* @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0)
* @param closure a closure (arg 1 is line, optional arg 2 is line number)
* @return the last value returned by the closure
* @throws IOException if an IOException occurs.
* @see #eachLine(java.io.Reader, int, groovy.lang.Closure)
* @since 1.5.7
*/
public static <T> T eachLine(InputStream stream, int firstLine, @ClosureParams(value=FromString.class,options={"String","String,Integer"}) Closure<T> closure) throws IOException {
return eachLine(new InputStreamReader(stream), firstLine, closure);
}
/**
* Iterates through the given reader line by line. Each line is passed to the
* given 1 or 2 arg closure. If the closure has two arguments, the line count is passed
* as the second argument. The Reader is closed before this method returns.
*
* @param self a Reader, closed after the method returns
* @param closure a closure (arg 1 is line, optional arg 2 is line number starting at line 1)
* @return the last value returned by the closure
* @throws IOException if an IOException occurs.
* @see #eachLine(java.io.Reader, int, groovy.lang.Closure)
* @since 1.5.6
*/
public static <T> T eachLine(Reader self, @ClosureParams(value=FromString.class,options={"String","String,Integer"}) Closure<T> closure) throws IOException {
return eachLine(self, 1, closure);
}
/**
* Iterates through the given reader line by line. Each line is passed to the
* given 1 or 2 arg closure. If the closure has two arguments, the line count is passed
* as the second argument. The Reader is closed before this method returns.
*
* @param self a Reader, closed after the method returns
* @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0)
* @param closure a closure which will be passed each line (or for 2 arg closures the line and line count)
* @return the last value returned by the closure
* @throws IOException if an IOException occurs.
* @since 1.5.7
*/
public static <T> T eachLine(Reader self, int firstLine, @ClosureParams(value=FromString.class,options={"String","String,Integer"}) Closure<T> closure) throws IOException {
BufferedReader br;
int count = firstLine;
T result = null;
if (self instanceof BufferedReader)
br = (BufferedReader) self;
else
br = new BufferedReader(self);
try {
while (true) {
String line = br.readLine();
if (line == null) {
break;
} else {
result = callClosureForLine(closure, line, count);
count++;
}
}
Reader temp = self;
self = null;
temp.close();
return result;
} finally {
closeWithWarning(self);
closeWithWarning(br);
}
}
/**
* Iterates through the given reader line by line, splitting each line using
* the given regex separator. For each line, the given closure is called with
* a single parameter being the list of strings computed by splitting the line
* around matches of the given regular expression. The Reader is closed afterwards.
* <p>
* Here is an example:
* <pre>
* def s = 'The 3 quick\nbrown 4 fox'
* def result = ''
* new StringReader(s).splitEachLine(/\d/){ parts ->
* result += "${parts[0]}_${parts[1]}|"
* }
* assert result == 'The _ quick|brown _ fox|'
* </pre>
*
* @param self a Reader, closed after the method returns
* @param regex the delimiting regular expression
* @param closure a closure
* @return the last value returned by the closure
* @throws IOException if an IOException occurs.
* @throws java.util.regex.PatternSyntaxException
* if the regular expression's syntax is invalid
* @see java.lang.String#split(java.lang.String)
* @since 1.5.5
*/
public static <T> T splitEachLine(Reader self, String regex, @ClosureParams(value=FromString.class,options="List<String>") Closure<T> closure) throws IOException {
return splitEachLine(self, Pattern.compile(regex), closure);
}
/**
* Iterates through the given reader line by line, splitting each line using
* the given regex separator Pattern. For each line, the given closure is called with
* a single parameter being the list of strings computed by splitting the line
* around matches of the given regular expression. The Reader is closed afterwards.
* <p>
* Here is an example:
* <pre>
* def s = 'The 3 quick\nbrown 4 fox'
* def result = ''
* new StringReader(s).splitEachLine(~/\d/){ parts ->
* result += "${parts[0]}_${parts[1]}|"
* }
* assert result == 'The _ quick|brown _ fox|'
* </pre>
*
* @param self a Reader, closed after the method returns
* @param pattern the regular expression Pattern for the delimiter
* @param closure a closure
* @return the last value returned by the closure
* @throws IOException if an IOException occurs.
* @throws java.util.regex.PatternSyntaxException
* if the regular expression's syntax is invalid
* @see java.lang.String#split(java.lang.String)
* @since 1.6.8
*/
public static <T> T splitEachLine(Reader self, Pattern pattern, @ClosureParams(value=FromString.class,options="List<String>") Closure<T> closure) throws IOException {
BufferedReader br;
T result = null;
if (self instanceof BufferedReader)
br = (BufferedReader) self;
else
br = new BufferedReader(self);
try {
while (true) {
String line = br.readLine();
if (line == null) {
break;
} else {
List vals = Arrays.asList(pattern.split(line));
result = closure.call(vals);
}
}
Reader temp = self;
self = null;
temp.close();
return result;
} finally {
closeWithWarning(self);
closeWithWarning(br);
}
}
/**
* Iterates through the given InputStream line by line using the specified
* encoding, splitting each line using the given separator. The list of tokens
* for each line is then passed to the given closure. Finally, the stream
* is closed.
*
* @param stream an InputStream
* @param regex the delimiting regular expression
* @param charset opens the stream with a specified charset
* @param closure a closure
* @return the last value returned by the closure
* @throws IOException if an IOException occurs.
* @throws java.util.regex.PatternSyntaxException
* if the regular expression's syntax is invalid
* @see #splitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure)
* @since 1.5.5
*/
public static <T> T splitEachLine(InputStream stream, String regex, String charset, @ClosureParams(value=FromString.class,options="List<String>") Closure<T> closure) throws IOException {
return splitEachLine(new BufferedReader(new InputStreamReader(stream, charset)), regex, closure);
}
/**
* Iterates through the given InputStream line by line using the specified
* encoding, splitting each line using the given separator Pattern. The list of tokens
* for each line is then passed to the given closure. Finally, the stream
* is closed.
*
* @param stream an InputStream
* @param pattern the regular expression Pattern for the delimiter
* @param charset opens the stream with a specified charset
* @param closure a closure
* @return the last value returned by the closure
* @throws IOException if an IOException occurs.
* @see #splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure)
* @since 1.6.8
*/
public static <T> T splitEachLine(InputStream stream, Pattern pattern, String charset, @ClosureParams(value=FromString.class,options="List<String>") Closure<T> closure) throws IOException {
return splitEachLine(new BufferedReader(new InputStreamReader(stream, charset)), pattern, closure);
}
/**
* Iterates through the given InputStream line by line, splitting each line using
* the given separator. The list of tokens for each line is then passed to
* the given closure. The stream is closed before the method returns.
*
* @param stream an InputStream
* @param regex the delimiting regular expression
* @param closure a closure
* @return the last value returned by the closure
* @throws IOException if an IOException occurs.
* @throws java.util.regex.PatternSyntaxException
* if the regular expression's syntax is invalid
* @see #splitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure)
* @since 1.5.6
*/
public static <T> T splitEachLine(InputStream stream, String regex, @ClosureParams(value=FromString.class,options="List<String>") Closure<T> closure) throws IOException {
return splitEachLine(new BufferedReader(new InputStreamReader(stream)), regex, closure);
}
/**
* Iterates through the given InputStream line by line, splitting each line using
* the given separator Pattern. The list of tokens for each line is then passed to
* the given closure. The stream is closed before the method returns.
*
* @param stream an InputStream
* @param pattern the regular expression Pattern for the delimiter
* @param closure a closure
* @return the last value returned by the closure
* @throws IOException if an IOException occurs.
* @see #splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure)
* @since 1.6.8
*/
public static <T> T splitEachLine(InputStream stream, Pattern pattern, @ClosureParams(value=FromString.class,options="List<String>") Closure<T> closure) throws IOException {
return splitEachLine(new BufferedReader(new InputStreamReader(stream)), pattern, closure);
}
/**
* Read a single, whole line from the given Reader.
*
* @param self a Reader
* @return a line
* @throws IOException if an IOException occurs.
* @since 1.0
*/
public static String readLine(Reader self) throws IOException {
if (self instanceof BufferedReader) {
BufferedReader br = (BufferedReader) self;
return br.readLine();
}
if (self.markSupported()) {
return readLineFromReaderWithMark(self);
}
return readLineFromReaderWithoutMark(self);
}
private static int charBufferSize = 4096; // half the default stream buffer size
private static int expectedLineLength = 160; // double the default line length
private static int EOF = -1; // End Of File
/*
* This method tries to read subsequent buffers from the reader using a mark
*/
private static String readLineFromReaderWithMark(final Reader input)
throws IOException {
char[] cbuf = new char[charBufferSize];
try {
input.mark(charBufferSize);
} catch (IOException e) {
// this should never happen
LOG.warning("Caught exception setting mark on supporting reader: " + e);
// fallback
return readLineFromReaderWithoutMark(input);
}
// could be changed into do..while, but then
// we might create an additional StringBuilder
// instance at the end of the stream
int count = input.read(cbuf);
if (count == EOF) // we are at the end of the input data
return null;
StringBuilder line = new StringBuilder(expectedLineLength);
// now work on the buffer(s)
int ls = lineSeparatorIndex(cbuf, count);
while (ls == -1) {
line.append(cbuf, 0, count);
count = input.read(cbuf);
if (count == EOF) {
// we are at the end of the input data
return line.toString();
}
ls = lineSeparatorIndex(cbuf, count);
}
line.append(cbuf, 0, ls);
// correct ls if we have \r\n
int skipLS = 1;
if (ls + 1 < count) {
// we are not at the end of the buffer
if (cbuf[ls] == '\r' && cbuf[ls + 1] == '\n') {
skipLS++;
}
} else {
if (cbuf[ls] == '\r' && input.read() == '\n') {
skipLS++;
}
}
//reset() and skip over last linesep
input.reset();
input.skip(line.length() + skipLS);
return line.toString();
}
/*
* This method reads without a buffer.
* It returns too many empty lines if \r\n combinations
* are used. Nothing can be done because we can't push
* back the character we have just read.
*/
private static String readLineFromReaderWithoutMark(Reader input)
throws IOException {
int c = input.read();
if (c == -1)
return null;
StringBuilder line = new StringBuilder(expectedLineLength);
while (c != EOF && c != '\n' && c != '\r') {
char ch = (char) c;
line.append(ch);
c = input.read();
}
return line.toString();
}
/*
* searches for \n or \r
* Returns -1 if not found.
*/
private static int lineSeparatorIndex(char[] array, int length) {
for (int k = 0; k < length; k++) {
if (isLineSeparator(array[k])) {
return k;
}
}
return -1;
}
/*
* true if either \n or \r
*/
private static boolean isLineSeparator(char c) {
return c == '\n' || c == '\r';
}
/**
* Reads the stream into a list, with one element for each line.
*
* @param stream a stream
* @return a List of lines
* @throws IOException if an IOException occurs.
* @see #readLines(java.io.Reader)
* @since 1.0
*/
public static List<String> readLines(InputStream stream) throws IOException {
return readLines(newReader(stream));
}
/**
* Reads the stream into a list, with one element for each line.
*
* @param stream a stream
* @param charset opens the stream with a specified charset
* @return a List of lines
* @throws IOException if an IOException occurs.
* @see #readLines(java.io.Reader)
* @since 1.6.8
*/
public static List<String> readLines(InputStream stream, String charset) throws IOException {
return readLines(newReader(stream, charset));
}
/**
* Reads the reader into a list of Strings, with one entry for each line.
* The reader is closed before this method returns.
*
* @param reader a Reader
* @return a List of lines
* @throws IOException if an IOException occurs.
* @since 1.0
*/
public static List<String> readLines(Reader reader) throws IOException {
IteratorClosureAdapter<String> closure = new IteratorClosureAdapter<String>(reader);
eachLine(reader, closure);
return closure.asList();
}
/**
* Read the content of this InputStream and return it as a String.
* The stream is closed before this method returns.
*
* @param is an input stream
* @return the text from that URL
* @throws IOException if an IOException occurs.
* @since 1.0
*/
public static String getText(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
return getText(reader);
}
/**
* Read the content of this InputStream using specified charset and return
* it as a String. The stream is closed before this method returns.
*
* @param is an input stream
* @param charset opens the stream with a specified charset
* @return the text from that URL
* @throws IOException if an IOException occurs.
* @since 1.0
*/
public static String getText(InputStream is, String charset) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset));
return getText(reader);
}
/**
* Read the content of the Reader and return it as a String. The reader
* is closed before this method returns.
*
* @param reader a Reader whose content we want to read
* @return a String containing the content of the buffered reader
* @throws IOException if an IOException occurs.
* @see #getText(java.io.BufferedReader)
* @since 1.0
*/
public static String getText(Reader reader) throws IOException {
BufferedReader bufferedReader = new BufferedReader(reader);
return getText(bufferedReader);
}
/**
* Read the content of the BufferedReader and return it as a String.
* The BufferedReader is closed afterwards.
*
* @param reader a BufferedReader whose content we want to read
* @return a String containing the content of the buffered reader
* @throws IOException if an IOException occurs.
* @since 1.0
*/
public static String getText(BufferedReader reader) throws IOException {
StringBuilder answer = new StringBuilder();
// reading the content of the file within a char buffer
// allow to keep the correct line endings
char[] charBuffer = new char[8192];
int nbCharRead /* = 0*/;
try {
while ((nbCharRead = reader.read(charBuffer)) != -1) {
// appends buffer
answer.append(charBuffer, 0, nbCharRead);
}
Reader temp = reader;
reader = null;
temp.close();
} finally {
closeWithWarning(reader);
}
return answer.toString();
}
/**
* Read the content of this InputStream and return it as a byte[].
* The stream is closed before this method returns.
*
* @param is an input stream
* @return the byte[] from that InputStream
* @throws IOException if an IOException occurs.
* @since 1.7.1
*/
public static byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream answer = new ByteArrayOutputStream();
// reading the content of the file within a byte buffer
byte[] byteBuffer = new byte[8192];
int nbByteRead /* = 0*/;
try {
while ((nbByteRead = is.read(byteBuffer)) != -1) {
// appends buffer
answer.write(byteBuffer, 0, nbByteRead);
}
} finally {
closeWithWarning(is);
}
return answer.toByteArray();
}
/**
* Write the byte[] to the output stream.
* The stream is closed before this method returns.
*
* @param os an output stream
* @param bytes the byte[] to write to the output stream
* @throws IOException if an IOException occurs.
* @since 1.7.1
*/
public static void setBytes(OutputStream os, byte[] bytes) throws IOException {
try {
os.write(bytes);
} finally {
closeWithWarning(os);
}
}
/**
* Write the text and append a newline (using the platform's line-ending).
*
* @param writer a BufferedWriter
* @param line the line to write
* @throws IOException if an IOException occurs.
* @since 1.0
*/
public static void writeLine(BufferedWriter writer, String line) throws IOException {
writer.write(line);
writer.newLine();
}
/**
* Creates an iterator which will traverse through the reader a line at a time.
*
* @param self a Reader object
* @return an Iterator for the Reader
* @see java.io.BufferedReader#readLine()
* @since 1.5.0
*/
public static Iterator<String> iterator(Reader self) {
final BufferedReader bufferedReader;
if (self instanceof BufferedReader)
bufferedReader = (BufferedReader) self;
else
bufferedReader = new BufferedReader(self);
return new Iterator<String>() {
String nextVal /* = null */;
boolean nextMustRead = true;
boolean hasNext = true;
public boolean hasNext() {
if (nextMustRead && hasNext) {
try {
nextVal = readNext();
nextMustRead = false;
} catch (IOException e) {
hasNext = false;
}
}
return hasNext;
}
public String next() {
String retval = null;
if (nextMustRead) {
try {
retval = readNext();
} catch (IOException e) {
hasNext = false;
}
} else
retval = nextVal;
nextMustRead = true;
return retval;
}
private String readNext() throws IOException {
String nv = bufferedReader.readLine();
if (nv == null)
hasNext = false;