|
| 1 | +// Copyright 2021 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package com.google.firebase.firestore.bundle; |
| 16 | + |
| 17 | +import androidx.annotation.Nullable; |
| 18 | +import java.io.IOException; |
| 19 | +import java.io.InputStream; |
| 20 | +import java.io.InputStreamReader; |
| 21 | +import java.nio.CharBuffer; |
| 22 | +import java.nio.charset.Charset; |
| 23 | +import org.json.JSONException; |
| 24 | +import org.json.JSONObject; |
| 25 | + |
| 26 | +/** |
| 27 | + * Reads the length-prefixed JSON stream for Bundles. |
| 28 | + * |
| 29 | + * <p>The class takes a bundle stream and presents abstractions to read bundled elements out of the |
| 30 | + * underlying content. |
| 31 | + */ |
| 32 | +public class BundleReader { |
| 33 | + /** The capacity for the internal char buffer. */ |
| 34 | + protected static final int BUFFER_CAPACITY = 1024; |
| 35 | + |
| 36 | + private final BundleSerializer serializer; |
| 37 | + private final InputStreamReader dataReader; |
| 38 | + private final Charset charset = Charset.forName("UTF-8"); |
| 39 | + |
| 40 | + @Nullable BundleMetadata metadata; |
| 41 | + private CharBuffer buffer; |
| 42 | + long bytesRead; |
| 43 | + |
| 44 | + public BundleReader(BundleSerializer serializer, InputStream data) { |
| 45 | + this.serializer = serializer; |
| 46 | + dataReader = new InputStreamReader(data, charset); |
| 47 | + buffer = CharBuffer.allocate(BUFFER_CAPACITY); |
| 48 | + |
| 49 | + buffer.flip(); // Start the buffer in "reading mode" |
| 50 | + } |
| 51 | + |
| 52 | + /** Returns the metadata element from the bundle. */ |
| 53 | + public BundleMetadata getBundleMetadata() throws IOException, JSONException { |
| 54 | + if (metadata != null) { |
| 55 | + return metadata; |
| 56 | + } |
| 57 | + BundleElement element = readNextElement(); |
| 58 | + if (!(element instanceof BundleMetadata)) { |
| 59 | + throw new IllegalArgumentException( |
| 60 | + "Expected first element in bundle to be a metadata object"); |
| 61 | + } |
| 62 | + metadata = (BundleMetadata) element; |
| 63 | + // We don't consider the metadata as part ot the bundle size, as it used to encode the size of |
| 64 | + // all remaining elements. |
| 65 | + bytesRead = 0; |
| 66 | + return metadata; |
| 67 | + } |
| 68 | + |
| 69 | + /** |
| 70 | + * Returns the next element from the bundle. Metadata elements can be accessed by invoking {@link |
| 71 | + * #getBundleMetadata} are not returned from this method. |
| 72 | + */ |
| 73 | + public BundleElement getNextElement() throws IOException, JSONException { |
| 74 | + // Makes sure metadata is read before proceeding. The metadata element is the first element |
| 75 | + // in the bundle stream. |
| 76 | + getBundleMetadata(); |
| 77 | + return readNextElement(); |
| 78 | + } |
| 79 | + |
| 80 | + /** Returns the number of bytes processed so far. */ |
| 81 | + public long getBytesRead() { |
| 82 | + return bytesRead; |
| 83 | + } |
| 84 | + |
| 85 | + public void close() throws IOException { |
| 86 | + dataReader.close(); |
| 87 | + } |
| 88 | + |
| 89 | + /** |
| 90 | + * Reads from the head of internal buffer, Pulls more data from underlying stream until a complete |
| 91 | + * element is found (including the prefixed length and the JSON string). |
| 92 | + * |
| 93 | + * <p>Once a complete element is read, it is dropped from internal buffer. |
| 94 | + * |
| 95 | + * <p>Returns either the bundled element, or null if we have reached the end of the stream. |
| 96 | + */ |
| 97 | + @Nullable |
| 98 | + private BundleElement readNextElement() throws IOException, JSONException { |
| 99 | + String lengthPrefix = readLengthPrefix(); |
| 100 | + if (lengthPrefix == null) { |
| 101 | + return null; |
| 102 | + } |
| 103 | + |
| 104 | + String json = readJsonString(Integer.parseInt(lengthPrefix)); |
| 105 | + bytesRead += lengthPrefix.length() + json.getBytes(charset).length; |
| 106 | + return decodeBundleElement(json); |
| 107 | + } |
| 108 | + |
| 109 | + /** |
| 110 | + * Reads the length prefix from the beginning of the internal buffer until the first '{'. Returns |
| 111 | + * the integer-decoded length. |
| 112 | + * |
| 113 | + * <p>If it reached the end of the stream, returns null. |
| 114 | + */ |
| 115 | + private @Nullable String readLengthPrefix() throws IOException { |
| 116 | + int nextOpenBracket; |
| 117 | + |
| 118 | + while ((nextOpenBracket = indexOfOpenBracket()) == -1) { |
| 119 | + if (!pullMoreData()) { |
| 120 | + break; |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + // We broke out of the loop because underlying stream is closed, and there happens to be no |
| 125 | + // more data to process. |
| 126 | + if (buffer.remaining() == 0) { |
| 127 | + return null; |
| 128 | + } |
| 129 | + |
| 130 | + // We broke out of the loop because underlying stream is closed, but still cannot find an |
| 131 | + // open bracket. |
| 132 | + if (nextOpenBracket == -1) { |
| 133 | + raiseError("Reached the end of bundle when a length string is expected."); |
| 134 | + } |
| 135 | + |
| 136 | + char[] c = new char[nextOpenBracket]; |
| 137 | + buffer.get(c); |
| 138 | + return new String(c); |
| 139 | + } |
| 140 | + |
| 141 | + /** Returns the index of the first open bracket, or -1 if none is found. */ |
| 142 | + private int indexOfOpenBracket() { |
| 143 | + buffer.mark(); |
| 144 | + try { |
| 145 | + for (int i = 0; i < buffer.remaining(); ++i) { |
| 146 | + if (buffer.get() == '{') { |
| 147 | + return i; |
| 148 | + } |
| 149 | + } |
| 150 | + return -1; |
| 151 | + } finally { |
| 152 | + buffer.reset(); |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + /** |
| 157 | + * Reads from a specified position from the internal buffer, for a specified number of bytes, |
| 158 | + * pulling more data from the underlying stream if needed. |
| 159 | + * |
| 160 | + * <p>Returns a string decoded from the read bytes. |
| 161 | + */ |
| 162 | + private String readJsonString(int length) throws IOException { |
| 163 | + StringBuilder json = new StringBuilder(length); |
| 164 | + |
| 165 | + int remaining = length; |
| 166 | + while (remaining > 0) { |
| 167 | + if (!pullMoreData()) { |
| 168 | + raiseError("Reached the end of bundle when more data was expected."); |
| 169 | + } |
| 170 | + |
| 171 | + int read = Math.min(remaining, buffer.remaining()); |
| 172 | + json.append(buffer, 0, read); |
| 173 | + buffer.position(buffer.position() + read); |
| 174 | + |
| 175 | + remaining -= read; |
| 176 | + } |
| 177 | + |
| 178 | + return json.toString(); |
| 179 | + } |
| 180 | + |
| 181 | + /** |
| 182 | + * Pulls more data from underlying stream into the internal buffer. |
| 183 | + * |
| 184 | + * @return whether more data is available |
| 185 | + */ |
| 186 | + private boolean pullMoreData() throws IOException { |
| 187 | + if (buffer.remaining() == 0) { |
| 188 | + buffer.compact(); |
| 189 | + dataReader.read(buffer); |
| 190 | + buffer.flip(); |
| 191 | + } |
| 192 | + return buffer.remaining() > 0; |
| 193 | + } |
| 194 | + |
| 195 | + /** Converts a JSON-encoded bundle element into its model class. */ |
| 196 | + private BundleElement decodeBundleElement(String json) throws JSONException { |
| 197 | + JSONObject object = new JSONObject(json); |
| 198 | + |
| 199 | + if (object.has("metadata")) { |
| 200 | + return serializer.decodeBundleMetadata(object.getJSONObject("metadata")); |
| 201 | + } else if (object.has("namedQuery")) { |
| 202 | + return serializer.decodeNamedQuery(object.getJSONObject("namedQuery")); |
| 203 | + } else if (object.has("documentMetadata")) { |
| 204 | + return serializer.decodeBundledDocumentMetadata(object.getJSONObject("documentMetadata")); |
| 205 | + } else if (object.has("document")) { |
| 206 | + return serializer.decodeDocument(object.getJSONObject("document")); |
| 207 | + } else { |
| 208 | + throw new IllegalArgumentException("Cannot decode unknown Bundle element: " + json); |
| 209 | + } |
| 210 | + } |
| 211 | + |
| 212 | + /** Closes the underlying stream and raises an IllegalArgumentException. */ |
| 213 | + private void raiseError(String message) throws IOException { |
| 214 | + close(); |
| 215 | + throw new IllegalArgumentException("Invalid bundle format: " + message); |
| 216 | + } |
| 217 | +} |
0 commit comments