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:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

protected UidNodeDescription mapToNode(final SearchResult searchResult, final String idAttributeName,
        final Map<String, String> attributeMapping, final Map<String, String> attributeDefaults)
        throws NamingException {
    final Attributes attributes = searchResult.getAttributes();
    final Collection<String> uidValues = this.mapAttribute(attributes.get(idAttributeName), String.class);
    final String uid = uidValues.iterator().next();

    final UidNodeDescription nodeDescription = new UidNodeDescription(searchResult.getNameInNamespace(), uid);

    final Attribute modifyTimestamp = attributes.get(this.modifyTimestampAttributeName);
    if (modifyTimestamp != null) {
        try {/* www  .j  a  v a 2s .c  o  m*/
            nodeDescription.setLastModified(this.timestampFormat.parse(modifyTimestamp.get().toString()));
            LOGGER.debug("Setting last modified of node {} to {}", uid, nodeDescription.getLastModified());
        } catch (final ParseException e) {
            throw new AlfrescoRuntimeException("Failed to parse timestamp.", e);
        }
    }

    final PropertyMap properties = nodeDescription.getProperties();
    for (final String key : attributeMapping.keySet()) {
        final QName keyQName = QName.createQName(key, this.namespaceService);

        final String attributeName = attributeMapping.get(key);
        if (attributeName != null) {
            final Attribute attribute = attributes.get(attributeName);
            final String defaultAttribute = attributeDefaults.get(key);

            if (attribute != null) {
                final Collection<Object> mappedAttributeValue = this.mapAttribute(attribute);
                if (mappedAttributeValue.size() == 1) {
                    final Object singleValue = mappedAttributeValue.iterator().next();
                    if (singleValue instanceof Serializable) {
                        properties.put(keyQName, (Serializable) singleValue);
                    } else {
                        properties.put(keyQName,
                                DefaultTypeConverter.INSTANCE.convert(String.class, singleValue));
                    }
                } else if (!mappedAttributeValue.isEmpty()) {
                    final ArrayList<Serializable> values = new ArrayList<>();
                    mappedAttributeValue.forEach((x) -> {
                        if (x instanceof Serializable) {
                            values.add((Serializable) x);
                        } else {
                            values.add(DefaultTypeConverter.INSTANCE.convert(String.class, x));
                        }
                    });
                    properties.put(keyQName, values);
                } else if (defaultAttribute != null) {
                    properties.put(keyQName, defaultAttribute);
                } else {
                    // Make sure that a 2nd sync, updates deleted ldap attributes (MNT-14026)
                    properties.put(keyQName, null);
                }
            } else if (defaultAttribute != null) {
                LOGGER.debug("Node {} does not provide attriute {} - using default value", uid, attributeName);
                properties.put(keyQName, defaultAttribute);
            } else {
                LOGGER.debug("Node {} does not provide attriute {} - setting to null", uid, attributeName);
                // Make sure that a 2nd sync, updates deleted ldap attributes (MNT-14026)
                properties.put(keyQName, null);
            }
        } else {
            LOGGER.debug("No attribute name has been configured for property {}", keyQName);
            final String defaultValue = attributeDefaults.get(key);
            if (defaultValue != null) {
                LOGGER.debug("Using default value for {} on node {}", keyQName, uid);
                properties.put(keyQName, defaultValue);
            }
        }
    }

    return nodeDescription;
}

From source file:org.nanoframework.orm.jedis.sharded.RedisClientImpl.java

@Override
public Set<String> sunion(final String... keys) {
    Assert.notEmpty(keys);/*  w ww . j a v a  2s . c  o m*/
    ShardedJedis jedis = null;
    try {
        jedis = POOL.getJedis(config.getRedisType());
        final Collection<Jedis> allShards;
        if ((allShards = jedis.getAllShards()).size() == 1) {
            return allShards.iterator().next().sdiff(keys);
        } else if (allShards.size() > 1) {
            final Set<String> unionSet = Sets.newLinkedHashSet();
            allShards.forEach(shard -> unionSet.addAll(shard.sunion(keys)));
            return unionSet;
        }

        return Collections.emptySet();
    } catch (final Throwable e) {
        throw new RedisClientException(e.getMessage(), e);
    } finally {
        POOL.close(jedis);
    }
}

