Example usage for java.lang.ref WeakReference WeakReference

List of usage examples for java.lang.ref WeakReference WeakReference

Introduction

In this page you can find the example usage for java.lang.ref WeakReference WeakReference.

Prototype

public WeakReference(T referent) 

Source Link

Document

Creates a new weak reference that refers to the given object.

Usage

From source file:net.sourceforge.checkstyle4ada.filters.AdaBlockSuppressionCommentFilter.java

/**
 * Set the FileContents for this filter.
 * @param aFileContents the FileContents for this filter.
 *//*from  w  ww  . j  a v  a 2 s .c om*/
public void setFileContents(FileContents aFileContents) {
    mFileContentsReference = new WeakReference(aFileContents);
}

From source file:net.jodah.typetools.TypeResolver.java

private static Map<TypeVariable<?>, Type> getTypeVariableMap(final Class<?> targetType,
        Class<?> functionalInterface) {
    Reference<Map<TypeVariable<?>, Type>> ref = typeVariableCache.get(targetType);
    Map<TypeVariable<?>, Type> map = ref != null ? ref.get() : null;

    if (map == null) {
        map = new HashMap<TypeVariable<?>, Type>();

        // Populate lambdas
        if (functionalInterface != null)
            populateLambdaArgs(functionalInterface, targetType, map);

        // Populate interfaces
        populateSuperTypeArgs(targetType.getGenericInterfaces(), map, functionalInterface != null);

        // Populate super classes and interfaces
        Type genericType = targetType.getGenericSuperclass();
        Class<?> type = targetType.getSuperclass();
        while (type != null && !Object.class.equals(type)) {
            if (genericType instanceof ParameterizedType)
                populateTypeArgs((ParameterizedType) genericType, map, false);
            populateSuperTypeArgs(type.getGenericInterfaces(), map, false);

            genericType = type.getGenericSuperclass();
            type = type.getSuperclass();
        }//from   w w w. ja  va  2  s  .c o  m

        // Populate enclosing classes
        type = targetType;
        while (type.isMemberClass()) {
            genericType = type.getGenericSuperclass();
            if (genericType instanceof ParameterizedType)
                populateTypeArgs((ParameterizedType) genericType, map, functionalInterface != null);

            type = type.getEnclosingClass();
        }

        if (CACHE_ENABLED)
            typeVariableCache.put(targetType, new WeakReference<Map<TypeVariable<?>, Type>>(map));
    }

    return map;
}

From source file:org.taverna.server.master.TavernaServer.java

@Override
@CallCounted//from w ww.j  av  a2s  . co m
@PerfLogged
@RolesAllowed(USER)
public Response submitWorkflowByURL(List<URI> referenceList, UriInfo ui) throws NoCreateException {
    jaxrsUriInfo.set(new WeakReference<>(ui));
    if (referenceList == null || referenceList.size() == 0)
        throw new NoCreateException("no workflow URI supplied");
    URI workflowURI = referenceList.get(0);
    checkCreatePolicy(workflowURI);
    Workflow workflow;
    try {
        workflow = support.getWorkflowDocumentFromURI(workflowURI);
    } catch (IOException e) {
        throw new NoCreateException("could not read workflow", e);
    }
    String name = support.buildWorkflow(workflow);
    return created(secure(ui).path("{uuid}").build(name)).build();
}

From source file:com.icesoft.faces.async.render.GroupAsyncRenderer.java

private void add(final Object object) {
    // todo: remove synchronized block as CopyOnWriteArraySet is used?
    synchronized (group) {
        if (!contains(object)) {
            if (group.add(new WeakReference(object))) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace(name + " added " + object);
                }/*w  ww. j a v  a 2 s .  c o m*/
            } else {
                if (LOG.isWarnEnabled()) {
                    LOG.warn(name + " already contains " + object);
                }
            }
        }
    }
}

From source file:com.digium.respokesdk.RespokeEndpoint.java

/**
 *  Associate a direct connection object with this endpoint. This method is used internally by the SDK should not be called by your client application.
 *
 *  @param newDirectConnection  The direct connection to associate
 *///from   www  .  ja  va 2 s.co m
public void setDirectConnection(RespokeDirectConnection newDirectConnection) {
    if (null != newDirectConnection) {
        directConnectionReference = new WeakReference<RespokeDirectConnection>(newDirectConnection);
    } else {
        directConnectionReference = null;
    }
}

From source file:android.support.v7.widget.XpAppCompatCompoundDrawableHelper.java

private Drawable resolveDrawable(TintTypedArray a, int resIndex, int index) {
    int resId = a.getResourceId(resIndex, 0);
    if (resId != 0) {
        final Drawable d = a.getDrawable(resIndex);
        final ColorStateList tint = mDrawableManager != null
                ? mDrawableManager.getTintList(mView.getContext(), resId)
                : null;/*from w ww  . j  a  v a  2s  . co m*/
        setInternalTint(d, tint, index);
        if (d != null) {
            DrawableUtils.fixDrawable(d);
        }
        mDrawables.put(index, new WeakReference<>(d));
        return d;
    } else {
        setInternalTint(null, null, index);
        mDrawables.put(index, new WeakReference<Drawable>(null));
        return null;
    }
}

