Ejemplo n.º 1
0
  @Override
  void retrieveSupplementalInfo() throws IOException {

    CharSequence contents =
        HttpHelper.downloadViaHttp(
            "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn,
            HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
      return;
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

      JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
      JSONArray items = topLevel.optJSONArray("items");
      if (items == null || items.isNull(0)) {
        return;
      }

      JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
      if (volumeInfo == null) {
        return;
      }

      title = volumeInfo.optString("title");
      pages = volumeInfo.optString("pageCount");

      JSONArray authorsArray = volumeInfo.optJSONArray("authors");
      if (authorsArray != null && !authorsArray.isNull(0)) {
        authors = new ArrayList<String>(authorsArray.length());
        for (int i = 0; i < authorsArray.length(); i++) {
          authors.add(authorsArray.getString(i));
        }
      }

    } catch (JSONException e) {
      throw new IOException(e.toString());
    }

    Collection<String> newTexts = new ArrayList<String>();
    maybeAddText(title, newTexts);
    maybeAddTextSeries(authors, newTexts);
    maybeAddText(pages == null || pages.length() == 0 ? null : pages + "pp.", newTexts);

    String baseBookUri =
        "http://www.google."
            + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
  }
  public JSONArray sort(JSONArray finalResult, String SearchQuery) {

    int i = 0;
    int[] relevanceFactor = new int[finalResult.length()];
    List<JSONObject> jsonValues = new ArrayList<JSONObject>();
    JSONArray sortedJsonArray = new JSONArray();
    String[] searchTerms;

    // System.out.println(finalResult.toString());

    while (!finalResult.isNull(i)) {
      JSONObject object = finalResult.getJSONObject(i);

      searchTerms = SearchQuery.split(" ");

      for (int l = 0; l < searchTerms.length; l++) {

        relevanceFactor[i] += getRelevanceFactor(searchTerms[l], object.getString("keywords"));
        relevanceFactor[i] += getRelevanceFactor(searchTerms[l], object.getString("text"));
        relevanceFactor[i] += getRelevanceFactor(searchTerms[l], object.getString("title"));
      }

      object.put("relevanceFactor", relevanceFactor[i]);
      // System.out.println("relevanceFactor: "+relevanceFactor[i]);

      jsonValues.add(object);

      i++;
    }

    Collections.sort(
        jsonValues,
        new Comparator<JSONObject>() {
          // You can change "Name" with "ID" if you want to sort by ID
          private static final String KEY_NAME = "relevanceFactor";

          public int compare(JSONObject a, JSONObject b) {

            int valA = 0;
            int valB = 0;

            try {
              valA = (Integer) a.get(KEY_NAME);
              valB = (Integer) b.get(KEY_NAME);
            } catch (JSONException e) {
              // do something
            }
            return -Integer.compare(valA, valB);
            // return valA.compareTo(valB);
            // if you want to change the sort order, simply use the following:
            // return -valA.compareTo(valB);
          }
        });

    for (int j = 0; j < finalResult.length(); j++) {
      sortedJsonArray.put(jsonValues.get(j));
    }
    // System.out.println("SORTED:"+sortedJsonArray.toString());
    return sortedJsonArray;
  }
Ejemplo n.º 3
0
  private JSONObject parseParameters(JSONArray data) throws JSONException {
    if (data.length() == 1 && !data.isNull(0)) {
      return (JSONObject) data.get(0);
    } else {
      errorCallback("Invalid arguments specified!");

      throw new IllegalArgumentException("Invalid arguments specified!");
    }
  }