From source file:org.apache.syncope.core.provisioning.java.data.AbstractAnyDataBinder.java

protected void fillTO(final AnyTO anyTO, final String realmFullPath,
        final Collection<? extends AnyTypeClass> auxClasses,
        final Collection<? extends PlainAttr<?>> plainAttrs, final Map<DerSchema, String> derAttrs,
        final Map<VirSchema, List<String>> virAttrs, final Collection<? extends ExternalResource> resources,
        final boolean details) {

    anyTO.setRealm(realmFullPath);//from   w  w w .j a va 2 s .c  om

    anyTO.getAuxClasses().addAll(auxClasses.stream().map(cls -> cls.getKey()).collect(Collectors.toList()));

    plainAttrs.stream().map(plainAttr -> {
        AttrTO.Builder attrTOBuilder = new AttrTO.Builder().schema(plainAttr.getSchema().getKey())
                .values(plainAttr.getValuesAsStrings());
        if (details) {
            attrTOBuilder.schemaInfo(schemaDataBinder.getPlainSchemaTO(plainAttr.getSchema()));
        }
        return attrTOBuilder;
    }).forEachOrdered(attrTOBuilder -> {
        anyTO.getPlainAttrs().add(attrTOBuilder.build());
    });

    derAttrs.entrySet().stream().map(entry -> {
        AttrTO.Builder attrTOBuilder = new AttrTO.Builder().schema(entry.getKey().getKey())
                .value(entry.getValue());
        if (details) {
            attrTOBuilder.schemaInfo(schemaDataBinder.getDerSchemaTO(entry.getKey()));
        }
        return attrTOBuilder;
    }).forEachOrdered(attrTOBuilder -> {
        anyTO.getDerAttrs().add(attrTOBuilder.build());
    });

    virAttrs.entrySet().stream().map(entry -> {
        AttrTO.Builder attrTOBuilder = new AttrTO.Builder().schema(entry.getKey().getKey())
                .values(entry.getValue());
        if (details) {
            attrTOBuilder.schemaInfo(schemaDataBinder.getVirSchemaTO(entry.getKey()));
        }
        return attrTOBuilder;
    }).forEachOrdered(attrTOBuilder -> {
        anyTO.getVirAttrs().add(attrTOBuilder.build());
    });

    resources.forEach(resource -> {
        anyTO.getResources().add(resource.getKey());
    });
}

From source file:org.nanoframework.orm.jedis.sharded.RedisClientImpl.java

@Override
public Set<String> sdiff(final String... keys) {
    Assert.notEmpty(keys);//from  www  . j ava 2  s . c  o  m
    ShardedJedis jedis = null;
    try {
        jedis = POOL.getJedis(config.getRedisType());
        final Collection<Jedis> allShards;
        if ((allShards = jedis.getAllShards()).size() == 1) {
            return allShards.iterator().next().sdiff(keys);
        } else if (allShards.size() > 1) {
            final Set<String> unionSet = Sets.newLinkedHashSet();
            Set<String> diffSet = Sets.newLinkedHashSet();
            allShards.forEach(shard -> {
                final Set<String> diff = shard.sdiff(keys);
                if (!unionSet.isEmpty()) {
                    diff.stream().filter(item -> !unionSet.contains(item)).forEach(item -> diffSet.add(item));
                } else {
                    diffSet.addAll(diff);
                }

                unionSet.addAll(diff);
            });

            return diffSet;
        }

        return Collections.emptySet();
    } catch (final Throwable e) {
        throw new RedisClientException(e.getMessage(), e);
    } finally {
        POOL.close(jedis);
    }
}

From source file:net.dv8tion.jda.core.managers.GuildController.java

