/** * 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; } }
/** * 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; } }
@Override protected com.android.volley.Response<String> parseNetworkResponse(NetworkResponse response) { this.statusCode = response.statusCode; this.responseHeaders = response.headers; /* Get the response data */ try { String json = ""; if (response.data != null) { json = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); } String log = "%1$s\nResponse code: %2$s\nResponse body: %3$s"; VolleyLog.v(log, getUrl(), statusCode, json); if (statusCode >= 200 && statusCode < 300) { /* Return the parsed result in a response wrapper */ return shouldCache() ? success(json, parseIgnoreCacheHeaders(response)) : success(json, parseCacheHeaders(response)); } else { return error(new ServerError(response)); } } catch (UnsupportedEncodingException e) { return error(new ParseError(e)); } }
public boolean writeHeader(OutputStream os) { try { DiskBasedCache.writeInt(os, DiskBasedCache.CACHE_MAGIC); DiskBasedCache.writeString(os, this.key); DiskBasedCache.writeString(os, this.etag == null ? "" : this.etag); DiskBasedCache.writeLong(os, this.serverDate); DiskBasedCache.writeLong(os, this.lastModified); DiskBasedCache.writeLong(os, this.ttl); DiskBasedCache.writeLong(os, this.softTtl); DiskBasedCache.writeStringStringMap(this.responseHeaders, os); os.flush(); return true; } catch (IOException e) { VolleyLog.d("%s", e.toString()); return false; } }
public synchronized void put(String key, Entry entry) { pruneIfNeeded(entry.data.length); File file = getFileForKey(key); try { BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); CacheHeader e = new CacheHeader(key, entry); if (e.writeHeader(fos)) { fos.write(entry.data); fos.close(); putEntry(key, e); } else { fos.close(); VolleyLog.d("Failed to write header for %s", file.getAbsolutePath()); throw new IOException(); } } catch (IOException e2) { if (!file.delete()) { VolleyLog.d("Could not clean up file %s", file.getAbsolutePath()); } } }
@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; } }
/** * 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."); }
/** * Returns the cache entry with the specified key if it exists, null otherwise. */ @Override public synchronized Entry get(String key) { CacheHeader entry = mEntries.get(key); // if the entry does not exist, return. if (entry == null) { return null; } File file = getFileForKey(key); CountingInputStream cis = null; try { cis = new CountingInputStream(new BufferedInputStream(new FileInputStream(file))); CacheHeader.readHeader(cis); // eat header byte[] data = streamToBytes(cis, (int) (file.length() - cis.bytesRead)); return entry.toCacheEntry(data); } catch (IOException e) { VolleyLog.d("%s: %s", file.getAbsolutePath(), e.toString()); remove(key); return null; } finally { if (cis != null) { try { cis.close(); } catch (IOException ioe) { return null; } } } }
/** * 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)); } }
/** * 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); } }
/** * 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()); } }
/** 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(); } }
/** * 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(); } }
/** * Initializes the DiskBasedCache by scanning for all files currently in the * specified root directory. Creates the root directory if necessary. */ @Override public synchronized void initialize() { if (!mRootDirectory.exists()) { if (!mRootDirectory.mkdirs()) { VolleyLog.e("Unable to create cache dir %s", mRootDirectory.getAbsolutePath()); } } /* DR ÆNDRING - løb ikke igennem cache-mappen, det tager henved 1 sekund per 100 elementer File[] files = mRootDirectory.listFiles(); if (files == null) { return; } for (File file : files) { FileInputStream fis = null; try { fis = new FileInputStream(file); CacheHeader entry = CacheHeader.readHeader(fis); entry.size = file.length(); putEntry(entry.key, entry); } catch (IOException e) { if (file != null) { file.delete(); } } finally { try { if (fis != null) { fis.close(); } } catch (IOException ignored) { } } } */ }
@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)); } } }
@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(); }
public <T> void addToRequestQueue(Request<T> req, String tag) { // set the default tag if tag is empty req.setTag(TextUtils.isEmpty(tag) ? TAG : tag); VolleyLog.d("Adding request to queue: %s", req.getUrl()); getRequestQueue().add(req); }
public void getAPI(){ humansaid = messageET.getText().toString(); jsonURL = "https://monigarr-monigarr-bots-v1.p.mashape.com/conversation_start.php?bot_id=1&say=" +humansaid+ "&format=json"; final ProgressDialog pDialog = new ProgressDialog(ParseJSONObject.this); pDialog.setMessage("Loading..."); pDialog.show(); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,jsonURL, null,new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { mBotResponse = JSONParser.parseFeed(response); yousaidTextView.setText("You Said :" + mBotResponse.getYouSaid()); botsaidTextView.setText("Bot Said :" + mBotResponse.getBotSaid()); Log.d(TAG, response.toString()); pDialog.dismiss(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); pDialog.hide(); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("X-Mashape-Key", developerkey); params.put("Accept", "text/plain"); return params; } }; Volley.newRequestQueue(getApplicationContext()).add(jsonObjReq); }
static SSLSocketFactory getSocketFactory() { if (socketFactory == null) { try { X509TrustManager trustManager = get509TrustManager(); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{trustManager}, null); socketFactory = sslContext.getSocketFactory(); } catch (NoSuchAlgorithmException | KeyManagementException e) { VolleyLog.e(TAG, "Unable to create the ssl socket factory."); return SSLCertificateSocketFactory.getDefault(0, null); } } return socketFactory; }
@Override public void validateCertificates(X509Certificate[] serverCertificates) throws CertificateException { boolean isSelfSigned = false; boolean isSignedWithCAParent = isSignedWithCAParent(serverCertificates); try { isSelfSigned = isSelfSigned(serverCertificates[0]); } catch (GeneralSecurityException e) { VolleyLog.d(TAG, "Something is invalid (key signature)"); } if (isSelfSigned) { throw new CertificateException("The certificate is self-signed."); } else if (!isSignedWithCAParent) { throw new CertificateException("The certificate is not signed with one of his CA's."); } }
/** * Verifies that the leaf certificate was signed using one of the eligible CA */ private boolean isSignedWithCAParent(X509Certificate[] certs) { X509Certificate cert = certs[0]; for (int i = 1; i < certs.length; i++) { PublicKey key = certs[i].getPublicKey(); try { cert.verify(key); return true; } catch (GeneralSecurityException e) { // do nothing, it's normal to throw an exception VolleyLog.d(TAG, "Something is invalid (key signature)"); } } return false; }
private Response<T> parseError(VolleyError error, BaseRequest request) { HttpResponse.Builder builder = new HttpResponse.Builder() .success(false) .request(request) .message(error.getMessage()); if (error instanceof NetworkError || error instanceof TimeoutError) { VolleyLog.e("Network error."); if (error.getCause() instanceof SSLHandshakeException) { VolleyLog.e("SSLHandshakeException: Insecure connection"); } return Response.error(builder.build()); } NetworkResponse response = error.networkResponse; if (response == null) { VolleyLog.e("Local error."); return Response.error(builder.build()); } String json = ""; if (response.data != null) { json = new String(response.data); } ResponseBody body = ResponseBody.create(MediaType.parse(response.headers.get("Content-Type")), json); return Response.error(body, builder.raw(json).code(response.statusCode).build()); }