Java Code Examples for com.facebook.internal.Utility#closeQuietly()

The following examples show how to use com.facebook.internal.Utility#closeQuietly() . 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: LikeActionController.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
/**
 * NOTE: This MUST be called ONLY via the CreateLikeActionControllerWorkItem class to ensure
 * that it happens on the right thread, at the right time.
 */
private static LikeActionController deserializeFromDiskSynchronously(String objectId) {
    LikeActionController controller = null;

    InputStream inputStream = null;
    try {
        String cacheKey = getCacheKeyForObjectId(objectId);
        inputStream = controllerDiskCache.get(cacheKey);
        if (inputStream != null) {
            String controllerJsonString = Utility.readStreamToString(inputStream);
            if (!Utility.isNullOrEmpty(controllerJsonString)) {
                controller = deserializeFromJson(controllerJsonString);
            }
        }
    } catch (IOException e) {
        Log.e(TAG, "Unable to deserialize controller from disk", e);
        controller = null;
    } finally {
        if (inputStream != null) {
            Utility.closeQuietly(inputStream);
        }
    }

    return controller;
}
 
Example 2
Source File: UrlRedirectCache.java    From FacebookNewsfeedSample-Android with Apache License 2.0 6 votes vote down vote up
static void cacheUrlRedirect(Context context, URL fromUrl, URL toUrl) {
    if (fromUrl == null || toUrl == null) {
        return;
    }

    OutputStream redirectStream = null;
    try {
        FileLruCache cache = getCache(context);
        redirectStream = cache.openPutStream(fromUrl.toString(), REDIRECT_CONTENT_TAG);
        redirectStream.write(toUrl.toString().getBytes());
    } catch (IOException e) {
        // Caching is best effort
    } finally {
        Utility.closeQuietly(redirectStream);
    }
}
 
Example 3
Source File: UrlRedirectCache.java    From HypFacebook with BSD 2-Clause "Simplified" License 6 votes vote down vote up
static void cacheUrlRedirect(Context context, URL fromUrl, URL toUrl) {
    if (fromUrl == null || toUrl == null) {
        return;
    }

    OutputStream redirectStream = null;
    try {
        FileLruCache cache = getCache(context);
        redirectStream = cache.openPutStream(fromUrl.toString(), REDIRECT_CONTENT_TAG);
        redirectStream.write(toUrl.toString().getBytes());
    } catch (IOException e) {
        // Caching is best effort
    } finally {
        Utility.closeQuietly(redirectStream);
    }
}
 
Example 4
Source File: AppEventsLogger.java    From facebook-api-android-maven with Apache License 2.0 6 votes vote down vote up
static void saveAppSessionInformation(Context context) {
    ObjectOutputStream oos = null;

    synchronized (staticLock) {
        if (hasChanges) {
            try {
                oos = new ObjectOutputStream(
                        new BufferedOutputStream(
                                context.openFileOutput(
                                        PERSISTED_SESSION_INFO_FILENAME,
                                        Context.MODE_PRIVATE)
                        )
                );
                oos.writeObject(appSessionInfoMap);
                hasChanges = false;
                Logger.log(LoggingBehavior.APP_EVENTS, "AppEvents", "App session info saved");
            } catch (Exception e) {
                Log.d(TAG, "Got unexpected exception: " + e.toString());
            } finally {
                Utility.closeQuietly(oos);
            }
        }
    }
}
 
Example 5
Source File: AppEventsLogger.java    From Abelana-Android with Apache License 2.0 6 votes vote down vote up
static void saveAppSessionInformation(Context context) {
    ObjectOutputStream oos = null;

    synchronized (staticLock) {
        if (hasChanges) {
            try {
                oos = new ObjectOutputStream(
                        new BufferedOutputStream(
                                context.openFileOutput(
                                        PERSISTED_SESSION_INFO_FILENAME,
                                        Context.MODE_PRIVATE)
                        )
                );
                oos.writeObject(appSessionInfoMap);
                hasChanges = false;
                Logger.log(LoggingBehavior.APP_EVENTS, "AppEvents", "App session info saved");
            } catch (Exception e) {
                Log.d(TAG, "Got unexpected exception: " + e.toString());
            } finally {
                Utility.closeQuietly(oos);
            }
        }
    }
}
 
