com.android.volley.VolleyLog Java Examples

The following examples show how to use com.android.volley.VolleyLog. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserAPIImpl.java    From the-tech-frontier-app with MIT License 6 votes vote down vote up
@Override
public void fetchUserInfo(String uid, String token, final DataListener<UserInfo> listener) {
    JsonObjectRequest request = new JsonObjectRequest(Constants.SINA_UID_TOKEN + uid
            + "&access_token=" + token, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    if (listener != null) {
                        listener.onComplete(mRespHandler.parse(response));
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.e("Error: ", error.getMessage());
                }
            });

    performRequest(request);
}
 
Example #2
Source File: BallMarkerLog.java    From Volley-Ball with MIT License 6 votes vote down vote up
/**
 * Closes the log, dumping it to logcat if the time difference between
 * the first and last markers is greater than {@link #MIN_DURATION_FOR_LOGGING_MS}.
 * @param header Header string to print above the marker log.
 */
public synchronized void finish(String header) {
    mFinished = true;

    long duration = getTotalDuration();
    if (duration <= MIN_DURATION_FOR_LOGGING_MS) {
        return;
    }

    long prevTime = mMarkers.get(0).time;
    VolleyLog.d("(%-4d ms) %s", duration, header);
    for (Marker marker : mMarkers) {
        long thisTime = marker.time;
        VolleyLog.d("(+%-4d) [%2d] %s", (thisTime - prevTime), marker.thread, marker.name);
        prevTime = thisTime;
    }
}
 
Example #3
Source File: DiskBasedCache.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the contents of this CacheHeader to the specified OutputStream.
 */
public boolean writeHeader(OutputStream os) {
    try {
        writeInt(os, CACHE_MAGIC);
        writeString(os, key);
        writeString(os, etag == null ? "" : etag);
        writeLong(os, serverDate);
        writeLong(os, ttl);
        writeLong(os, softTtl);
        writeStringStringMap(responseHeaders, os);
        os.flush();
        return true;
    } catch (IOException e) {
        VolleyLog.d("%s", e.toString());
        return false;
    }
}
 
Example #4
Source File: DiskBasedCache.java    From WayHoo with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the contents of this CacheHeader to the specified OutputStream.
 */
public boolean writeHeader(OutputStream os) {
    try {
        writeInt(os, CACHE_MAGIC);
        writeString(os, key);
        writeString(os, etag == null ? "" : etag);
        writeLong(os, serverDate);
        writeLong(os, ttl);
        writeLong(os, softTtl);
        writeStringStringMap(responseHeaders, os);
        os.flush();
        return true;
    } catch (IOException e) {
        VolleyLog.d("%s", e.toString());
        return false;
    }
}
 
Example #5
Source File: DiskBasedCache.java    From SaveVolley with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the contents of this CacheHeader to the specified OutputStream.
 */
/*
 * 写入一条缓存 CacheHeader
 * 先写入一个 CACHE_MAGIC 标识,标记着 CacheHeader 数据的开始
 * 然后开始写 CacheHeader 的内容
 */
public boolean writeHeader(OutputStream os) {
    try {
        // 先写入一个 CACHE_MAGIC 标识
        writeInt(os, CACHE_MAGIC);
        writeString(os, key);
        writeString(os, etag == null ? "" : etag);
        writeLong(os, serverDate);
        writeLong(os, lastModified);
        writeLong(os, ttl);
        writeLong(os, softTtl);
        writeStringStringMap(responseHeaders, os);
        os.flush();
        return true;
    } catch (IOException e) {
        VolleyLog.d("%s", e.toString());
        return false;
    }
}
 
