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:ch.entwine.weblounge.common.impl.content.movie.LazyMovieResourceImpl.java

/**
 * Loads the audio visual header only.//from   ww  w.ja  v  a2s  .c om
 */
protected void loadAudioVisualHeader() {
    try {

        // Get a hold of the audio visual reader
        MovieResourceReader reader = (readerRef != null) ? readerRef.get() : null;
        if (reader == null) {
            reader = new MovieResourceReader();
            readerRef = new WeakReference<MovieResourceReader>(reader);
        }

        // If no separate header was given, then we need to load the whole thing
        // instead.
        if (headerXml == null) {
            loadAudioVisual();
            return;
        }

        // Load the audio visual header
        audioVisual = reader.readHeader(IOUtils.toInputStream(headerXml, "utf-8"), uri.getSite());
        isHeaderLoaded = true;
        if (isHeaderLoaded && isBodyLoaded)
            cleanupAfterLoading();
        else
            headerXml = null;

    } catch (Throwable e) {
        logger.error("Failed to lazy-load header of {}", uri);
        throw new IllegalStateException(e);
    }
}

From source file:com.berniesanders.fieldthebern.views.MapScreenView.java

private void injectSelf(Context context) {
    //This is a hack to safely get a reference to the activity.
    //Flow is internally already passing around the references in a private Map<Path,Context>
    //So we use a little hacky reflection tool to steal the activity ref
    //but hold it in a weak ref
    //TODO: we could probably change this to a "controller"
    PathContext pathContext = (PathContext) context;
    Map<Path, Context> contextMap = new HashMap<>();
    try {/*w w  w  . ja  v a2 s  . co  m*/
        contextMap = (Map<Path, Context>) FieldUtils.readDeclaredField(context, "contexts", true);
    } catch (IllegalAccessException e) {
        Timber.e(e, "error reading path contexts...");
        e.printStackTrace();
    }

    for (Context ctx : contextMap.values()) {
        if (ctx instanceof Activity) {
            Timber.v("We found an activity!");
            activityWeakReference = new WeakReference<>((Activity) ctx);
        }
    }

    DaggerService.<MapScreen.Component>getDaggerComponent(context, DaggerService.DAGGER_SERVICE).inject(this);
}

From source file:com.puppycrawl.tools.checkstyle.filters.SuppressionCommentFilter.java

/**
 * Set the FileContents for this filter.
 * @param fileContents the FileContents for this filter.
 *///w w  w .j  a  va  2  s  .  com
public void setFileContents(FileContents fileContents) {
    fileContentsReference = new WeakReference<>(fileContents);
}

From source file:co.com.parsoniisolutions.custombottomsheetbehavior.lib.behaviors.BackdropBottomSheetBehavior.java

/**
 * Look into the CoordiantorLayout for the {@link BottomSheetBehaviorGoogleMapsLike}
 * @param coordinatorLayout with app:layout_behavior= {@link BottomSheetBehaviorGoogleMapsLike}
 *//*w  ww. ja v a2  s .c  o  m*/
private void getBottomSheetBehavior(@NonNull CoordinatorLayout coordinatorLayout) {

    for (int i = 0; i < coordinatorLayout.getChildCount(); i++) {
        View child = coordinatorLayout.getChildAt(i);

        if (child instanceof NestedScrollingParent) {

            try {
                BottomSheetBehaviorGoogleMapsLike temp = BottomSheetBehaviorGoogleMapsLike.from(child);
                mBottomSheetBehaviorRef = new WeakReference<>(temp);
                break;
            } catch (IllegalArgumentException e) {
            }
        }
    }
}

From source file:ch.entwine.weblounge.common.impl.content.page.LazyPageImpl.java

/**
 * Loads the page header only.//ww  w .j  a  v  a 2s . c  o  m
 */
protected void loadPageHeader() {
    try {

        // Get a hold of the page reader
        PageReader reader = (readerRef != null) ? readerRef.get() : null;
        if (reader == null) {
            reader = new PageReader();
            readerRef = new WeakReference<PageReader>(reader);
        }

        // If no separate header was given, then we need to load the whole thing
        // instead.
        if (headerXml == null) {
            loadPage();
            return;
        }

        // Load the page header
        page = reader.readHeader(IOUtils.toInputStream(headerXml, "utf-8"), uri.getSite());
        isHeaderLoaded = true;
        if (isHeaderLoaded && isBodyLoaded)
            cleanupAfterLoading();
        else
            headerXml = null;

    } catch (Throwable e) {
        logger.error("Failed to lazy-load header of {}", uri);
        throw new IllegalStateException(e);
    }
}

From source file:com.google.blockly.model.BlockFactory.java

/**
 * Creates a block of the specified type using one of the master blocks known to this factory.
 * If the prototypeName is not one of the known block types null will be returned instead.
 *
 * @param prototypeName The name of the block type to create.
 * @param uuid The id of the block if loaded from XML; null otherwise.
 *
 * @return A new block of that type or null.
 *///from w  ww.java2 s  .  c  o m
