Example usage for java.util Collection forEach

List of usage examples for java.util Collection forEach

Introduction

In this page you can find the example usage for java.util Collection forEach.

Prototype

default void forEach(Consumer<? super T> action) 

Source Link

Document

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Usage

From source file:com.hortonworks.streamline.streams.security.service.SecurityCatalogService.java

private Set<Role> getParentRoles(Long childRoleId) {
    List<QueryParam> qps = QueryParam.params(RoleHierarchy.CHILD_ID, String.valueOf(childRoleId));
    Collection<RoleHierarchy> roleHierarchies = dao.find(RoleHierarchy.NAMESPACE, qps);
    Set<Role> res = new HashSet<>();
    roleHierarchies.forEach(rh -> {
        res.add(getRole(rh.getParentId()));
    });//from  w ww.  j  av  a 2s  .c  o m
    return res;
}

From source file:at.ac.tuwien.qse.sepm.gui.controller.impl.GridViewImpl.java

@FXML
private void initialize() {
    LOGGER.debug("initializing");

    this.grid = new PaginatedImageGrid(menu);
    content.setCenter(grid);/*w  ww.j a  va  2s.c  om*/
    menu.addListener(new MenuListener());
    organizer.setFilterChangeAction(this::handleFilterChange);

    // Selected photos are shown in the inspector.
    grid.setSelectionChangeAction(inspector::setEntities);

    // CTRL+A select all photos.
    root.setOnMouseClicked((event) -> root.requestFocus());
    root.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
        if (event.isControlDown() && event.getCode() == KeyCode.A) {
            grid.selectAll();
        }
    });

    // Updated photos that no longer match the filter are removed from the grid.
    inspector.setUpdateHandler(() -> {
        Collection<Photo> photos = inspector.getEntities();

        List<Photo> toRemove = new ArrayList<>(photos.size());
        List<Photo> toUpdate = new ArrayList<>(photos.size());

        photos.forEach(p -> {
            if (!organizer.accept(p)) {
                organizer.remove(p);
                toRemove.add(p);
            } else {
                toUpdate.add(p);
            }
        });

        grid.removePhotos(toRemove);
        grid.updatePhotos(toUpdate);
    });

    // Apply the initial filter.
    handleFilterChange();

    // subscribe to photo events
    photoService.subscribeCreate(this::handlePhotoCreated);
    photoService.subscribeUpdate(this::handlePhotoUpdated);
    photoService.subscribeDelete(this::handlePhotoDeleted);

    root.setOnDragEntered(this::handleDragEntered);
    root.setOnDragOver(this::handleDragOver);
    root.setOnDragDropped(this::handleDragDropped);
    root.setOnDragExited(this::handleDragExited);

    try {
        if (workspaceService.getDirectories().isEmpty()) {
            folderDropTarget.setVisible(true);
        }
    } catch (ServiceException ex) {
        ErrorDialog.show(root, "Fehler beim Laden der Bildordner", "");
    }
}

From source file:com.github.blindpirate.gogradle.task.go.GoTest.java

private void rewritePackageName(File reportDir) {
    Collection<File> htmlFiles = filterFilesRecursively(reportDir, new SuffixFileFilter(".html"),
            TrueFileFilter.INSTANCE);//from w  w  w. ja  va 2s  . c om
    String rewriteScript = IOUtils
            .toString(GoTest.class.getClassLoader().getResourceAsStream(REWRITE_SCRIPT_RESOURCE));
    htmlFiles.forEach(htmlFile -> {
        String content = IOUtils.toString(htmlFile);
        content = content.replace("</body>", "</body>" + rewriteScript);
        IOUtils.write(htmlFile, content);
    });
}

From source file:org.apache.hadoop.hbase.client.SimpleRequestController.java

@Override
public void decTaskCounters(Collection<byte[]> regions, ServerName sn) {
    regions.forEach(regBytes -> {
        AtomicInteger regionCnt = taskCounterPerRegion.get(regBytes);
        regionCnt.decrementAndGet();//from w  ww.  jav  a  2  s .  c o  m
    });

    taskCounterPerServer.get(sn).decrementAndGet();
    tasksInProgress.decrementAndGet();
    synchronized (tasksInProgress) {
        tasksInProgress.notifyAll();
    }
}

From source file:org.apache.usergrid.persistence.map.impl.MapSerializationImpl.java

private <T> T getValuesCQL(final MapScope scope, final Collection<String> keys,
        final ResultsBuilderCQL<T> builder) {

    final List<ByteBuffer> serializedKeys = new ArrayList<>();

    keys.forEach(key -> serializedKeys.add(getMapEntryPartitionKey(scope, key)));

    Clause in = QueryBuilder.in("key", serializedKeys);
    Statement statement = QueryBuilder.select().all().from(MAP_ENTRIES_TABLE).where(in);

    ResultSet resultSet = session.execute(statement);

    return builder.buildResultsCQL(resultSet);
}

From source file:io.neba.core.resourcemodels.registration.ModelRegistry.java

/**
 * @return a shallow copy of all registered sources for models, never
 * <code>null</code> but rather an empty list.
 *///w w  w  . ja va2s. co  m
public List<OsgiModelSource<?>> getModelSources() {
    Collection<Collection<OsgiModelSource<?>>> sources = this.typeNameToModelSourcesMap.values();
    List<OsgiModelSource<?>> linearizedSources = new LinkedList<>();
    sources.forEach(linearizedSources::addAll);
    return linearizedSources;
}

From source file:com.hortonworks.streamline.streams.security.service.SecurityCatalogService.java

