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:acmi.l2.clientmod.l2smr.Controller.java

@FXML
private void modify() {
    ModifyDialog modifyDialog = new ModifyDialog();
    if (ButtonType.OK == modifyDialog.showAndWait().orElse(ButtonType.CANCEL)) {
        Collection<Actor> selected = this.table.getSelectionModel().getSelectedItems();

        selected.forEach(modifyDialog.getTransform());

        updateSMAPane();//from  w w  w.ja  v  a 2s  .c  o  m

        try (UnrealPackage up = new UnrealPackage(
                new File(getMapsDir(), this.unrChooser.getSelectionModel().getSelectedItem()), false)) {
            for (Actor actor : selected) {
                UnrealPackage.ExportEntry entry = up.getExportTable().get(actor.getInd());
                byte[] raw = entry.getObjectRawData();
                Offsets offsets = actor.getOffsets();
                StaticMeshActorUtil.setLocation(raw, offsets, actor.getX(), actor.getY(), actor.getZ());
                entry.setObjectRawData(raw);
            }
        } catch (UncheckedIOException e) {
            onException("Staticmesh modify failed", e);
        }
    }
}

From source file:ai.grakn.test.graql.analytics.AnalyticsTest.java

@Test
public void testDegreeIsPersisted() throws Exception {
    // TODO: Fix on TinkerGraphComputer
    assumeFalse(usingTinker());//from w w w.  java  2s. c o  m

    // create a simple graph
    RoleType pet = graph.putRoleType("pet");
    RoleType owner = graph.putRoleType("owner");
    RoleType breeder = graph.putRoleType("breeder");
    RelationType mansBestFriend = graph.putRelationType("mans-best-friend").hasRole(pet).hasRole(owner)
            .hasRole(breeder);
    EntityType person = graph.putEntityType("person").playsRole(owner).playsRole(breeder);
    EntityType animal = graph.putEntityType("animal").playsRole(pet);

    // make one person breeder and owner
    Entity coco = animal.addEntity();
    Entity dave = person.addEntity();
    Relation daveBreedsAndOwnsCoco = mansBestFriend.addRelation().putRolePlayer(pet, coco).putRolePlayer(owner,
            dave);

    // manual degrees
    Map<String, Long> referenceDegrees = new HashMap<>();
    referenceDegrees.put(coco.getId(), 1L);
    referenceDegrees.put(dave.getId(), 1L);
    referenceDegrees.put(daveBreedsAndOwnsCoco.getId(), 2L);

    // validate
    graph.commit();

    // compute and persist degrees
    Analytics analytics = new Analytics(graph.getKeyspace(), new HashSet<>(), new HashSet<>());
    analytics.degreesAndPersist();

    // check degrees are correct
    graph = factory.getGraph();
    GraknGraph finalGraph = graph;
    referenceDegrees.entrySet().forEach(entry -> {
        Instance instance = finalGraph.getConcept(entry.getKey());
        if (instance.isEntity()) {
            assertTrue(instance.asEntity().resources().iterator().next().getValue().equals(entry.getValue()));
        } else if (instance.isRelation()) {
            assertTrue(instance.asRelation().resources().iterator().next().getValue().equals(entry.getValue()));
        }
    });

    // check only expected resources exist
    Collection<String> allConcepts = new ArrayList<>();
    ResourceType<Long> rt = graph.getResourceType(Analytics.degree);
    Collection<Resource<Long>> degrees = rt.instances();
    Map<Instance, Long> currentDegrees = new HashMap<>();
    degrees.forEach(degree -> {
        Long degreeValue = degree.getValue();
        degree.ownerInstances().forEach(instance -> currentDegrees.put(instance, degreeValue));
    });

    // check all resources exist and no more
    assertTrue(CollectionUtils.isEqualCollection(currentDegrees.values(), referenceDegrees.values()));

    // persist again and check again
    analytics.degreesAndPersist();

    // check only expected resources exist
    graph = factory.getGraph();
    rt = graph.getResourceType(Analytics.degree);
    degrees = rt.instances();
    degrees.forEach(i -> i.ownerInstances().iterator().forEachRemaining(r -> allConcepts.add(r.getId())));

    // check degrees are correct
    GraknGraph finalGraph1 = graph;
    referenceDegrees.entrySet().forEach(entry -> {
        Instance instance = finalGraph1.getConcept(entry.getKey());
        if (instance.isEntity()) {
            assertTrue(instance.asEntity().resources().iterator().next().getValue().equals(entry.getValue()));
        } else if (instance.isRelation()) {
            assertTrue(instance.asRelation().resources().iterator().next().getValue().equals(entry.getValue()));
        }
    });

    degrees = rt.instances();
    currentDegrees.clear();
    degrees.forEach(degree -> {
        Long degreeValue = degree.getValue();
        degree.ownerInstances().forEach(instance -> currentDegrees.put(instance, degreeValue));
    });

    // check all resources exist and no more
    assertTrue(CollectionUtils.isEqualCollection(currentDegrees.values(), referenceDegrees.values()));
}

