1 /*
2 * Copyright 2013-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License").
5 * You may not use this file except in compliance with the License.
6 * A copy of the License is located at
7 *
8 * http://aws.amazon.com/apache2.0
9 *
10 * or in the "license" file accompanying this file. This file is distributed
11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 * express or implied. See the License for the specific language governing
13 * permissions and limitations under the License.
14 */
15 package com.amazonaws.util;
16
17 import com.amazonaws.internal.Releasable;
18 import java.io.ByteArrayOutputStream;
19 import java.io.Closeable;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25
26
27 /**
28 * Utilities for IO operations.
29 */
30 public enum IOUtils {
31 ;
32 private static final int BUFFER_SIZE = 1024 * 4;
33 private static final Log defaultLog = LogFactory.getLog(IOUtils.class);
34
35 /**
36 * Reads and returns the rest of the given input stream as a byte array.
37 * Caller is responsible for closing the given input stream.
38 */
39 public static byte[] toByteArray(InputStream is) throws IOException {
40 ByteArrayOutputStream output = new ByteArrayOutputStream();
41 try {
42 byte[] b = new byte[BUFFER_SIZE];
43 int n = 0;
44 while ((n = is.read(b)) != -1) {
45 output.write(b, 0, n);
46 }
47 return output.toByteArray();
48 } finally {
49 output.close();
50 }
51 }
52
53 /**
54 * Reads and returns the rest of the given input stream as a string.
55 * Caller is responsible for closing the given input stream.
56 */
57 public static String toString(InputStream is) throws IOException {
58 return new String(toByteArray(is), StringUtils.UTF8);
59 }
60
61 /**
62 * Closes the given Closeable quietly.
63 *
64 * @param is the given closeable
65 * @param log logger used to log any failure should the close fail
66 */
67 public static void closeQuietly(Closeable is, Log log) {
68 if (is != null) {
69 try {
70 is.close();
71 } catch (IOException ex) {
72 Log logger = log == null ? defaultLog : log;
73 if (logger.isDebugEnabled()) {
74 logger.debug("Ignore failure in closing the Closeable", ex);
75 }
76 }
77 }
78 }
79
80 /**
81 * Releases the given {@link Closeable} especially if it was an instance of
82 * {@link Releasable}.
83 * <p>
84 * For example, the creation of a <code>ResettableInputStream</code> would entail
85 * physically opening a file. If the opened file is meant to be closed only
86 * (in a finally block) by the very same code block that created it, then it
87 * is necessary that the release method must not be called while the
88 * execution is made in other stack frames.
89 *
90 * In such case, as other stack frames may inadvertently or indirectly call
91 * the close method of the stream, the creator of the stream would need to
92 * explicitly disable the accidental closing via
93 * <code>ResettableInputStream#disableClose()</code>, so that the release method
94 * becomes the only way to truly close the opened file.
95 */
96 public static void release(Closeable is, Log log) {
97 closeQuietly(is, log);
98 if (is instanceof Releasable) {
99 Releasable r = (Releasable) is;
100 r.release();
101 }
102 }
103
104 /**
105 * Copies all bytes from the given input stream to the given output stream.
106 * Caller is responsible for closing the streams.
107 *
108 * @throws IOException if there is any IO exception during read or write.
109 */
110 public static long copy(InputStream in, OutputStream out) throws IOException {
111 return copy(in, out, Long.MAX_VALUE);
112 }
113
114 /**
115 * Copies all bytes from the given input stream to the given output stream.
116 * Caller is responsible for closing the streams.
117 *
118 * @throws IOException if there is any IO exception during read or write or the read limit is exceeded.
119 */
120 public static long copy(InputStream in, OutputStream out, long readLimit)
121 throws IOException {
122 byte[] buf = new byte[BUFFER_SIZE];
123 long count = 0;
124 int n = 0;
125 while ((n = in.read(buf)) > -1) {
126 out.write(buf, 0, n);
127 count += n;
128 if (count >= readLimit) {
129 throw new IOException("Read limit exceeded: " + readLimit);
130 }
131 }
132 return count;
133 }
134
135 /**
136 * Read all remaining data in the stream.
137 *
138 * @param in InputStream to read.
139 */
140 public static void drainInputStream(InputStream in) {
141 try {
142 while (in.read() != -1) {
143 // Do nothing.
144 }
145 } catch (IOException ignored) {
146 // Stream may be self closed by HTTP client so we ignore any failures.
147 }
148 }
149 }
150