public Role removeRole(Long roleId) {
    // check if role is part of any parent roles, if so parent role should be deleted first.
    Set<Role> parentRoles = getParentRoles(roleId);
    if (!parentRoles.isEmpty()) {
        throw new IllegalStateException("Role is a child role of the following parent role(s): " + parentRoles
                + ". Parent roles must be deleted first.");
    }// ww  w . jav  a2  s .c om

    // check if role has any users
    List<QueryParam> qps = QueryParam.params(UserRole.ROLE_ID, String.valueOf(roleId));
    Collection<UserRole> userRoles = listUserRoles(qps);
    if (!userRoles.isEmpty()) {
        throw new IllegalStateException("Role has users");
    }

    // remove child role associations
    qps = QueryParam.params(RoleHierarchy.PARENT_ID, String.valueOf(roleId));
    Collection<RoleHierarchy> roleHierarchies = dao.find(RoleHierarchy.NAMESPACE, qps);
    LOG.info("Removing child role association for role id {}", roleId);
    roleHierarchies.forEach(rh -> removeChildRole(roleId, rh.getChildId()));

    // remove permissions assigned to role
    qps = QueryParam.params(AclEntry.SID_ID, String.valueOf(roleId), AclEntry.SID_TYPE,
            AclEntry.SidType.ROLE.toString());
    LOG.info("Removing ACL entries for role id {}", roleId);
    listAcls(qps).forEach(aclEntry -> removeAcl(aclEntry.getId()));
    Role role = new Role();
    role.setId(roleId);
    return dao.remove(new StorableKey(Role.NAMESPACE, role.getPrimaryKey()));
}

From source file:org.duniter.elasticsearch.synchro.SynchroService.java

public void synchronize() {

    final boolean enableSynchroWebsocket = pluginSettings.enableSynchroWebsocket();

    // Closing all opened WS
    if (enableSynchroWebsocket) {
        closeWsClientEndpoints();//from   www.  j a  va  2s . com
    }

    List<String> currencyIds;
    try {
        currencyIds = currencyDao.getCurrencyIds();
    } catch (Exception e) {
        logger.error("Could not retrieve indexed currencies", e);
        currencyIds = null;
    }

    if (CollectionUtils.isEmpty(currencyIds) || CollectionUtils.isEmpty(peerApiFilters)) {
        logger.warn("Skipping synchronization: no indexed currency or no API configured");
        return;
    }

    currencyIds.forEach(currencyId -> peerApiFilters.forEach(peerApiFilter -> {

        logger.info(String.format("[%s] [%s] Starting synchronization... {discovery: %s}", currencyId,
                peerApiFilter.name(), pluginSettings.enableSynchroDiscovery()));

        // Get peers for currencies and API
        Collection<Peer> peers = getPeersFromApi(currencyId, peerApiFilter);
        if (CollectionUtils.isNotEmpty(peers)) {
            peers.forEach(p -> synchronizePeer(p, enableSynchroWebsocket));
            logger.info(String.format("[%s] [%s] Synchronization [OK]", currencyId, peerApiFilter.name()));
        } else {
            logger.info(String.format("[%s] [%s] Synchronization [OK] - no endpoint to synchronize", currencyId,
                    peerApiFilter.name()));
        }
    }));
}

From source file:io.mandrel.data.export.DelimiterSeparatedValuesExporter.java

@Override
public void export(Collection<Blob> blobs) {
    if (addHeader && !headerAdded) {
        try {/*  w  w  w . j a va2 s .  c  om*/
            csvWriter.writeHeader("url", "statusCode", "statusText", "lastCrawlDate", "outlinks",
                    "timeToFetch");
        } catch (Exception e) {
            log.debug("Can not write header {}", csvWriter.getLineNumber(), e);
        }
        headerAdded = true;
    }

    List<Object> buffer = new ArrayList<>(6);

    blobs.forEach(page -> {
        buffer.add(page.getMetadata().getUri());
        buffer.add(page.getMetadata().getFetchMetadata().getStatusCode());
        buffer.add(page.getMetadata().getFetchMetadata().getStatusText());
        buffer.add(page.getMetadata().getFetchMetadata().getLastCrawlDate());
        buffer.add(page.getMetadata().getFetchMetadata().getOutlinks());
        buffer.add(page.getMetadata().getFetchMetadata().getTimeToFetch());

        try {
            csvWriter.write(buffer);
        } catch (Exception e) {
            log.debug("Can not write line {}", csvWriter.getLineNumber(), e);
        }

        buffer.clear();
    });
}

From source file:io.tilt.minka.business.leader.distributor.Distributor.java

private void sendCurrentIssues() {
    final Multimap<Shard, ShardDuty> issues = auditor.getCurrentReallocation().getGroupedIssues();
    final Iterator<Shard> it = issues.keySet().iterator();
    while (it.hasNext()) {
        final Shard shard = it.next();
        // check it's still in ptable
        if (partitionTable.getShardsByState(ONLINE).contains(shard)) {
            final Collection<ShardDuty> duties = auditor.getCurrentReallocation().getGroupedIssues().get(shard);
            if (!duties.isEmpty()) {
                if (transportMany(duties, shard)) {
                    // dont mark to wait for those already confirmed (from fallen shards)
                    duties.forEach(
                            duty -> duty.registerEvent((duty.getState() == PREPARED ? SENT : CONFIRMED)));
                } else {
                    logger.error("{}: Couldnt transport current issues !!!", getClass().getSimpleName());
                }/*w w  w.  j a v  a  2s.  co m*/
            } else {
                throw new IllegalStateException("No duties grouped by shard at Reallocation !!");
            }
        } else {
            logger.error("{}: PartitionTable lost transport's target shard: {}", getClass().getSimpleName(),
                    shard);
        }
    }
}