Ejemplo n.º 4
0
  public Patient findRegisterInfo(String patientId) {

    Patient patient = new Patient();

    try {
      String url = propertyUrl + "findRegisterInfo.do";
      HttpPost request = new HttpPost(url);

      List<NameValuePair> params = new ArrayList<NameValuePair>();

      params.add(new BasicNameValuePair("patientId", patientId));

      request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

      HttpResponse response = UserValidationImpl.httpClient.execute(request);
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

        String str = EntityUtils.toString(response.getEntity());

        JSONObject rer = new JSONObject(str);

        JSONObject re = rer.getJSONObject("reObject");

        boolean success = re.getBoolean("success");

        if (!success) {
          return null;
        }

        JSONArray ja = re.getJSONArray("data");

        if (ja == null) {
          return null;
        }
        if (ja.equals(null)) {
          return null;
        }
        if (ja.isNull(0)) {
          return null;
        }

        JSONObject jobj = ja.getJSONObject(0);

        patient.setPatientId(patientId);
        patient.setPatientName(jobj.getString("patientName"));
        patient.setAge(jobj.getString("age"));
        patient.setSex(jobj.getString("sex"));
        patient.setSeatNo("001");
        patient.setDiseaseName(jobj.getString("diseaseName"));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return patient;
  }
Ejemplo n.º 5
0
 @NonNull
 public static C2977a m8930a(@NonNull JSONObject jSONObject) {
   C2977a c2977a = new C2977a();
   try {
     JSONArray jSONArray = jSONObject.getJSONArray("results");
     if (!jSONArray.isNull(0)) {
       c2977a.m8927a(C2978e.m8932b(jSONArray.getJSONObject(0)));
       c2977a.m8928a(C2978e.m8933c(jSONObject));
       C3095y.m9471a("purchaseResults:" + c2977a.toString());
     }
   } catch (Throwable e) {
     C3095y.m9474a("Failed to parse tinder purchase result object", e);
   }
   return c2977a;
 }
Ejemplo n.º 6
0
  /**
   * Executes the request and returns PluginResult.
   *
   * @param action The action to execute.
   * @param args JSONArry of arguments for the plugin.
   * @param callbackId The callback id used when calling back into JavaScript.
   * @return A PluginResult object with a status and message.
   */
  public PluginResult execute(String action, JSONArray args, String callbackId) {
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";

    try {
      if (action.equals("open")) {
        this.openDatabase(args.getString(0), "1", "database", 5000000);
        // this.openDatabase(args.getString(0), args.getString(1),
        //		args.getString(2), args.getLong(3));
      } else if (action.equals("executeSqlBatch")) {
        String[] queries = null;
        String[] queryIDs = null;
        String trans_id = null;
        JSONObject a = null;
        JSONArray jsonArr = null;
        int paramLen = 0;
        JSONArray[] jsonparams = null;

        if (args.isNull(0)) {
          queries = new String[0];
        } else {
          int len = args.length();
          queries = new String[len];
          queryIDs = new String[len];
          jsonparams = new JSONArray[len];

          for (int i = 0; i < len; i++) {
            a = args.getJSONObject(i);
            queries[i] = a.getString("query");
            queryIDs[i] = a.getString("query_id");
            trans_id = a.getString("trans_id");
            jsonArr = a.getJSONArray("params");
            paramLen = jsonArr.length();
            jsonparams[i] = jsonArr;
          }
        }
        if (trans_id != null) this.executeSqlBatch(queries, jsonparams, queryIDs, trans_id);
        else Log.v("error", "null trans_id");
      }
      return new PluginResult(status, result);
    } catch (JSONException e) {
      return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    }
  }
Ejemplo n.º 7
0
  public ArrayList<String> getOtrFingerprints() {
    synchronized (this.keys) {
      final ArrayList<String> fingerprints = new ArrayList<String>();
      try {
        if (this.keys.has("otr_fingerprints")) {
          final JSONArray prints = this.keys.getJSONArray("otr_fingerprints");
          for (int i = 0; i < prints.length(); ++i) {
            final String print = prints.isNull(i) ? null : prints.getString(i);
            if (print != null && !print.isEmpty()) {
              fingerprints.add(prints.getString(i));
            }
          }
        }
      } catch (final JSONException ignored) {

      }
      return fingerprints;
    }
  }
Ejemplo n.º 8
0
 public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
     throws JSONException {
   JSONArray resultValues;
   if (action.equals("init")) {
     this.acquireLock();
   }
   if (action.equals("getScreenWidth")) {
     resultValues = this.getScreenWidth();
   }
   if (action.equals("getScreenHeight")) {
     resultValues = this.getScreenHeight();
   }
   if (action.equals("getScreenDestiny")) {
     resultValues = this.getScreenDestiny();
   }
   if (resultValues.isNull(0)) {
     callbackContext.success();
   } else {
     callbackContext.success(resultValues);
   }
   return true;
 }
Ejemplo n.º 9
0
 /**
  * Parses the given {@link JSONArray} into a {@link ArrayList} of {@link Result}s.
  *
  * @param resList {@link JSONArray} containing the raw result information
  * @return a {@link ArrayList} of {@link Result}s containing the parsed data
  */
 private ArrayList<Result> parseResultList(final JSONArray resList) {
   ArrayList<Result> resultList = new ArrayList<Result>();
   for (int i = 0; i < resList.length(); i++) {
     if (!resList.isNull(i)) {
       try {
         JSONObject obj = resList.getJSONObject(i);
         if (obj.has("url")) {
           Artist artist;
           Album album;
           Track track;
           if (obj.has("artist")) {
             artist = Artist.get(obj.get("artist").toString());
           } else {
             artist = Artist.get("");
           }
           if (obj.has("album")) {
             album = Album.get(obj.get("album").toString(), artist);
           } else {
             album = Album.get("", artist);
           }
           if (obj.has("track")) {
             track = Track.get(obj.get("track").toString(), album, artist);
           } else {
             track = Track.get("", album, artist);
           }
           if (obj.has("albumpos")) {
             track.setAlbumPos(Integer.valueOf(obj.get("albumpos").toString()));
           }
           if (obj.has("discnumber")) {
             track.setAlbumPos(Integer.valueOf(obj.get("discnumber").toString()));
           }
           if (obj.has("year")) {
             String yearString = obj.get("year").toString();
             if (yearString.matches("-?\\d+")) {
               track.setYear(Integer.valueOf(yearString));
             }
           }
           if (obj.has("duration")) {
             track.setDuration(Math.round(Float.valueOf(obj.get("duration").toString()) * 1000));
           }
           artist.addAlbum(album);
           Result result = new Result(obj.get("url").toString(), track);
           if (obj.has("bitrate")) {
             result.setBitrate(Integer.valueOf(obj.get("bitrate").toString()));
           }
           if (obj.has("size")) {
             result.setSize(Integer.valueOf(obj.get("size").toString()));
           }
           if (obj.has("purchaseUrl")) {
             result.setPurchaseUrl(obj.get("purchaseUrl").toString());
           }
           if (obj.has("linkUrl")) {
             result.setLinkUrl(obj.get("linkUrl").toString());
           }
           if (obj.has("score")) {
             result.setTrackScore(Float.valueOf(obj.get("score").toString()));
           }
           result.setResolvedBy(this);
           result.setArtist(artist);
           result.setAlbum(album);
           result.setTrack(track);
           album.addQuery(Query.get(result, false));
           artist.addQuery(Query.get(result, false));
           resultList.add(result);
         }
       } catch (JSONException e) {
         Log.e(TAG, "parseResultList: " + e.getClass() + ": " + e.getLocalizedMessage());
       }
     }
   }
   return resultList;
 }
Ejemplo n.º 10
0
  @Override
  public void run() {
    String after = "";
    int j = 1;
    while (j < n + 1) {
      if (Main.proceed) {
        String afterString = "";
        if (j != 1) {
          afterString = "&after=" + after;
        }
        // can ignore trying to find a "after" value
        try {
          String subfull =
              "http://www.reddit.com/r/"
                  + sub
                  + "/"
                  + s.toString().toLowerCase()
                  + ".json?t="
                  + t.toString().toLowerCase()
                  + "&limit=1"
                  + afterString;
          System.out.println(subfull);
          JSONObject json =
              JSONReader.readJsonFromUrl(
                  "http://www.reddit.com/r/"
                      + sub
                      + "/"
                      + s.toString().toLowerCase()
                      + ".json?t="
                      + t.toString().toLowerCase()
                      + "&limit=1"
                      + afterString);

          JSONObject data = json.getJSONObject("data");

          after = data.getString("after");
          System.out.println(after);
          JSONArray children = data.getJSONArray("children");
          if (!children.isNull(0)) {
            JSONObject value = children.getJSONObject(0).getJSONObject("data");
            // after = (String)
            // children.getJSONObject(0).getString("kind")+"_"+value.getString("id");
            System.out.println(
                "domain: " + value.getString("domain") + " url: " + value.getString("url"));
            if ((value.getString("domain").equals("imgur.com")
                    && !value.getString("url").contains("/a/"))
                || value.getString("url").contains(".jpg")
                || value.getString("url").contains(".jpeg")
                || value.getString("url").contains(".png")) {
              String image = value.getString("url");
              if (value.getString("domain").equals("imgur.com") && !image.contains(".jpg")) {
                if (image.contains(",")) {
                  String[] parts = image.split(",");
                  image = parts[0];
                }
                if (image.contains("/a/")) {
                  image = image + "#0";
                }
                image = image + ".jpg";
              }
              ImageDownloader.getImage(image, folder, j);
              String path = folder + "\\" + j + ".jpg";
              File theDir = new File(folder);
              if (!theDir.exists()) {
                boolean result = theDir.mkdir();
              }
              System.out.println(path);

              SPI.INSTANCE.SystemParametersInfo(
                  new UINT_PTR(SPI.SPI_SETDESKWALLPAPER),
                  new UINT_PTR(0),
                  path,
                  new UINT_PTR(SPI.SPIF_UPDATEINIFILE | SPI.SPIF_SENDWININICHANGE));
              waiting(interval);

            } else {
              System.out.println("Skipping not a jpg");
            }
            if (j == n || after.equals("null")) {
              j = 1;
            } else {
              j++;
            }
          } else {
            j = 1;
          }
          // System.out.println(after);
        } catch (Exception e) {
          e.printStackTrace();
        }

      } else {
        j = n + 1;
      }
    }
  }
Ejemplo n.º 11
0
  /**
   * Uploads the specified file to the server URL provided using an HTTP multipart request.
   *
   * @param source Full path of the file on the file system
   * @param target URL of the server to receive the file
   * @param args JSON Array of args
   * @param callbackContext callback id for optional progress reports
   *     <p>args[2] fileKey Name of file request parameter args[3] fileName File name to be used on
   *     server args[4] mimeType Describes file content type args[5] params key:value pairs of
   *     user-defined parameters
   * @return FileUploadResult containing result of upload request
   */
  private void upload(
      final String source, final String target, JSONArray args, CallbackContext callbackContext)
      throws JSONException {
    Log.d(LOG_TAG, "upload " + source + " to " + target);

    // Setup the options
    final String fileKey = getArgument(args, 2, "file");
    final String fileName = getArgument(args, 3, "image.jpg");
    final String mimeType = getArgument(args, 4, "image/jpeg");
    final JSONObject params =
        args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5);
    final boolean trustEveryone = args.optBoolean(6);
    // Always use chunked mode unless set to false as per API
    final boolean chunkedMode = args.optBoolean(7) || args.isNull(7);
    // Look for headers on the params map for backwards compatibility with older Cordova versions.
    final JSONObject headers =
        args.optJSONObject(8) == null ? params.optJSONObject("headers") : args.optJSONObject(8);
    final String objectId = args.getString(9);
    final String httpMethod = getArgument(args, 10, "POST");

    Log.d(LOG_TAG, "fileKey: " + fileKey);
    Log.d(LOG_TAG, "fileName: " + fileName);
    Log.d(LOG_TAG, "mimeType: " + mimeType);
    Log.d(LOG_TAG, "params: " + params);
    Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
    Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);
    Log.d(LOG_TAG, "headers: " + headers);
    Log.d(LOG_TAG, "objectId: " + objectId);
    Log.d(LOG_TAG, "httpMethod: " + httpMethod);

    final URL url;
    try {
      url = new URL(target);
    } catch (MalformedURLException e) {
      JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0);
      Log.e(LOG_TAG, error.toString(), e);
      callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
      return;
    }
    final boolean useHttps = url.getProtocol().equals("https");

    final RequestContext context = new RequestContext(source, target, callbackContext);
    synchronized (activeRequests) {
      activeRequests.put(objectId, context);
    }

    cordova
        .getThreadPool()
        .execute(
            new Runnable() {
              public void run() {
                if (context.aborted) {
                  return;
                }
                HttpURLConnection conn = null;
                HostnameVerifier oldHostnameVerifier = null;
                SSLSocketFactory oldSocketFactory = null;
                int totalBytes = 0;
                int fixedLength = -1;
                try {
                  // Create return object
                  FileUploadResult result = new FileUploadResult();
                  FileProgressResult progress = new FileProgressResult();

                  // ------------------ CLIENT REQUEST
                  // Open a HTTP connection to the URL based on protocol
                  if (useHttps) {
                    // Using standard HTTPS connection. Will not allow self signed certificate
                    if (!trustEveryone) {
                      conn = (HttpsURLConnection) httpClient.open(url);
                    }
                    // Use our HTTPS connection that blindly trusts everyone.
                    // This should only be used in debug environments
                    else {
                      // Setup the HTTPS connection class to trust everyone
                      HttpsURLConnection https = (HttpsURLConnection) httpClient.open(url);
                      oldSocketFactory = trustAllHosts(https);
                      // Save the current hostnameVerifier
                      oldHostnameVerifier = https.getHostnameVerifier();
                      // Setup the connection not to verify hostnames
                      https.setHostnameVerifier(DO_NOT_VERIFY);
                      conn = https;
                    }
                  }
                  // Return a standard HTTP connection
                  else {
                    conn = httpClient.open(url);
                  }

                  // Allow Inputs
                  conn.setDoInput(true);

                  // Allow Outputs
                  conn.setDoOutput(true);

                  // Don't use a cached copy.
                  conn.setUseCaches(false);

                  // Use a post method.
                  conn.setRequestMethod(httpMethod);
                  conn.setRequestProperty(
                      "Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

                  // Set the cookies on the response
                  String cookie = CookieManager.getInstance().getCookie(target);
                  if (cookie != null) {
                    conn.setRequestProperty("Cookie", cookie);
                  }

                  // Handle the other headers
                  if (headers != null) {
                    addHeadersToRequest(conn, headers);
                  }

                  /*
                   * Store the non-file portions of the multipart data as a string, so that we can add it
                   * to the contentSize, since it is part of the body of the HTTP request.
                   */
                  StringBuilder beforeData = new StringBuilder();
                  try {
                    for (Iterator<?> iter = params.keys(); iter.hasNext(); ) {
                      Object key = iter.next();
                      if (!String.valueOf(key).equals("headers")) {
                        beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
                        beforeData
                            .append("Content-Disposition: form-data; name=\"")
                            .append(key.toString())
                            .append('"');
                        beforeData.append(LINE_END).append(LINE_END);
                        beforeData.append(params.getString(key.toString()));
                        beforeData.append(LINE_END);
                      }
                    }
                  } catch (JSONException e) {
                    Log.e(LOG_TAG, e.getMessage(), e);
                  }

                  beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
                  beforeData
                      .append("Content-Disposition: form-data; name=\"")
                      .append(fileKey)
                      .append("\";");
                  beforeData.append(" filename=\"").append(fileName).append('"').append(LINE_END);
                  beforeData
                      .append("Content-Type: ")
                      .append(mimeType)
                      .append(LINE_END)
                      .append(LINE_END);
                  byte[] beforeDataBytes = beforeData.toString().getBytes("UTF-8");
                  byte[] tailParamsBytes =
                      (LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END).getBytes("UTF-8");

                  // Get a input stream of the file on the phone
                  InputStream sourceInputStream =
                      webView.resolveUri(Uri.parse(source)).getInputStream();

                  int stringLength = beforeDataBytes.length + tailParamsBytes.length;
                  if (sourceInputStream instanceof FileInputStream) {
                    fixedLength =
                        (int) ((FileInputStream) sourceInputStream).getChannel().size()
                            + stringLength;
                    progress.setLengthComputable(true);
                    progress.setTotal(fixedLength);
                  }
                  Log.d(LOG_TAG, "Content Length: " + fixedLength);
                  // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo
                  // devices.
                  // http://code.google.com/p/android/issues/detail?id=3164
                  // It also causes OOM if HTTPS is used, even on newer devices.
                  boolean useChunkedMode =
                      chunkedMode
                          && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps);
                  useChunkedMode = useChunkedMode || (fixedLength == -1);

                  if (useChunkedMode) {
                    conn.setChunkedStreamingMode(MAX_BUFFER_SIZE);
                    // Although setChunkedStreamingMode sets this header, setting it explicitly here
                    // works
                    // around an OutOfMemoryException when using https.
                    conn.setRequestProperty("Transfer-Encoding", "chunked");
                  } else {
                    conn.setFixedLengthStreamingMode(fixedLength);
                  }

                  conn.connect();

                  OutputStream sendStream = null;
                  try {
                    sendStream = conn.getOutputStream();
                    synchronized (context) {
                      if (context.aborted) {
                        return;
                      }
                      context.currentOutputStream = sendStream;
                    }
                    // We don't want to change encoding, we just want this to write for all Unicode.
                    sendStream.write(beforeDataBytes);
                    totalBytes += beforeDataBytes.length;

                    // create a buffer of maximum size
                    int bytesAvailable = sourceInputStream.available();
                    int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
                    byte[] buffer = new byte[bufferSize];

                    // read file and write it into form...
                    int bytesRead = sourceInputStream.read(buffer, 0, bufferSize);

                    long prevBytesRead = 0;
                    while (bytesRead > 0) {
                      result.setBytesSent(totalBytes);
                      sendStream.write(buffer, 0, bytesRead);
                      totalBytes += bytesRead;
                      if (totalBytes > prevBytesRead + 102400) {
                        prevBytesRead = totalBytes;
                        Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes");
                      }
                      bytesAvailable = sourceInputStream.available();
                      bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
                      bytesRead = sourceInputStream.read(buffer, 0, bufferSize);

                      // Send a progress event.
                      progress.setLoaded(totalBytes);
                      PluginResult progressResult =
                          new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
                      progressResult.setKeepCallback(true);
                      context.sendPluginResult(progressResult);
                    }

                    // send multipart form data necessary after file data...
                    sendStream.write(tailParamsBytes);
                    totalBytes += tailParamsBytes.length;
                    sendStream.flush();
                  } finally {
                    safeClose(sourceInputStream);
                    safeClose(sendStream);
                  }
                  context.currentOutputStream = null;
                  Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength);

                  // ------------------ read the SERVER RESPONSE
                  String responseString;
                  int responseCode = conn.getResponseCode();
                  Log.d(LOG_TAG, "response code: " + responseCode);
                  Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields());
                  TrackingInputStream inStream = null;
                  try {
                    inStream = getInputStream(conn);
                    synchronized (context) {
                      if (context.aborted) {
                        return;
                      }
                      context.currentInputStream = inStream;
                    }

                    ByteArrayOutputStream out =
                        new ByteArrayOutputStream(Math.max(1024, conn.getContentLength()));
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                    // write bytes to file
                    while ((bytesRead = inStream.read(buffer)) > 0) {
                      out.write(buffer, 0, bytesRead);
                    }
                    responseString = out.toString("UTF-8");
                  } finally {
                    context.currentInputStream = null;
                    safeClose(inStream);
                  }

                  Log.d(LOG_TAG, "got response from server");
                  Log.d(
                      LOG_TAG, responseString.substring(0, Math.min(256, responseString.length())));

                  // send request and retrieve response
                  result.setResponseCode(responseCode);
                  result.setResponse(responseString);

                  context.sendPluginResult(
                      new PluginResult(PluginResult.Status.OK, result.toJSONObject()));
                } catch (FileNotFoundException e) {
                  JSONObject error =
                      createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
                  Log.e(LOG_TAG, error.toString(), e);
                  context.sendPluginResult(
                      new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
                } catch (IOException e) {
                  JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
                  Log.e(LOG_TAG, error.toString(), e);
                  Log.e(
                      LOG_TAG,
                      "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes.");
                  context.sendPluginResult(
                      new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
                } catch (JSONException e) {
                  Log.e(LOG_TAG, e.getMessage(), e);
                  context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                } catch (Throwable t) {
                  // Shouldn't happen, but will
                  JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
                  Log.e(LOG_TAG, error.toString(), t);
                  context.sendPluginResult(
                      new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
                } finally {
                  synchronized (activeRequests) {
                    activeRequests.remove(objectId);
                  }

                  if (conn != null) {
                    // Revert back to the proper verifier and socket factories
                    // Revert back to the proper verifier and socket factories
                    if (trustEveryone && useHttps) {
                      HttpsURLConnection https = (HttpsURLConnection) conn;
                      https.setHostnameVerifier(oldHostnameVerifier);
                      https.setSSLSocketFactory(oldSocketFactory);
                    }
                  }
                }
              }
            });
  }
