Example usage for java.util ArrayDeque getFirst

List of usage examples for java.util ArrayDeque getFirst

Introduction

In this page you can find the example usage for java.util ArrayDeque getFirst.

Prototype

public E getFirst() 

Source Link

Usage

From source file:Main.java

public static void main(String[] args) {

    ArrayDeque<Integer> deque = new ArrayDeque<Integer>(8);

    deque.add(3);//  w  w  w .j  a  v a  2s .c o m
    deque.add(2);
    deque.add(1);
    deque.add(18);

    System.out.println(deque);

    // getFirst() will retrieve element at first(head) position
    int retval = deque.getFirst();
    System.out.println("Retrieved Element is = " + retval);
}

From source file:com.espertech.esper.core.context.util.StatementAgentInstanceUtil.java

private static void evaluateEventForStatementInternal(EPServicesContext servicesContext, EventBean theEvent,
        List<AgentInstance> agentInstances) {
    // context was created - reevaluate for the given event
    ArrayDeque<FilterHandle> callbacks = new ArrayDeque<FilterHandle>(2);
    servicesContext.getFilterService().evaluate(theEvent, callbacks); // evaluates for ALL statements
    if (callbacks.isEmpty()) {
        return;//  w  w  w  .  j  av a2s.  c  o m
    }

    // there is a single callback and a single context, if they match we are done
    if (agentInstances.size() == 1 && callbacks.size() == 1) {
        AgentInstance agentInstance = agentInstances.get(0);
        if (agentInstance.getAgentInstanceContext().getStatementId()
                .equals(callbacks.getFirst().getStatementId())) {
            process(agentInstance, servicesContext, callbacks, theEvent);
        }
        return;
    }

    // use the right sorted/unsorted Map keyed by AgentInstance to sort
    boolean isPrioritized = servicesContext.getConfigSnapshot().getEngineDefaults().getExecution()
            .isPrioritized();
    Map<AgentInstance, Object> stmtCallbacks;
    if (!isPrioritized) {
        stmtCallbacks = new HashMap<AgentInstance, Object>();
    } else {
        stmtCallbacks = new TreeMap<AgentInstance, Object>(AgentInstanceComparator.INSTANCE);
    }

    // process all callbacks
    for (FilterHandle filterHandle : callbacks) {
        // determine if this filter entry applies to any of the affected agent instances
        String statementId = filterHandle.getStatementId();
        AgentInstance agentInstanceFound = null;
        for (AgentInstance agentInstance : agentInstances) {
            if (agentInstance.getAgentInstanceContext().getStatementId().equals(statementId)) {
                agentInstanceFound = agentInstance;
                break;
            }
        }
        if (agentInstanceFound == null) { // when the callback is for some other stmt
            continue;
        }

        EPStatementHandleCallback handleCallback = (EPStatementHandleCallback) filterHandle;
        EPStatementAgentInstanceHandle handle = handleCallback.getAgentInstanceHandle();

        // Self-joins require that the internal dispatch happens after all streams are evaluated.
        // Priority or preemptive settings also require special ordering.
        if (handle.isCanSelfJoin() || isPrioritized) {
            Object stmtCallback = stmtCallbacks.get(agentInstanceFound);
            if (stmtCallback == null) {
                stmtCallbacks.put(agentInstanceFound, handleCallback);
            } else if (stmtCallback instanceof ArrayDeque) {
                ArrayDeque<EPStatementHandleCallback> q = (ArrayDeque<EPStatementHandleCallback>) stmtCallback;
                q.add(handleCallback);
            } else {
                ArrayDeque<EPStatementHandleCallback> q = new ArrayDeque<EPStatementHandleCallback>(4);
                q.add((EPStatementHandleCallback) stmtCallback);
                q.add(handleCallback);
                stmtCallbacks.put(agentInstanceFound, q);
            }
            continue;
        }

        // no need to be sorted, process
        process(agentInstanceFound, servicesContext, Collections.<FilterHandle>singletonList(handleCallback),
                theEvent);
    }

    if (stmtCallbacks.isEmpty()) {
        return;
    }

    // Process self-join or sorted prioritized callbacks
    for (Map.Entry<AgentInstance, Object> entry : stmtCallbacks.entrySet()) {
        AgentInstance agentInstance = entry.getKey();
        Object callbackList = entry.getValue();
        if (callbackList instanceof ArrayDeque) {
            process(agentInstance, servicesContext, (Collection<FilterHandle>) callbackList, theEvent);
        } else {
            process(agentInstance, servicesContext,
                    Collections.<FilterHandle>singletonList((FilterHandle) callbackList), theEvent);
        }
        if (agentInstance.getAgentInstanceContext().getEpStatementAgentInstanceHandle().isPreemptive()) {
            return;
        }
    }
}

