Example usage for java.util LinkedList removeFirst

List of usage examples for java.util LinkedList removeFirst

Introduction

In this page you can find the example usage for java.util LinkedList removeFirst.

Prototype

public E removeFirst() 

Source Link

Document

Removes and returns the first element from this list.

Usage

From source file:edu.csun.ecs.cs.multitouchj.application.whiteboard.ui.InteractiveCanvas.java

protected void drawPoints() {
    synchronized (previousPoints) {
        synchronized (resizableBufferedImage) {
            // clear points for pen if it's been long since last changed
            long currentTime = new Date().getTime();
            for (int id : pens.keySet()) {
                if (previousTimes.containsKey(id)) {
                    long time = previousTimes.get(id);
                    if ((currentTime - time) > POINT_CLEAR_DURATION) {
                        previousPoints.remove(id);
                        previousTimes.remove(id);
                    }/*from www  .  j av a  2s. c  o m*/
                }
            }

            DisplayMode displayMode = getWindowManager().getDisplayManager().getCurrentDisplayMode();
            BufferedImage bufferedImage = resizableBufferedImage.getBufferedImage();

            Graphics2D graphics = bufferedImage.createGraphics();
            for (int id : pens.keySet()) {
                Pen pen = pens.get(id);
                LinkedList<Point> points = previousPoints.get(id);
                if ((pen != null) && (points != null) && (points.size() > 1)) {
                    log.debug("id: " + id + ", points: " + points.size());

                    Point previousPoint = points.removeFirst();
                    Iterator<Point> iterator = points.iterator();
                    while (iterator.hasNext()) {
                        Point point = iterator.next();
                        if (iterator.hasNext()) {
                            iterator.remove();
                        }

                        graphics.setStroke(pen.getStroke());
                        graphics.setPaint(pen.getPaint());
                        graphics.drawLine((int) Math.floor(previousPoint.getX()),
                                (displayMode.getHeight() - (int) Math.floor(previousPoint.getY())),
                                (int) Math.floor(point.getX()),
                                (displayMode.getHeight() - (int) Math.floor(point.getY())));

                        previousPoint = point;
                    }

                    setDirty(true);
                }
            }
            graphics.dispose();
        }
    }
}

From source file:mitm.djigzo.web.services.security.HMACFilterImpl.java

private void calculateHMACs(MarkupWriter writer, List<String> hmacs) {
    Document document = writer.getDocument();

    if (document != null) {
        Element root = document.getRootElement();

        if (root != null) {
            LinkedList<Element> queue = new LinkedList<Element>();

            queue.add(root);//from w w  w . j  av a 2s .  co m

            while (!queue.isEmpty()) {
                Element element = queue.removeFirst();

                if (element == null) {
                    continue;
                }

                String elementName = element.getAttribute("name");

                if (elementName != null) {
                    elementName = elementName.trim().toLowerCase();
                }

                if (protectedElements.contains(elementName)) {
                    /*
                     * It's a protected item so we should calculate the HMAC of the value
                     */
                    String value = element.getAttribute("value");

                    String hmac;

                    try {
                        hmac = calculateHMAC(value, true /* create ASO if not exist */);
                    } catch (InvalidKeyException e) {
                        throw new DjigzoRuntimeException(e);
                    } catch (NoSuchAlgorithmException e) {
                        throw new DjigzoRuntimeException(e);
                    }

                    if (hmac == null) {
                        throw new DjigzoRuntimeException("hmac is null.");
                    }

                    if (hmacs != null) {
                        hmacs.add(hmac);
                    } else {
                        /*
                         * Add the HMAC checksum as a hidden element
                         */
                        element.element("input", "type", "hidden", "name", HMAC_PARAMETER, "value", hmac);
                    }
                }

                for (Node n : element.getChildren()) {
                    Element child = null;

                    if (n instanceof Element) {
                        child = (Element) n;
                    }

                    if (child != null)
                        queue.addLast(child);
                }
            }
        }
    }
}

From source file:alma.acs.nc.sm.generic.AcsScxmlEngine.java

/**
 * Gets the signals that would trigger transitions for the current state.
 * <p>//from  w  ww. j  a v  a2s. c  om
 * When actually sending such signals later on, the SM may have moved to a different state.
 * To prevent this, you can synchronize on this AcsScxmlEngine, which will block concurrent calls to {@link #fireSignal(Enum)}.
 * <p>
 * This method can be useful for displaying applicable signals in a GUI,
 * or to reject signals (with exception etc) that do not "fit" the current state
 * (while normally such signals would be silently ignored). 
 * The latter gets used in {@link #fireSignalWithErrorFeedback(Enum)}.
 * 
 * @see org.apache.commons.scxml.semantics.SCXMLSemanticsImpl#enumerateReachableTransitions(SCXML, Step, ErrorReporter)
 */