Ejemplo n.º 12
0
 public boolean isNull(int index) {
   return baseArgs.isNull(index);
 }
  /**
   * Executes the request and returns PluginResult.
   *
   * @param action The action to execute.
   * @param args JSONArry of arguments for the plugin.
   * @param cbc Callback context from Cordova API
   */
  @Override
  public boolean execute(String action, JSONArray args, CallbackContext cbc) {
    try {
      boolean status = true;

      if (action.equals("open")) {
        JSONObject o = args.getJSONObject(0);
        String dbname = o.getString("name");

        this.openDatabase(dbname, null);
      } else if (action.equals("close")) {
        JSONObject o = args.getJSONObject(0);
        String dbname = o.getString("path");

        this.closeDatabase(dbname);
      } else if (action.equals("delete")) {
        /* Stop & give up if API < 16: */
        if (android.os.Build.VERSION.SDK_INT < 16) return false;

        JSONObject o = args.getJSONObject(0);
        String dbname = o.getString("path");

        status = this.deleteDatabase(dbname);
      } else if (action.equals("executePragmaStatement")) {
        String dbName = args.getString(0);
        String query = args.getString(1);

        JSONArray jparams = (args.length() < 3) ? null : args.getJSONArray(2);

        String[] params = null;

        if (jparams != null) {
          params = new String[jparams.length()];

          for (int j = 0; j < jparams.length(); j++) {
            if (jparams.isNull(j)) params[j] = "";
            else params[j] = jparams.getString(j);
          }
        }

        Cursor myCursor = this.getDatabase(dbName).rawQuery(query, params);

        String result = this.getRowsResultFromQuery(myCursor).getJSONArray("rows").toString();

        this.sendJavascriptCB("window.SQLitePluginCallback.p1('" + id + "', " + result + ");");
      } else if (action.equals("executeSqlBatch")
          || action.equals("executeBatchTransaction")
          || action.equals("backgroundExecuteSqlBatch")) {
        String[] queries = null;
        String[] queryIDs = null;

        JSONArray jsonArr = null;
        int paramLen = 0;
        JSONArray[] jsonparams = null;

        JSONObject allargs = args.getJSONObject(0);
        JSONObject dbargs = allargs.getJSONObject("dbargs");
        String dbName = dbargs.getString("dbname");
        JSONArray txargs = allargs.getJSONArray("executes");

        if (txargs.isNull(0)) {
          queries = new String[0];
        } else {
          int len = txargs.length();
          queries = new String[len];
          queryIDs = new String[len];
          jsonparams = new JSONArray[len];

          for (int i = 0; i < len; i++) {
            JSONObject a = txargs.getJSONObject(i);
            queries[i] = a.getString("sql");
            queryIDs[i] = a.getString("qid");
            jsonArr = a.getJSONArray("params");
            paramLen = jsonArr.length();
            jsonparams[i] = jsonArr;
          }
        }

        boolean ex = action.equals("executeBatchTransaction");

        if (action.equals("backgroundExecuteSqlBatch"))
          this.executeSqlBatchInBackground(dbName, queries, jsonparams, queryIDs, cbc);
        else this.executeSqlBatch(dbName, queries, jsonparams, queryIDs, cbc);
      }

      return status;
    } catch (JSONException e) {
      // TODO: signal JSON problem to JS

      return false;
    }
  }