From source file:com.espertech.esper.collection.TestTimeWindow.java

public void testAddRemove() {
    assertTrue(windowRemovable.getOldestTimestamp() == null);
    assertTrue(windowRemovable.isEmpty());

    windowRemovable.add(19, beans[0]);//from ww w.ja v  a 2  s. c om
    assertTrue(windowRemovable.getOldestTimestamp() == 19L);
    assertFalse(windowRemovable.isEmpty());
    windowRemovable.add(19, beans[1]);
    assertTrue(windowRemovable.getOldestTimestamp() == 19L);
    windowRemovable.add(20, beans[2]);
    assertTrue(windowRemovable.getOldestTimestamp() == 19L);
    windowRemovable.add(20, beans[3]);
    windowRemovable.add(21, beans[4]);
    windowRemovable.add(22, beans[5]);
    assertTrue(windowRemovable.getOldestTimestamp() == 19L);

    windowRemovable.remove(beans[4]);
    windowRemovable.remove(beans[0]);
    windowRemovable.remove(beans[3]);

    ArrayDeque<EventBean> beanList = windowRemovable.expireEvents(19);
    assertTrue(beanList == null);

    beanList = windowRemovable.expireEvents(20);
    assertTrue(beanList.size() == 1);
    assertTrue(beanList.getFirst() == beans[1]);

    beanList = windowRemovable.expireEvents(21);
    assertTrue(beanList.size() == 1);
    assertTrue(beanList.getFirst() == beans[2]);
    assertFalse(windowRemovable.isEmpty());
    assertTrue(windowRemovable.getOldestTimestamp() == 22);

    beanList = windowRemovable.expireEvents(22);
    assertTrue(beanList.size() == 0);

    beanList = windowRemovable.expireEvents(23);
    assertTrue(beanList.size() == 1);
    assertTrue(beanList.getFirst() == beans[5]);
    assertTrue(windowRemovable.isEmpty());
    assertTrue(windowRemovable.getOldestTimestamp() == null);

    beanList = windowRemovable.expireEvents(23);
    assertTrue(beanList == null);
    assertTrue(windowRemovable.isEmpty());
    assertTrue(windowRemovable.getOldestTimestamp() == null);

    assertEquals(0, windowRemovable.getReverseIndex().size());
}

From source file:com.google.gwt.emultest.java.util.ArrayDequeTest.java

public void testGetFirst() {
    Object o1 = new Object();
    Object o2 = new Object();

    ArrayDeque<Object> deque = new ArrayDeque<>();
    try {//www  .j a  v a2s  . co m
        deque.getFirst();
        fail();
    } catch (NoSuchElementException expected) {
    }

    deque.add(o1);
    assertEquals(o1, deque.getFirst());
    checkDequeSizeAndContent(deque, o1);

    deque.add(o2);
    assertEquals(o1, deque.getFirst());
    checkDequeSizeAndContent(deque, o1, o2);

    deque.clear();
    assertTrue(deque.isEmpty());
    try {
        deque.getFirst();
        fail();
    } catch (NoSuchElementException expected) {
    }
}

From source file:com.rammelkast.anticheatreloaded.config.yaml.CommentedConfiguration.java