Example 6
Source File: UrlRedirectCache.java    From aws-mobile-self-paced-labs-samples with Apache License 2.0 6 votes vote down vote up
static void cacheUrlRedirect(Context context, URL fromUrl, URL toUrl) {
    if (fromUrl == null || toUrl == null) {
        return;
    }

    OutputStream redirectStream = null;
    try {
        FileLruCache cache = getCache(context);
        redirectStream = cache.openPutStream(fromUrl.toString(), REDIRECT_CONTENT_TAG);
        redirectStream.write(toUrl.toString().getBytes());
    } catch (IOException e) {
        // Caching is best effort
    } finally {
        Utility.closeQuietly(redirectStream);
    }
}
 
Example 7
Source File: FacebookActivityTestCase.java    From FacebookImageShareIntent with MIT License 6 votes vote down vote up
protected File createTempFileFromAsset(String assetPath) throws IOException {
    InputStream inputStream = null;
    FileOutputStream outStream = null;

    try {
        AssetManager assets = getActivity().getResources().getAssets();
        inputStream = assets.open(assetPath);

        File outputDir = getActivity().getCacheDir(); // context being the Activity pointer
        File outputFile = File.createTempFile("prefix", assetPath, outputDir);
        outStream = new FileOutputStream(outputFile);

        final int bufferSize = 1024 * 2;
        byte[] buffer = new byte[bufferSize];
        int n = 0;
        while ((n = inputStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, n);
        }

        return outputFile;
    } finally {
        Utility.closeQuietly(outStream);
        Utility.closeQuietly(inputStream);
    }
}
 
Example 8
Source File: ImageResponseCacheTests.java    From FacebookImageShareIntent with MIT License 6 votes vote down vote up
private Bitmap readImage(String uri, boolean expectedFromCache) {
    Bitmap bmp = null;
    InputStream istream = null;
    try
    {
        URI url = new URI(uri);
        // Check if the cache contains value for this url
        boolean isInCache = (ImageResponseCache.getCache(safeGetContext()).get(url.toString()) != null);
        assertTrue(isInCache == expectedFromCache);
        // Read the image
        istream = ImageResponseCache.getCachedImageStream(url, safeGetContext());
        if (istream == null) {
            HttpURLConnection connection = (HttpURLConnection)url.toURL().openConnection();
            istream = ImageResponseCache.interceptAndCacheImageStream(safeGetContext(), connection);
        }
        assertTrue(istream != null);
        bmp = BitmapFactory.decodeStream(istream);
        assertTrue(bmp != null);
    } catch (Exception e) {
         assertNull(e);
    } finally {
        Utility.closeQuietly(istream);
    }
    return bmp;
}
 
Example 9
Source File: VideoUploader.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
private void initialize()
        throws FileNotFoundException {
    ParcelFileDescriptor fileDescriptor = null;
    try {
        if (Utility.isFileUri(videoUri)) {
            fileDescriptor = ParcelFileDescriptor.open(
                    new File(videoUri.getPath()),
                    ParcelFileDescriptor.MODE_READ_ONLY);
            videoSize = fileDescriptor.getStatSize();
            videoStream = new ParcelFileDescriptor.AutoCloseInputStream(fileDescriptor);
        } else if (Utility.isContentUri(videoUri)) {
            videoSize = Utility.getContentSize(videoUri);
            videoStream = FacebookSdk
                    .getApplicationContext()
                    .getContentResolver()
                    .openInputStream(videoUri);
        } else {
            throw new FacebookException("Uri must be a content:// or file:// uri");
        }
    } catch (FileNotFoundException e) {
        Utility.closeQuietly(videoStream);

        throw e;
    }
}
 
Example 10
Source File: VideoUploader.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
private static void issueResponse(
        final UploadContext uploadContext,
        final FacebookException error,
        final String videoId) {
    // Remove the UploadContext synchronously
    // Once the UploadContext is removed, this is the only reference to it.
    removePendingUpload(uploadContext);

    Utility.closeQuietly(uploadContext.videoStream);

    if (uploadContext.callback != null) {
        if (error != null) {
            ShareInternalUtility.invokeOnErrorCallback(uploadContext.callback, error);
        } else if (uploadContext.isCanceled) {
            ShareInternalUtility.invokeOnCancelCallback(uploadContext.callback);
        } else {
            ShareInternalUtility.invokeOnSuccessCallback(uploadContext.callback, videoId);
        }
    }
}
 