From source file:io.sqp.client.impl.SqpConnectionImpl.java

CompletableFuture<Void> closeServerResources(Collection<CloseableServerResource> resources) {
    if (resources.isEmpty()) {
        return CompletableFuture.completedFuture(null);
    }//  w  ww.j  a v  a  2s.c  o  m
    CompletableFuture<Void> future = new CompletableFuture<>();

    List<String> cursorIds = resources.stream().filter(r -> r instanceof CursorImpl)
            .map(CloseableServerResource::getId).collect(Collectors.toList());
    List<String> statementIds = resources.stream().filter(r -> r instanceof PreparedStatementImpl)
            .map(CloseableServerResource::getId).collect(Collectors.toList());
    // now set their status to closed
    resources.forEach(CloseableServerResource::setClosed);

    // remove them from the open resource list
    // TODO: wait for success?
    cursorIds.forEach(_openServerResources::remove);
    statementIds.forEach(_openServerResources::remove);

    send(new ReleaseMessage(cursorIds, statementIds), new ConfirmationResponseHandler(future,
            MessageType.ReleaseCompleteMessage, "waiting for a cursor/statement release confirmation"));
    return future;
}

From source file:org.ligoj.app.plugin.id.resource.UserOrgResource.java

/**
 * Validate assigned groups, and return corresponding group identifiers. The groups must be visible by the
 * principal, and added/removed groups from the user must be writable by the principal.
 *
 * @param previousGroups/* ww  w . ja  v  a 2 s . c om*/
 *            The current user's groups.used to validate the changes.
 * @param desiredGroups
 *            The groups the principal user has assigned to the user. In this list, there are some read-only groups
 *            previously assigned to this user. Only the changes are checked.
 * @param delegates
 *            The delegates (read/write) of the principal user.
 */
private void validateAndGroupsCN(final Collection<String> previousGroups,
        final Collection<String> desiredGroups, final List<DelegateOrg> delegates) {
    // Check visibility of the desired groups
    desiredGroups.forEach(g -> getGroup().findByIdExpected(securityHelper.getLogin(), g));

    // Check the visible updated groups can be edited by the principal
    CollectionUtils.disjunction(desiredGroups, previousGroups).forEach(g -> validateWriteGroup(g, delegates));
}

From source file:org.eclipse.hawkbit.repository.test.util.TestdataFactory.java

/**
 * Creates {@link DistributionSet} in repository including three
 * {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT}
 * , {@link #SM_TYPE_APP}.//from www . j a va 2  s. c  om
 * 
 * @param prefix
 *            for {@link SoftwareModule}s and {@link DistributionSet}s name,
 *            vendor and description.
 * @param version
 *            {@link DistributionSet#getVersion()} and
 *            {@link SoftwareModule#getVersion()} extended by a random
 *            number.updat
 * @param tags
 *            {@link DistributionSet#getTags()}
 * 
 * @return {@link DistributionSet} entity.
 */
public DistributionSet createDistributionSet(final String prefix, final String version,
        final Collection<DistributionSetTag> tags) {

    final DistributionSet set = createDistributionSet(prefix, version, false);

    tags.forEach(
            tag -> distributionSetManagement.toggleTagAssignment(Arrays.asList(set.getId()), tag.getName()));

    return distributionSetManagement.get(set.getId()).get();

}

From source file:org.trustedanalytics.cloud.cc.CcClient.java

@Override
public Collection<CcOrgPermission> getUserPermissions(UUID user, Collection<UUID> orgsFilter) {

    Collection<CcOrg> orgs = getUserOrgs(user);
    if (!orgsFilter.isEmpty()) {
        orgs.removeIf(ccOrg -> !orgsFilter.contains(ccOrg.getGuid()));
    }/*from w w  w. java  2s  . c o  m*/

    Collection<CcOrg> managedOrganizations = getManagedOrganizations(user);
    Collection<CcOrg> auditedOrganizations = getAuditedOrganizations(user);
    Collection<CcOrg> billingManagedOrganizations = getBillingManagedOrganizations(user);

    Collection<CcOrgPermission> permissions = new ArrayList<>();
    orgs.forEach(org -> {
        boolean isManager = managedOrganizations.contains(org);
        boolean isAuditor = auditedOrganizations.contains(org);
        boolean isBillingManager = billingManagedOrganizations.contains(org);
        permissions.add(new CcOrgPermission(org, isManager, isAuditor, isBillingManager));
    });

    return permissions;
}

