@Test
  public void testCacheEntryNull() throws VolleyError {
    when(cache.get(anyString())).thenReturn(null);

    dispatcher.processRequest(request);
    verify(mockNetwork).performRequest(request);
  }
  // Lyrics response in this method can be handled in a better way.If the response was jsonarray or
  // jsonobject,
  // it can be parsed quickly.
  private void getLyricDetails() {
    // We first check for cached request
    Cache cache = MusicSearchController.getInstance().getRequestQueue().getCache();
    Entry entry = cache.get(lyricsURL);

    if (entry != null) {
      // fetch the data from cache
      try {
        String data = new String(entry.data, "UTF-8");
        // Display the first 500 characters of the response string.
        lyricsDetail.setText("Response is: " + data);
        // hideProgressDialog();
        setProgressBarIndeterminateVisibility(false);
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }

    } else {

      // making fresh volley request and getting json
      // Request a string response from the provided URL.
      StringRequest stringRequest =
          new StringRequest(
              Request.Method.GET,
              lyricsURL,
              new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                  // Display the first 500 characters of the response
                  // string.
                  Log.d(TAG, response);
                  lyricsDetail.setText("Response is: " + response);
                }
              },
              new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                  lyricsDetail.setText("Could not get lyrics details");
                }
              });

      // Adding request to volley request queue
      MusicSearchController.getInstance().addToRequestQueue(stringRequest);
    }
  }
Beispiel #3
0
  public void getData() {
    Cache cache = AppController.getInstance().getRequestQueue().getCache();
    Cache.Entry entry = cache.get(URL_FEED);
    if (entry != null) {
      // fetch the data from cache
      try {
        String data = new String(entry.data, "UTF-8");
        try {
          parseJsonFeed(new JSONObject(data));
        } catch (JSONException e) {
          e.printStackTrace();
        }
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }

    } else {
      // making fresh volley request and getting json
      JsonObjectRequest jsonReq =
          new JsonObjectRequest(
              Request.Method.GET,
              URL_FEED,
              "",
              new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                  VolleyLog.d(TAG, "Response: " + response.toString());
                  if (response != null) {
                    parseJsonFeed(response);
                  }
                }
              },
              new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                  VolleyLog.d(TAG, "Error: " + error.getMessage());
                }
              });

      // Adding request to volley request queue
      AppController.getInstance().addToRequestQueue(jsonReq);
    }
  }
  private void handleResult(User user) {
    if (mListener != null) {

      if (error != null) {
        mListener.onError(error.getMessage());
        return;
      }

      // Check if user image bitmap in cache
      Cache cache = AppController.getInstance().getRequestQueue().getCache();
      Cache.Entry entry = cache.get(user.getPhoto());
      if (entry != null) {
        // Decode byte array (entry.data) to bitmap
        user.setBitmapPhoto(LocationAppUtils.decodeByteToBitmap(entry.data));
      }

      mListener.onUserInfoFetched(user);
    }
  }
  @Before
  public void setUp() throws Exception {
    initMocks(this);
    dispatcher = new SyncDispatcher(cache, mockNetwork);
    Response response = Response.success(null, cacheEntry);

    when(cache.get(anyString())).thenReturn(cacheEntry);
    when(request.parseNetworkResponse(any(NetworkResponse.class))).thenReturn(response);
    when(request.getCacheKey()).thenReturn("test-cache-key");
  }
