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:com.activiti.android.ui.fragments.AlfrescoFragment.java

public void displayWaiting(int contentId) {
    dialogRef = new WeakReference<>(new MaterialDialog.Builder(getActivity()).title(R.string.please_wait)
            .content(contentId).progress(true, 0).show());
}

From source file:com.honeywell.printer.net.autobaln_websocket.WebSocketConnection.java

public void connect(URI webSocketURI, String[] subprotocols, ConnectionHandler connectionObserver,
        WebSocketOptions options) throws WebSocketException {
    if (isConnected()) {
        throw new WebSocketException("already connected");
    }/*from  w w  w. j a v a  2 s .  co m*/

    if (webSocketURI == null) {
        throw new WebSocketException("WebSockets URI null.");
    } else {
        this.mWebSocketURI = webSocketURI;
        if (!mWebSocketURI.getScheme().equals(WS_URI_SCHEME)
                && !mWebSocketURI.getScheme().equals(WSS_URI_SCHEME)) {
            throw new WebSocketException("unsupported scheme for WebSockets URI");
        }

        this.mWebSocketSubprotocols = subprotocols;
        this.mWebSocketConnectionObserver = new WeakReference<ConnectionHandler>(connectionObserver);
        this.mWebSocketOptions = new WebSocketOptions(options);

        connect();
    }
}

From source file:net.sf.mcf2pdf.mcfelements.util.ImageUtil.java

/**
 * Loads the given CLP or SVG file and creates a BufferedImage with the given dimensions. As CLP files contain Vector images,
 * they can be scaled to every size needed. The contents are scaled to the given width and height, <b>not</b> preserving any
 * ratio of the image./*from   w  w w.ja  va2 s. c om*/
 *
 * @param clpFile CLP or SVG file.
 * @param widthPixel The width, in pixels, the resulting image shall have.
 * @param heightPixel The height, in pixels, the resulting image shall have.
 *
 * @return An image displaying the contents of the loaded CLP file.
 *
 * @throws IOException If any I/O related problem occurs reading the file.
 */
public static BufferedImage loadClpFile(File clpFile, int widthPixel, int heightPixel) throws IOException {
    FileInputStream fis = new FileInputStream(clpFile);
    ClpInputStream cis = null;
    InputStream in = clpFile.getName().toLowerCase().endsWith(".clp") ? (cis = new ClpInputStream(fis)) : fis;

    UserAgentAdapter userAgentAdapter = new UserAgentAdapter();
    BridgeContext bridgeContext = new BridgeContext(userAgentAdapter);

    SVGDocument svgDocument;
    GraphicsNode rootSvgNode;
    try {
        String parser = XMLResourceDescriptor.getXMLParserClassName();
        SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser);
        svgDocument = (SVGDocument) factory.createDocument(clpFile.toURI().toString(),
                new InputStreamReader(in, "ISO-8859-1"));
        rootSvgNode = getRootNode(svgDocument, bridgeContext);
    } finally {
        IOUtils.closeQuietly(cis);
        IOUtils.closeQuietly(fis);
    }

    float[] vb = ViewBox.parseViewBoxAttribute(svgDocument.getRootElement(),
            svgDocument.getRootElement().getAttribute("viewBox"), bridgeContext);

    AffineTransform usr2dev = ViewBox.getPreserveAspectRatioTransform(vb,
            SVGPreserveAspectRatio.SVG_PRESERVEASPECTRATIO_NONE, true, widthPixel, heightPixel);

    BufferedImage img = new BufferedImage(widthPixel, heightPixel, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = img.createGraphics();

    g2d.setColor(new Color(0.0f, 0.0f, 0.0f, 0.0f));
    g2d.fillRect(0, 0, widthPixel, heightPixel);
    g2d.transform(usr2dev);

    // fixes "Graphics2D from BufferedImage lacks BUFFERED_IMAGE hint" - part 1
    final Object oldBufferedImage = g2d.getRenderingHint(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE);
    g2d.setRenderingHint(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE, new WeakReference<BufferedImage>(img));
    rootSvgNode.paint(g2d);
    // fixes "Graphics2D from BufferedImage lacks BUFFERED_IMAGE hint" - part 2
    if (oldBufferedImage != null)
        g2d.setRenderingHint(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE, oldBufferedImage);
    else
        g2d.getRenderingHints().remove(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE);

    g2d.dispose();
    return img;
}

From source file:com.finchuk.clock2.stopwatch.ui.StopwatchFragment.java

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // TOneverDO: Move to onCreate(). When the device rotates, onCreate() _is_ called,
    // but trying to find the FAB in the Activity's layout will fail, and we would get back
    // a null reference. This is probably because this Fragment's onCreate() is called
    // BEFORE the Activity's onCreate.
    // TODO: Any better alternatives to control the Activity's FAB from here?
    mActivityFab = new WeakReference<>((FloatingActionButton) getActivity().findViewById(R.id.fab));
    // There is no documentation for isMenuVisible(), so what exactly does it do?
    // My guess is it checks for the Fragment's options menu. But we never initialize this
    // Fragment with setHasOptionsMenu(), let alone we don't actually inflate a menu in here.
    // My guess is when this Fragment becomes actually visible, it "hooks" onto the menu
    // options "internal API" and inflates its menu in there if it has one.
    ///*  www.  ja va2  s  . c  om*/
    // To us, this just makes for a very good visibility check.
    if (savedInstanceState != null && isMenuVisible()) {
        // This is a pretty good indication that we just rotated.
        // isMenuVisible() filters out the case when you rotate on page 1 and scroll
        // to page 2, the icon will prematurely change; that happens because at page 2,
        // this Fragment will be instantiated for the first time for the current configuration,
        // and so the lifecycle from onCreate() to onActivityCreated() occurs. As such,
        // we will have a non-null savedInstanceState and this would call through.
        //
        // The reason when you open up the app for the first time and scrolling to page 2
        // doesn't prematurely change the icon is the savedInstanceState is null, and so
        // this call would be filtered out sufficiently just from the first check.
        syncFabIconWithStopwatchState(isStopwatchRunning());
    }
}

