Example usage for java.util ArrayDeque isEmpty

List of usage examples for java.util ArrayDeque isEmpty

Introduction

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

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this deque contains no elements.

Usage

From source file:org.apache.hadoop.hbase.thrift.TestMutationWriteToWAL.java

@Test
public void testMutationWriteToWAL() throws Exception {
    HBaseTestingUtility.setThreadNameFromMethod();
    final Configuration conf = TEST_UTIL.getConfiguration();
    FileSystem fs = FileSystem.get(conf);
    List<String> expectedLogEntries = new ArrayList<String>();

    try {//  w  w  w  .  j a v a2  s  . c o  m
        Hbase.Client client = createClient();
        client.createTable(HTestConst.DEFAULT_TABLE_BYTE_BUF, HTestConst.DEFAULT_COLUMN_DESC_LIST);
        int expectedEntriesForRow[] = new int[NUM_ROWS];
        for (int i = NUM_ROWS - 1; i >= 0; --i) {
            final String row = getRow(i);
            List<Mutation> mutations = new ArrayList<Mutation>();

            // writeToWAL cannot depend on column, only on the row
            boolean writeToWAL = i % 3 == 0;

            for (int j = 0; j < NUM_COLS_PER_ROW; ++j) {
                final String qual = getCol(j);

                boolean isDelete = shouldDelete(i, j);
                if (!isDelete) {
                    expectedEntriesForRow[i]++;
                }

                final String value = isDelete ? "" : getValue(i, j);

                Mutation m = new Mutation(false,
                        ByteBuffer.wrap(Bytes.toBytes(HTestConst.DEFAULT_CF_STR + ":" + qual)),
                        ByteBuffer.wrap(Bytes.toBytes(value)), writeToWAL, HConstants.LATEST_TIMESTAMP);
                m.isDelete = isDelete;

                mutations.add(m);
                if (writeToWAL) {
                    expectedLogEntries.add(row + "," + qual + "," + value + "," + m.isDelete);
                }
            }
            final ByteBuffer rowBuf = ByteBuffer.wrap(Bytes.toBytes(row));
            // Exercise both APIs.
            if (i % 2 == 0) {
                client.mutateRow(HTestConst.DEFAULT_TABLE_BYTE_BUF, rowBuf, mutations, null, null);
            } else {
                List<BatchMutation> rowBatches = new ArrayList<BatchMutation>();
                BatchMutation bm = new BatchMutation(rowBuf, mutations);
                rowBatches.add(bm);
                client.mutateRows(HTestConst.DEFAULT_TABLE_BYTE_BUF, rowBatches, null, null);
            }
        }
        client.disableTable(HTestConst.DEFAULT_TABLE_BYTE_BUF);
        client.enableTable(HTestConst.DEFAULT_TABLE_BYTE_BUF);

        // Check that all the data is there
        for (int i = 0; i < NUM_ROWS; ++i) {
            final String row = getRow(i);
            List<TRowResult> results = client.getRow(HTestConst.DEFAULT_TABLE_BYTE_BUF,
                    ByteBuffer.wrap(Bytes.toBytes(row)), null);
            TRowResult result = results.get(0);
            assertEquals("No results found for row " + row, expectedEntriesForRow[i], result.getColumnsSize());
            Map<ByteBuffer, TCell> sortedColumns = new TreeMap<ByteBuffer, TCell>(result.getColumns());
            int j = -1;
            for (Map.Entry<ByteBuffer, TCell> entry : sortedColumns.entrySet()) {
                ++j;
                while (shouldDelete(i, j)) {
                    ++j;
                }
                assertEquals(HTestConst.DEFAULT_CF_STR + ":" + getCol(j),
                        Bytes.toStringBinaryRemaining(entry.getKey()));
                assertEquals(getValue(i, j), Bytes.toStringBinary(entry.getValue().getValue()));
            }
        }
    } finally {
        closeClientSockets();
    }

    TEST_UTIL.shutdownMiniHBaseCluster();

    final Path baseDir = new Path(conf.get(HConstants.HBASE_DIR));
    final Path oldLogDir = new Path(baseDir, HConstants.HREGION_OLDLOGDIR_NAME);
    int nLogFilesRead = 0;
    List<String> actualLogEntries = new ArrayList<String>();
    ArrayDeque<FileStatus> checkQueue = new ArrayDeque<FileStatus>(
            java.util.Arrays.asList(fs.listStatus(oldLogDir)));
    while (!checkQueue.isEmpty()) {
        FileStatus logFile = checkQueue.pop();
        if (logFile.isDir()) {
            checkQueue.addAll(java.util.Arrays.asList(fs.listStatus(logFile.getPath())));
            continue;
        }
        HLog.Reader r = HLog.getReader(fs, logFile.getPath(), conf);
        LOG.info("Reading HLog: " + logFile.getPath());
        HLog.Entry entry = null;
        while ((entry = r.next(entry)) != null) {
            if (!Bytes.equals(entry.getKey().getTablename(), HTestConst.DEFAULT_TABLE_BYTES)) {
                continue;
            }
            for (KeyValue kv : entry.getEdit().getKeyValues()) {
                if (Bytes.equals(kv.getRow(), HLog.METAROW)) {
                    continue;
                }
                actualLogEntries.add(Bytes.toStringBinary(kv.getRow()) + ","
                        + Bytes.toStringBinary(kv.getQualifier()) + "," + Bytes.toStringBinary(kv.getValue())
                        + "," + (kv.getType() == KeyValue.Type.DeleteColumn.getCode()));
            }
        }
        r.close();
        ++nLogFilesRead;
    }
    assertTrue(nLogFilesRead > 0);
    Collections.sort(expectedLogEntries);
    Collections.sort(actualLogEntries);
    LOG.info("Expected log entries: " + expectedLogEntries.size() + ", actual log entries: "
            + actualLogEntries.size());
    assertEquals(expectedLogEntries.toString(), actualLogEntries.toString());
}