Beispiel #6
0
 public static <T> T getCacheFile(InputBase input, Class<T> clazz) {
   Cache cache = requestQueue.getCache();
   Request<T> request =
       new GsonRequest<T>(input.method(), input.toString(), "", clazz, null, null, null, null);
   Cache.Entry entry = cache.get(request.getCacheKey());
   if (entry != null) {
     try {
       String json = new String(entry.data, "UTF-8");
       if (clazz == String.class) {
         return (T) json;
       }
       // File类型写文件后返回file对象
       else if (clazz == File.class) {
         String fileName = TextUtil.md5(input.toString());
         File outFile =
             new File(DirectoryManager.getDirectory(DirectoryManager.DIR.DATA), fileName);
         FileUtils.writeFile(outFile.getAbsolutePath(), entry.data);
         return (T) outFile;
       }
       // 替换服务端可能返回的错误的data格式
       json = json.replace("\"data\":[]", "\"data\":{}");
       // 服务器返回errNo=0
       if (json.matches(ERROR_NO_0_EXPRESSION)) {
         T data;
         JSONObject jsonObject = new JSONObject(json);
         json = jsonObject.getString("data");
         // 其他属于Gson请求,解析对象返回
         Gson gson = GsonUtil.createBuilder();
         data = (T) gson.fromJson(json, clazz);
         return data;
       }
       // 服务器返回errNo != 0
       else {
         return null;
       }
     } catch (Exception e) {
       return null;
     }
   }
   return null;
 }
  @Override
  public void run() {
    if (DEBUG) {
      VolleyLog.v("start new dispatcher");
    }
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    // Make a blocking call to initialize the cache.
    mCache.initialize();
    while (true) {
      try {
        // Get a request from the cache triage queue, blocking until at least one is available.
        final Request<?> request = mCacheQueue.take();
        request.addMarker("cache-queue-take");
        // If the request has been canceled, don't bother dispatching it.
        if (request.isCanceled()) {
          request.finish("cache-discard-canceled");
          continue;
        }

        // Attempt to retrieve this item from cache.
        Cache.Entry entry = mCache.get(request.getCacheKey());
        if (entry == null) {
          request.addMarker("cache-miss");
          // Cache miss; send off to the network dispatcher.
          mNetworkQueue.put(request);
          continue;
        }

        // If it is completely expired, just send it to the network.
        if (entry.isExpired()) {
          request.addMarker("cache-hit-expired");
          request.setCacheEntry(entry);
          mNetworkQueue.put(request);
          continue;
        }

        // We have a cache hit; parse its data for delivery back to the request.
        request.addMarker("cache-hit");
        Response<?> response =
            request.parseNetworkResponse(
                new NetworkResponse(entry.data, entry.responseHeaders)); // TODO
        request.addMarker("cache-hit-parsed");

        if (!entry.refreshNeeded()) {
          // Completely unexpired cache hit. Just deliver the response.
          mDelivery.postResponse(request, response);
        } else {
          // Soft-expired cache hit. We can deliver the cached response,
          // but we need to also send the request to the network for
          // refreshing.
          request.addMarker("cache-hit-refresh-needed");
          request.setCacheEntry(entry);

          // Mark the response as intermediate.
          response.intermediate = true;

          // Post the intermediate response back to the user and have
          // the delivery then forward the request along to the network.
          mDelivery.postResponse(
              request,
              response,
              new Runnable() {
                @Override
                public void run() {
                  try {
                    mNetworkQueue.put(request);
                  } catch (InterruptedException e) {
                    // Not much we can do about this.
                  }
                }
              });
        }

      } catch (InterruptedException e) {
        // We may have been interrupted because it was time to quit.
        if (mQuit) {
          return;
        }
        continue;
      }
    }
  }
  @SuppressLint("NewApi")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    listView = (ListView) findViewById(R.id.propertyListView);

    paButton = (Button) findViewById(R.id.paButton);
    pdButton = (Button) findViewById(R.id.pdButton);
    baButton = (Button) findViewById(R.id.baButton);
    bdButton = (Button) findViewById(R.id.bdButton);

    feedItems = new ArrayList<Property>();

    listAdapter = new PropertyListAdapter(this, feedItems);
    listView.setAdapter(listAdapter);

    // Attach the listener to the AdapterView onCreate
    listView.setOnScrollListener(
        new EndlessScrollListener() {
          @Override
          public void onLoadMore(int page, int totalItemsCount) {
            findProperties(feedOrder, page);
          }
        });

    // We first check for cached request
    Cache cache = AppController.getInstance().getRequestQueue().getCache();
    Cache.Entry entry = cache.get(URL_FEED);
    if (entry != null) {
      // fetch the data from cache
      try {
        String data = new String(entry.data, "UTF-8");
        try {
          parseJsonFeed(new JSONObject(data));
        } catch (JSONException e) {
          e.printStackTrace();
        }
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }

    } else {
      // First time you run the app there is no order and values are coming in default order.
      findProperties(feedOrder, pageCount);
    }

    paButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            pageCount = 0;
            feedOrder = "pa";
            listView.setSelection(0);
            findProperties(feedOrder, pageCount);
          }
        });

    pdButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            pageCount = 0;
            feedOrder = "pd";
            listView.setSelection(0);
            findProperties(feedOrder, pageCount);
          }
        });

    baButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            pageCount = 0;
            feedOrder = "ba";
            listView.setSelection(0);
            findProperties(feedOrder, pageCount);
          }
        });

    bdButton.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            pageCount = 0;
            feedOrder = "bd";
            listView.setSelection(0);
            findProperties(feedOrder, pageCount);
          }
        });
  }
  private void _webServiceGetServices() {
    _urlWebService = "http://52.72.85.214/ws/ObtenerServicios";

    progressBar.setVisibility(View.VISIBLE);
    //        buttonSeleccionarServicios.setVisibility(View.GONE);

    Cache.Entry entry = cache.get(_urlWebService);
    if (entry != null) {
      try {
        String data = new String(entry.data, "UTF-8");
        Log.e("Cache", "" + data);
        // handle data, like converting it to xml, json, bitmap etc.,
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    } else {
      Log.e("Cache", "empty");

      // Cached response doesn't exists. Make network call here
    }

    JsonObjectRequest jsonObjReq =
        new JsonObjectRequest(
            Request.Method.GET,
            _urlWebService,
            null,
            new Response.Listener<JSONObject>() {

              @Override
              public void onResponse(JSONObject response) {
                try {
                  String message = response.getString("message");
                  Log.w("Mensaje : ", message);
                  JSONArray servicios = response.getJSONArray("result");
                  JSONObject object;

                  for (int i = 0; i <= servicios.length() - 1; i++) {
                    object = servicios.getJSONObject(i);

                    Servicio servicio = new Servicio();
                    servicio.setImagen(object.getString("imagenServicio"));
                    servicio.setId(object.getString("codigoServicio"));
                    servicio.setNombreServicio(object.getString("nombreServicio"));
                    servicio.setDescripcionServicio(object.getString("descripcionServicio"));
                    servicio.setValorServicio(object.getString("valorServicio"));
                    servicioList.add(servicio);
                  }

                  progressBar.setVisibility(View.GONE);
                  linearLayoutPrecioTotal.setVisibility(View.VISIBLE);
                  //
                  // buttonSeleccionarServicios.setVisibility(View.VISIBLE);
                  mAdapter.notifyDataSetChanged();

                } catch (JSONException e) {

                  progressBar.setVisibility(View.GONE);
                  // buttonSeleccionarServicios.setVisibility(View.GONE);

                  AlertDialog.Builder builder =
                      new AlertDialog.Builder(SolicitarServicio.this.getActivity());
                  builder
                      .setMessage(e.getMessage().toString())
                      .setPositiveButton(
                          "Aceptar",
                          new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                              // Intent intent = new Intent(Pago.this.getApplicationContext(),
                              // Registro.class);
                              // startActivity(intent);
                              // finish();
                            }
                          })
                      .show();

                  e.printStackTrace();
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {

                if (error instanceof TimeoutError) {

                  AlertDialog.Builder builder =
                      new AlertDialog.Builder(SolicitarServicio.this.getActivity());
                  builder
                      .setMessage("Error de conexión, sin respuesta del servidor.")
                      .setPositiveButton(
                          "Aceptar",
                          new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                              // Intent intent = new Intent(Pago.this.getApplicationContext(),
                              // Registro.class);
                              // startActivity(intent);
                              // finish();
                            }
                          })
                      .show();

                } else if (error instanceof NoConnectionError) {

                  AlertDialog.Builder builder =
                      new AlertDialog.Builder(SolicitarServicio.this.getActivity());
                  builder
                      .setMessage("Por favor, conectese a la red.")
                      .setPositiveButton(
                          "Aceptar",
                          new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                              // Intent intent = new Intent(Pago.this.getApplicationContext(),
                              // Registro.class);
                              // startActivity(intent);
                              // finish();
                            }
                          })
                      .show();

                } else if (error instanceof AuthFailureError) {

                  AlertDialog.Builder builder =
                      new AlertDialog.Builder(SolicitarServicio.this.getActivity());
                  builder
                      .setMessage(
                          "Error de autentificación en la red, favor contacte a su proveedor de servicios.")
                      .setPositiveButton(
                          "Aceptar",
                          new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                              // Intent intent = new Intent(Pago.this.getApplicationContext(),
                              // Registro.class);
                              // startActivity(intent);
                              // finish();
                            }
                          })
                      .show();

                } else if (error instanceof ServerError) {

                  AlertDialog.Builder builder =
                      new AlertDialog.Builder(SolicitarServicio.this.getActivity());
                  builder
                      .setMessage("Error server, sin respuesta del servidor.")
                      .setPositiveButton(
                          "Aceptar",
                          new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                              // Intent intent = new Intent(Pago.this.getApplicationContext(),
                              // Registro.class);
                              // startActivity(intent);
                              // finish();
                            }
                          })
                      .show();

                } else if (error instanceof NetworkError) {

                  AlertDialog.Builder builder =
                      new AlertDialog.Builder(SolicitarServicio.this.getActivity());
                  builder
                      .setMessage("Error de red, contacte a su proveedor de servicios.")
                      .setPositiveButton(
                          "Aceptar",
                          new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                              // Intent intent = new Intent(Pago.this.getApplicationContext(),
                              // Registro.class);
                              // startActivity(intent);
                              // finish();
                            }
                          })
                      .show();

                } else if (error instanceof ParseError) {

                  AlertDialog.Builder builder =
                      new AlertDialog.Builder(SolicitarServicio.this.getActivity());
                  builder
                      .setMessage(
                          "Error de conversión Parser, contacte a su proveedor de servicios.")
                      .setPositiveButton(
                          "Aceptar",
                          new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                              // Intent intent = new Intent(Pago.this.getApplicationContext(),
                              // Registro.class);
                              // startActivity(intent);
                              // finish();
                            }
                          })
                      .show();
                }

                progressBar.setVisibility(View.GONE);
                // buttonSeleccionarServicios.setVisibility(View.GONE);
              }
            }) {
          @Override
          public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            headers.put("WWW-Authenticate", "xBasic realm=".concat(""));
            headers.put("MyToken", sharedPreferences.getString("MyToken"));
            return headers;
          }
        };

    jsonObjReq.setRetryPolicy(
        new DefaultRetryPolicy(10000, 3, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    ControllerSingleton.getInstance().addToReqQueue(jsonObjReq, "");
  }
Beispiel #10
0
 public static <T> void removeCacheFile(InputBase input, Class<T> clazz) {
   Cache cache = requestQueue.getCache();
   Request<T> request =
       new GsonRequest<T>(input.method(), input.toString(), "", clazz, null, null, null, null);
   cache.remove(request.getCacheKey());
 }
  @Override
  public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
      try {
        // Take a request from the queue.
        request = mQueue.take();
      } catch (InterruptedException e) {
        // We may have been interrupted because it was time to quit.
        if (mQuit) {
          return;
        }
        continue;
      }

      try {
        request.addMarker("network-queue-take");

        // If the request was cancelled already, do not perform the
        // network request.
        if (request.isCanceled()) {
          request.finish("network-discard-cancelled");
          continue;
        }

        // Tag the request (if API >= 14)
        if (Build.VERSION.SDK_INT >= 14) {
          TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
        }

        // Perform the network request.
        NetworkResponse networkResponse = mNetwork.performRequest(request);
        request.addMarker("network-http-complete");

        // If the server returned 304 AND we delivered a response already,
        // we're done -- don't deliver a second identical response.
        if (networkResponse.notModified && request.hasHadResponseDelivered()) {
          request.finish("not-modified");
          continue;
        }

        // Parse the response here on the worker thread.
        Response<?> response = request.parseNetworkResponse(networkResponse);
        request.addMarker("network-parse-complete");

        // Write to cache if applicable.
        // TODO: Only update cache metadata instead of entire record for 304s.
        if (request.shouldCache() && response.cacheEntry != null) {
          mCache.put(request.getCacheKey(), response.cacheEntry);
          request.addMarker("network-cache-written");
        }

        // Post the response back.
        request.markDelivered();
        mDelivery.postResponse(request, response);
      } catch (VolleyError volleyError) {
        parseAndDeliverNetworkError(request, volleyError);
      } catch (Exception e) {
        VolleyLog.e(e, "Unhandled exception %s", e.toString());
        mDelivery.postError(request, new VolleyError(e));
      }
    }
  }