From source file:org.apache.syncope.core.provisioning.java.propagation.PropagationManagerImpl.java

/**
 * Create propagation tasks.// w  w w . j  a  v  a  2  s . c o m
 *
 * @param any to be provisioned
 * @param password clear text password to be provisioned
 * @param changePwd whether password should be included for propagation attributes or not
 * @param enable whether user must be enabled or not
 * @param deleteOnResource whether any must be deleted anyway from external resource or not
 * @param propByRes operation to be performed per resource
 * @param vAttrs virtual attributes to be set
 * @return list of propagation tasks created
 */
protected List<PropagationTaskTO> createTasks(final Any<?> any, final String password, final boolean changePwd,
        final Boolean enable, final boolean deleteOnResource, final PropagationByResource propByRes,
        final Collection<AttrTO> vAttrs) {

    LOG.debug("Provisioning {}:\n{}", any, propByRes);

    // Avoid duplicates - see javadoc
    propByRes.purge();
    LOG.debug("After purge {}:\n{}", any, propByRes);

    // Virtual attributes
    Set<String> virtualResources = new HashSet<>();
    virtualResources.addAll(propByRes.get(ResourceOperation.CREATE));
    virtualResources.addAll(propByRes.get(ResourceOperation.UPDATE));
    virtualResources.addAll(dao(any.getType().getKind()).findAllResourceKeys(any.getKey()));

    Map<String, Set<Attribute>> vAttrMap = new HashMap<>();
    if (vAttrs != null) {
        vAttrs.forEach(vAttr -> {
            VirSchema schema = virSchemaDAO.find(vAttr.getSchema());
            if (schema == null) {
                LOG.warn("Ignoring invalid {} {}", VirSchema.class.getSimpleName(), vAttr.getSchema());
            } else if (schema.isReadonly()) {
                LOG.warn("Ignoring read-only {} {}", VirSchema.class.getSimpleName(), vAttr.getSchema());
            } else if (anyUtilsFactory.getInstance(any).getAllowedSchemas(any, VirSchema.class).contains(schema)
                    && virtualResources.contains(schema.getProvision().getResource().getKey())) {

                Set<Attribute> values = vAttrMap.get(schema.getProvision().getResource().getKey());
                if (values == null) {
                    values = new HashSet<>();
                    vAttrMap.put(schema.getProvision().getResource().getKey(), values);
                }
                values.add(AttributeBuilder.build(schema.getExtAttrName(), vAttr.getValues()));

                propByRes.add(ResourceOperation.UPDATE, schema.getProvision().getResource().getKey());
            } else {
                LOG.warn("{} not owned by or {} not allowed for {}", schema.getProvision().getResource(),
                        schema, any);
            }
        });
    }
    LOG.debug("With virtual attributes {}:\n{}\n{}", any, propByRes, vAttrMap);

    List<PropagationTaskTO> tasks = new ArrayList<>();

    propByRes.asMap().entrySet().forEach(entry -> {
        ExternalResource resource = resourceDAO.find(entry.getKey());
        Provision provision = resource == null ? null : resource.getProvision(any.getType()).orElse(null);
        List<? extends Item> mappingItems = provision == null ? Collections.<Item>emptyList()
                : MappingUtils.getPropagationItems(provision.getMapping().getItems());

        if (resource == null) {
            LOG.error("Invalid resource name specified: {}, ignoring...", entry.getKey());
        } else if (provision == null) {
            LOG.error("No provision specified on resource {} for type {}, ignoring...", resource,
                    any.getType());
        } else if (mappingItems.isEmpty()) {
            LOG.warn("Requesting propagation for {} but no propagation mapping provided for {}", any.getType(),
                    resource);
        } else {
            PropagationTaskTO task = new PropagationTaskTO();
            task.setResource(resource.getKey());
            task.setObjectClassName(provision.getObjectClass().getObjectClassValue());
            task.setAnyTypeKind(any.getType().getKind());
            task.setAnyType(any.getType().getKey());
            if (!deleteOnResource) {
                task.setEntityKey(any.getKey());
            }
            task.setOperation(entry.getValue());
            task.setOldConnObjectKey(propByRes.getOldConnObjectKey(resource.getKey()));

            Pair<String, Set<Attribute>> preparedAttrs = mappingManager.prepareAttrs(any, password, changePwd,
                    enable, provision);
            task.setConnObjectKey(preparedAttrs.getKey());

            // Check if any of mandatory attributes (in the mapping) is missing or not received any value: 
            // if so, add special attributes that will be evaluated by PropagationTaskExecutor
            List<String> mandatoryMissing = new ArrayList<>();
            List<String> mandatoryNullOrEmpty = new ArrayList<>();
            mappingItems.stream()
                    .filter(item -> (!item.isConnObjectKey()
                            && JexlUtils.evaluateMandatoryCondition(item.getMandatoryCondition(), any)))
                    .forEachOrdered(item -> {
                        Attribute attr = AttributeUtil.find(item.getExtAttrName(), preparedAttrs.getValue());
                        if (attr == null) {
                            mandatoryMissing.add(item.getExtAttrName());
                        } else if (attr.getValue() == null || attr.getValue().isEmpty()) {
                            mandatoryNullOrEmpty.add(item.getExtAttrName());
                        }
                    });
            if (!mandatoryMissing.isEmpty()) {
                preparedAttrs.getValue().add(AttributeBuilder
                        .build(PropagationTaskExecutor.MANDATORY_MISSING_ATTR_NAME, mandatoryMissing));
            }
            if (!mandatoryNullOrEmpty.isEmpty()) {
                preparedAttrs.getValue().add(AttributeBuilder.build(
                        PropagationTaskExecutor.MANDATORY_NULL_OR_EMPTY_ATTR_NAME, mandatoryNullOrEmpty));
            }

            if (vAttrMap.containsKey(resource.getKey())) {
                preparedAttrs.getValue().addAll(vAttrMap.get(resource.getKey()));
            }

            task.setAttributes(POJOHelper.serialize(preparedAttrs.getValue()));

            tasks.add(task);

            LOG.debug("PropagationTask created: {}", task);
        }
    });

    return tasks;
}