public Block obtainBlock(String prototypeName, @Nullable String uuid) {
    // First search for any existing instance
    Block block;
    if (uuid != null) {
        WeakReference<Block> ref = mBlockRefs.get(uuid);
        if (ref != null) {
            block = ref.get();
            if (block != null) {
                throw new IllegalArgumentException(
                        "Block with given UUID \"" + uuid + "\" already exists. Duplicate UUIDs not allowed.");
            }
        }
    }

    // Existing instance not found.  Constructing a new one.
    if (!mBlockTemplates.containsKey(prototypeName)) {
        Log.w(TAG, "Block " + prototypeName + " not found.");
        return null;
    }
    Block.Builder builder = new Block.Builder(mBlockTemplates.get(prototypeName));
    if (uuid != null) {
        builder.setUuid(uuid);
    }
    block = builder.build();
    mBlockRefs.put(block.getId(), new WeakReference<Block>(block));
    return block;
}

From source file:ch.entwine.weblounge.common.impl.content.page.PageReader.java

/**
 * This method is called when a <code>Page</code> object is instantiated.
 * /*from w w  w. j  a va  2s  .  c o m*/
 * @param is
 *          the xml input stream
 * @param site
 *          the page's site
 * @throws ParserConfigurationException
 *           if the SAX parser setup failed
 * @throws IOException
 *           if reading the input stream fails
 * @throws SAXException
 *           if an error occurs while parsing
 */
public PageImpl readHeader(InputStream is, Site site)
        throws SAXException, IOException, ParserConfigurationException {
    if (page == null) {
        page = new PageImpl(new PageURIImpl(site, "/"));
    }
    readHeader = true;
    readBody = false;
    SAXParser parser = parserRef.get();
    if (parser == null) {
        parser = parserFactory.newSAXParser();
        parserRef = new WeakReference<SAXParser>(parser);
    }
    parser.parse(is, this);
    return page;
}

From source file:com.gh.bmd.jrt.android.v4.core.DefaultObjectContextRoutineBuilder.java

/**
 * Constructor./*from w  w w.j ava2  s .c  o m*/
 *
 * @param context     the routine context.
 * @param targetClass the target object class.
 * @throws java.lang.NullPointerException if any of the parameter is null.
 */
@SuppressWarnings("ConstantConditions")
private DefaultObjectContextRoutineBuilder(@Nonnull final Object context, @Nonnull final Class<?> targetClass) {

    if (context == null) {

        throw new NullPointerException("the routine context must not be null");
    }

    mContext = new WeakReference<Object>(context);
    mTargetClass = targetClass;
    final HashSet<String> bindingSet = new HashSet<String>();

    for (final Method method : targetClass.getMethods()) {

        final Bind annotation = method.getAnnotation(Bind.class);

        if (annotation != null) {

            final String name = annotation.value();

            if (bindingSet.contains(name)) {

                throw new IllegalArgumentException(
                        "the name '" + name + "' has already been used to identify a different" + " method");
            }

            bindingSet.add(name);
        }
    }
}

From source file:edu.unc.lib.dl.cdr.services.model.FailedEnhancementMap.java

/**
 * Retrieves the FailedEnhancementEntry matching pid and service name, either from the cache or from disk.
 * //from w  ww .jav a 2s.  c  om
 * @param pid
 * @param serviceName
 * @return
 */
public synchronized FailedEnhancementEntry get(String pid, String serviceName) {
    Map<String, WeakReference<FailedEnhancementEntry>> cache = this.pidToService.get(pid);
    // Either the enhancement hasn't failed or the map is out of sync, lets be optimistic and say its not there
    if (cache == null)
        return null;
    WeakReference<FailedEnhancementEntry> entryRef = cache.get(serviceName);
    if (entryRef != null && entryRef.get() != null)
        return entryRef.get();

    // Entry isn't in the cache, retrieve it from the file system
    FailedEnhancementEntry entry;
    try {
        entry = this.deserializeFailure(pid, serviceName);
    } catch (IOException e) {
        return null;
    }
    entryRef = new WeakReference<FailedEnhancementEntry>(entry);
    cache.put(serviceName, entryRef);

    this.serviceToPID.get(serviceName).put(pid, entryRef);
    return entry;
}

From source file:ch.entwine.weblounge.common.impl.content.AbstractResourceReaderImpl.java

/**
 * This method is called to read the head section of a resource.
 * //from   w w  w. j av  a 2  s  .co  m
 * @param is
 *          the xml input stream
 * @param site
 *          the site
 * @throws ParserConfigurationException
 *           if the SAX parser setup failed
 * @throws IOException
 *           if reading the input stream fails
 * @throws SAXException
 *           if an error occurs while parsing
 */
public T readHeader(InputStream is, Site site) throws SAXException, IOException, ParserConfigurationException {
    if (resource == null) {
        resource = createResource(site);
    }
    readHeader = true;
    readBody = false;
    SAXParser parser = parserRef.get();
    if (parser == null) {
        parser = parserFactory.newSAXParser();
        parserRef = new WeakReference<SAXParser>(parser);
    }
    parser.parse(is, this);
    return resource;
}