Ejemplo n.º 14
0
  /**
   * Attempts to upload data with the given information passed in through the QDataSet constructor
   *
   * @return The ID of the data set created on iSENSE, or -1 if the upload failed
   */
  public int upload() {

    int dataSetID = -1;
    if (this.rdyForUpload) {
      //			switch (type) {
      //			case DATA:

      // TODO - check for closed experiment
      //				if (sid == -1) {
      //
      //					if (addr.equals("")) {
      //						sid = UploadQueue.getRapi().createSession(eid, name, desc,
      //								"N/A", "N/A", "United States");
      //					} else {
      //						sid = UploadQueue.getRapi().createSession(eid, name, desc,
      //								addr, city + ", " + state, country);
      //					}
      //
      //					// Failure to create session or not logged in
      //					if (sid == -1) {
      //						success = false;
      //						break;
      //					} else QueueLayout.lastSID = sid;
      //				}
      //
      //				// Experiment Closed Checker
      //				if (sid == -400) {
      //					success = false;
      //					break;
      //				} else {
      JSONArray dataJSON = prepDataForUpload();
      if (!(dataJSON.isNull(0))) {

        //					success = UploadQueue.getRapi().putSessionData(sid, eid,
        //							dataJSON);

        JSONObject jobj = new JSONObject();
        try {
          jobj.put("data", dataJSON);
        } catch (JSONException e) {
          // uh oh
          e.printStackTrace();
        }
        jobj = UploadQueue.getAPI().rowsToCols(jobj);

        System.out.println("JOBJ: " + jobj.toString());

        dataSetID = UploadQueue.getAPI().uploadDataSet(Integer.parseInt(projID), jobj, name);
        System.out.println("Data set ID from Upload is: " + dataSetID);
      }
      //				}
      //				break;
      // TODO - pictures and stuff
      //			case PIC:
      //				if (sid == -1) sid = QueueLayout.lastSID;
      //				if (name.equals("")) {
      //					success = UploadQueue.getRapi().uploadPictureToSession(
      //							picture, eid, sid, "*Session Name Not Provided*",
      //							"N/A");
      //				} else {
      //					success = UploadQueue.getRapi().uploadPictureToSession(
      //							picture, eid, sid, name, "N/A");
      //				}
      //
      //				break;
      //
      //			case BOTH:
      //				if (sid == -1) {
      //
      //					if (addr.equals("")) {
      //						sid = UploadQueue.getRapi().createSession(eid, name, desc,
      //								"N/A", "N/A", "United States");
      //					} else {
      //						sid = UploadQueue.getRapi().createSession(eid, name, desc,
      //								addr, city + ", " + state, country);
      //					}
      //
      //					if (sid == -1) {
      //						success = false;
      //						break;
      //					} else QueueLayout.lastSID = sid;
      //				}
      //
      //				// Experiment Closed Checker
      //				if (sid == -400) {
      //					success = false;
      //					break;
      //				} else {
      //					JSONArray dataJSON = prepDataForUpload();
      //					if (!(dataJSON.isNull(0))) {
      //
      //						success = UploadQueue.getRapi().putSessionData(sid, eid,
      //								dataJSON);
      //						success = UploadQueue.getRapi().uploadPictureToSession(
      //								picture, eid, sid, name, "N/A");
      //
      //					}
      //				}
      //
      //				break;
      //			}
    }

    return dataSetID;
  }
Ejemplo n.º 15
0
    /**
     * Get rows results from query cursor.
     *
     * @param cur Cursor into query results
     * @return results in string form
     */
    private JSONObject executeSqlStatementNDK(
        String query, JSONArray paramsAsJson, CallbackContext cbc) throws Exception {
      JSONObject rowsResult = new JSONObject();

      boolean hasRows = false;

      SQLiteStatement myStatement = mydb.prepareStatement(query);

      try {
        String[] params = null;

        params = new String[paramsAsJson.length()];

        for (int i = 0; i < paramsAsJson.length(); ++i) {
          if (paramsAsJson.isNull(i)) {
            myStatement.bindNull(i + 1);
          } else {
            Object p = paramsAsJson.get(i);
            if (p instanceof Float || p instanceof Double)
              myStatement.bindDouble(i + 1, paramsAsJson.getDouble(i));
            else if (p instanceof Number) myStatement.bindLong(i + 1, paramsAsJson.getLong(i));
            else myStatement.bindTextNativeString(i + 1, paramsAsJson.getString(i));
          }
        }

        hasRows = myStatement.step();
      } catch (Exception ex) {
        ex.printStackTrace();
        String errorMessage = ex.getMessage();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql[Batch](): Error=" + errorMessage);

        // cleanup statement and throw the exception:
        myStatement.dispose();
        throw ex;
      }

      // If query result has rows
      if (hasRows) {
        JSONArray rowsArrayResult = new JSONArray();
        String key = "";
        int colCount = myStatement.getColumnCount();

        // Build up JSON result object for each row
        do {
          JSONObject row = new JSONObject();
          try {
            for (int i = 0; i < colCount; ++i) {
              key = myStatement.getColumnName(i);

              switch (myStatement.getColumnType(i)) {
                case SQLColumnType.NULL:
                  row.put(key, JSONObject.NULL);
                  break;

                case SQLColumnType.REAL:
                  row.put(key, myStatement.getColumnDouble(i));
                  break;

                case SQLColumnType.INTEGER:
                  row.put(key, myStatement.getColumnLong(i));
                  break;

                case SQLColumnType.BLOB:
                case SQLColumnType.TEXT:
                default: // (just in case)
                  row.put(key, myStatement.getColumnTextNativeString(i));
              }
            }

            rowsArrayResult.put(row);

          } catch (JSONException e) {
            e.printStackTrace();
          }
        } while (myStatement.step());

        try {
          rowsResult.put("rows", rowsArrayResult);
        } catch (JSONException e) {
          e.printStackTrace();
        }
      }

      myStatement.dispose();

      return rowsResult;
    }
Ejemplo n.º 16
0
  private boolean executeAndPossiblyThrow(Action action, JSONArray args, CallbackContext cbc)
      throws JSONException {

    boolean status = true;
    JSONObject o;
    String dbname;

    switch (action) {
      case open:
        o = args.getJSONObject(0);
        dbname = o.getString("name");
        // open database and start reading its queue
        this.startDatabase(dbname, o, cbc);
        break;

      case close:
        o = args.getJSONObject(0);
        dbname = o.getString("path");
        // put request in the q to close the db
        this.closeDatabase(dbname, cbc);
        break;

      case delete:
        o = args.getJSONObject(0);
        dbname = o.getString("path");

        deleteDatabase(dbname, cbc);

        break;

      case executeSqlBatch:
      case backgroundExecuteSqlBatch:
        String[] queries = null;
        String[] queryIDs = null;

        JSONArray jsonArr = null;
        int paramLen = 0;
        JSONArray[] jsonparams = null;

        JSONObject allargs = args.getJSONObject(0);
        JSONObject dbargs = allargs.getJSONObject("dbargs");
        dbname = dbargs.getString("dbname");
        JSONArray txargs = allargs.getJSONArray("executes");

        if (txargs.isNull(0)) {
          queries = new String[0];
        } else {
          int len = txargs.length();
          queries = new String[len];
          queryIDs = new String[len];
          jsonparams = new JSONArray[len];

          for (int i = 0; i < len; i++) {
            JSONObject a = txargs.getJSONObject(i);
            queries[i] = a.getString("sql");
            queryIDs[i] = a.getString("qid");
            jsonArr = a.getJSONArray("params");
            paramLen = jsonArr.length();
            jsonparams[i] = jsonArr;
          }
        }

        // put db query in the queue to be executed in the db thread:
        DBQuery q = new DBQuery(queries, queryIDs, jsonparams, cbc);
        DBRunner r = dbrmap.get(dbname);
        if (r != null) {
          try {
            r.q.put(q);
          } catch (Exception e) {
            Log.e(SQLitePlugin.class.getSimpleName(), "couldn't add to queue", e);
            cbc.error("couldn't add to queue");
          }
        } else {
          cbc.error("database not open");
        }
        break;
    }

    return status;
  }
Ejemplo n.º 17
0
  /**
   * Convert a JSONObject containing a bibJSON entry to a BibEntry
   *
   * @param bibJsonEntry The JSONObject to convert
   * @return the converted BibEntry
   */
  public BibEntry parseBibJSONtoBibtex(JSONObject bibJsonEntry, String keywordSeparator) {
    // Fields that are directly accessible at the top level BibJson object
    String[] singleFieldStrings = {
      FieldName.YEAR, FieldName.TITLE, FieldName.ABSTRACT, FieldName.MONTH
    };

    // Fields that are accessible in the journal part of the BibJson object
    String[] journalSingleFieldStrings = {FieldName.PUBLISHER, FieldName.NUMBER, FieldName.VOLUME};

    BibEntry entry = new BibEntry();
    entry.setType("article");

    // Authors
    if (bibJsonEntry.has("author")) {
      JSONArray authors = bibJsonEntry.getJSONArray("author");
      List<String> authorList = new ArrayList<>();
      for (int i = 0; i < authors.length(); i++) {
        if (authors.getJSONObject(i).has("name")) {
          authorList.add(authors.getJSONObject(i).getString("name"));
        } else {
          LOGGER.info("Empty author name.");
        }
      }
      entry.setField(FieldName.AUTHOR, String.join(" and ", authorList));
    } else {
      LOGGER.info("No author found.");
    }

    // Direct accessible fields
    for (String field : singleFieldStrings) {
      if (bibJsonEntry.has(field)) {
        entry.setField(field, bibJsonEntry.getString(field));
      }
    }

    // Page numbers
    if (bibJsonEntry.has("start_page")) {
      if (bibJsonEntry.has("end_page")) {
        entry.setField(
            FieldName.PAGES,
            bibJsonEntry.getString("start_page") + "--" + bibJsonEntry.getString("end_page"));
      } else {
        entry.setField(FieldName.PAGES, bibJsonEntry.getString("start_page"));
      }
    }

    // Journal
    if (bibJsonEntry.has("journal")) {
      JSONObject journal = bibJsonEntry.getJSONObject("journal");
      // Journal title
      if (journal.has("title")) {
        entry.setField(FieldName.JOURNAL, journal.getString("title"));
      } else {
        LOGGER.info("No journal title found.");
      }
      // Other journal related fields
      for (String field : journalSingleFieldStrings) {
        if (journal.has(field)) {
          entry.setField(field, journal.getString(field));
        }
      }
    } else {
      LOGGER.info("No journal information found.");
    }

    // Keywords
    if (bibJsonEntry.has("keywords")) {
      JSONArray keywords = bibJsonEntry.getJSONArray("keywords");
      LinkedHashSet<String> keywordList = new LinkedHashSet<>();
      for (int i = 0; i < keywords.length(); i++) {
        if (!keywords.isNull(i)) {
          keywordList.add(keywords.getString(i));
        }
      }
      entry.putKeywords(keywordList, keywordSeparator);
    }

    // Identifiers
    if (bibJsonEntry.has("identifier")) {
      JSONArray identifiers = bibJsonEntry.getJSONArray("identifier");
      for (int i = 0; i < identifiers.length(); i++) {
        String type = identifiers.getJSONObject(i).getString("type");
        if ("doi".equals(type)) {
          entry.setField(FieldName.DOI, identifiers.getJSONObject(i).getString("id"));
        } else if ("pissn".equals(type)) {
          entry.setField(FieldName.ISSN, identifiers.getJSONObject(i).getString("id"));
        } else if ("eissn".equals(type)) {
          entry.setField(FieldName.ISSN, identifiers.getJSONObject(i).getString("id"));
        }
      }
    }

    // Links
    if (bibJsonEntry.has("link")) {
      JSONArray links = bibJsonEntry.getJSONArray("link");
      for (int i = 0; i < links.length(); i++) {
        if (links.getJSONObject(i).has("type")) {
          String type = links.getJSONObject(i).getString("type");
          if ("fulltext".equals(type) && links.getJSONObject(i).has("url")) {
            entry.setField(FieldName.URL, links.getJSONObject(i).getString("url"));
          }
        }
      }
    }

    return entry;
  }
Ejemplo n.º 18
0
  @Override
  public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
      throws JSONException {
    mFolderName = args.isNull(10) ? mFolderName : args.getString(10);
    mGalleryFolder = createFolders();

    if (action.equals("show")) {
      try {
        Log.i(LOG_TAG, action);
        this.callbackContext = callbackContext;

        // make sure an image URI has been provided
        if (args.isNull(0)) {
          callbackContext.error("Cannot start aviary, an image URI is required.");
          return true;
        }

        // parameters
        String source = args.getString(0); // 0 - image URI
        String outputFormat =
            args.isNull(1)
                ? Bitmap.CompressFormat.JPEG.name()
                : args.getString(1); // 1 - EXTRA_OUTPUT_FORMAT
        int quality = args.isNull(2) ? 95 : args.getInt(2); // 2 - EXTRA_OUTPUT_QUALITY

        String[] toolList = new String[] {}; // 3 - EXTRA_TOOLS_LIST
        if (!args.isNull(3)) {
          JSONArray toolArray = args.getJSONArray(3);
          toolList = new String[toolArray.length()];
          for (int i = 0; i < toolArray.length(); i++) {
            toolList[i] = toolArray.getString(i);
          }
        }

        Boolean hideExitUnsaveConfirmation =
            args.isNull(4) ? false : args.getBoolean(4); // 4 - EXTRA_HIDE_EXIT_UNSAVE_CONFIRMATION
        Boolean enableEffectsPacks =
            args.isNull(5) ? false : args.getBoolean(5); // 5 - EXTRA_EFFECTS_ENABLE_EXTERNAL_PACKS
        Boolean enableFramesPacks =
            args.isNull(6) ? false : args.getBoolean(6); // 6 - EXTRA_FRAMES_ENABLE_EXTERNAL_PACKS
        Boolean enableStickersPacks =
            args.isNull(7) ? false : args.getBoolean(7); // 7 - EXTRA_STICKERS_ENABLE_EXTERNAL_PACKS
        Boolean disableVibration =
            args.isNull(8) ? false : args.getBoolean(8); // 8 - EXTRA_TOOLS_DISABLE_VIBRATION
        Boolean inSaveOnNoChanges =
            args.isNull(9) ? true : args.getBoolean(9); // 9 - EXTRA_IN_SAVE_ON_NO_CHANGES

        // get URI
        Uri uri = Uri.parse(source);

        // first check the external storage availability
        if (!isExternalStorageAvilable()) {
          callbackContext.error("Cannot start aviary, external storage unavailable.");
          return true;
        }
        String mOutputFilePath;

        // create a temporary file where to store the resulting image
        File file = getNextFileName();
        if (null != file) {
          mOutputFilePath = file.getAbsolutePath();
        } else {
          callbackContext.error("Cannot start aviary, failed to create a temp file.");
          return true;
        }

        // Create the intent needed to start feather
        Class<FeatherActivity> clsAviary = FeatherActivity.class;
        Intent newIntent = new Intent(this.cordova.getActivity(), clsAviary);

        // set the parameters
        newIntent.setData(uri);
        newIntent.putExtra(Constants.EXTRA_OUTPUT, Uri.parse("file://" + mOutputFilePath));
        newIntent.putExtra(Constants.EXTRA_OUTPUT_FORMAT, outputFormat);
        newIntent.putExtra(Constants.EXTRA_OUTPUT_QUALITY, quality);

        if (toolList.length > 0) {
          newIntent.putExtra(Constants.EXTRA_TOOLS_LIST, toolList);
        }

        newIntent.putExtra(
            Constants.EXTRA_HIDE_EXIT_UNSAVE_CONFIRMATION, hideExitUnsaveConfirmation);

        newIntent.putExtra(Constants.EXTRA_EFFECTS_ENABLE_EXTERNAL_PACKS, enableEffectsPacks);
        newIntent.putExtra(Constants.EXTRA_FRAMES_ENABLE_EXTERNAL_PACKS, enableFramesPacks);
        newIntent.putExtra(Constants.EXTRA_STICKERS_ENABLE_EXTERNAL_PACKS, enableStickersPacks);

        // http://developers.aviary.com/docs/android/intent-parameters#EXTRA_MAX_IMAGE_SIZE
        // newIntent.putExtra(Constants.EXTRA_MAX_IMAGE_SIZE, 1000);

        // since a minor bug exists that when explicitly setting this to false disables vibration so
        // only set if true
        if (disableVibration) {
          newIntent.putExtra(Constants.EXTRA_TOOLS_DISABLE_VIBRATION, disableVibration);
        }

        newIntent.putExtra(Constants.EXTRA_IN_SAVE_ON_NO_CHANGES, inSaveOnNoChanges);

        cordova.getActivity().startActivityForResult(newIntent, ACTION_REQUEST_FEATHER);
        cordova.setActivityResultCallback(this);
        return true;
      } catch (Exception ex) {
        Log.e(LOG_TAG, ex.toString());
        callbackContext.error("Unknown error occured showing aviary.");
      }
    } else if (action.equals("prepareForShow")) {
      // nothing to do on Android
      callbackContext.success();
    }

    return false;
  }
Ejemplo n.º 19
0
  /** Parses a url pointing to a Google JSON object to a Route object. */
  public static Route parse(String feedUrl) throws IOException, JSONException {
    // Turn the stream into a string
    String result = convertStreamToString(getInputStream(feedUrl));
    if (result == null) {
      return null;
    }
    Log.d("GoogleParser", result);

    Route route = new Route();
    // Transform the string into a JSON object
    JSONObject json = new JSONObject(result);
    JSONObject jsonRoute = json.getJSONArray("routes").getJSONObject(0);

    // Get the bounds - northeast and southwest
    JSONObject jsonBounds = jsonRoute.getJSONObject("bounds");
    JSONObject jsonNortheast = jsonBounds.getJSONObject("northeast");
    LatLng northEast = new LatLng(jsonNortheast.getDouble("lat"), jsonNortheast.getDouble("lng"));
    JSONObject jsonSouthwest = jsonBounds.getJSONObject("southwest");
    LatLng southWest = new LatLng(jsonSouthwest.getDouble("lat"), jsonSouthwest.getDouble("lng"));
    route.setLatLgnBounds(northEast, southWest);

    // Get the order of the waypoints
    JSONArray jsonWaypointOrder = jsonRoute.getJSONArray("waypoint_order");
    int numberOfWaypoints = jsonWaypointOrder.length();
    int[] waypointOrder = new int[numberOfWaypoints];
    for (int i = 0; i < numberOfWaypoints; i++) {
      waypointOrder[i] = jsonWaypointOrder.getInt(i);
    }
    route.setWaypointOrder(waypointOrder);

    // Retrieve and decode the polyline
    route.addPoints(
        decodePolyLine(jsonRoute.getJSONObject("overview_polyline").getString("points")));

    // Get copyright notice (Google terms of service requirement)
    route.setCopyright(jsonRoute.getString("copyrights"));

    // Get any warnings provided (Google terms of service requirement)
    JSONArray warnings = jsonRoute.getJSONArray("warnings");
    if (!warnings.isNull(0)) {
      route.setWarning(warnings.getString(0));
    }

    // Loop through the legs for this route
    JSONArray legs = jsonRoute.getJSONArray("legs");
    for (int legIndex = 0; legIndex < legs.length(); legIndex++) {
      Leg leg = new Leg();
      JSONObject jsonLeg = legs.getJSONObject(legIndex);

      // Get distance and time estimation
      leg.setDurationText(jsonLeg.getJSONObject("duration").getString("text"));
      leg.setDurationValue(Double.parseDouble(leg.getDurationText().split(" ")[0]));
      leg.setDistanceText(jsonLeg.getJSONObject("distance").getString("text"));
      leg.setDistanceValue(Double.parseDouble(leg.getDistanceText().split(" ")[0]));

      // Get the start and end locations and addresses
      leg.setStartAddress(jsonLeg.getString("start_address"));
      leg.setEndAddress(jsonLeg.getString("end_address"));
      JSONObject startOfLeg = jsonLeg.getJSONObject("start_location");
      leg.setStartLocation(new LatLng(startOfLeg.getDouble("lat"), startOfLeg.getDouble("lng")));
      JSONObject endOfLeg = jsonLeg.getJSONObject("end_location");
      leg.setEndLocation(new LatLng(endOfLeg.getDouble("lat"), endOfLeg.getDouble("lng")));

      // Loop through the steps for this leg
      JSONArray steps = jsonLeg.getJSONArray("steps");
      for (int stepIndex = 0; stepIndex < steps.length(); stepIndex++) {
        Step step = new Step();
        JSONObject jsonStep = steps.getJSONObject(stepIndex);

        // Get the start and end location for this step
        JSONObject start = jsonStep.getJSONObject("start_location");
        step.setStart(new LatLng(start.getDouble("lat"), start.getDouble("lng")));
        JSONObject end = jsonStep.getJSONObject("end_location");
        step.setEnd(new LatLng(end.getDouble("lat"), end.getDouble("lng")));

        // Strip html from Google directions and set as turn instruction
        step.setInstruction(jsonStep.getString("html_instructions").replaceAll("<(.*?)*>", ""));

        leg.addStep(step);
      }

      route.addLeg(leg);
    }

    return route;
  }