@Override
public String saveToString() {
    yamlOptions.setIndent(options().indent());
    yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);

    // String header = buildHeader(); - CommentedConfiguration
    String dump = yaml.dump(getValues(false));

    if (dump.equals(BLANK_CONFIG)) {
        dump = "";
    }// ww w  . j  a v  a 2 s.co m

    // Begin CommentedConfiguration
    StringBuilder builder = new StringBuilder();

    String[] lines = dump.split("\n");
    ArrayDeque<String> queue = new ArrayDeque<String>();
    for (String string : lines) {
        queue.add(string);
    }

    int i = 0;
    while (queue.size() > 0) {
        if (comments.containsKey(i)) {
            builder.append(comments.get(i));

            // Handle subsequent comments
            int b = i;
            while (true) {
                b++;
                if (comments.containsKey(b)) {
                    builder.append('\n');
                    builder.append(comments.get(b));
                } else {
                    break;
                }
            }
            builder.append('\n');
            i = b;
        }

        builder.append(queue.getFirst());
        builder.append('\n');
        queue.pop();
        i++;
    }
    // End CommentedConfiguration

    return builder.toString();
}

From source file:com.espertech.esper.core.service.EPRuntimeImpl.java

/**
 * Processing multiple filter matches for a statement.
 * @param handle statement handle/* w  ww .  j a  va2  s . co m*/
 * @param callbackList object containing callbacks
 * @param theEvent to process
 * @param version filter version
 */
public void processStatementFilterMultiple(EPStatementAgentInstanceHandle handle, Object callbackList,
        EventBean theEvent, long version) {
    handle.getStatementAgentInstanceLock().acquireWriteLock(services.getStatementLockFactory());
    try {
        if (handle.isHasVariables()) {
            services.getVariableService().setLocalVersion();
        }
        if (!handle.isCurrentFilter(version)) {
            if (handle.getFilterFaultHandler() != null) {
                handle.getFilterFaultHandler().handleFilterFault(theEvent, version);
            }

            ArrayDeque<FilterHandle> callbackListNew = getCallbackList(theEvent, handle.getStatementId());
            if (callbackListNew.isEmpty()) {
                callbackList = Collections.emptyList();
            } else if (callbackListNew.size() == 1) {
                callbackList = ((EPStatementHandleCallback) callbackListNew.getFirst()).getFilterCallback();
            } else {
                ArrayDeque<FilterHandleCallback> q = new ArrayDeque<FilterHandleCallback>(
                        callbackListNew.size());
                callbackList = q;
                for (FilterHandle callback : callbackListNew) {
                    EPStatementHandleCallback handleCallbackFilter = (EPStatementHandleCallback) callback;
                    q.add(handleCallbackFilter.getFilterCallback());
                }
            }
        }

        if (callbackList instanceof Collection) {
            Collection<FilterHandleCallback> callbackColl = (Collection<FilterHandleCallback>) callbackList;
            if (isSubselectPreeval) {
                // sub-selects always go first
                for (FilterHandleCallback callback : callbackColl) {
                    if (callback.isSubSelect()) {
                        callback.matchFound(theEvent, callbackColl);
                    }
                }

                for (FilterHandleCallback callback : callbackColl) {
                    if (!callback.isSubSelect()) {
                        callback.matchFound(theEvent, callbackColl);
                    }
                }
            } else {
                // sub-selects always go last
                for (FilterHandleCallback callback : callbackColl) {
                    if (!callback.isSubSelect()) {
                        callback.matchFound(theEvent, callbackColl);
                    }
                }

                for (FilterHandleCallback callback : callbackColl) {
                    if (callback.isSubSelect()) {
                        callback.matchFound(theEvent, callbackColl);
                    }
                }
            }
        } else {
            FilterHandleCallback single = (FilterHandleCallback) callbackList;
            single.matchFound(theEvent, null);
        }

        // internal join processing, if applicable
        handle.internalDispatch(this.engineFilterAndDispatchTimeContext);
    } catch (RuntimeException ex) {
        services.getExceptionHandlingService().handleException(ex, handle);
    } finally {
        handle.getStatementAgentInstanceLock().releaseWriteLock(services.getStatementLockFactory());
    }
}