/**
 * Modifies the complete {@link net.dv8tion.jda.core.entities.Role Role} set of the specified {@link net.dv8tion.jda.core.entities.Member Member}
 * <br>The provided roles will replace all current Roles of the specified Member.
 *
 * <p><u>The new roles <b>must not</b> contain the Public Role of the Guild</u>
 *
 * <h1>Warning</h1>//  www .  ja  v a  2s  .  c o  m
 * <b>This may <u>not</u> be used together with any other role add/remove/modify methods for the same Member
 * within one event listener cycle! The changes made by this require cache updates which are triggered by
 * lifecycle events which are received later. This may only be called again once the specific Member has been updated
 * by a {@link net.dv8tion.jda.core.events.guild.member.GenericGuildMemberEvent GenericGuildMemberEvent} targeting the same Member.</b>
 *
 * <p>Possible {@link net.dv8tion.jda.core.requests.ErrorResponse ErrorResponses} caused by
 * the returned {@link net.dv8tion.jda.core.requests.RestAction RestAction} include the following:
 * <ul>
 *     <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
 *     <br>The Members Roles could not be modified due to a permission discrepancy</li>
 *
 *     <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS}
 *     <br>We were removed from the Guild before finishing the task</li>
 *
 *     <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#UNKNOWN_MEMBER UNKNOWN_MEMBER}
 *     <br>The target Member was removed from the Guild before finishing the task</li>
 * </ul>
 *
 * @param  member
 *         A {@link net.dv8tion.jda.core.entities.Member Member} of which to override the Roles of
 * @param  roles
 *         New collection of {@link net.dv8tion.jda.core.entities.Role Roles} for the specified Member
 *
 * @throws net.dv8tion.jda.core.exceptions.GuildUnavailableException
 *         If the guild is temporarily not {@link net.dv8tion.jda.core.entities.Guild#isAvailable() available}
 * @throws net.dv8tion.jda.core.exceptions.PermissionException
 *         If the provided roles are higher in the Guild's hierarchy
 *         and thus cannot be modified by the currently logged in account
 * @throws IllegalArgumentException
 *         <ul>
 *             <li>If any of the provided arguments is {@code null}</li>
 *             <li>If any of the provided arguments is not from this Guild</li>
 *             <li>If any of the specified {@link net.dv8tion.jda.core.entities.Role Roles} is managed</li>
 *             <li>If any of the specified {@link net.dv8tion.jda.core.entities.Role Roles} is the {@code Public Role} of this Guild</li>
 *         </ul>
 *
 * @return {@link net.dv8tion.jda.core.requests.restaction.AuditableRestAction AuditableRestAction}
 *
 * @see    #modifyMemberRoles(Member, Collection)
 */
@CheckReturnValue
public AuditableRestAction<Void> modifyMemberRoles(Member member, Collection<Role> roles) {
    checkAvailable();
    Checks.notNull(member, "member");
    Checks.notNull(roles, "roles");
    checkGuild(member.getGuild(), "member");
    roles.forEach(role -> {
        Checks.notNull(role, "role in collection");
        checkGuild(role.getGuild(), "role: " + role.toString());
        checkPosition(role);
    });

    if (roles.contains(guild.getPublicRole()))
        throw new IllegalArgumentException(
                "Cannot add the PublicRole of a Guild to a Member. All members have this role by default!");

    //Make sure that the current managed roles are preserved and no new ones are added.
    List<Role> currentManaged = roles.stream().filter(Role::isManaged).collect(Collectors.toList());
    List<Role> newManaged = roles.stream().filter(Role::isManaged).collect(Collectors.toList());
    if (currentManaged.size() != 0 || newManaged.size() != 0) {
        currentManaged.removeIf(newManaged::contains);

        if (currentManaged.size() > 0)
            throw new IllegalArgumentException(
                    "Cannot remove managed roles from a member! Roles: " + currentManaged.toString());
        if (newManaged.size() > 0)
            throw new IllegalArgumentException(
                    "Cannot add managed roles to a member! Roles: " + newManaged.toString());
    }

    //This is identical to the rest action stuff in #modifyMemberRoles(Member, Collection<Role>, Collection<Role>)
    JSONObject body = new JSONObject().put("roles",
            roles.stream().map(Role::getId).collect(Collectors.toList()));
    Route.CompiledRoute route = Route.Guilds.MODIFY_MEMBER.compile(guild.getId(), member.getUser().getId());

    return new AuditableRestAction<Void>(guild.getJDA(), route, body) {
        @Override
        protected void handleResponse(Response response, Request<Void> request) {
            if (response.isOk())
                request.onSuccess(null);
            else
                request.onFailure(response);
        }
    };
}

