1
2/*
3 * Copyright (C) 2010 Google Inc.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18// This file is a copy of caliper's InterleavedReader.java
19// (from code.google.com, last change Sep 9 2011)
20// with Android specific changes marked with "BEGIN android-changed".
21
22package vogar.monitor;
23
24import com.google.gson.JsonParser;
25
26import java.io.BufferedReader;
27import java.io.Closeable;
28import java.io.IOException;
29import java.io.Reader;
30
31/**
32 * Reads a stream containing inline JSON objects. Each JSON object is prefixed
33 * by a marker string and suffixed by a newline character.
34 */
35public final class InterleavedReader implements Closeable {
36
37  /**
38   * The length of the scratch buffer to search for markers in. Also acts as an
39   * upper bound on the length of returned strings. Not used as an I/O buffer.
40   */
41  private static final int BUFFER_LENGTH = 80;
42
43  private final String marker;
44  private final BufferedReader reader;
45  private final JsonParser jsonParser = new JsonParser();
46
47  public static final String DEFAULT_MARKER = "//ZxJ/";
48
49  public InterleavedReader(Reader reader) {
50    this(DEFAULT_MARKER, reader);
51  }
52
53  public InterleavedReader(String marker, Reader reader) {
54    if (marker.length() > BUFFER_LENGTH) {
55      throw new IllegalArgumentException("marker.length() > BUFFER_LENGTH");
56    }
57    this.marker = marker;
58    this.reader = reader instanceof BufferedReader
59        ? (BufferedReader) reader
60        : new BufferedReader(reader);
61  }
62
63  /**
64   * Returns the next value in the stream: either a String, a JsonElement, or
65   * null to indicate the end of the stream. Callers should use instanceof to
66   * inspect the return type.
67   */
68  public Object read() throws IOException {
69    char[] buffer = new char[BUFFER_LENGTH];
70    // BEGIN android-changed:
71    // Double the lookahead size. This is a safety measure in the presence of
72    // new lines, where the line feed character is being skipped. The lookahead
73    // check in the BufferedReader class does not take these skipped characters
74    // into account.
75    reader.mark(BUFFER_LENGTH << 1);
76    // END android-changed.
77    int count = 0;
78    int textEnd;
79
80    while (true) {
81      int r = reader.read(buffer, count, buffer.length - count);
82
83      if (r == -1) {
84        // the input is exhausted; return the remaining characters
85        textEnd = count;
86        break;
87      }
88
89      count += r;
90      int possibleMarker = findPossibleMarker(buffer, count);
91
92      if (possibleMarker != 0) {
93        // return the characters that precede the marker
94        textEnd = possibleMarker;
95        break;
96      }
97
98      if (count < marker.length()) {
99        // the buffer contains only the prefix of a marker so we must read more
100        continue;
101      }
102
103      // we've read a marker so return the value that follows
104      reader.reset();
105      String json = reader.readLine().substring(marker.length());
106      return jsonParser.parse(json);
107    }
108
109    if (count == 0) {
110      return null;
111    }
112
113    // return characters
114    reader.reset();
115    count = reader.read(buffer, 0, textEnd);
116    return new String(buffer, 0, count);
117  }
118
119  @Override public void close() throws IOException {
120    reader.close();
121  }
122
123  /**
124   * Returns the index of marker in {@code chars}, stopping at {@code limit}.
125   * Should the chars end with a prefix of marker, the offset of that prefix
126   * is returned.
127   */
128  int findPossibleMarker(char[] chars, int limit) {
129    search:
130    for (int i = 0; true; i++) {
131      for (int m = 0; m < marker.length() && i + m < limit; m++) {
132        if (chars[i + m] != marker.charAt(m)) {
133          continue search;
134        }
135      }
136      return i;
137    }
138  }
139}
140