From source file:com.vgi.mafscaling.VECalc.java

protected void loadLogFile() {
    fileChooser.setMultiSelectionEnabled(true);
    if (JFileChooser.APPROVE_OPTION != fileChooser.showOpenDialog(this))
        return;//from ww w  .ja va 2 s  .c o m
    File[] files = fileChooser.getSelectedFiles();
    for (File file : files) {
        BufferedReader br = null;
        ArrayDeque<String[]> buffer = new ArrayDeque<String[]>();
        try {
            br = new BufferedReader(new FileReader(file.getAbsoluteFile()));
            String line = br.readLine();
            if (line != null) {
                String[] elements = line.split("(\\s*)?,(\\s*)?", -1);
                getColumnsFilters(elements);

                boolean resetColumns = false;
                if (logThrottleAngleColIdx >= 0 || logFfbColIdx >= 0 || logSdColIdx >= 0
                        || (logWbAfrColIdx >= 0 && isOl) || (logStockAfrColIdx >= 0 && !isOl)
                        || (logAfLearningColIdx >= 0 && !isOl) || (logAfCorrectionColIdx >= 0 && !isOl)
                        || logRpmColIdx >= 0 || logMafColIdx >= 0 || logIatColIdx >= 0 || logMpColIdx >= 0) {
                    if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null,
                            "Would you like to reset column names or filter values?", "Columns/Filters Reset",
                            JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE))
                        resetColumns = true;
                }

                if (resetColumns || logThrottleAngleColIdx < 0 || logFfbColIdx < 0 || logSdColIdx < 0
                        || (logWbAfrColIdx < 0 && isOl) || (logStockAfrColIdx < 0 && !isOl)
                        || (logAfLearningColIdx < 0 && !isOl) || (logAfCorrectionColIdx < 0 && !isOl)
                        || logRpmColIdx < 0 || logMafColIdx < 0 || logIatColIdx < 0 || logMpColIdx < 0) {
                    ColumnsFiltersSelection selectionWindow = new VEColumnsFiltersSelection(false);
                    if (!selectionWindow.getUserSettings(elements) || !getColumnsFilters(elements))
                        return;
                }

                if (logClOlStatusColIdx == -1)
                    clValue = -1;

                String[] flds;
                String[] afrflds;
                boolean removed = false;
                int i = 2;
                int clol = -1;
                int row = getLogTableEmptyRow();
                double thrtlMaxChange2 = thrtlMaxChange + thrtlMaxChange / 2.0;
                double throttle = 0;
                double pThrottle = 0;
                double ppThrottle = 0;
                double afr = 0;
                double rpm;
                double ffb;
                double iat;
                clearRunTables();
                setCursor(new Cursor(Cursor.WAIT_CURSOR));
                for (int k = 0; k <= afrRowOffset && line != null; ++k) {
                    line = br.readLine();
                    if (line != null)
                        buffer.addFirst(line.split(",", -1));
                }
                try {
                    while (line != null && buffer.size() > afrRowOffset) {
                        afrflds = buffer.getFirst();
                        flds = buffer.removeLast();
                        line = br.readLine();
                        if (line != null)
                            buffer.addFirst(line.split(",", -1));
                        ppThrottle = pThrottle;
                        pThrottle = throttle;
                        throttle = Double.valueOf(flds[logThrottleAngleColIdx]);
                        try {
                            if (row > 0 && Math.abs(pThrottle - throttle) > thrtlMaxChange) {
                                if (!removed)
                                    Utils.removeRow(row--, logDataTable);
                                removed = true;
                            } else if (row <= 0 || Math.abs(ppThrottle - throttle) <= thrtlMaxChange2) {
                                // Filters
                                afr = (isOl ? Double.valueOf(afrflds[logWbAfrColIdx])
                                        : Double.valueOf(afrflds[logStockAfrColIdx]));
                                rpm = Double.valueOf(flds[logRpmColIdx]);
                                ffb = Double.valueOf(flds[logFfbColIdx]);
                                iat = Double.valueOf(flds[logIatColIdx]);
                                if (clValue != -1)
                                    clol = Integer.valueOf(flds[logClOlStatusColIdx]);
                                boolean flag = isOl ? ((afr <= afrMax || throttle >= thrtlMin) && afr <= afrMax)
                                        : (afrMin <= afr);
                                if (flag && clol == clValue && rpmMin <= rpm && ffbMin <= ffb && ffb <= ffbMax
                                        && iat <= iatMax) {
                                    removed = false;
                                    if (!isOl)
                                        trims.add(Double.valueOf(flds[logAfLearningColIdx])
                                                + Double.valueOf(flds[logAfCorrectionColIdx]));
                                    Utils.ensureRowCount(row + 1, logDataTable);
                                    logDataTable.setValueAt(rpm, row, 0);
                                    logDataTable.setValueAt(iat, row, 1);
                                    logDataTable.setValueAt(Double.valueOf(flds[logMpColIdx]), row, 2);
                                    logDataTable.setValueAt(ffb, row, 3);
                                    logDataTable.setValueAt(afr, row, 4);
                                    logDataTable.setValueAt(Double.valueOf(flds[logMafColIdx]), row, 5);
                                    logDataTable.setValueAt(Double.valueOf(flds[logSdColIdx]), row, 6);
                                    row += 1;
                                } else
                                    removed = true;
                            } else
                                removed = true;
                        } catch (NumberFormatException e) {
                            logger.error(e);
                            JOptionPane.showMessageDialog(null,
                                    "Error parsing number at " + file.getName() + " line " + i + ": " + e,
                                    "Error processing file", JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                        i += 1;
                    }
                } finally {
                    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                }
            }
        } catch (Exception e) {
            logger.error(e);
            JOptionPane.showMessageDialog(null, e, "Error opening file", JOptionPane.ERROR_MESSAGE);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        }
    }
}