Example 11
Source File: ImageDownloader.java    From aws-mobile-self-paced-labs-samples with Apache License 2.0 5 votes vote down vote up
private static void readFromCache(RequestKey key, Context context, boolean allowCachedRedirects) {
    InputStream cachedStream = null;
    boolean isCachedRedirect = false;
    if (allowCachedRedirects) {
        URL redirectUrl = UrlRedirectCache.getRedirectedUrl(context, key.url);
        if (redirectUrl != null) {
            cachedStream = ImageResponseCache.getCachedImageStream(redirectUrl, context);
            isCachedRedirect = cachedStream != null;
        }
    }

    if (!isCachedRedirect) {
        cachedStream = ImageResponseCache.getCachedImageStream(key.url, context);
    }

    if (cachedStream != null) {
        // We were able to find a cached image.
        Bitmap bitmap = BitmapFactory.decodeStream(cachedStream);
        Utility.closeQuietly(cachedStream);
        issueResponse(key, null, bitmap, isCachedRedirect);
    } else {
        // Once the old downloader context is removed, we are thread-safe since this is the
        // only reference to it
        DownloaderContext downloaderContext = removePendingRequest(key);
        if (downloaderContext != null && !downloaderContext.isCancelled) {
            enqueueDownload(downloaderContext.request, key);
        }
    }
}
 
Example 12
Source File: AppEventsLogger.java    From Abelana-Android with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static void restoreAppSessionInformation(Context context) {
    ObjectInputStream ois = null;

    synchronized (staticLock) {
        if (!isLoaded) {
            try {
                ois =
                        new ObjectInputStream(
                                context.openFileInput(PERSISTED_SESSION_INFO_FILENAME));
                appSessionInfoMap =
                        (HashMap<AccessTokenAppIdPair, FacebookTimeSpentData>) ois.readObject();
                Logger.log(
                        LoggingBehavior.APP_EVENTS,
                        "AppEvents",
                        "App session info loaded");
            } catch (FileNotFoundException fex) {
            } catch (Exception e) {
                Log.d(TAG, "Got unexpected exception: " + e.toString());
            } finally {
                Utility.closeQuietly(ois);
                context.deleteFile(PERSISTED_SESSION_INFO_FILENAME);
                if (appSessionInfoMap == null) {
                    appSessionInfoMap =
                            new HashMap<AccessTokenAppIdPair, FacebookTimeSpentData>();
                }
                // Regardless of the outcome of the load, the session information cache
                // is always deleted. Therefore, always treat the session information cache
                // as loaded
                isLoaded = true;
                hasChanges = false;
            }
        }
    }
}
 
Example 13
Source File: AppEventsLogger.java    From Abelana-Android with Apache License 2.0 5 votes vote down vote up
private void write() {
    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(
                new BufferedOutputStream(context.openFileOutput(PERSISTED_EVENTS_FILENAME, 0)));
        oos.writeObject(persistedEvents);
    } catch (Exception e) {
        Log.d(TAG, "Got unexpected exception: " + e.toString());
    } finally {
        Utility.closeQuietly(oos);
    }
}
 
Example 14
Source File: AppEventsLogger.java    From facebook-api-android-maven with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static void restoreAppSessionInformation(Context context) {
    ObjectInputStream ois = null;

    synchronized (staticLock) {
        if (!isLoaded) {
            try {
                ois =
                        new ObjectInputStream(
                                context.openFileInput(PERSISTED_SESSION_INFO_FILENAME));
                appSessionInfoMap =
                        (HashMap<AccessTokenAppIdPair, FacebookTimeSpentData>) ois.readObject();
                Logger.log(
                        LoggingBehavior.APP_EVENTS,
                        "AppEvents",
                        "App session info loaded");
            } catch (FileNotFoundException fex) {
            } catch (Exception e) {
                Log.d(TAG, "Got unexpected exception: " + e.toString());
            } finally {
                Utility.closeQuietly(ois);
                context.deleteFile(PERSISTED_SESSION_INFO_FILENAME);
                if (appSessionInfoMap == null) {
                    appSessionInfoMap =
                            new HashMap<AccessTokenAppIdPair, FacebookTimeSpentData>();
                }
                // Regardless of the outcome of the load, the session information cache
                // is always deleted. Therefore, always treat the session information cache
                // as loaded
                isLoaded = true;
                hasChanges = false;
            }
        }
    }
}
 