From source file:net.dv8tion.jda.core.managers.GuildController.java

/**
 * Modifies the {@link net.dv8tion.jda.core.entities.Role Roles} of the specified {@link net.dv8tion.jda.core.entities.Member Member}
 * by adding and removing a collection of roles.
 * <br>None of the provided roles may be the <u>Public Role</u> of the current Guild.
 * <br>If a role is both in {@code rolesToAdd} and {@code rolesToRemove} it will be removed.
 *
 * <p>None of the provided collections may be null
 * <br>To only add or remove roles use either {@link #removeRolesFromMember(Member, Collection)} or {@link #addRolesToMember(Member, Collection)}
 *
 * <h1>Warning</h1>//w ww .j a  v  a2s .c  o m
 * <b>This may <u>not</u> be used together with any other role add/remove/modify methods for the same Member
 * within one event listener cycle! The changes made by this require cache updates which are triggered by
 * lifecycle events which are received later. This may only be called again once the specific Member has been updated
 * by a {@link net.dv8tion.jda.core.events.guild.member.GenericGuildMemberEvent GenericGuildMemberEvent} targeting the same Member.</b>
 *
 * <p>Possible {@link net.dv8tion.jda.core.requests.ErrorResponse ErrorResponses} caused by
 * the returned {@link net.dv8tion.jda.core.requests.RestAction RestAction} include the following:
 * <ul>
 *     <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
 *     <br>The Members Roles could not be modified due to a permission discrepancy</li>
 *
 *     <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS}
 *     <br>We were removed from the Guild before finishing the task</li>
 *
 *     <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#UNKNOWN_MEMBER UNKNOWN_MEMBER}
 *     <br>The target Member was removed from the Guild before finishing the task</li>
 * </ul>
 *
 * @param  member
 *         The {@link net.dv8tion.jda.core.entities.Member Member} that should be modified
 * @param  rolesToAdd
 *         A {@link java.util.Collection Collection} of {@link net.dv8tion.jda.core.entities.Role Roles}
 *         to add to the current Roles the specified {@link net.dv8tion.jda.core.entities.Member Member} already has
 * @param  rolesToRemove
 *         A {@link java.util.Collection Collection} of {@link net.dv8tion.jda.core.entities.Role Roles}
 *         to remove from the current Roles the specified {@link net.dv8tion.jda.core.entities.Member Member} already has
 *
 * @throws net.dv8tion.jda.core.exceptions.GuildUnavailableException
 *         If the guild is temporarily not {@link net.dv8tion.jda.core.entities.Guild#isAvailable() available}
 * @throws net.dv8tion.jda.core.exceptions.PermissionException
 *         If the provided roles are higher in the Guild's hierarchy
 *         and thus cannot be modified by the currently logged in account
 * @throws IllegalArgumentException
 *         <ul>
 *             <li>If any of the provided arguments is {@code null}</li>
 *             <li>If any of the specified Roles is managed or is the {@code Public Role} of the Guild</li>
 *         </ul>
 *
 * @return {@link net.dv8tion.jda.core.requests.restaction.AuditableRestAction AuditableRestAction}
 */