From source file:com.polyvi.xface.http.XHttpWorker.java

/**
 * ??http//from w ww  .j a v a  2  s .  c  o  m
 *
 * @param request
 * @param contentType
 * @param handler
 */
private void doHttpRequest(HttpUriRequest request, String contentType, XAsyncHttpResponseHandler handler) {
    if (contentType != null) {
        request.addHeader("Content-Type", contentType);
    }
    if (handler.isAsync()) {
        Future<?> task = mThreadPool.submit(new XAsyncHttpRequest(mHttpClient, mHttpContext, request, handler));
        mRequestList.add(new WeakReference<Future<?>>(task));
    } else {
        new XAsyncHttpRequest(mHttpClient, mHttpContext, request, handler).run();
    }

}

From source file:cat.ereza.customactivityoncrash.CustomActivityOnCrash.java

/**
 * Installs CustomActivityOnCrash on the application using the default error activity.
 *
 * @param context Context to use for obtaining the ApplicationContext. Must not be null.
 *//* w  w  w  .  ja  v  a  2s. co  m*/
public static void install(Context context) {
    try {
        if (context == null) {
            Log.e(TAG, "Install failed: context is null!");
        } else {
            if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                Log.w(TAG,
                        "CustomActivityOnCrash will be installed, but may not be reliable in API lower than 14");
            }

            //INSTALL!
            final Thread.UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler();

            if (oldHandler != null && oldHandler.getClass().getName().startsWith(CAOC_HANDLER_PACKAGE_NAME)) {
                Log.e(TAG, "You have already installed CustomActivityOnCrash, doing nothing!");
            } else {
                if (oldHandler != null
                        && !oldHandler.getClass().getName().startsWith(DEFAULT_HANDLER_PACKAGE_NAME)) {
                    Log.e(TAG,
                            "IMPORTANT WARNING! You already have an UncaughtExceptionHandler, are you sure this is correct? If you use ACRA, Crashlytics or similar libraries, you must initialize them AFTER CustomActivityOnCrash! Installing anyway, but your original handler will not be called.");
                }

                application = (Application) context.getApplicationContext();

                //We define a default exception handler that does what we want so it can be called from Crashlytics/ACRA
                Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                    @Override
                    public void uncaughtException(Thread thread, final Throwable throwable) {
                        Log.e(TAG,
                                "App has crashed, executing CustomActivityOnCrash's UncaughtExceptionHandler",
                                throwable);

                        if (hasCrashedInTheLastSeconds(application)) {
                            Log.e(TAG,
                                    "App already crashed in the last 2 seconds, not starting custom error activity because we could enter a restart loop. Are you sure that your app does not crash directly on init?",
                                    throwable);
                            if (oldHandler != null) {
                                oldHandler.uncaughtException(thread, throwable);
                                return;
                            }
                        } else {
                            setLastCrashTimestamp(application, new Date().getTime());

                            if (errorActivityClass == null) {
                                errorActivityClass = guessErrorActivityClass(application);
                            }

                            if (isStackTraceLikelyConflictive(throwable, errorActivityClass)) {
                                Log.e(TAG,
                                        "Your application class or your error activity have crashed, the custom activity will not be launched!");
                                if (oldHandler != null) {
                                    oldHandler.uncaughtException(thread, throwable);
                                    return;
                                }
                            } else if (launchErrorActivityWhenInBackground || !isInBackground) {

                                final Intent intent = new Intent(application, errorActivityClass);
                                StringWriter sw = new StringWriter();
                                PrintWriter pw = new PrintWriter(sw);
                                throwable.printStackTrace(pw);
                                String stackTraceString = sw.toString();

                                //Reduce data to 128KB so we don't get a TransactionTooLargeException when sending the intent.
                                //The limit is 1MB on Android but some devices seem to have it lower.
                                //See: http://developer.android.com/reference/android/os/TransactionTooLargeException.html
                                //And: http://stackoverflow.com/questions/11451393/what-to-do-on-transactiontoolargeexception#comment46697371_12809171
                                if (stackTraceString.length() > MAX_STACK_TRACE_SIZE) {
                                    String disclaimer = " [stack trace too large]";
                                    stackTraceString = stackTraceString.substring(0,
                                            MAX_STACK_TRACE_SIZE - disclaimer.length()) + disclaimer;
                                }

                                if (enableAppRestart && restartActivityClass == null) {
                                    //We can set the restartActivityClass because the app will terminate right now,
                                    //and when relaunched, will be null again by default.
                                    restartActivityClass = guessRestartActivityClass(application);
                                } else if (!enableAppRestart) {
                                    //In case someone sets the activity and then decides to not restart
                                    restartActivityClass = null;
                                }

                                String userLogString = "";
                                while (!userLogs.isEmpty()) {
                                    userLogString += userLogs.poll();
                                }

                                intent.putExtra(EXTRA_STACK_TRACE, stackTraceString);
                                intent.putExtra(EXTRA_USER_ACTION_TRACE, userLogString);
                                intent.putExtra(EXTRA_RESTART_ACTIVITY_CLASS, restartActivityClass);
                                intent.putExtra(EXTRA_SHOW_ERROR_DETAILS, showErrorDetails);
                                intent.putExtra(EXTRA_EVENT_LISTENER, eventListener);
                                intent.putExtra(EXTRA_IMAGE_DRAWABLE_ID, defaultErrorActivityDrawableId);
                                intent.setFlags(
                                        Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                if (eventListener != null) {
                                    eventListener.onLaunchErrorActivity();
                                }
                                application.startActivity(intent);
                            }
                        }
                        final Activity lastActivity = lastActivityCreated.get();
                        if (lastActivity != null) {
                            //We finish the activity, this solves a bug which causes infinite recursion.
                            //This is unsolvable in API<14, so beware!
                            //See: https://github.com/ACRA/acra/issues/42
                            lastActivity.finish();
                            lastActivityCreated.clear();
                        }
                        killCurrentProcess();
                    }
                });
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                    application
                            .registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
                                int currentlyStartedActivities = 0;
                                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

                                @Override
                                public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                                    if (activity.getClass() != errorActivityClass) {
                                        // Copied from ACRA:
                                        // Ignore activityClass because we want the last
                                        // application Activity that was started so that we can
                                        // explicitly kill it off.
                                        lastActivityCreated = new WeakReference<>(activity);
                                    }
                                    userLogs.add(dateFormat.format(new Date()) + " "
                                            + activity.getLocalClassName() + " created\n");
                                }

                                @Override
                                public void onActivityStarted(Activity activity) {
                                    currentlyStartedActivities++;
                                    isInBackground = (currentlyStartedActivities == 0);
                                    //Do nothing
                                }

                                @Override
                                public void onActivityResumed(Activity activity) {
                                    userLogs.add(dateFormat.format(new Date()) + " "
                                            + activity.getLocalClassName() + " resumed\n");
                                }

                                @Override
                                public void onActivityPaused(Activity activity) {
                                    userLogs.add(dateFormat.format(new Date()) + " "
                                            + activity.getLocalClassName() + " paused\n");
                                }

                                @Override
                                public void onActivityStopped(Activity activity) {
                                    //Do nothing
                                    currentlyStartedActivities--;
                                    isInBackground = (currentlyStartedActivities == 0);
                                }

                                @Override
                                public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                                    //Do nothing
                                }

                                @Override
                                public void onActivityDestroyed(Activity activity) {
                                    userLogs.add(dateFormat.format(new Date()) + " "
                                            + activity.getLocalClassName() + " destroyed\n");
                                }
                            });
                }

                Log.i(TAG, "CustomActivityOnCrash has been installed.");
            }
        }
    } catch (Throwable t) {
        Log.e(TAG,
                "An unknown error occurred while installing CustomActivityOnCrash, it may not have been properly initialized. Please report this as a bug if needed.",
                t);
    }
}