public synchronized Set<S> getApplicableSignals() {
    Set<String> events = new HashSet<String>();

    @SuppressWarnings("unchecked")
    Set<TransitionTarget> stateSet = new HashSet<TransitionTarget>(exec.getCurrentStatus().getStates());
    LinkedList<TransitionTarget> todoList = new LinkedList<TransitionTarget>(stateSet);

    while (!todoList.isEmpty()) {
        TransitionTarget tt = todoList.removeFirst();
        @SuppressWarnings("unchecked")
        List<Transition> transitions = tt.getTransitionsList();
        for (Transition t : transitions) {
            String event = t.getEvent();
            events.add(event);
        }
        TransitionTarget parentTT = tt.getParent();
        if (parentTT != null && !stateSet.contains(parentTT)) {
            stateSet.add(parentTT);
            todoList.addLast(parentTT);
        }
    }

    // convert signal names to enum constants
    Set<S> ret = new HashSet<S>();
    for (String signalName : events) {
        S signal = Enum.valueOf(signalType, signalName);
        ret.add(signal);
    }
    return ret;
}

From source file:org.fusesource.jms.pool.PooledConnectionFactory.java

public synchronized Connection createConnection(String userName, String password) throws JMSException {
    if (stopped.get()) {
        LOG.debug("PooledConnectionFactory is stopped, skip create new connection.");
        return null;
    }// w  w  w  .  j  a va 2  s. c o  m

    ConnectionKey key = new ConnectionKey(userName, password);
    LinkedList<ConnectionPool> pools = cache.get(key);

    if (pools == null) {
        pools = new LinkedList<ConnectionPool>();
        cache.put(key, pools);
    }

    ConnectionPool connection = null;
    if (pools.size() == maxConnections) {
        connection = pools.removeFirst();
    }

    // Now.. we might get a connection, but it might be that we need to
    // dump it..
    if (connection != null && connection.expiredCheck()) {
        connection = null;
    }

    if (connection == null) {
        Connection delegate = createConnection(key);
        connection = createConnectionPool(delegate);
    }
    pools.add(connection);
    return new PooledConnection(connection);
}

From source file:com.alibaba.citrus.turbine.util.CsrfToken.java

/** csrf token?token? */
public String getUniqueToken() {
    HttpSession session = request.getSession();
    String key = getKey();/*from   ww w  . j  av  a 2  s .co m*/
    String tokenOfRequest = (String) request.getAttribute(key);
    int maxTokens = getMaxTokens();

    if (tokenOfRequest == null) {
        // token
        // ?session?token
        // tokentokensession
        // tokentoken
        LinkedList<String> tokens = getTokensInSession(session, key);

        tokenOfRequest = getGenerator().generateUniqueToken();
        request.setAttribute(key, tokenOfRequest);

        tokens.addLast(tokenOfRequest);

        while (tokens.size() > maxTokens) {
            tokens.removeFirst();
        }

        setTokensInSession(session, key, tokens);
    }

    return tokenOfRequest;
}

From source file:opennlp.model.OnePassRealValueDataIndexer.java

protected List index(LinkedList<Event> events, Map<String, Integer> predicateIndex) {
    Map<String, Integer> omap = new HashMap<String, Integer>();

    int numEvents = events.size();
    int outcomeCount = 0;
    List eventsToCompare = new ArrayList(numEvents);
    List<Integer> indexedContext = new ArrayList<Integer>();

    for (int eventIndex = 0; eventIndex < numEvents; eventIndex++) {
        Event ev = (Event) events.removeFirst();
        String[] econtext = ev.getContext();
        ComparableEvent ce;//from   w w  w  .ja va  2  s.co m

        int ocID;
        String oc = ev.getOutcome();

        if (omap.containsKey(oc)) {
            ocID = omap.get(oc);
        } else {
            ocID = outcomeCount++;
            omap.put(oc, ocID);
        }

        for (int i = 0; i < econtext.length; i++) {
            String pred = econtext[i];
            if (predicateIndex.containsKey(pred)) {
                indexedContext.add(predicateIndex.get(pred));
            }
        }

        //drop events with no active features
        if (indexedContext.size() > 0) {
            int[] cons = new int[indexedContext.size()];
            for (int ci = 0; ci < cons.length; ci++) {
                cons[ci] = indexedContext.get(ci);
            }
            ce = new ComparableEvent(ocID, cons, ev.getValues());
            eventsToCompare.add(ce);
        } else {
            LOG.debug("Dropped event " + ev.getOutcome() + ":" + Arrays.asList(ev.getContext()));
        }
        //    recycle the TIntArrayList
        indexedContext.clear();
    }
    outcomeLabels = toIndexedStringArray(omap);
    predLabels = toIndexedStringArray(predicateIndex);
    return eventsToCompare;
}