From source file:com.espertech.esper.view.window.TimeWindowView.java

/**
 * This method removes (expires) objects from the window and schedules a new callback for the
 * time when the next oldest message would expire from the window.
 *///w  ww.  j av  a2s.  co  m
protected final void expire() {
    long expireBeforeTimestamp = agentInstanceContext.getStatementContext().getSchedulingService().getTime()
            - millisecondsBeforeExpiry + 1;

    // Remove from the timeWindow any events that have an older or timestamp then the given timestamp
    // The window extends from X to (X - millisecondsBeforeExpiry + 1)
    ArrayDeque<EventBean> expired = timeWindow.expireEvents(expireBeforeTimestamp);

    // If there are child views, fireStatementStopped update method
    if (this.hasViews()) {
        if ((expired != null) && (!expired.isEmpty())) {
            EventBean[] oldEvents = expired.toArray(new EventBean[expired.size()]);
            if (viewUpdatedCollection != null) {
                viewUpdatedCollection.update(null, oldEvents);
            }
            updateChildren(null, oldEvents);
        }
    }

    scheduleExpiryCallback();
}

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

/**
 * Dispatches when the statement is stopped any remaining results.
 *//*from  w ww  . ja  v  a2s . co  m*/
public void dispatchOnStop() {
    lastIterableEvent = null;
    ArrayDeque<UniformPair<EventBean[]>> dispatches = lastResults.get();
    if (dispatches.isEmpty()) {
        return;
    }
    execute();

    lastResults = new ThreadLocal<ArrayDeque<UniformPair<EventBean[]>>>() {
        protected synchronized ArrayDeque<UniformPair<EventBean[]>> initialValue() {
            return new ArrayDeque<UniformPair<EventBean[]>>();
        }
    };
}

From source file:com.heliosdecompiler.helios.gui.controller.FileTreeController.java

private void handleChanges(State startingState, List<TreeNode> changes) {
    ArrayDeque<State> check = new ArrayDeque<>();
    check.add(startingState);/*from   w w  w  .  ja va2s  . c  o m*/
    while (!check.isEmpty()) {
        State next = check.pop();
        TreeNode match = Utils.find(next.needle, next.haystack);
        if (match != null) {
            for (TreeNode current : next.needle.getChildren()) {
                check.add(new State(current, match.getChildren()));
            }
        } else {
            changes.add(next.needle);
        }
    }
}

From source file:com.heliosdecompiler.helios.gui.controller.FileTreeController.java