Example #6
Source File: RestVolleyImageCache.java    From RestVolley with Apache License 2.0 6 votes vote down vote up
private Bitmap getBitmapFromDiskLruCache(String key) {
    if (getDiskCache() == null) {
        return null;
    }

    String cachePath = new StringBuilder(getDiskCachePath()).append(File.separator).append(key).append(".0").toString();
    File cacheFile = new File(cachePath);
    try {
        if (cacheFile.exists()) {
            return ImageProcessor.decode(cachePath);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } catch (OutOfMemoryError error) {
        VolleyLog.e("Caught OOM for %d byte image, uri=%s", cacheFile.length(), cachePath);
    }

    return null;
}
 
Example #7
Source File: DiskBasedCache.java    From product-emm with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the contents of this CacheHeader to the specified OutputStream.
 */
public boolean writeHeader(OutputStream os) {
    try {
        writeInt(os, CACHE_MAGIC);
        writeString(os, key);
        writeString(os, etag == null ? "" : etag);
        writeLong(os, serverDate);
        writeLong(os, lastModified);
        writeLong(os, ttl);
        writeLong(os, softTtl);
        writeStringStringMap(responseHeaders, os);
        os.flush();
        return true;
    } catch (IOException e) {
        VolleyLog.d("%s", e.toString());
        return false;
    }
}
 
Example #8
Source File: DiskBasedCache.java    From android-common-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the contents of this CacheHeader to the specified OutputStream.
 */
public boolean writeHeader(OutputStream os) {
    try {
        writeInt(os, CACHE_MAGIC);
        writeString(os, key);
        writeString(os, etag == null ? "" : etag);
        writeLong(os, serverDate);
        writeLong(os, ttl);
        writeLong(os, softTtl);
        writeStringStringMap(responseHeaders, os);
        os.flush();
        return true;
    } catch (IOException e) {
        VolleyLog.d("%s", e.toString());
        return false;
    }
}
 
Example #9
Source File: ImageRequest.java    From SaveVolley with Apache License 2.0 5 votes vote down vote up
@Override protected Response<Bitmap> parseNetworkResponse(NetworkResponse response) {
    // Serialize all decode on a global lock to reduce concurrent heap usage.
    // 解析 ImageRequest 的网络请求这块进行加锁,避免 OOM
    synchronized (sDecodeLock) {
        try {
            return doParse(response);
        } catch (OutOfMemoryError e) {
            // 发生 OOM,返回一个只带有 error 的 Response
            VolleyLog.e("Caught OOM for %d byte image, url=%s", response.data.length, getUrl());
            return Response.error(new ParseError(e));
        }
    }
}
 
Example #10
Source File: DiskBasedCache.java    From barterli_android with Apache License 2.0 5 votes vote down vote up
/**
 * Removes the specified key from the cache if it exists.
 */
@Override
public synchronized void remove(String key) {
    boolean deleted = getFileForKey(key).delete();
    removeEntry(key);
    if (!deleted) {
        VolleyLog.d("Could not delete cache entry for key=%s, filename=%s",
                key, getFilenameForKey(key));
    }
}
 
Example #11
Source File: JsonRequest.java    From android-project-wo2b with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] getBody() {
    try {
        return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
    } catch (UnsupportedEncodingException uee) {
        VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                mRequestBody, PROTOCOL_CHARSET);
        return null;
    }
}
 
Example #12
Source File: DiskBasedCache.java    From volley with Apache License 2.0 5 votes vote down vote up
/**
 * Clears the cache. Deletes all cached files from disk.
 */
@Override
public synchronized void clear() {
    File[] files = mRootDirectory.listFiles();
    if (files != null) {
        for (File file : files) {
            file.delete();
        }
    }
    mEntries.clear();
    mTotalSize = 0;
    VolleyLog.d("Cache cleared.");
}
 
Example #13
Source File: JsonRequest.java    From SimplifyReader with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] getBody() {
    try {
        return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
    } catch (UnsupportedEncodingException uee) {
        VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                mRequestBody, PROTOCOL_CHARSET);
        return null;
    }
}
 
Example #14
Source File: DiskBasedCache.java    From SimplifyReader with Apache License 2.0 5 votes vote down vote up
/**
 * Clears the cache. Deletes all cached files from disk.
 */
@Override
public synchronized void clear() {
    File[] files = mRootDirectory.listFiles();
    if (files != null) {
        for (File file : files) {
            file.delete();
        }
    }
    mEntries.clear();
    mTotalSize = 0;
    VolleyLog.d("Cache cleared.");
}
 
