|
| 1 | +// Copyright 2019 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.android.datatransport.cct.internal; |
| 16 | + |
| 17 | +import android.util.JsonReader; |
| 18 | +import android.util.JsonToken; |
| 19 | +import android.util.MalformedJsonException; |
| 20 | +import androidx.annotation.Nullable; |
| 21 | +import com.google.android.datatransport.runtime.logging.Logging; |
| 22 | +import com.google.auto.value.AutoValue; |
| 23 | +import java.io.EOFException; |
| 24 | +import java.io.IOException; |
| 25 | +import java.io.Reader; |
| 26 | + |
| 27 | +@AutoValue |
| 28 | +public abstract class LogResponse { |
| 29 | + private static final String LOG_TAG = "LogResponseInternal"; |
| 30 | + |
| 31 | + /** Client should wait for next_request_wait_millis before sending the next log request. */ |
| 32 | + public abstract long getNextRequestWaitMillis(); |
| 33 | + |
| 34 | + static LogResponse create(long nextRequestWaitMillis) { |
| 35 | + return new AutoValue_LogResponse(nextRequestWaitMillis); |
| 36 | + } |
| 37 | + |
| 38 | + @Nullable |
| 39 | + public static LogResponse fromJson(@Nullable Reader reader) throws IOException { |
| 40 | + if (reader == null) { |
| 41 | + return null; |
| 42 | + } |
| 43 | + |
| 44 | + JsonReader jsonReader = new JsonReader(reader); |
| 45 | + try { |
| 46 | + jsonReader.beginObject(); |
| 47 | + while (jsonReader.hasNext()) { |
| 48 | + String name = jsonReader.nextName(); |
| 49 | + if (name.equals("nextRequestWaitMillis")) { |
| 50 | + if (jsonReader.peek() == JsonToken.STRING) { |
| 51 | + return LogResponse.create(Long.parseLong(jsonReader.nextString())); |
| 52 | + } else { |
| 53 | + return LogResponse.create(jsonReader.nextLong()); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + return null; |
| 58 | + } catch (MalformedJsonException | EOFException e) { |
| 59 | + Logging.e(LOG_TAG, "Couldn't parse json response from backend.", e); |
| 60 | + return null; |
| 61 | + } finally { |
| 62 | + jsonReader.close(); |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments