public static ArrayList<Deal> getDeals(
      String url, final RequestQueue requestQueue, int startPage, int endPage) {
    RequestFuture<String> requestFuture = RequestFuture.newFuture();
    ArrayList<Deal> deals = new ArrayList<>((endPage - startPage) * 10);

    String pageParam = null;
    for (int i = startPage; i < endPage; i++) {
      String xml = null;
      pageParam = String.format(L.PAGE_PARAM, i);

      StringRequest stringRequest =
          new StringRequest(Request.Method.GET, url + pageParam, requestFuture, requestFuture);

      try {
        requestQueue.add(stringRequest);
        xml = requestFuture.get(30000, TimeUnit.MILLISECONDS);
        HttpsURLConnection connection = getFeed(url + pageParam);
        try {

          deals.addAll(DomXmlMapper.xmlToDeal(connection.getInputStream()));
        } catch (Exception e) {

        } finally {
          connection.disconnect();
          Thread.sleep(100);
        }
        //                deals.addAll(DomXmlMapper.xmlToDeal(xml));

      } catch (Exception e) {
        L.d(TAG, "Error while retreiving feed", e);
      }
    }
    return deals;
  }
 @Override
 protected void onHandleIntent(Intent intent) {
   String url = null;
   String userName = intent.getStringExtra(PROVIDED_USER_NAME);
   String instrumentName = intent.getStringExtra(PROVIDED_INSTRUMENT);
   try {
     url = URLDecoder.decode(getString(R.string.poll_post_url, instrumentName, userName), "UTF-8");
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
   if (url == null) return;
   RequestFuture<String> future = RequestFuture.newFuture();
   StringRequest request = new StringRequest(Request.Method.POST, url, future, future);
   Volley.newRequestQueue(getApplicationContext()).add(request);
   try {
     String response = future.get(30, TimeUnit.SECONDS);
     PostPollDto dto = new Gson().fromJson(response, PostPollDto.class);
     if (dto.getStatus().toLowerCase().equalsIgnoreCase("ok")) {
       PreferencesUtil.savePollInstrument(getApplicationContext(), instrumentName);
       PreferencesUtil.saveUserName(getApplicationContext(), userName);
       EventBus.getDefault().post(new PollPostEvent());
     } else {
       EventBus.getDefault().post(new PollPostEvent(dto.getMsg()));
     }
   } catch (InterruptedException | ExecutionException | TimeoutException e) {
     EventBus.getDefault().post(new PollPostEvent(e.getLocalizedMessage()));
   }
 }
Example #3
0
  @Override
  public ArrayList<String> autocomplete(String input) {
    ArrayList<String> resultList = null;

    String url = Urls.getAutocompleteUrl(input);
    RequestFuture<JSONObject> future = RequestFuture.newFuture();
    JsonObjectRequest request = new JsonObjectRequest(url, null, future, future);
    requestQueue.add(request);

    try {
      JSONObject response = future.get(10, TimeUnit.SECONDS);
      JSONArray predictions = response.getJSONArray("predictions");

      // Extract the Place descriptions from the results
      resultList = new ArrayList<String>(predictions.length());
      for (int i = 0; i < predictions.length(); i++) {
        JSONArray terms = predictions.getJSONObject(i).getJSONArray("terms");
        resultList.add(terms.getJSONObject(0).getString("value"));
      }

    } catch (InterruptedException | ExecutionException | TimeoutException | JSONException e) {
      e.printStackTrace();
    }
    return resultList;
  }
Example #4
0
  private String doRequest(int method, String relativeUrl, final Map<String, String> params) {
    final String url = baseUrl + relativeUrl;
    StringRequest sr;
    String response;

    RequestFuture<String> future = RequestFuture.newFuture();
    if (params != null) {
      sr =
          new StringRequest(method, url, future, future) {
            @Override
            protected Map<String, String> getParams() {
              return params;
            }
          };
    } else {
      sr = new StringRequest(method, url, future, future);
    }

    Log.v(DEBUG_TAG, "StringRequest " + sr.getUrl());
    queue.add(sr);

    try {
      response = future.get(30, TimeUnit.SECONDS);
    } catch (InterruptedException | TimeoutException | ExecutionException e) {
      e.printStackTrace();
      return null;
    }

    return response;
  }
  @Override
  protected EncounterAddFailedEvent doInBackground(Void... params) {
    RequestFuture<Encounter> encounterFuture = RequestFuture.newFuture();

    mServer.addEncounter(mPatient, mEncounter, encounterFuture, encounterFuture);
    Encounter encounter;
    try {
      encounter = encounterFuture.get();
    } catch (InterruptedException e) {
      return new EncounterAddFailedEvent(EncounterAddFailedEvent.Reason.INTERRUPTED, e);
    } catch (ExecutionException e) {
      LOG.e(e, "Server error while adding encounter");

      EncounterAddFailedEvent.Reason reason = EncounterAddFailedEvent.Reason.UNKNOWN_SERVER_ERROR;
      if (e.getCause() != null) {
        String errorMessage = e.getCause().getMessage();
        if (errorMessage.contains("failed to validate")) {
          reason = EncounterAddFailedEvent.Reason.FAILED_TO_VALIDATE;
        } else if (errorMessage.contains("Privileges required")) {
          reason = EncounterAddFailedEvent.Reason.FAILED_TO_AUTHENTICATE;
        }
      }
      LOG.e("Error response: %s", ((VolleyError) e.getCause()).networkResponse);

      return new EncounterAddFailedEvent(reason, (VolleyError) e.getCause());
    }

    if (encounter.uuid == null) {
      LOG.e(
          "Although the server reported an encounter successfully added, it did not "
              + "return a UUID for that encounter. This indicates a server error.");

      return new EncounterAddFailedEvent(
          EncounterAddFailedEvent.Reason.FAILED_TO_SAVE_ON_SERVER, null /*exception*/);
    }

    AppEncounter appEncounter = AppEncounter.fromNet(mPatient.uuid, encounter);

    if (appEncounter.observations.length > 0) {
      int inserted =
          mContentResolver.bulkInsert(
              Contracts.Observations.CONTENT_URI, appEncounter.toContentValuesArray());

      if (inserted != appEncounter.observations.length) {
        LOG.w(
            "Inserted %d observations for encounter. Expected: %d",
            inserted, appEncounter.observations.length);
        return new EncounterAddFailedEvent(
            EncounterAddFailedEvent.Reason.INVALID_NUMBER_OF_OBSERVATIONS_SAVED,
            null /*exception*/);
      }
    } else {
      LOG.w("Encounter was sent to the server but contained no observations.");
    }

    mUuid = encounter.uuid;

    return null;
  }
Example #6
0
 /**
  * 发起一个同步HTTP请求
  *
  * @param method
  * @param url
  * @param name
  * @param file
  * @param clazz
  * @return
  * @throws java.util.concurrent.ExecutionException
  * @throws InterruptedException
  */
 public static <T> T requestSync(
     int method, String url, String refer, String name, File file, Class<T> clazz)
     throws ExecutionException, InterruptedException {
   Request<T> request;
   RequestFuture<T> future = RequestFuture.newFuture();
   if (null == file) {
     request = new GsonRequest<T>(method, url, refer, clazz, null, null, future, future);
     request.setRetryPolicy(
         RetryPolicyFactory.getRetryPolicy(RetryPolicyFactory.RETRY_POLICY.NORMAL));
   } else {
     request = new GsonRequest<T>(method, url, refer, clazz, name, file, future, future);
     request.setRetryPolicy(
         RetryPolicyFactory.getRetryPolicy(RetryPolicyFactory.RETRY_POLICY.MULTIPART));
   }
   requestQueue.add(request);
   T t = future.get();
   return t;
 }
  public static boolean likeMemoryOnServer(Context context, Like like) {
    String url =
        Constants.URL_MEMORY_UPDATE
            + like.getJourneyId()
            + "/memories/"
            + like.getMemoryLocalId()
            + "/like";

    Map<String, String> params = new HashMap<>();
    params.put("api_key", TJPreferences.getApiKey(context));

    Log.d(TAG, "uploading like with parameters " + params);
    Log.d(TAG, "uploading like with url " + url);

    final RequestFuture<JSONObject> futureRequest = RequestFuture.newFuture();
    CustomJsonRequest jsonRequest =
        new CustomJsonRequest(
            com.android.volley.Request.Method.POST, url, params, futureRequest, futureRequest);

    AppController.getInstance().getRequestQueue().add(jsonRequest);
    try {
      JSONObject response = futureRequest.get(30, TimeUnit.SECONDS);
      Log.d(TAG, "memory liked successfully on server with response " + response);
      like.setIdOnServer(response.getJSONArray("likes").getJSONObject(0).getString("id"));
      /*LikeDataSource.updateLike(like, context);*/
      return true;
    } catch (InterruptedException e) {
      Log.d(TAG, "like couldnot be uploaded InterruptedException");
      e.printStackTrace();
    } catch (ExecutionException e) {
      Log.d(TAG, "like couldnot be uploaded ExecutionException");
      e.printStackTrace();
    } catch (TimeoutException e) {
      Log.d(TAG, "like couldnot be uploaded TimeoutException");
      e.printStackTrace();
    } catch (JSONException e) {
      Log.d(TAG, "like couldnot be parsed although uploaded successfully");
      e.printStackTrace();
    }
    return false;
  }
  public static boolean unlikeMemoryOnServer(Context context, Like like) {
    String url =
        Constants.URL_MEMORY_UPDATE
            + like.getJourneyId()
            + "/memories/"
            + like.getMemoryLocalId()
            + "/unlike";

    Map<String, String> params = new HashMap<>();
    params.put("api_key", TJPreferences.getApiKey(context));

    Log.d(TAG, "unliking memory with parameters " + params);
    Log.d(TAG, "unliking memory with url " + url);

    final RequestFuture<JSONObject> futureRequest = RequestFuture.newFuture();
    CustomJsonRequest jsonRequest =
        new CustomJsonRequest(
            com.android.volley.Request.Method.PUT, url, params, futureRequest, futureRequest);

    AppController.getInstance().getRequestQueue().add(jsonRequest);
    try {
      JSONObject response = futureRequest.get(30, TimeUnit.SECONDS);
      LikeDataSource.deleteLike(context, like.getId());
      Log.d(TAG, "memory unliked successfully on server with response " + response);
      return true;
    } catch (InterruptedException e) {
      Log.d(TAG, "couldnot unlike InterruptedException");
      e.printStackTrace();
    } catch (ExecutionException e) {
      Log.d(TAG, "couldnot unlike ExecutionException");
      e.printStackTrace();
    } catch (TimeoutException e) {
      Log.d(TAG, "couldnot unlike TimeoutException");
      e.printStackTrace();
    }
    return false;
  }