From source file:io.pravega.segmentstore.server.host.ZKSegmentContainerMonitor.java

/**
 * The container assignment monitor./*from w w  w  .j  a v  a  2  s  . c  om*/
 * This method will fetch the current owned containers for this host and ensures that the local containers' state
 * reflects this.
 */
@Synchronized
private void checkAssignment() {
    long traceId = LoggerHelpers.traceEnter(log, "checkAssignment");
    try {
        Exceptions.checkNotClosed(closed.get(), this);

        // Fetch the list of containers that is supposed to be owned by this host.
        Set<Integer> desiredList = getDesiredContainerList();
        if (desiredList != null) {
            Collection<Integer> runningContainers = new HashSet<>(this.handles.keySet());
            Collection<Integer> containersPendingTasks = new HashSet<>(this.pendingTasks);

            // Filter out containers which have pending tasks so we don't initiate conflicting events on the same
            // containers. Events for these containers will be tried on subsequent runs of this executor.
            Collection<Integer> containersToBeStarted = CollectionHelpers.filterOut(desiredList,
                    runningContainers);
            containersToBeStarted = CollectionHelpers.filterOut(containersToBeStarted, containersPendingTasks);

            Collection<Integer> containersToBeStopped = CollectionHelpers.filterOut(runningContainers,
                    desiredList);
            containersToBeStopped = CollectionHelpers.filterOut(containersToBeStopped, containersPendingTasks);

            log.info(
                    "Container Changes: Desired = {}, Current = {}, PendingTasks = {}, ToStart = {}, ToStop = {}.",
                    desiredList, runningContainers, containersPendingTasks, containersToBeStarted,
                    containersToBeStopped);

            // Initiate the start and stop tasks asynchronously.
            containersToBeStarted.forEach(this::startContainer);
            containersToBeStopped.forEach(this::stopContainer);
        } else {
            log.warn("No segment container assignments found");
        }
    } catch (Throwable e) {
        // Need to catch all exceptions here since throwing any exception here will halt this scheduled job.
        log.warn("Failed to monitor the segmentcontainer assignment: ", e);
    } finally {
        LoggerHelpers.traceLeave(log, "checkAssignment", traceId);
    }
}

From source file:com.vmware.photon.controller.deployer.xenon.workflow.DeploymentWorkflowService.java

