1 package org.paneris.util;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.OutputStream;
6
7 public class IoUtils {
8
9
10
11 public static byte[] slurp(InputStream i, int estimate, int limit)
12 throws IOException {
13 byte[] b = new byte[estimate];
14 int p = 0;
15
16 for (;;) {
17 int g = i.read(b, p, Math.min(b.length, limit) - p);
18 if (g == -1) break;
19 p += g;
20 if (p >= limit) break;
21 if (p >= b.length) {
22 byte[] c = new byte[2 * b.length];
23 System.arraycopy(b, 0, c, 0, p);
24 b = c;
25 }
26 }
27
28 i.close();
29
30 if (p == b.length)
31 return b;
32 else {
33 byte[] c = new byte[p];
34 System.arraycopy(b, 0, c, 0, p);
35 return c;
36 }
37 }
38
39 public static byte[] slurp(InputStream i, int estimate) throws IOException {
40 return slurp(i, estimate, Integer.MAX_VALUE);
41 }
42
43
44
45
46
47 public static byte[] slurpOutputOf_bytes(String[] command,
48 int estimate, int limit)
49 throws IOException {
50 Process proc = Runtime.getRuntime().exec(command);
51
52 byte[] output = IoUtils.slurp(proc.getInputStream(), estimate, limit);
53
54 if (output.length >= limit) {
55 try {
56 proc.destroy();
57 } catch (Exception e) {}
58 throw new ProcessFailedException(
59 command[0] + " was terminated after producing more than " +
60 limit + " bytes of output",
61 "");
62 }
63
64 byte[] errors = IoUtils.slurp(proc.getErrorStream(), estimate, limit);
65
66 try {
67 if (proc.waitFor() != 0)
68 throw new ProcessFailedException(
69 command[0] + " failed",
70 new String(errors, 0, Math.min(500, errors.length)));
71
72 return output;
73 }
74 catch (InterruptedException e) {
75 throw new IOException("interrupted while waiting for " +
76 command[0] + " to complete");
77 }
78 }
79
80
81
82
83
84 public static String slurpOutputOf(String[] command, int estimate, int limit)
85 throws IOException {
86 return new String(slurpOutputOf_bytes(command, estimate, limit));
87 }
88
89 public static void copy(InputStream i, int buf, OutputStream o)
90 throws IOException {
91 byte b[] = new byte[buf];
92 for (;;) {
93 int g = i.read(b);
94 if (g == -1) break;
95 o.write(b, 0, g);
96 }
97 }
98 }