@CheckReturnValue
public AuditableRestAction<Void> modifyMemberRoles(Member member, Collection<Role> rolesToAdd,
        Collection<Role> rolesToRemove) {
    checkAvailable();
    Checks.notNull(member, "member");
    Checks.notNull(rolesToAdd, "Collection containing roles to be added to the member");
    Checks.notNull(rolesToRemove, "Collection containing roles to be removed from the member");
    checkGuild(member.getGuild(), "member");
    checkPermission(Permission.MANAGE_ROLES);
    rolesToAdd.forEach(role -> {
        Checks.notNull(role, "role in rolesToAdd");
        checkGuild(role.getGuild(), "role: " + role.toString());
        checkPosition(role);
        if (role.isManaged())
            throw new IllegalArgumentException(
                    "Cannot add a Managed role to a Member. Role: " + role.toString());
    });
    rolesToRemove.forEach(role -> {
        Checks.notNull(role, "role in rolesToRemove");
        checkGuild(role.getGuild(), "role: " + role.toString());
        checkPosition(role);
        if (role.isManaged())
            throw new IllegalArgumentException(
                    "Cannot remove a Managed role from a Member. Role: " + role.toString());
    });

    Set<Role> currentRoles = new HashSet<>(((MemberImpl) member).getRoleSet());
    currentRoles.addAll(rolesToAdd);
    currentRoles.removeAll(rolesToRemove);

    if (currentRoles.contains(guild.getPublicRole()))
        throw new IllegalArgumentException(
                "Cannot add the PublicRole of a Guild to a Member. All members have this role by default!");

    JSONObject body = new JSONObject().put("roles",
            currentRoles.stream().map(Role::getId).collect(Collectors.toList()));
    Route.CompiledRoute route = Route.Guilds.MODIFY_MEMBER.compile(guild.getId(), member.getUser().getId());

    return new AuditableRestAction<Void>(guild.getJDA(), route, body) {
        @Override
        protected void handleResponse(Response response, Request<Void> request) {
            if (response.isOk())
                request.onSuccess(null);
            else
                request.onFailure(response);
        }
    };
}

From source file:org.csanchez.jenkins.plugins.kubernetes.PodTemplateBuilder.java

private Map<String, EnvVar> defaultEnvVars(KubernetesSlave slave, String workingDir,
        Collection<TemplateEnvVar> globalEnvVars) {
    // Last-write wins map of environment variable names to values
    HashMap<String, String> env = new HashMap<>();

    if (slave != null) {
        // Add some default env vars for Jenkins
        env.put("JENKINS_SECRET", slave.getComputer().getJnlpMac());
        env.put("JENKINS_NAME", slave.getComputer().getName());

        KubernetesCloud cloud = slave.getKubernetesCloud();

        String url = cloud.getJenkinsUrlOrDie();

        env.put("JENKINS_URL", url);
        if (!StringUtils.isBlank(cloud.getJenkinsTunnel())) {
            env.put("JENKINS_TUNNEL", cloud.getJenkinsTunnel());
        }//from  w  w  w . j  a  v a 2  s  .c  om

        if (slave.getKubernetesCloud().isAddMasterProxyEnvVars()) {
            // see if the env vars for proxy that the remoting.jar looks for 
            // are set on the master, and if so, propagate them to the slave
            // vs. having to set on each pod template; if explicitly set already
            // the processing of globalEnvVars below will override;
            // see org.jenkinsci.remoting.engine.JnlpAgentEndpointResolver
            String noProxy = System.getenv("no_proxy");
            if (!StringUtils.isBlank(noProxy)) {
                env.put("no_proxy", noProxy);
            }
            String httpProxy = null;
            if (System.getProperty("http.proxyHost") == null) {
                httpProxy = System.getenv("http_proxy");
            }
            if (!StringUtils.isBlank(httpProxy)) {
                env.put("http_proxy", httpProxy);
            }
        }
    }

    // Running on OpenShift Enterprise, security concerns force use of arbitrary user ID
    // As a result, container is running without a home set for user, resulting into using `/` for some tools,
    // and `?` for java build tools. So we force HOME to a safe location.
    env.put("HOME", workingDir);

    Map<String, EnvVar> envVarsMap = new HashMap<>();

    env.entrySet()
            .forEach(item -> envVarsMap.put(item.getKey(), new EnvVar(item.getKey(), item.getValue(), null)));

    if (globalEnvVars != null) {
        globalEnvVars.forEach(item -> envVarsMap.put(item.getKey(), item.buildEnvVar()));
    }
    return envVarsMap;
}

