Bug 1250782 - Allow MozResponse to return a Json array body draft
authorEdouard Oger <eoger@fastmail.com>
Wed, 18 May 2016 12:22:49 -0700
changeset 369916 c198efa3f68f45608f695abd3520c032e0e74a31
parent 369317 16663eb3dcfa759f25b5e27b101bc79270c156f2
child 369917 af73c7d91ed120b146fca3d2cc9730ff5819361e
push id18951
push userbmo:edouard.oger@gmail.com
push dateTue, 24 May 2016 00:09:32 +0000
bugs1250782
milestone49.0a1
Bug 1250782 - Allow MozResponse to return a Json array body MozReview-Commit-ID: B40vvA0E7xJ
mobile/android/services/src/main/java/org/mozilla/gecko/sync/net/MozResponse.java
--- a/mobile/android/services/src/main/java/org/mozilla/gecko/sync/net/MozResponse.java
+++ b/mobile/android/services/src/main/java/org/mozilla/gecko/sync/net/MozResponse.java
@@ -6,18 +6,22 @@ package org.mozilla.gecko.sync.net;
 
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.io.Reader;
 import java.util.Scanner;
 
+import org.json.simple.JSONArray;
+import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
 import org.mozilla.gecko.background.common.log.Logger;
 import org.mozilla.gecko.sync.ExtendedJSONObject;
+import org.mozilla.gecko.sync.NonArrayJSONException;
 import org.mozilla.gecko.sync.NonObjectJSONException;
 
 import ch.boye.httpclientandroidlib.Header;
 import ch.boye.httpclientandroidlib.HttpEntity;
 import ch.boye.httpclientandroidlib.HttpResponse;
 import ch.boye.httpclientandroidlib.HttpStatus;
 import ch.boye.httpclientandroidlib.impl.cookie.DateParseException;
 import ch.boye.httpclientandroidlib.impl.cookie.DateUtils;
@@ -105,16 +109,43 @@ public class MozResponse {
     try {
       Reader in = new BufferedReader(new InputStreamReader(content, "UTF-8"));
       return new ExtendedJSONObject(in);
     } finally {
       content.close();
     }
   }
 
+  public JSONArray jsonArrayBody() throws NonArrayJSONException, IOException {
+    final JSONParser parser = new JSONParser();
+    try {
+      if (body != null) {
+        // Do it from the cached String.
+        return (JSONArray) parser.parse(body);
+      }
+
+      final HttpEntity entity = this.response.getEntity();
+      if (entity == null) {
+        throw new IOException("no entity");
+      }
+
+      final InputStream content = entity.getContent();
+      final Reader in = new BufferedReader(new InputStreamReader(content, "UTF-8"));
+      try {
+        return (JSONArray) parser.parse(in);
+      } finally {
+        in.close();
+      }
+    } catch (ClassCastException | ParseException e) {
+      NonArrayJSONException exception = new NonArrayJSONException("value must be a json array");
+      exception.initCause(e);
+      throw exception;
+    }
+  }
+
   protected boolean hasHeader(String h) {
     return this.response.containsHeader(h);
   }
 
   public MozResponse(HttpResponse res) {
     response = res;
   }