|
| 1 | +/* |
| 2 | + * Copyright 2021-2022 Cufy and ProgSpaceSA |
| 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 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package org.cufy.http.internal.util; |
| 17 | + |
| 18 | +import org.jetbrains.annotations.ApiStatus; |
| 19 | +import org.jetbrains.annotations.Contract; |
| 20 | +import org.jetbrains.annotations.NotNull; |
| 21 | + |
| 22 | +import java.io.ByteArrayOutputStream; |
| 23 | +import java.io.IOException; |
| 24 | +import java.io.InputStream; |
| 25 | + |
| 26 | +/** |
| 27 | + * Internal utilities to deal with streams. |
| 28 | + * |
| 29 | + * @author LSafer |
| 30 | + * @version 1.0.0 |
| 31 | + * @since 1.0.0 ~2022.01.07 |
| 32 | + */ |
| 33 | +@ApiStatus.Internal |
| 34 | +public final class StreamUtil { |
| 35 | + /** |
| 36 | + * Utility classes shall have no instances. |
| 37 | + * |
| 38 | + * @throws AssertionError when called. |
| 39 | + * @since 1.0.0 ~2022.01.07 |
| 40 | + */ |
| 41 | + private StreamUtil() { |
| 42 | + throw new AssertionError("No instance for you!"); |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * A utility function to read all the bytes in a particular input stream. The stream |
| 47 | + * will not be closed automatically. |
| 48 | + * |
| 49 | + * @param is the input stream. |
| 50 | + * @return the bytes from reading the input stream. |
| 51 | + * @throws IOException if any I/O exception occurs while reading the input stream. |
| 52 | + * @since 1.0.0 ~2022.01.07 |
| 53 | + */ |
| 54 | + @Contract(mutates = "param") |
| 55 | + public static byte @NotNull [] readAllBytes(@NotNull InputStream is) throws IOException { |
| 56 | + ByteArrayOutputStream baos = new ByteArrayOutputStream(); |
| 57 | + |
| 58 | + //noinspection CheckForOutOfMemoryOnLargeArrayAllocation |
| 59 | + byte[] buffer = new byte[8192]; |
| 60 | + |
| 61 | + while (true) { |
| 62 | + int read = is.read(buffer, 0, buffer.length); |
| 63 | + |
| 64 | + if (read < 0) |
| 65 | + break; |
| 66 | + |
| 67 | + if (read == 0) |
| 68 | + continue; |
| 69 | + |
| 70 | + baos.write(buffer, 0, read); |
| 71 | + } |
| 72 | + |
| 73 | + return baos.toByteArray(); |
| 74 | + } |
| 75 | +} |
0 commit comments