Example #15
Source File: ImageRequest.java    From volley with Apache License 2.0 5 votes vote down vote up
/**
     * Scales one side of a rectangle to fit aspect ratio.
     *
     * @param maxPrimary Maximum size of the primary dimension (i.e. width for
     *        max width), or zero to maintain aspect ratio with secondary
     *        dimension
     * @param maxSecondary Maximum size of the secondary dimension, or zero to
     *        maintain aspect ratio with primary dimension
     * @param actualPrimary Actual size of the primary dimension
     * @param actualSecondary Actual size of the secondary dimension
     */
//    private static int getResizedDimension(int maxPrimary, int maxSecondary, int actualPrimary,
//            int actualSecondary) {
//        // If no dominant value at all, just return the actual.
//        if (maxPrimary == 0 && maxSecondary == 0) {
//            return actualPrimary;
//        }
//
//        // If primary is unspecified, scale primary to match secondary's scaling ratio.
//        if (maxPrimary == 0) {
//            double ratio = (double) maxSecondary / (double) actualSecondary;
//            return (int) (actualPrimary * ratio);
//        }
//
//        if (maxSecondary == 0) {
//            return maxPrimary;
//        }
//
//        double ratio = (double) actualSecondary / (double) actualPrimary;
//        int resized = maxPrimary;
//        if (resized * ratio > maxSecondary) {
//            resized = (int) (maxSecondary / ratio);
//        }
//        return resized;
//    }

    @Override
    protected Response<Bitmap> parseNetworkResponse(NetworkResponse response) {
        // Serialize all decode on a global lock to reduce concurrent heap usage.
        synchronized (sDecodeLock) {
            try {
                return doParse(response);
            } catch (OutOfMemoryError e) {
                VolleyLog.e("Caught OOM for %d byte image, url=%s", response.data.length, getUrl());
                return Response.error(new ParseError(e));
            }
        }
    }
 
Example #16
Source File: DiskBasedCache.java    From SimplifyReader with Apache License 2.0 5 votes vote down vote up
/**
 * Removes the specified key from the cache if it exists.
 */
@Override
public synchronized void remove(String key) {
    boolean deleted = getFileForKey(key).delete();
    removeEntry(key);
    if (!deleted) {
        VolleyLog.d("Could not delete cache entry for key=%s, filename=%s",
                key, getFilenameForKey(key));
    }
}
 
Example #17
Source File: DiskBasedCache.java    From product-emm with Apache License 2.0 5 votes vote down vote up
/**
 * Prunes the cache to fit the amount of bytes specified.
 * @param neededSpace The amount of bytes we are trying to fit into the cache.
 */
private void pruneIfNeeded(int neededSpace) {
    if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes) {
        return;
    }
    if (VolleyLog.DEBUG) {
        VolleyLog.v("Pruning old cache entries.");
    }

    long before = mTotalSize;
    int prunedFiles = 0;
    long startTime = SystemClock.elapsedRealtime();

    Iterator<Map.Entry<String, CacheHeader>> iterator = mEntries.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, CacheHeader> entry = iterator.next();
        CacheHeader e = entry.getValue();
        boolean deleted = getFileForKey(e.key).delete();
        if (deleted) {
            mTotalSize -= e.size;
        } else {
           VolleyLog.d("Could not delete cache entry for key=%s, filename=%s",
                   e.key, getFilenameForKey(e.key));
        }
        iterator.remove();
        prunedFiles++;

        if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes * HYSTERESIS_FACTOR) {
            break;
        }
    }

    if (VolleyLog.DEBUG) {
        VolleyLog.v("pruned %d files, %d bytes, %d ms",
                prunedFiles, (mTotalSize - before), SystemClock.elapsedRealtime() - startTime);
    }
}
 
Example #18
Source File: DiskBasedCache.java    From volley_demo with Apache License 2.0 5 votes vote down vote up
/**
 * Prunes the cache to fit the amount of bytes specified.
 * @param neededSpace The amount of bytes we are trying to fit into the cache.
 */