private void failTask(Collection<Throwable> failures) {
    failures.forEach((throwable) -> ServiceUtils.logSevere(this, throwable));
    TaskUtils.sendSelfPatch(this, buildPatch(TaskState.TaskStage.FAILED, null, failures.iterator().next()));
}

From source file:com.hurence.logisland.processor.EvaluateJsonPath.java

/**
 * Provides cleanup of the map for any JsonPath values that may have been created. This will remove common values shared between multiple instances, but will be regenerated when the next
 * validation cycle occurs as a result of isStale()
 *
 * @param processContext context/*from   w  w  w  .  j ava  2  s. c  o  m*/
 */
/*  @OnRemoved
  public void onRemoved(ProcessContext processContext) {
for (PropertyDescriptor propertyDescriptor : getPropertyDescriptors()) {
    if (propertyDescriptor.isDynamic()) {
        cachedJsonPathMap.remove(processContext.getProperty(propertyDescriptor).getValue());
    }
}
  }*/
@Override
public Collection<Record> process(ProcessContext processContext, Collection<Record> records)
        throws ProcessException {
    String returnType = processContext.getPropertyValue(RETURN_TYPE).asString();

    String representationOption = processContext.getPropertyValue(NULL_VALUE_DEFAULT_REPRESENTATION).asString();
    final String nullDefaultValue = NULL_REPRESENTATION_MAP.get(representationOption);

    /* Build the JsonPath expressions from attributes */
    final Map<String, JsonPath> attributeToJsonPathMap = new HashMap<>();

    for (final Map.Entry<PropertyDescriptor, String> entry : processContext.getProperties().entrySet()) {
        if (!entry.getKey().isDynamic()) {
            continue;
        }
        final JsonPath jsonPath = JsonPath.compile(entry.getValue());
        attributeToJsonPathMap.put(entry.getKey().getName(), jsonPath);
    }

    String jsonInputField = processContext.getPropertyValue(JSON_INPUT_FIELD).asString();

    records.forEach(record -> {
        if (record.hasField(jsonInputField)) {
            DocumentContext documentContext = null;
            try {
                documentContext = validateAndEstablishJsonContext(record.getField(jsonInputField).asString());
            } catch (InvalidJsonException e) {
                logger.error("Record {} did not have valid JSON content.", record);
                record.addError(ERROR_INVALID_JSON_FIELD,
                        "unable to parse content of field : " + jsonInputField);
            }

            final Map<String, String> jsonPathResults = new HashMap<>();
            for (final Map.Entry<String, JsonPath> attributeJsonPathEntry : attributeToJsonPathMap.entrySet()) {

                final String jsonPathAttrKey = attributeJsonPathEntry.getKey();
                final JsonPath jsonPathExp = attributeJsonPathEntry.getValue();
                final String pathNotFound = processContext.getPropertyValue(PATH_NOT_FOUND).asString();

                final AtomicReference<Object> resultHolder = new AtomicReference<>(null);
                try {
                    final Object result = documentContext.read(jsonPathExp);
                    if (returnType.equals(RETURN_TYPE_SCALAR) && !isJsonScalar(result)) {
                        String error = String.format(
                                "Unable to return a scalar value for the expression %s "
                                        + "for Record %s. Evaluated value was %s.",
                                jsonPathExp.getPath(), record.getId(), result.toString());

                        logger.error(error);
                        record.addError(ERROR_INVALID_JSON_FIELD, error);
                    }
                    resultHolder.set(result);
                } catch (PathNotFoundException e) {

                    if (pathNotFound.equals(PATH_NOT_FOUND_WARN)) {

                        String error = String.format("Record %s could not find path %s for field %s..",
                                record.getId(), jsonPathExp.getPath(), jsonPathAttrKey);
                        logger.error(error);
                        record.addError(ERROR_INVALID_JSON_FIELD, error);
                    }
                    jsonPathResults.put(jsonPathAttrKey, StringUtils.EMPTY);

                }

                final FieldType resultType = getResultType(resultHolder.get());
                if (resultType != FieldType.STRING)
                    record.setField(jsonPathAttrKey, resultType, resultHolder.get());
                else
                    record.setField(jsonPathAttrKey, resultType,
                            getResultRepresentation(resultHolder.get(), nullDefaultValue));

            }

        } else {
            String error = String.format("Record %s has no field %s.", record.getId(), jsonInputField);
            logger.error(error);
            record.addError(ERROR_INVALID_JSON_FIELD, error);
        }
    });

    return records;
}