From source file:com.hortonworks.streamline.streams.catalog.service.StreamCatalogService.java

public Collection<Topology> listTopologies(List<QueryParam> queryParams) {
    Collection<Topology> topologies = this.dao.find(TOPOLOGY_NAMESPACE, queryParams);
    topologies.forEach(t -> t.setVersionTimestamp(getVersionTimestamp(t.getVersionId())));
    return topologies;
}

From source file:com.marklogic.entityservices.tests.TestEntityTypes.java

@Test
public void testInvalidEntityTypes() throws URISyntaxException {

    URL sourcesFilesUrl = client.getClass().getResource("/invalid-models");

    @SuppressWarnings("unchecked")
    Collection<File> invalidEntityTypeFiles = FileUtils.listFiles(new File(sourcesFilesUrl.getPath()),
            FileFilterUtils.trueFileFilter(), FileFilterUtils.trueFileFilter());
    Set<String> invalidEntityTypes = new HashSet<String>();

    JSONDocumentManager docMgr = client.newJSONDocumentManager();
    DocumentWriteSet writeSet = docMgr.newWriteSet();

    for (File f : invalidEntityTypeFiles) {
        if (f.getName().startsWith(".")) {
            continue;
        }//from  w w  w.j  a  v a 2 s  . c  o m
        ;
        if (!(f.getName().endsWith(".json") || f.getName().endsWith(".xml"))) {
            continue;
        }
        ;
        logger.info("Loading " + f.getName());
        writeSet.add(f.getName(), new FileHandle(f));
        invalidEntityTypes.add(f.getName());
    }
    docMgr.write(writeSet);

    for (String entityType : invalidEntityTypes) {
        logger.info("Checking invalid: " + entityType);
        @SuppressWarnings("unused")
        JacksonHandle handle = null;
        try {
            handle = evalOneResult("es:model-validate(fn:doc('" + entityType.toString() + "'))",
                    new JacksonHandle());
            fail("eval should throw an exception for invalid cases." + entityType);

        } catch (TestEvalException e) {
            assertTrue("Must contain invalidity message. Message was " + e.getMessage(),
                    e.getMessage().contains("ES-MODEL-INVALID"));

            assertTrue("Message must be expected one for " + entityType.toString() + ".  Was " + e.getMessage(),
                    e.getMessage().contains(invalidMessages.get(entityType)));

            // check once more for validating map representation
            if (entityType.endsWith(".json")) {
                try {
                    handle = evalOneResult(
                            "es:model-validate(xdmp:fron-json(fn:doc('" + entityType.toString() + "')))",
                            new JacksonHandle());
                    fail("eval should throw an exception for invalid cases." + entityType);
                } catch (TestEvalException e1) {
                    // pass
                }
            }
        }
    }

    logger.info("Cleaning up invalid types");
    Collection<String> names = new ArrayList<String>();
    invalidEntityTypeFiles.forEach(f -> {
        names.add(f.getName());
    });
    docMgr.delete(names.toArray(new String[] {}));

}

From source file:com.hortonworks.streamline.streams.catalog.service.StreamCatalogService.java

private Collection<Topology> listTopologies(Long versionId) {
    Collection<Topology> topologies = this.dao.find(TOPOLOGY_NAMESPACE, versionIdQueryParam(versionId));
    Long versionTimestamp = getVersionTimestamp(versionId);
    topologies.forEach(x -> x.setVersionTimestamp(versionTimestamp));
    return topologies;
}