From source file:cc.osint.graphd.server.GraphServerHandler.java

@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    String clientId = "" + e.getChannel().getId();
    if (null == clientStateMap.get(clientId)) {
        ConcurrentHashMap<String, String> clientState = new ConcurrentHashMap<String, String>();
        clientState.put(ST_NAMECON, DEFAULT_CONNECTION_NAME + "-" + clientId);
        clientStateMap.put(clientId, clientState);
        clientIdChannelMap.put(clientId, e.getChannel());

        /*//from  w w w .  ja v  a 2 s.co m
         * start "client fiber & channel" & connect them
        */
        Fiber fiber = fiberFactory.create();
        fiber.start();
        org.jetlang.channels.Channel<JSONObject> inboundChannel = new MemoryChannel<JSONObject>();
        InboundChannelProcess inboundChannelProcess = new InboundChannelProcess(clientId, fiber, inboundChannel, // jetlang channel
                e.getChannel()); // netty channel
        inboundChannelMap.put(clientId, new WeakReference<InboundChannelProcess>(inboundChannelProcess));

        log.info(clientId + ": " + inboundChannelMap.get(clientId));

        inboundChannel.subscribe(fiber, inboundChannelProcess);
    }
    e.getChannel().write("-graphd " + InetAddress.getLocalHost().getHostName() + GraphServerProtocol.SPACE
            + clientId + GraphServerProtocol.NL);
}

From source file:io.kristal.locationplugin.LocationPlugin.java

/***********************************************************************************************
 *
 * COBALT//from ww w .j a v  a 2 s . co  m
 *
 **********************************************************************************************/

@Override
public void onMessage(CobaltPluginWebContainer webContainer, JSONObject message) {
    try {
        String action = message.getString(Cobalt.kJSAction);

        switch (action) {
        case JSActionStartLocation:
            JSONObject data = message.getJSONObject(Cobalt.kJSData);
            mMode = data.getString(kJSMode);
            if (!(MODE_ALL.equals(mMode) || MODE_FILTER.equals(mMode))) {
                throw new JSONException(TAG + " - onMessage: unknown mode " + mMode);
            }
            mAccuracy = (float) data.optDouble(kJSAccuracy, ACCURACY_DEFAULT_VALUE);
            mFrequency = data.optLong(kJSFrequency, FREQUENCY_DEFAULT_VALUE);
            mTimeout = data.optLong(kJSTimeout, TIMEOUT_DEFAULT_VALUE);
            mTimestamp = data.optLong(kJSTimestamp, TIMESTAMP_DEFAULT_VALUE);

            mActivity = new WeakReference<>(webContainer.getActivity());
            mFragment = new WeakReference<>(webContainer.getFragment());

            Activity activity = mActivity.get();
            if (activity != null) {
                getActiveProviders(activity);
                if (mProviders.size() != 0) {
                    requestLocationPermission(activity);
                } else {
                    sendStatus(STATUS_DISABLED);
                }
            }
            break;
        case JSActionStopLocation:
            stopLocationUpdates();
            break;
        default:
            if (Cobalt.DEBUG) {
                Log.d(TAG, "onMessage: unknown action " + action);
            }
            break;
        }
    } catch (JSONException exception) {
        if (Cobalt.DEBUG) {
            Log.d(TAG,
                    "onMessage: action field missing or is not a string or data field is missing or is not an object. "
                            + message.toString());
        }
        exception.printStackTrace();
    }
}

From source file:com.appassit.common.Utils.java

public static String formatDate(long time) {
    if (calendar == null || calendar.get() == null) {
        calendar = new WeakReference<Calendar>(Calendar.getInstance());
    }/*from ww w  . j  av  a 2  s.  com*/
    Calendar target = calendar.get();
    target.setTimeInMillis(time);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    return sdf.format(target.getTime());
}

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

protected Object getBeanParameter(final RequestCommand command, final Class<?> beanParameterType)
        throws JsonParseException, JsonMappingException, IOException {
    Object result = null;/*  w ww . j  av a2s  . co m*/

    final HttpRequest request = command.getRequest();

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

        final long contentLength = entity.getContentLength();

        if (0 < contentLength) {
            final WeakReference<InputStream> is = new WeakReference<InputStream>(entity.getContent());

            if (0 < is.get().available())
                result = getObjectMapperService().readValue(is.get(), beanParameterType);
        } 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:com.partytv.server.ImageManager.java

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

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

/**
 * Loads the image body only.//from  www. j a  v  a  2s  .  c  o m
 */
protected void loadImageBody() {
    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);
        }

        // Load the image body
        image = reader.readBody(IOUtils.toInputStream(imageXml, "utf-8"), uri.getSite());
        isBodyLoaded = true;
        if (isHeaderLoaded && isBodyLoaded)
            cleanupAfterLoading();
        else if (headerXml != null)
            imageXml = null;

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