From source file:com.apptentive.android.sdk.module.engagement.interaction.fragment.MessageCenterFragment.java

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    hostingActivityRef = new WeakReference<Activity>((Activity) context);
    messagingActionHandler = new MessageCenterFragment.MessagingActionHandler(this);
}

From source file:cn.com.wo.bitmap.ImageCache.java

/**
 * Adds a bitmap to both memory and disk cache.
 * @param data Unique identifier for the bitmap to store
 * @param value The bitmap drawable to store
 */// w  ww.j  a v a  2s  . c o m
public void addBitmapToCache(String data, BitmapDrawable value) {
    if (data == null || value == null) {
        return;
    }

    // Add to memory cache
    if (mMemoryCache != null) {
        if (RecyclingBitmapDrawable.class.isInstance(value)) {
            // The removed entry is a recycling drawable, so notify it 
            // that it has been added into the memory cache
            ((RecyclingBitmapDrawable) value).setIsCached(true);
        }
        mMemoryCache.put(data, new WeakReference<BitmapDrawable>(value));
    }

    synchronized (mDiskCacheLock) {
        // Add to disk cache
        if (mDiskLruCache != null) {
            final String key = hashKeyForDisk(data);
            OutputStream out = null;
            try {
                DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);
                if (snapshot == null) {
                    final DiskLruCache.Editor editor = mDiskLruCache.edit(key);
                    if (editor != null) {
                        out = editor.newOutputStream(DISK_CACHE_INDEX);
                        value.getBitmap().compress(mCacheParams.compressFormat, mCacheParams.compressQuality,
                                out);
                        editor.commit();
                        out.close();
                    }
                } else {
                    snapshot.getInputStream(DISK_CACHE_INDEX).close();
                }
            } catch (final IOException e) {
                if (ImageFetcher.isDebug)
                    Log.d(ImageFetcher.TAG, "ImageCache addBitmapToCache - " + e);
            } catch (Exception e) {
                if (ImageFetcher.isDebug)
                    Log.d(ImageFetcher.TAG, "ImageCache addBitmapToCache - " + e);
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {
                }
            }
        }
    }
}