private void pruneIfNeeded(int neededSpace) {
    if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes) {
        return;
    }
    if (VolleyLog.DEBUG) {
        VolleyLog.v("Pruning old cache entries.");
    }

    long before = mTotalSize;
    int prunedFiles = 0;
    long startTime = SystemClock.elapsedRealtime();

    Iterator<Map.Entry<String, CacheHeader>> iterator = mEntries.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, CacheHeader> entry = iterator.next();
        CacheHeader e = entry.getValue();
        boolean deleted = getFileForKey(e.key).delete();
        if (deleted) {
            mTotalSize -= e.size;
        } else {
           VolleyLog.d("Could not delete cache entry for key=%s, filename=%s",
                   e.key, getFilenameForKey(e.key));
        }
        iterator.remove();
        prunedFiles++;

        if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes * HYSTERESIS_FACTOR) {
            break;
        }
    }

    if (VolleyLog.DEBUG) {
        VolleyLog.v("pruned %d files, %d bytes, %d ms",
                prunedFiles, (mTotalSize - before), SystemClock.elapsedRealtime() - startTime);
    }
}
 
Example #19
Source File: BasicNetwork.java    From android_tv_metro with Apache License 2.0 5 votes vote down vote up
/**
 * Logs requests that took over SLOW_REQUEST_THRESHOLD_MS to complete.
 */
private void logSlowRequests(long requestLifetime, Request<?> request,
        byte[] responseContents, StatusLine statusLine) {
    if (DEBUG || requestLifetime > SLOW_REQUEST_THRESHOLD_MS) {
        VolleyLog.d("HTTP response for request=<%s> [lifetime=%d], [size=%s], " +
                "[rc=%d], [retryCount=%s]", request, requestLifetime,
                responseContents != null ? responseContents.length : "null",
                statusLine.getStatusCode(), request.getRetryPolicy().getCurrentRetryCount());
    }
}
 
Example #20
Source File: JacksonNetwork.java    From volley-jackson-extension with Apache License 2.0 5 votes vote down vote up
/**
 * Copied from {@link com.android.volley.toolbox.BasicNetwork}
 *
 * Reads the contents of HttpEntity into a byte[].
 *
 */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
	PoolingByteArrayOutputStream bytes = new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
	byte[] buffer = null;
	try {
		InputStream in = entity.getContent();
		if (in == null) {
			throw new ServerError();
		}
		buffer = mPool.getBuf(1024);
		int count;
		while ((count = in.read(buffer)) != -1) {
			bytes.write(buffer, 0, count);
		}
		return bytes.toByteArray();
	} finally {
		try {
			// Close the InputStream and release the resources by "consuming the content".
			entity.consumeContent();
		} catch (IOException e) {
			// This can happen if there was an exception above that left the entity in
			// an invalid state.
			VolleyLog.v("Error occured when calling consumingContent");
		}
		mPool.returnBuf(buffer);
		bytes.close();
	}
}
 
Example #21
Source File: BasicNetwork.java    From product-emm with Apache License 2.0 5 votes vote down vote up
/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
    PoolingByteArrayOutputStream bytes =
            new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
    byte[] buffer = null;
    try {
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        buffer = mPool.getBuf(1024);
        int count;
        while ((count = in.read(buffer)) != -1) {
            bytes.write(buffer, 0, count);
        }
        return bytes.toByteArray();
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VolleyLog.v("Error occured when calling consumingContent");
        }
        mPool.returnBuf(buffer);
        bytes.close();
    }
}
 
Example #22
Source File: DiskBasedCache.java    From volley_demo with Apache License 2.0 5 votes vote down vote up
/**
 * Clears the cache. Deletes all cached files from disk.
 */
@Override
public synchronized void clear() {
    File[] files = mRootDirectory.listFiles();
    if (files != null) {
        for (File file : files) {
            file.delete();
        }
    }
    mEntries.clear();
    mTotalSize = 0;
    VolleyLog.d("Cache cleared.");
}
 