public void updateTree(List<TreeNode> add, List<TreeNode> remove) {
    Set<TreeItem<TreeNode>> updated = new HashSet<>();

    ArrayDeque<TreeNode> queue = new ArrayDeque<>();
    queue.addAll(add);//  ww  w . j  a  v  a  2 s . c  o  m

    while (!queue.isEmpty()) {
        TreeNode thisNode = queue.pop();

        TreeItem<TreeNode> parent;

        if (thisNode.getParent() == null) {
            parent = rootItem;
        } else {
            parent = itemMap.get(thisNode.getParent());
        }

        updated.add(parent);

        TreeItem<TreeNode> thisItem = new TreeItem<>(thisNode);
        thisItem.addEventHandler(TreeItem.<TreeNode>branchExpandedEvent(), event -> {
            if (thisItem.getChildren().size() == 1) {
                thisItem.getChildren().get(0).setExpanded(true);
            }
        });
        thisItem.setGraphic(new ImageView(new Image(getIconForTreeItem(thisNode))));
        FutureTask<Void> call = new FutureTask<>(() -> {
            parent.getChildren().add(thisItem);
            return null;
        });
        Platform.runLater(call);
        try {
            call.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        itemMap.put(thisNode, thisItem);

        queue.addAll(thisNode.getChildren());
    }

    for (TreeItem<TreeNode> parent : updated) {
        if (parent.getChildren().size() > 1) {
            FutureTask<Void> call = new FutureTask<>(() -> {
                parent.getChildren().sort((a, b) -> {
                    int ac = a.getValue().getChildren().size();
                    int bc = b.getValue().getChildren().size();

                    if (ac == 0 && bc != 0)
                        return 1;
                    else if (ac != 0 && bc == 0)
                        return -1;
                    return a.getValue().getDisplayName().compareTo(b.getValue().getDisplayName());
                });
                return null;
            });
            Platform.runLater(call);
            try {
                call.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

    queue.addAll(remove);

    while (!queue.isEmpty()) {
        TreeNode thisNode = queue.pop();
        TreeItem<TreeNode> thisItem = itemMap.remove(thisNode);
        thisItem.getParent().getChildren().remove(thisItem);
        queue.addAll(thisNode.getChildren());
    }
}

From source file:com.heliosdecompiler.helios.gui.controller.FileTreeController.java

@FXML
public void initialize() {
    this.rootItem = new TreeItem<>(new TreeNode("[root]"));
    this.root.setRoot(this.rootItem);
    this.root.setCellFactory(new TreeCellFactory<>(node -> {
        if (node.getParent() == null) {
            ContextMenu export = new ContextMenu();

            MenuItem exportItem = new MenuItem("Export");

            export.setOnAction(e -> {
                File file = messageHandler.chooseFile().withInitialDirectory(new File("."))
                        .withTitle(Message.GENERIC_CHOOSE_EXPORT_LOCATION_JAR.format())
                        .withExtensionFilter(new FileFilter(Message.FILETYPE_JAVA_ARCHIVE.format(), "*.jar"),
                                true)//from  w  w w . j  a va 2s.co  m
                        .promptSave();

                OpenedFile openedFile = (OpenedFile) node.getMetadata().get(OpenedFile.OPENED_FILE);

                Map<String, byte[]> clone = new HashMap<>(openedFile.getContents());

                backgroundTaskHelper.submit(
                        new BackgroundTask(Message.TASK_SAVING_FILE.format(node.getDisplayName()), true, () -> {
                            try {
                                if (!file.exists()) {
                                    if (!file.createNewFile()) {
                                        throw new IOException("Could not create export file");
                                    }
                                }

                                try (ZipOutputStream zipOutputStream = new ZipOutputStream(
                                        new FileOutputStream(file))) {
                                    for (Map.Entry<String, byte[]> ent : clone.entrySet()) {
                                        ZipEntry zipEntry = new ZipEntry(ent.getKey());
                                        zipOutputStream.putNextEntry(zipEntry);
                                        zipOutputStream.write(ent.getValue());
                                        zipOutputStream.closeEntry();
                                    }
                                }

                                messageHandler.handleMessage(Message.GENERIC_EXPORTED.format());
                            } catch (IOException ex) {
                                messageHandler.handleException(Message.ERROR_IOEXCEPTION_OCCURRED.format(), ex);
                            }
                        }));
            });

            export.getItems().add(exportItem);
            return export;
        }
        return null;
    }));

    root.addEventHandler(KeyEvent.KEY_RELEASED, event -> {
        if (event.getCode() == KeyCode.ENTER) {
            TreeItem<TreeNode> selected = this.root.getSelectionModel().getSelectedItem();
            if (selected != null) {
                if (selected.getChildren().size() != 0) {
                    selected.setExpanded(!selected.isExpanded());
                } else {
                    getParentController().getAllFilesViewerController().handleClick(selected.getValue());
                }
            }
        }
    });

    Tooltip tooltip = new Tooltip();
    StringBuilder search = new StringBuilder();

    List<TreeItem<TreeNode>> searchContext = new ArrayList<>();
    AtomicInteger searchIndex = new AtomicInteger();

    root.focusedProperty().addListener((observable, oldValue, newValue) -> {
        if (!newValue) {
            tooltip.hide();
            search.setLength(0);
        }
    });

    root.boundsInLocalProperty().addListener((observable, oldValue, newValue) -> {
        Bounds bounds = root.localToScreen(newValue);
        tooltip.setAnchorX(bounds.getMinX());
        tooltip.setAnchorY(bounds.getMinY());
    });

    root.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
        if (tooltip.isShowing() && event.getCode() == KeyCode.UP) {
            if (searchIndex.decrementAndGet() < 0) {
                searchIndex.set(searchContext.size() - 1);
            }
        } else if (tooltip.isShowing() && event.getCode() == KeyCode.DOWN) {
            if (searchIndex.incrementAndGet() >= searchContext.size()) {
                searchIndex.set(0);
            }
        } else {
            return;
        }
        event.consume();

        root.scrollTo(root.getRow(searchContext.get(searchIndex.get())));
        root.getSelectionModel().select(searchContext.get(searchIndex.get()));
    });

    root.addEventHandler(KeyEvent.KEY_TYPED, event -> {
        if (event.getCharacter().charAt(0) == '\b') {
            if (search.length() > 0) {
                search.setLength(search.length() - 1);
            }
        } else if (event.getCharacter().charAt(0) == '\u001B') { //esc
            tooltip.hide();
            search.setLength(0);
            return;
        } else if (search.length() > 0
                || (search.length() == 0 && StringUtils.isAlphanumeric(event.getCharacter()))) {
            search.append(event.getCharacter());
            if (!tooltip.isShowing()) {
                tooltip.show(root.getScene().getWindow());
            }
        }

        if (!tooltip.isShowing())
            return;

        String str = search.toString();
        tooltip.setText("Search for: " + str);

        searchContext.clear();

        ArrayDeque<TreeItem<TreeNode>> deque = new ArrayDeque<>();
        deque.addAll(rootItem.getChildren());

        while (!deque.isEmpty()) {
            TreeItem<TreeNode> item = deque.poll();
            if (item.getValue().getDisplayName().contains(str)) {
                searchContext.add(item);
            }
            if (item.isExpanded() && item.getChildren().size() > 0)
                deque.addAll(item.getChildren());
        }

        searchIndex.set(0);
        if (searchContext.size() > 0) {
            root.scrollTo(root.getRow(searchContext.get(0)));
            root.getSelectionModel().select(searchContext.get(0));
        }
    });

    openedFileController.loadedFiles().addListener((MapChangeListener<String, OpenedFile>) change -> {
        if (change.getValueAdded() != null) {
            updateTree(change.getValueAdded());
        }
        if (change.getValueRemoved() != null) {
            this.rootItem.getChildren()
                    .removeIf(ti -> ti.getValue().equals(change.getValueRemoved().getRoot()));
        }
    });
}

From source file:edu.oregonstate.eecs.mcplan.domains.planetwars.PwSimulator.java

@Override
public void untakeLastAction() {
    final ArrayDeque<PwEvent> frame = event_history.pop();
    final int frame_size = frame.size();
    while (!frame.isEmpty()) {
        final PwEvent e = frame.pop();
        e.undoAction(s);//from  ww  w  .j  a va  2s  .  c o m
    }
    s.t -= 1;
    depth_ -= frame_size;
}

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

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

    ArrayDeque<Object> deque = new ArrayDeque<>();
    assertNull(deque.pollLast());//  w ww. j av  a  2  s . c  o m
    assertTrue(deque.isEmpty());

    deque.add(o1);
    assertEquals(o1, deque.pollLast());
    assertTrue(deque.isEmpty());
    assertNull(deque.pollFirst());

    deque.add(o1);
    deque.add(o2);
    assertEquals(o2, deque.pollLast());
    checkDequeSizeAndContent(deque, o1);
    assertEquals(o1, deque.pollLast());
    assertTrue(deque.isEmpty());
    assertNull(deque.pollLast());
}

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

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

    ArrayDeque<Object> deque = new ArrayDeque<>();
    assertNull(deque.pollFirst());//  www  .  j a v  a  2s.  c  o m
    assertTrue(deque.isEmpty());

    deque.add(o1);
    assertEquals(o1, deque.pollFirst());
    assertTrue(deque.isEmpty());
    assertNull(deque.pollFirst());

    deque.add(o1);
    deque.add(o2);
    assertEquals(o1, deque.pollFirst());
    checkDequeSizeAndContent(deque, o2);
    assertEquals(o2, deque.pollFirst());
    assertTrue(deque.isEmpty());
    assertNull(deque.pollFirst());
}

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

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

    ArrayDeque<Object> deque = new ArrayDeque<>();
    assertNull(deque.poll());/*from www  .  j  ava 2 s  .c  o  m*/

    deque.add(o1);
    assertEquals(o1, deque.poll());
    assertTrue(deque.isEmpty());

    deque.add(o1);
    deque.add(o2);
    assertEquals(o1, deque.poll());
    checkDequeSizeAndContent(deque, o2);
    assertEquals(o2, deque.poll());
    assertTrue(deque.isEmpty());
    assertNull(deque.poll());
}