Example 15
Source File: AppEventsLogger.java    From facebook-api-android-maven with Apache License 2.0 5 votes vote down vote up
private void write() {
    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(
                new BufferedOutputStream(context.openFileOutput(PERSISTED_EVENTS_FILENAME, 0)));
        oos.writeObject(persistedEvents);
    } catch (Exception e) {
        Log.d(TAG, "Got unexpected exception: " + e.toString());
    } finally {
        Utility.closeQuietly(oos);
    }
}
 
Example 16
Source File: ImageDownloader.java    From HypFacebook with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static void readFromCache(RequestKey key, Context context, boolean allowCachedRedirects) {
    InputStream cachedStream = null;
    boolean isCachedRedirect = false;
    if (allowCachedRedirects) {
        URL redirectUrl = UrlRedirectCache.getRedirectedUrl(context, key.url);
        if (redirectUrl != null) {
            cachedStream = ImageResponseCache.getCachedImageStream(redirectUrl, context);
            isCachedRedirect = cachedStream != null;
        }
    }

    if (!isCachedRedirect) {
        cachedStream = ImageResponseCache.getCachedImageStream(key.url, context);
    }

    if (cachedStream != null) {
        // We were able to find a cached image.
        Bitmap bitmap = BitmapFactory.decodeStream(cachedStream);
        Utility.closeQuietly(cachedStream);
        issueResponse(key, null, bitmap, isCachedRedirect);
    } else {
        // Once the old downloader context is removed, we are thread-safe since this is the
        // only reference to it
        DownloaderContext downloaderContext = removePendingRequest(key);
        if (downloaderContext != null && !downloaderContext.isCancelled) {
            enqueueDownload(downloaderContext.request, key);
        }
    }
}
 
Example 17
Source File: LikeActionController.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
/**
 * NOTE: This MUST be called ONLY via the SerializeToDiskWorkItem class to ensure that it
 * happens on the right thread, at the right time.
 */
private static void serializeToDiskSynchronously(String cacheKey, String controllerJson) {
    OutputStream outputStream = null;
    try {
        outputStream = controllerDiskCache.openPutStream(cacheKey);
        outputStream.write(controllerJson.getBytes());
    } catch (IOException e) {
        Log.e(TAG, "Unable to serialize controller to disk", e);
    } finally {
        if (outputStream != null) {
            Utility.closeQuietly(outputStream);
        }
    }
}
 
Example 18
Source File: ImageDownloader.java    From FacebookNewsfeedSample-Android with Apache License 2.0 5 votes vote down vote up
private static void readFromCache(RequestKey key, Context context, boolean allowCachedRedirects) {
    InputStream cachedStream = null;
    boolean isCachedRedirect = false;
    if (allowCachedRedirects) {
        URL redirectUrl = UrlRedirectCache.getRedirectedUrl(context, key.url);
        if (redirectUrl != null) {
            cachedStream = ImageResponseCache.getCachedImageStream(redirectUrl, context);
            isCachedRedirect = cachedStream != null;
        }
    }

    if (!isCachedRedirect) {
        cachedStream = ImageResponseCache.getCachedImageStream(key.url, context);
    }

    if (cachedStream != null) {
        // We were able to find a cached image.
        Bitmap bitmap = BitmapFactory.decodeStream(cachedStream);
        Utility.closeQuietly(cachedStream);
        issueResponse(key, null, bitmap, isCachedRedirect);
    } else {
        // Once the old downloader context is removed, we are thread-safe since this is the
        // only reference to it
        DownloaderContext downloaderContext = removePendingRequest(key);
        if (downloaderContext != null && !downloaderContext.isCancelled) {
            enqueueDownload(downloaderContext.request, key);
        }
    }
}