Example #23
Source File: BasicNetwork.java    From TitanjumNote with Apache License 2.0 5 votes vote down vote up
/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(HttpEntity entity) throws IOException,
                                                       ServerError {
    PoolingByteArrayOutputStream bytes =
            new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
    byte[] buffer = null;
    try {
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        buffer = mPool.getBuf(1024);
        int count;
        while ((count = in.read(buffer)) != -1) {
            bytes.write(buffer, 0, count);
        }
        return bytes.toByteArray();
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VolleyLog.v("Error occured when calling consumingContent");
        }
        mPool.returnBuf(buffer);
        bytes.close();
    }
}
 
Example #24
Source File: DiskBasedCache.java    From SaveVolley with Apache License 2.0 5 votes vote down vote up
/**
 * Clears the cache. Deletes all cached files from disk.
 */
/*
 * 清空磁盘上的文件缓存
 */
@Override public synchronized void clear() {
    File[] files = mRootDirectory.listFiles();
    if (files != null) {
        for (File file : files) {
            file.delete();
        }
    }
    mEntries.clear();
    mTotalSize = 0;
    VolleyLog.d("Cache cleared.");
}
 
Example #25
Source File: DbTools.java    From volley with Apache License 2.0 5 votes vote down vote up
private synchronized static DbTools getInstance(DaoConfig daoConfig) {
    DbTools dao = daoMap.get(daoConfig.getDbName());
    if (dao == null) {
        dao = new DbTools(daoConfig);
        daoMap.put(daoConfig.getDbName(), dao);
    } else {
        dao.daoConfig = daoConfig;
    }

    // update the database if needed
    SQLiteDatabase database = dao.database;
    int oldVersion = database.getVersion();
    int newVersion = daoConfig.getDbVersion();
    if (oldVersion != newVersion) {
        if (oldVersion != 0) {
            DbUpgradeListener upgradeListener = daoConfig.getDbUpgradeListener();
            if (upgradeListener != null) {
                upgradeListener.onUpgrade(dao, oldVersion, newVersion);
            } else {
                try {
                    dao.dropDb();
                } catch (DbException e) {
                    VolleyLog.e(e.getMessage(), e);
                }
            }
        }
        database.setVersion(newVersion);
    }

    return dao;
}
 
Example #26
Source File: DeleteRequest.java    From swagger-aem with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] getBody() throws AuthFailureError {
  if(entity == null) {
    return null;
  }
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  try {
    entity.writeTo(bos);
  }
  catch (IOException e) {
    VolleyLog.e("IOException writing to ByteArrayOutputStream");
  }
  return bos.toByteArray();
}
 
Example #27
Source File: PutRequest.java    From swagger-aem with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] getBody() throws AuthFailureError {
  if(entity == null) {
    return null;
  }
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  try {
    entity.writeTo(bos);
  }
  catch (IOException e) {
    VolleyLog.e("IOException writing to ByteArrayOutputStream");
  }
  return bos.toByteArray();
}
 
Example #28
Source File: PostRequest.java    From swagger-aem with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] getBody() throws AuthFailureError {
  if(entity == null) {
    return null;
  }
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  try {
    entity.writeTo(bos);
  }
  catch (IOException e) {
    VolleyLog.e("IOException writing to ByteArrayOutputStream");
  }
  return bos.toByteArray();
}
 
Example #29
Source File: PostRequest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] getBody() throws AuthFailureError {
  if(entity == null) {
    return null;
  }
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  try {
    entity.writeTo(bos);
  }
  catch (IOException e) {
    VolleyLog.e("IOException writing to ByteArrayOutputStream");
  }
  return bos.toByteArray();
}
 
Example #30
Source File: BasicNetwork.java    From device-database with Apache License 2.0 5 votes vote down vote up
/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
    PoolingByteArrayOutputStream bytes =
            new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
    byte[] buffer = null;
    try {
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        buffer = mPool.getBuf(1024);
        int count;
        while ((count = in.read(buffer)) != -1) {
            bytes.write(buffer, 0, count);
        }
        return bytes.toByteArray();
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VolleyLog.v("Error occured when calling consumingContent");
        }
        mPool.returnBuf(buffer);
        bytes.close();
    }
}