From source file:org.alfresco.solr.tracker.CascadeTracker.java

private void processCascades() throws IOException {
    //System.out.println("######### processCascades()");
    int num = 50;
    List<Transaction> txBatch = null;
    do {//from w  ww  .  j ava  2  s  .  c om
        try {
            getWriteLock().acquire();
            txBatch = infoSrv.getCascades(num);
            if (txBatch.size() == 0) {
                //No transactions to process for cascades.
                return;
            }

            ArrayList<Long> txIds = new ArrayList<Long>();
            Set<Long> txIdSet = new HashSet<Long>();
            for (Transaction tx : txBatch) {
                txIds.add(tx.getId());
                txIdSet.add(tx.getId());
            }

            List<NodeMetaData> nodeMetaDatas = infoSrv.getCascadeNodes(txIds);

            //System.out.println("########### Cascade node meta datas:"+nodeMetaDatas.size());
            if (nodeMetaDatas.size() > 0) {
                LinkedList<NodeMetaData> stack = new LinkedList<NodeMetaData>();
                stack.addAll(nodeMetaDatas);
                int batchSize = 10;

                do {
                    List<NodeMetaData> batch = new ArrayList<NodeMetaData>();
                    while (batch.size() < batchSize && stack.size() > 0) {
                        batch.add(stack.removeFirst());
                    }

                    CascadeIndexWorkerRunnable worker = new CascadeIndexWorkerRunnable(this.threadHandler,
                            batch, infoSrv);
                    this.threadHandler.scheduleTask(worker);
                } while (stack.size() > 0);
            }
            //Update the transaction records.
            updateTransactionsAfterAsynchronous(txBatch);
            //System.out.println("######################: Finished Cascade Run #########");
        } catch (AuthenticationException e) {
            throw new IOException(e);
        } catch (JSONException e) {
            throw new IOException(e);
        } catch (InterruptedException e) {
            throw new IOException(e);
        } finally {
            //System.out.println("###################: Releasing Cascade write lock");
            getWriteLock().release();
        }

    } while (txBatch.size() > 0);
}

From source file:org.mycard.net.network.RequestQueue.java

/** helper */
private Request removeFirst(LinkedHashMap<HttpHost, LinkedList<Request>> requestQueue) {
    Request ret = null;//from  www.  jav  a2  s. c  o  m
    Iterator<Map.Entry<HttpHost, LinkedList<Request>>> iter = requestQueue.entrySet().iterator();
    if (iter.hasNext()) {
        Map.Entry<HttpHost, LinkedList<Request>> entry = iter.next();
        LinkedList<Request> reqList = entry.getValue();
        ret = reqList.removeFirst();
        if (reqList.isEmpty()) {
            requestQueue.remove(entry.getKey());
        }
    }
    return ret;
}

From source file:org.mycard.net.network.RequestQueue.java

/***
 * @return a request for given host if possible
 *///  www  .jav  a  2s.co m
public synchronized Request getRequest(HttpHost host) {
    Request ret = null;

    if (mPending.containsKey(host)) {
        LinkedList<Request> reqList = mPending.get(host);
        ret = reqList.removeFirst();
        if (reqList.isEmpty()) {
            mPending.remove(host);
        }
    }
    //if (HttpLog.LOGV) HttpLog.v("RequestQueue.getRequest(" + host + ") => " + ret);
    return ret;
}

From source file:com.opera.core.systems.scope.services.ums.WindowManager.java

public void closeAllWindows() {
    logger.fine("closeAllWindows");
    LinkedList<Integer> list = new LinkedList<Integer>(windows.asStack());
    boolean canCloseAll = services.getExec().getActionList().contains("Close all pages");

    if (canCloseAll) {
        services.getExec().action("Close all pages");
    } else {/* w  w  w  .j av a 2 s . c  om*/
        while (!list.isEmpty()) {
            closeWindow(list.removeFirst());

            // BAD HACK! DELAYING CLOSE-WINDOW
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.warning(
                    "Bad hack: sleeping 10ms between closing of windows, to prevent opera from crashing!");
            // BAD HACK DONE!
        }
    }
}