public Bitmap getBitmap(String fileId, String size, boolean fromUrl) { File file = fileCache.getFile(fileId + size); // from SD cache Bitmap bitmap = decodeFile(file, size); if (bitmap != null) { return bitmap; } // from web try { bitmap = null; if (fromUrl) { InputStream is = ConnectionHandler.httpGetRequest(fileId, UsersManagement.getLoginUser().getId()); OutputStream os = new FileOutputStream(file); Utils.copyStream(is, os); os.close(); is.close(); } else { CouchDB.downloadFile(fileId, file); } bitmap = decodeFile(file, size); return bitmap; // return ConnectionHandler.getBitmapObject(url); } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } }
@Test public void concurrent_download() throws IOException { FileHashes hashes = mock(FileHashes.class); when(hashes.of(any(File.class))).thenReturn("ABCDE"); final FileCache cache = new FileCache(tempFolder.newFolder(), log, hashes); FileCache.Downloader downloader = new FileCache.Downloader() { public void download(String filename, File toFile) throws IOException { // Emulate a concurrent download that adds file to cache before File cachedFile = new File(new File(cache.getDir(), "ABCDE"), "sonar-foo-plugin-1.5.jar"); FileUtils.write(cachedFile, "downloaded by other"); FileUtils.write(toFile, "downloaded by me"); } }; // do not fail File cachedFile = cache.get("sonar-foo-plugin-1.5.jar", "ABCDE", downloader); assertThat(cachedFile).isNotNull().exists().isFile(); assertThat(cachedFile.getName()).isEqualTo("sonar-foo-plugin-1.5.jar"); assertThat(cachedFile.getParentFile().getParentFile()).isEqualTo(cache.getDir()); assertThat(FileUtils.readFileToString(cachedFile)).contains("downloaded by"); }
@Test public void found_in_cache() throws IOException { FileCache cache = FileCache.create(tempFolder.newFolder(), log); // populate the cache. Assume that hash is correct. File cachedFile = new File(new File(cache.getDir(), "ABCDE"), "sonar-foo-plugin-1.5.jar"); FileUtils.write(cachedFile, "body"); assertThat(cache.get("sonar-foo-plugin-1.5.jar", "ABCDE")) .isNotNull() .exists() .isEqualTo(cachedFile); }
public Bitmap getBitmap(String url) throws IOException { File f = fileCache.getFile(url); // from SD cache Bitmap b = decodeFile(f); if (b != null) return b; OutputStream os = null; // from web try { Bitmap bitmap = null; URL imageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection(); conn.setConnectTimeout(60000); conn.setReadTimeout(60000); conn.setInstanceFollowRedirects(true); InputStream is = conn.getInputStream(); os = new FileOutputStream(f); Utils.CopyStream(is, os); bitmap = decodeFile(f); return bitmap; } finally { try { if (os != null) os.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
private Bitmap getBitmap(String url, int requiredSize) { File f = fileCache.getFile(url); Bitmap b = decodeFile(f, requiredSize); if (b != null) return b; Utils.logDebug(TAG, "load image from " + url); Bitmap bitmap = null; InputStream is = null; OutputStream os = null; try { HttpTransport httpTransport = new HttpTransport(); is = httpTransport.executeGetRequest(url); os = new FileOutputStream(f); Utils.copyStream(is, os); bitmap = decodeFile(f, requiredSize); } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); } finally { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } return bitmap; }
/** * download url theo height va width * * @author: truonglt2 * @param url * @param requestWidth * @param requestHeight * @return * @return: Bitmap * @throws: */ public Bitmap getBitmap(String url, int requestWidth, int requestHeight) { File f = fileCache.getFile(url); // from SD cache Bitmap b = decodeFile(f, requestWidth, requestHeight); if (b != null) return b; // from web try { Bitmap bitmap = null; URL imageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setInstanceFollowRedirects(true); InputStream is = conn.getInputStream(); OutputStream os = new FileOutputStream(f); Utils.CopyStream(is, os); os.close(); bitmap = decodeFile(f, requestWidth, requestHeight); return bitmap; } catch (Exception ex) { ex.printStackTrace(); return null; } }
public Bitmap getBitmap(String url) { File f = fileCache.getFile(url); // from SD cache Bitmap bitmap = decodeFile(f); if (bitmap != null) { Logger.error("ImageLoader", "fileCache.returnBitmap : " + url); return bitmap; } // from web try { bitmap = null; InputStream is = ConnectionHandler.httpGetRequest(url, UsersManagement.getLoginUser().getId()); OutputStream os = new FileOutputStream(f); Utils.copyStream(is, os); os.close(); is.close(); // conn.disconnect(); bitmap = decodeFile(f); return bitmap; // return ConnectionHandler.getBitmapObject(url); } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } }
@Override public Boolean loadInBackground() { boolean flag = false; // 进行开启下载任务 try { byte[] bs = webCache.getByteFromInternet(url); if (bs != null) { String json = new String(bs, "utf-8"); List<News> list = JsonUtils.turnToJson(json); for (News news : list) { // 将list加入数据库中 newshander.insertToSQL(news); // 下载图片 String url = news.getLitpic(); byte[] bytes = webCache.getByteFromInternet(url); // 保存图片 Bitmap compress = Compress.ImageCompress(bytes, 60, 60); String filename = fileCache.addToSdcard(url, BitmapToByte.bitmapToByte(compress)); newshander.updata(url, filename); memoryCache.addtoCache(filename, compress); } } } catch (Exception e) { e.printStackTrace(); } return flag; }
private Bitmap getBitmap(String url) { File f = fileCache.getFile(url); // from SD cache Bitmap b = decodeFile(f); if (b != null) return b; // from web try { Bitmap bitmap = null; URL imageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setInstanceFollowRedirects(true); InputStream is = conn.getInputStream(); OutputStream os = new FileOutputStream(f); Utils.CopyStream(is, os); os.close(); conn.disconnect(); bitmap = decodeFile(f); return bitmap; } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } }
/* * This function is strictly for use by internal APIs. Not that we have * anything external but there is some trickery here! The getBitmap function * cannot be invoked from the UI thread. Having to deal with complexity of * when & how to call this API is too much for those who just want to have * the bitmap. This is a utility function and is public because it is to be * shared by other components in the internal implementation. */ public Bitmap getBitmap( String serverUrl, boolean cacheBitmap, int bestWidth, int bestHeight, String source) { File f = mFileCache.getFile(serverUrl); // from SD cache Bitmap b = decodeFile(f, bestHeight, bestWidth, source); if (b != null) { Logging.i(TAG, "Image Available in SD card: ", false, classLevelLogEnabled); if (cacheBitmap) mAisleImagesCache.putBitmap(serverUrl, b); return b; } // from web try { if (serverUrl == null || serverUrl.length() < 1) { return null; } Logging.i( TAG, "Image DownLoad Time starts At: " + System.currentTimeMillis(), false, classLevelLogEnabled); Bitmap bitmap = null; URL imageUrl = new URL(serverUrl); HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setInstanceFollowRedirects(true); InputStream is = conn.getInputStream(); int hashCode = serverUrl.hashCode(); String filename = String.valueOf(hashCode); OutputStream os = new FileOutputStream(f); Utils.CopyStream(is, os); os.close(); Logging.i( TAG, "Image DownLoad Time Ends At: " + System.currentTimeMillis(), false, classLevelLogEnabled); Logging.i( TAG, "Bitmap Decode Time Starts At: " + System.currentTimeMillis(), false, classLevelLogEnabled); bitmap = decodeFile(f, bestHeight, bestWidth, source); Logging.i( TAG, "Bitmap Decode Time Ends At: " + System.currentTimeMillis(), false, classLevelLogEnabled); if (cacheBitmap) mAisleImagesCache.putBitmap(serverUrl, bitmap); return bitmap; } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) { // mAisleImagesCache.evictAll(); } return null; } }
public FileCache build() { if (userHome == null) { userHome = findHome(); } File cacheDir = new File(userHome, "cache"); return FileCache.create(cacheDir, logger); }
public File get(String inode) throws DotStateException, DotDataException, DotSecurityException { File file = fileCache.get(inode); if ((file == null) || !InodeUtils.isSet(file.getInode())) { file = (File) HibernateUtil.load(File.class, inode); fileCache.add(file); WorkingCache.removeAssetFromCache(file); WorkingCache.addToWorkingAssetToCache(file); LiveCache.removeAssetFromCache(file); if (file.isLive()) { LiveCache.addToLiveAssetToCache(file); } } return file; }
@Test public void download_corrupted_file() throws IOException { thrown.expect(IllegalStateException.class); thrown.expectMessage("INVALID HASH"); FileHashes hashes = mock(FileHashes.class); FileCache cache = new FileCache(tempFolder.newFolder(), log, hashes); when(hashes.of(any(File.class))).thenReturn("VWXYZ"); FileCache.Downloader downloader = new FileCache.Downloader() { public void download(String filename, File toFile) throws IOException { FileUtils.write(toFile, "corrupted body"); } }; cache.get("sonar-foo-plugin-1.5.jar", "ABCDE", downloader); }
public BaseObject getXml(String id, String className, String fileName) { BaseObject xmlObject = memoryCache.getXml(id); if (xmlObject == null) { xmlObject = fileCache.getXml(id); if (xmlObject == null) { // Set default xml. fileCache.setDefaultXml(id, className, fileName); xmlObject = fileCache.getXml(id); } if (xmlObject != null) { memoryCache.setXml(id, xmlObject); } } return xmlObject; }
@Test public void download_and_add_to_cache() throws IOException { FileHashes hashes = mock(FileHashes.class); FileCache cache = new FileCache(tempFolder.newFolder(), log, hashes); when(hashes.of(any(File.class))).thenReturn("ABCDE"); FileCache.Downloader downloader = new FileCache.Downloader() { public void download(String filename, File toFile) throws IOException { FileUtils.write(toFile, "body"); } }; File cachedFile = cache.get("sonar-foo-plugin-1.5.jar", "ABCDE", downloader); assertThat(cachedFile).isNotNull().exists().isFile(); assertThat(cachedFile.getName()).isEqualTo("sonar-foo-plugin-1.5.jar"); assertThat(cachedFile.getParentFile().getParentFile()).isEqualTo(cache.getDir()); assertThat(FileUtils.readFileToString(cachedFile)).isEqualTo("body"); }
public void deleteFromCache(File file) throws DotDataException, DotStateException, DotSecurityException { fileCache.remove(file); WorkingCache.removeAssetFromCache(file); if (file.isLive()) { LiveCache.removeAssetFromCache(file); } CacheLocator.getIdentifierCache().removeFromCacheByVersionable(file); }
private Bitmap getBitmap(String url) { File f = fileCache.getFile(url); // from SD cache Bitmap b = Util.decodeFile(f); if (b != null) return b; // from web return mNetwork.httpGetBitmap(url, f); }
public BaseObject setXml( final String id, final String xmlString, final Class<? extends BaseObject> c) { BaseObject xmlObject = Util.convertXmlToObject(xmlString, c); if (xmlObject != null) { DbCache dbObject = new DbCache(id, xmlString, c.getName()); fileCache.setXml(dbObject); xmlObject.setLastUpdateDate(dbObject.getDate()); memoryCache.setXml(id, xmlObject); } return xmlObject; }
public FileCache build() { if (userHome == null) { String path = System.getenv("SONAR_USER_HOME"); if (path == null) { // Default path = FileUtils.getUserDirectoryPath() + File.separator + ".sonar"; } userHome = new File(path); } File cacheDir = new File(userHome, "cache"); return FileCache.create(cacheDir, log); }
public FileCache build() { if (userHome == null) { String path = System.getenv("SONAR_USER_HOME"); if (path == null) { // Default path = System.getProperty("user.home") + File.separator + ".sonar"; } userHome = new File(path); } File cacheDir = new File(userHome, "cache"); return FileCache.create(cacheDir, logger); }
/** * ** display a image from the network * * @param url image url * @param view imageView * @return null */ public void DisplayImage(String url, ImageView view) { imageViews.put(view, url); Bitmap bitmap = null; // memoryCache.get(url); File f = fileCache.getFile(url); if (f != null) bitmap = BitmapUtil.decodeFile(f, 480); if (bitmap != null) { view.setImageBitmap(BitmapUtil.handleReflection(bitmap)); } else { // Log.e("no cache in memory" , "downloading!"); queuePhoto(url, view); Bitmap bitmap1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.placeholder); view.setImageBitmap(BitmapUtil.handleReflection(bitmap1)); } }
@SuppressWarnings("unchecked") public File saveFile( File newFile, java.io.File dataFile, Folder parentFolder, Identifier identifier) throws DotDataException { boolean localTransation = false; try { localTransation = DbConnectionFactory.getConnection().getAutoCommit(); if (localTransation) { HibernateUtil.startTransaction(); } // old working file File oldFile = null; // if new identifier if (identifier == null || !InodeUtils.isSet(identifier.getInode())) { identifier = APILocator.getIdentifierAPI().createNew(newFile, parentFolder); newFile.setIdentifier(identifier.getInode()); HibernateUtil.save(newFile); APILocator.getVersionableAPI().setWorking(newFile); saveFileData(newFile, null, dataFile); } else { APILocator.getVersionableAPI().removeLive(identifier.getId()); } if (UtilMethods.isSet(dataFile)) { HibernateUtil.save(newFile); saveFileData(newFile, null, dataFile); } if (oldFile != null && InodeUtils.isSet(oldFile.getInode())) { APILocator.getFileAPI().invalidateCache(oldFile); fileCache.remove(oldFile); WorkingCache.removeAssetFromCache(oldFile); } LiveCache.removeAssetFromCache(newFile); if (newFile.isLive()) { LiveCache.addToLiveAssetToCache(newFile); } WorkingCache.addToWorkingAssetToCache(newFile); if (localTransation) { HibernateUtil.commitTransaction(); } } catch (Exception e) { if (localTransation) { HibernateUtil.rollbackTransaction(); } throw new DotDataException(e.getMessage(), e); } return newFile; }
/** * 执行网络请求加载图片 * * @param url * @param requiredSize * @return */ private Bitmap getBitmap(String url, int requiredSize, PhotoToLoad photoToLoad) { File f = fileCache.getFile(url); // 先从文件缓存中查找是否有 Bitmap b = decodeFile(f, requiredSize); if (b != null) return b; // 最后从指定的url中下载图片 try { Bitmap bitmap = null; URL imageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setInstanceFollowRedirects(true); InputStream is = conn.getInputStream(); OutputStream os = new FileOutputStream(f); // CopyStream(is, os, conn.getContentLength(), photoToLoad); photoToLoad.totalSize = conn.getContentLength(); int buffer_size = 1024; byte[] bytes = new byte[buffer_size]; for (; ; ) { int count = is.read(bytes, 0, buffer_size); if (count == -1) { break; } os.write(bytes, 0, count); if (null != photoToLoad.onImageLoaderListener) { // 如果设置了图片加载监听,则回调 Message msg = rHandler.obtainMessage(); photoToLoad.currentSize += count; msg.arg1 = IMAGE_LOADER_PROCESS; msg.obj = photoToLoad; rHandler.sendMessage(msg); } } is.close(); os.close(); bitmap = decodeFile(f, requiredSize); return bitmap; } catch (Exception ex) { Logger.w(TAG, ex); return null; } }
private Bitmap getBitmap(String url) { // File f=fileCache.getFile(url); File f = fileCache.getFile(url); // from SD cache // CHECK : if trying to decode file which not exist in cache return null Bitmap b = decodeFile(f); if (b != null) return b; // Download image file from web try { System.out.println("Downloading image::" + url); Bitmap bitmap = null; URL imageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setInstanceFollowRedirects(true); InputStream is = conn.getInputStream(); // Constructs a new FileOutputStream that writes to file // if file not exist then it will create file OutputStream os = new FileOutputStream(f); // See Utils class CopyStream method // It will each pixel from input stream and // write pixels to output stream (file) Utils.CopyStream(is, os); os.close(); conn.disconnect(); // Now file created and going to resize file with defined height // Decodes image and scales it to reduce memory consumption bitmap = decodeFile(f); return bitmap; } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } }
// To get Image URI from url public Uri getImageUri(String url) { File f = fileCache.getFile(url); if (f == null) { return null; } File imageFile = new File(f.getParent() + "/fununlimitedJoke.png"); /* Bitmap bmp= memoryCache.get(url); */ Uri uri = null; try { Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, null); FileOutputStream out = new FileOutputStream(imageFile); bitmap.compress(Bitmap.CompressFormat.PNG, 85, out); out.flush(); out.close(); uri = Uri.fromFile(imageFile); } catch (Exception e) { // TODO Auto-generated catch block Log.e("Exception While Sharing Joke", "Get File URI CAlled"); return null; } return uri; }
public void clearCache() { memoryCache.clear(); fileCache.clear(); }
@Test public void not_in_cache() throws IOException { FileCache cache = FileCache.create(tempFolder.newFolder(), log); assertThat(cache.get("sonar-foo-plugin-1.5.jar", "ABCDE")).isNull(); }
/** * @param url * @return */ private Bitmap downloadBitmap(String url) { // try to get image from file cache File file = fileCache.getFromFileCache(url); Bitmap bitmap = null; try { bitmap = BitmapFactory.decodeStream(new FlushedInputStream(new FileInputStream(file))); } catch (FileNotFoundException e1) { bitmap = null; } if (bitmap != null) { return bitmap; } // end of try final HttpClient httpClient = AndroidHttpClient.newInstance("image_downloader"); // final HttpClient httpClient = new DefaultHttpClient(); final HttpGet getRequest = new HttpGet(url); try { HttpResponse httpResponse = httpClient.execute(getRequest); final int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(LOG_TAG, "Error " + statusCode + " while retrieving bitmap from " + url); return null; } final HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { InputStream inputStream = null; try { inputStream = httpEntity.getContent(); // save file to file cache fileCache.addToFileCache(url, inputStream); // end of save // TODO return BitmapFactory.decodeStream( new FlushedInputStream(new FlushedInputStream(new FileInputStream(file)))); } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) { inputStream.close(); } httpEntity.consumeContent(); } } } catch (IOException e) { getRequest.abort(); Log.w(LOG_TAG, "I/O error while retrieving bitmap from " + url, e); } catch (IllegalStateException e) { getRequest.abort(); Log.w(LOG_TAG, "Incorrect URL: " + url); } catch (Exception e) { getRequest.abort(); Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e); } finally { if ((httpClient instanceof AndroidHttpClient)) { ((AndroidHttpClient) httpClient).close(); } } return null; } // end of downloadBitmap
public static void main(final String[] args) { final File fileInputDir = new File("input"); if (!fileInputDir.exists() || !fileInputDir.isDirectory()) { return; } String columnMetadataText; final StringBuilder sb = new StringBuilder(); BufferedReader br; try { br = new BufferedReader(new FileReader(new File("res/column_metadata.txt"))); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } columnMetadataText = sb.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } // For each file in the input folder for (File file : fileInputDir.listFiles()) { final String fileName = file.getName(); System.out.println("Generating code for " + fileName); final char[] buffer = new char[2048]; sb.setLength(0); final Reader in; try { in = new InputStreamReader(new FileInputStream(file), "UTF-8"); int read; do { read = in.read(buffer, 0, buffer.length); if (read != -1) { sb.append(buffer, 0, read); } } while (read >= 0); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return; } catch (FileNotFoundException e) { e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } final String content = sb.toString(); if (content.length() == 0) { System.out.println("file is empty."); return; } try { final JSONObject root = new JSONObject(content); final JSONObject jsonDatabase = root.getJSONObject("database"); // Classes generation String classPackage, classesPrefix, contentClassesPrefix, dbAuthorityPackage, providerFolder; int dbVersion; boolean hasProviderSubclasses; classPackage = jsonDatabase.getString("package"); classesPrefix = jsonDatabase.getString("classes_prefix"); contentClassesPrefix = jsonDatabase.optString("content_classes_prefix", ""); dbAuthorityPackage = jsonDatabase.optString("authority_package", classPackage); providerFolder = jsonDatabase.optString("provider_folder", PathUtils.PROVIDER_DEFAULT); dbVersion = jsonDatabase.getInt("version"); hasProviderSubclasses = jsonDatabase.optBoolean("has_subclasses"); ArrayList<TableData> classDataList = TableData.getClassesData(root.getJSONArray("tables"), contentClassesPrefix, dbVersion); // Database generation DatabaseGenerator.generate( fileName, classPackage, dbVersion, dbAuthorityPackage, classesPrefix, classDataList, providerFolder, hasProviderSubclasses); FileCache.saveFile( PathUtils.getAndroidFullPath( fileName, classPackage, providerFolder + "." + PathUtils.UTIL) + "ColumnMetadata.java", String.format(columnMetadataText, classPackage, providerFolder + "." + PathUtils.UTIL)); } catch (JSONException e) { e.printStackTrace(); return; } } }
public void clearFileCache() { fileCache.clear(); }