From source file:com.vgi.mafscaling.OpenLoop.java

protected void loadLogFile() {
    fileChooser.setMultiSelectionEnabled(true);
    if (JFileChooser.APPROVE_OPTION != fileChooser.showOpenDialog(this))
        return;// w  w w . j  a v a  2 s.  co  m
    boolean isPolSet = polfTable.isSet();
    File[] files = fileChooser.getSelectedFiles();
    for (File file : files) {
        BufferedReader br = null;
        ArrayDeque<String[]> buffer = new ArrayDeque<String[]>();
        try {
            br = new BufferedReader(new FileReader(file.getAbsoluteFile()));
            String line = br.readLine();
            if (line != null) {
                String[] elements = line.split("(\\s*)?,(\\s*)?", -1);
                getColumnsFilters(elements, false);

                boolean resetColumns = false;
                if (logThtlAngleColIdx >= 0 || logAfLearningColIdx >= 0 || logAfCorrectionColIdx >= 0
                        || logMafvColIdx >= 0 || logAfrColIdx >= 0 || logRpmColIdx >= 0 || logLoadColIdx >= 0
                        || logCommandedAfrCol >= 0) {
                    if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null,
                            "Would you like to reset column names or filter values?", "Columns/Filters Reset",
                            JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE))
                        resetColumns = true;
                }

                if (resetColumns || logThtlAngleColIdx < 0 || logAfLearningColIdx < 0
                        || logAfCorrectionColIdx < 0 || logMafvColIdx < 0 || logAfrColIdx < 0
                        || logRpmColIdx < 0 || logLoadColIdx < 0 || (logCommandedAfrCol < 0 && !isPolSet)) {
                    ColumnsFiltersSelection selectionWindow = new OLColumnsFiltersSelection(isPolSet);
                    if (!selectionWindow.getUserSettings(elements) || !getColumnsFilters(elements, isPolSet))
                        return;
                }

                String[] flds;
                String[] afrflds;
                boolean wotFlag = true;
                boolean foundWot = false;
                double throttle;
                double stft;
                double ltft;
                double afr;
                double rpm;
                double load;
                double mafv;
                double cmdafr = 0;
                double afrErr = 0;
                int skipRowCount = 0;
                int row = 0;
                int i = 0;
                int j = 0;
                for (; i < runTables.length; ++i) {
                    if (runTables[i].getValueAt(0, 0).toString().isEmpty())
                        break;
                }
                if (i == runTables.length)
                    return;
                setCursor(new Cursor(Cursor.WAIT_CURSOR));
                for (int k = 0; k <= afrRowOffset && line != null; ++k) {
                    line = br.readLine();
                    if (line != null)
                        buffer.addFirst(line.split(",", -1));
                }
                while (line != null && buffer.size() > afrRowOffset) {
                    afrflds = buffer.getFirst();
                    flds = buffer.removeLast();
                    line = br.readLine();
                    if (line != null)
                        buffer.addFirst(line.split(",", -1));

                    try {
                        throttle = Double.valueOf(flds[logThtlAngleColIdx]);
                        if (row == 0 && throttle < 99)
                            wotFlag = false;
                        if (throttle < wotPoint) {
                            if (wotFlag == true) {
                                wotFlag = false;
                                skipRowCount = 0;
                                j -= 1;
                                while (j > 0 && skipRowCount < skipRowsOnTransition) {
                                    runTables[i].setValueAt("", j, 0);
                                    runTables[i].setValueAt("", j, 1);
                                    runTables[i].setValueAt("", j, 2);
                                    skipRowCount += 1;
                                    j -= 1;
                                }
                                skipRowCount = 0;
                            }
                        } else {
                            if (wotFlag == false) {
                                wotFlag = true;
                                skipRowCount = 0;
                                if (foundWot) {
                                    i += 1;
                                    if (i == runTables.length)
                                        return;
                                }
                                if (row > 0)
                                    j = 0;
                            }
                            if (skipRowCount >= skipRowsOnTransition) {
                                mafv = Double.valueOf(flds[logMafvColIdx]);
                                if (minMafV <= mafv) {
                                    foundWot = true;
                                    stft = Double.valueOf(flds[logAfCorrectionColIdx]);
                                    ltft = Double.valueOf(flds[logAfLearningColIdx]);
                                    afr = Double.valueOf(afrflds[logAfrColIdx]);
                                    rpm = Double.valueOf(flds[logRpmColIdx]);
                                    load = Double.valueOf(flds[logLoadColIdx]);

                                    afr = afr / ((100.0 - (ltft + stft)) / 100.0);

                                    if (logCommandedAfrCol >= 0)
                                        cmdafr = Double.valueOf(flds[logCommandedAfrCol]);
                                    else if (isPolSet)
                                        cmdafr = Utils.calculateCommandedAfr(rpm, load, minWotEnrichment,
                                                polfTable);
                                    else {
                                        JOptionPane.showMessageDialog(null,
                                                "Please set either \"Commanded AFR\" column or \"Primary Open Loop Fueling\" table",
                                                "Error", JOptionPane.ERROR_MESSAGE);
                                        return;
                                    }

                                    afrErr = (afr - cmdafr) / cmdafr * 100.0;
                                    if (Math.abs(afrErr) <= afrErrPrct) {
                                        Utils.ensureRowCount(j + 1, runTables[i]);
                                        runTables[i].setValueAt(rpm, j, 0);
                                        runTables[i].setValueAt(mafv, j, 1);
                                        runTables[i].setValueAt(afrErr, j, 2);
                                        j += 1;
                                    }
                                }
                            }
                            skipRowCount += 1;
                        }
                    } catch (NumberFormatException e) {
                        logger.error(e);
                        JOptionPane.showMessageDialog(null,
                                "Error parsing number at " + file.getName() + " line " + (row + 1) + ": " + e,
                                "Error processing file", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    row += 1;
                }

                if (!foundWot) {
                    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                    JOptionPane.showMessageDialog(null, "Sorry, no WOT pulls were found in the log file",
                            "No WOT data", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        } catch (Exception e) {
            logger.error(e);
            JOptionPane.showMessageDialog(null, e, "Error opening file", JOptionPane.ERROR_MESSAGE);
        } finally {
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        }
    }
}