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:cn.moon.superwechat.runtimepermissions.PermissionsManager.java

/**
 * This method adds the {@link PermissionsResultAction} to the current list
 * of pending actions that will be completed when the permissions are
 * received. The list of permissions passed to this method are registered
 * in the PermissionsResultAction object so that it will be notified of changes
 * made to these permissions./*from ww  w .j a va2s  . c  o m*/
 *
 * @param permissions the required permissions for the action to be executed.
 * @param action      the action to add to the current list of pending actions.
 */
private synchronized void addPendingAction(@NonNull String[] permissions,
        @Nullable PermissionsResultAction action) {
    if (action == null) {
        return;
    }
    action.registerPermissions(permissions);
    mPendingActions.add(new WeakReference<PermissionsResultAction>(action));
}

From source file:com.adeptj.runtime.server.Server.java

/**
 * Bootstrap Undertow Server and OSGi Framework.
 *//*w ww.ja  va  2 s . c  o m*/
@Override
public void start() {
    LOGGER.debug("AdeptJ Runtime jvm args: {}", this.runtimeArgs);
    this.cfgReference = new WeakReference<>(Configs.of().undertow());
    Config undertowConf = Objects.requireNonNull(this.cfgReference.get());
    Config httpConf = undertowConf.getConfig(Constants.KEY_HTTP);
    int httpPort = this.handlePortAvailability(httpConf);
    LOGGER.info("Starting AdeptJ Runtime @port: [{}]", httpPort);
    this.printBanner();
    this.deploymentManager = Servlets.newContainer().addDeployment(this.deploymentInfo());
    this.deploymentManager.deploy();
    try {
        this.rootHandler = this.rootHandler(this.deploymentManager.start());
        this.undertow = this
                .enableHttp2(ServerOptions.build(this.workerOptions(Undertow.builder()), undertowConf))
                .addHttpListener(httpPort, httpConf.getString(Constants.KEY_HOST)).setHandler(this.rootHandler)
                .build();
        this.undertow.start();
    } catch (Exception ex) { // NOSONAR
        throw new InitializationException(ex.getMessage(), ex);
    }
    this.createServerConfFile();
}

From source file:WeakReferenceList.java

/**
 * Creates a new reference for the given object.
 *
 * @param o the object.//from   w  w  w.  j av  a  2  s .co  m
 * @return a WeakReference for the object o without any ReferenceQueue attached.
 */
private Reference createReference(final Object o) {
    return new WeakReference(o);
}

From source file:cn.com.loopj.android.http.AsyncHttpResponseHandler.java

@Override
public void setTag(Object TAG) {
    this.TAG = new WeakReference<Object>(TAG);
}

From source file:architecture.ee.component.core.lifecycle.BootstrapImpl.java

@SuppressWarnings("unchecked")
public <T> T getBootstrapComponent(Class<T> requiredType) throws ComponentNotFoundException {
    if (requiredType == null) {
        throw new ComponentNotFoundException();
    }//from www.j  a  va  2 s .co m

    if (requiredType == Repository.class) {
        lock.lock();
        try {
            if (repository.getState() != State.INITIALIZED) {
                repository.initialize();
            }
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }
        return (T) repository;
    }
    if (references.get(requiredType) == null) {
        try {
            if (getBootstrapApplicationContext() == null) {
                throw new IllegalStateException(L10NUtils.getMessage("003051"));
            }
            if (ContextLoader.getCurrentWebApplicationContext() != null) {
                log.debug("searching in current web application context");
                references.put(requiredType, new WeakReference<T>(
                        ContextLoader.getCurrentWebApplicationContext().getBean(requiredType)));
            } else {
                log.debug("searching in bootstrap application context");
                references.put(requiredType,
                        new WeakReference<T>(getBootstrapApplicationContext().getBean(requiredType)));
            }
        } catch (BeansException e) {
            throw new ComponentNotFoundException(L10NUtils.format("003052", requiredType.getName()), e);
        }
    }
    return (T) references.get(requiredType).get();
}

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

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

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

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

        // Load the image header
        image = 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:at.the.gogo.panoramio.panoviewer.ImageManager.java

/**
 * Adds an observer to be notified when the set of items held by this
 * ImageManager changes./*from   w  w  w  . j  a  va2  s.  c  o m*/
 */
public void addObserver(final DataSetObserver observer) {
    final WeakReference<DataSetObserver> obs = new WeakReference<DataSetObserver>(observer);
    mObservers.add(obs);
}

From source file:org.Cherry.Modules.Web.Engine.RequestInterceptor.java

protected User getUser(final HttpRequest request) {
    User result = null;//w  ww . ja  v a2s.c o m

    if (request instanceof HttpEntityEnclosingRequest) {
        final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();

        final long contentLength = entity.getContentLength();

        if (0 < contentLength) {
            WeakReference<InputStream> is;

            try {
                is = new WeakReference<InputStream>(entity.getContent());
            } catch (IllegalStateException | IOException err) {
                throw new IllegalStateException(err);
            }

            try {
                result = getObjectMapperService().readValue(is.get(), User.class);
            } catch (final IOException err) {
                throw new IllegalStateException(err);
            }
        } else
            warn("{}", "Undefined content/length 0! Did the sender missed it?!");
    } else
        throw new IllegalArgumentException("Expected request of type [" + HttpEntityEnclosingRequest.class
                + "] but found [" + request.getClass() + "]");

    return result;
}

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

/**
 * Loads the file header only.//  w  w w.  j av a 2s  . com
 */
protected void loadFileHeader() {
    try {

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

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

        // Load the file header
        file = 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:android.content.res.VectorResources.java

@Override
Drawable loadDrawable(TypedValue value, int id) throws NotFoundException {
    boolean isColorDrawable = false;
    if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
        isColorDrawable = true;/*from ww w .j a  v  a  2 s  . c o m*/
    }
    final long key = isColorDrawable ? value.data : (((long) value.assetCookie) << 32) | value.data;

    Drawable dr = getCachedDrawable(isColorDrawable ? mColorDrawableCache : mDrawableCache, key);

    if (dr != null) {
        return dr;
    }

    if (isColorDrawable) {
        dr = new ColorDrawable(value.data);
    }

    if (dr == null) {
        if (value.string == null) {
            throw new NotFoundException("Resource is not a Drawable (color or path): " + value);
        }

        String file = value.string.toString();

        if (file.endsWith(".xml")) {
            // Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
            try {
                XmlResourceParser rp = getXml(id);
                // XmlResourceParser rp = loadXmlResourceParser(
                //         file, id, value.assetCookie, "drawable");
                dr = createDrawableFromXml(rp);
                rp.close();
            } catch (Exception e) {
                // Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
                NotFoundException rnf = new NotFoundException(
                        "File " + file + " from drawable resource ID #0x" + Integer.toHexString(id));
                rnf.initCause(e);
                throw rnf;
            }
            // Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);

        } else {
            // Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
            try {
                InputStream is = openRawResource(id, value);
                //InputStream is = mAssets.openNonAsset(
                //        value.assetCookie, file, AssetManager.ACCESS_STREAMING);
                //                System.out.println("Opened file " + file + ": " + is);
                dr = Drawable.createFromResourceStream(this, value, is, file, null);
                is.close();
                //                System.out.println("Created stream: " + dr);
            } catch (Exception e) {
                // Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
                NotFoundException rnf = new NotFoundException(
                        "File " + file + " from drawable resource ID #0x" + Integer.toHexString(id));
                rnf.initCause(e);
                throw rnf;
            }
            // Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
        }
    }
    Drawable.ConstantState cs;
    if (dr != null) {
        dr.setChangingConfigurations(value.changingConfigurations);
        cs = dr.getConstantState();
        if (cs != null) {
            synchronized (mAccessLock) {
                //Log.i(TAG, "Saving cached drawable @ #" +
                //        Integer.toHexString(key.intValue())
                //        + " in " + this + ": " + cs);
                if (isColorDrawable) {
                    mColorDrawableCache.put(key, new WeakReference<Drawable.ConstantState>(cs));
                } else {
                    mDrawableCache.put(key, new WeakReference<Drawable.ConstantState>(cs));
                }
            }
        }
    }

    return dr;
}