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:org.codice.ddf.security.sts.claims.property.UsersAttributesFileClaimsHandler.java

private Set<String> convertToSetOfStrings(final Object attributeValueObject) {
    if (attributeValueObject instanceof String) {
        final String singleValuedAttributeValue = (String) attributeValueObject;
        return Collections.singleton(singleValuedAttributeValue);
    } else if (attributeValueObject instanceof Collection) {
        final Collection<?> multiValuedAttributeValues = (Collection<?>) attributeValueObject;

        if (multiValuedAttributeValues.isEmpty()) {
            final String reason = "Expected attributes to not have a value of an empty Collection";
            final String errorMessage = createErrorMessage(reason);
            LOGGER.error(errorMessage);//from   w  w w  .  j  a  v a  2s .com
            throw new IllegalStateException(reason);
        }

        ImmutableSet.Builder<String> immutableSetBuilder = ImmutableSet.builder();
        multiValuedAttributeValues.forEach(multiValuedAttributeValue -> {
            if (!(multiValuedAttributeValue instanceof String)) {
                final String reason = "Expected the attribute values that are a Collection to only contain String values";
                final String errorMessage = createErrorMessage(reason);
                LOGGER.error(errorMessage);
                throw new IllegalStateException(reason);
            }

            immutableSetBuilder.add((String) multiValuedAttributeValue);
        });

        return immutableSetBuilder.build();
    } else {
        final String reason = "Expected attribute values to be a String or a Collection";
        final String errorMessage = createErrorMessage(reason);
        LOGGER.error(errorMessage);
        throw new IllegalStateException(reason);
    }
}

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

private SyncopeClientException checkMandatoryOnResources(final Any<?> any,
        final Collection<? extends ExternalResource> resources) {

    SyncopeClientException reqValMissing = SyncopeClientException
            .build(ClientExceptionType.RequiredValuesMissing);

    resources.forEach(resource -> {
        Optional<? extends Provision> provision = resource.getProvision(any.getType());
        if (resource.isEnforceMandatoryCondition() && provision.isPresent()) {
            List<String> missingAttrNames = evaluateMandatoryCondition(provision.get(), any);
            if (!missingAttrNames.isEmpty()) {
                LOG.error("Mandatory schemas {} not provided with values", missingAttrNames);

                reqValMissing.getElements().addAll(missingAttrNames);
            }/*  www.  j a  v  a  2s  .c o  m*/
        }
    });

    return reqValMissing;
}

From source file:org.onosproject.store.primitives.impl.EventuallyConsistentMapImpl.java

private void processUpdates(Collection<UpdateEntry<K, V>> updates) {
    if (destroyed) {
        return;/*from   w w  w  .jav a 2s .c  o  m*/
    }
    updates.forEach(update -> {
        final K key = update.key();
        final MapValue<V> value = update.value() == null ? null : update.value().copy();
        if (value == null || value.isTombstone()) {
            MapValue<V> previousValue = removeInternal(key, Optional.empty(), Optional.ofNullable(value));
            if (previousValue != null && previousValue.isAlive()) {
                notifyListeners(new EventuallyConsistentMapEvent<>(mapName, REMOVE, key, previousValue.get()));
            }
        } else if (putInternal(key, value)) {
            notifyListeners(new EventuallyConsistentMapEvent<>(mapName, PUT, key, value.get()));
        }
    });
}

From source file:io.mindmaps.engine.loader.DistributedLoader.java

public DistributedLoader(String graphNameInit, Collection<String> hosts) {
    ConfigProperties prop = ConfigProperties.getInstance();
    batchSize = prop.getPropertyAsInt(ConfigProperties.BATCH_SIZE_PROPERTY);
    graphName = graphNameInit;/*from   ww  w  .j a  v a  2  s  . c o m*/
    batch = new HashSet<>();
    hostsArray = hosts.toArray(new String[hosts.size()]);
    currentHost = 0;
    pollingFrequency = 30000;

    threadsNumber = prop.getAvailableThreads() * 3;

    // create availability map
    availability = new HashMap<>();
    hosts.forEach(h -> availability.put(h, new Semaphore(threadsNumber)));

    jobsTerminated = new HashMap<>();
    hosts.forEach(h -> jobsTerminated.put(h, 0));
}

From source file:de.hska.ld.core.config.security.openidconnect.OIDCSecurityConfig.java

@Override
@SuppressWarnings("unchecked")
protected void configure(HttpSecurity http) throws Exception {
    OIDCAuthenticationFilter oidcFilter = openIdConnectAuthenticationFilter();
    oidcFilter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
        @Override/*from  ww  w  . j a v a  2s  .  com*/
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) throws IOException, ServletException {
            response.sendRedirect(env.getProperty("module.core.oidc.redirect.to.client"));
        }
    });
    oidcFilter.setApplicationEventPublisher(new ApplicationEventPublisher() {
        @Override
        public void publishEvent(ApplicationEvent event) {
            Object source = event.getSource();
            OIDCAuthenticationToken token = null;
            if (source != null) {
                token = (OIDCAuthenticationToken) source;
            }
            if (token != null) {
                Map map = (Map) token.getPrincipal();
                Iterator iterator = map.entrySet().iterator();
                String subId = null;
                String issuer = null;
                if (iterator.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
                    if ("sub".equals(entry.getKey())) {
                        // check if sub id is already present in the database
                        subId = entry.getValue();
                        if (subId == null) {
                            throw new UnsupportedOperationException("No subId found!");
                        }
                    }
                }
                if (iterator.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
                    if ("iss".equals(entry.getKey())) {
                        issuer = entry.getValue();
                        if (!env.getProperty("module.core.oidc.identity.provider.url").equals(issuer)) {
                            throw new UnsupportedOperationException("Wrong or no issuer found!");
                        }
                    }
                }

                User currentUserInDb = userService.findBySubIdAndIssuer(subId, issuer);
                UserInfo oidcUserInfo = ((OIDCAuthenticationToken) source).getUserInfo();

                if (currentUserInDb == null && oidcUserInfo != null) {
                    User savedUser = createNewUserFirstLogin(token, subId, issuer, oidcUserInfo);
                    try {
                        userEventsPublisher.sendUserLoginEvent(savedUser);
                        userEventsPublisher.sendUserFirstLoginEvent(savedUser);
                    } catch (Exception e) {
                        //
                    }
                    LoggingContext.put("user_email", EscapeUtil.escapeJsonForLogging(savedUser.getEmail()));
                    Logger.trace("User logs in for the first time.");
                    LoggingContext.clear();
                } else if (oidcUserInfo != null) {
                    User savedUser = updateUserInformationFromOIDC(token, currentUserInDb, oidcUserInfo);
                    try {
                        userEventsPublisher.sendUserLoginEvent(savedUser);
                    } catch (Exception e) {
                        //
                    }
                    LoggingContext.put("user_email", EscapeUtil.escapeJsonForLogging(savedUser.getEmail()));
                    Logger.trace("User logs in.");
                    LoggingContext.clear();
                } else {
                    // oidc information is null
                    throw new UnsupportedOperationException("No OIDC information found!");
                }
            }
        }

        private User updateUserInformationFromOIDC(OIDCAuthenticationToken token, User currentUserInDb,
                UserInfo oidcUserInfo) {
            // get the current authentication details of the user
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            enrichAuthoritiesWithStoredAuthorities(currentUserInDb, auth);

            // check for profile updates since the last login
            String oidcUpdatedTime = token.getUserInfo().getUpdatedTime();
            // oidc time: "20150701_090039"
            // oidc format: "yyyyMMdd_HHmmss"
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            User savedUser = null;
            try {
                Date date = sdf.parse(oidcUpdatedTime);
                if (currentUserInDb.getEmail() == null
                        || currentUserInDb.getLastupdatedAt().getTime() > date.getTime()) {
                    currentUserInDb.setFullName(oidcUserInfo.getName());
                    currentUserInDb.setEmail(oidcUserInfo.getEmail());
                    savedUser = userService.save(currentUserInDb);
                } else {
                    savedUser = currentUserInDb;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return savedUser;
        }

        private User createNewUserFirstLogin(OIDCAuthenticationToken token, String subId, String issuer,
                UserInfo oidcUserInfo) {
            // create a new user
            User user = new User();
            // check for colliding user names (via preferred user name)
            String prefferedUsername = oidcUserInfo.getPreferredUsername();
            User userWithGivenPreferredUserName = userService.findByUsername(prefferedUsername);
            int i = 0;
            if (userWithGivenPreferredUserName != null) {
                while (userWithGivenPreferredUserName != null) {
                    prefferedUsername = oidcUserInfo.getPreferredUsername() + "#" + i;
                    userWithGivenPreferredUserName = userService.findByUsername(prefferedUsername);
                }
            }
            user.setUsername(prefferedUsername);

            user.setFullName(oidcUserInfo.getName());
            user.setEmail(oidcUserInfo.getEmail());
            user.setEnabled(true);
            // apply roles
            List<Role> roleList = new ArrayList<Role>();
            Role userRole = roleService.findByName("ROLE_USER");
            if (userRole == null) {
                // create initial roles
                String newUserRoleName = "ROLE_USER";
                userRole = createNewUserRole(newUserRoleName);
                String newAdminRoleName = "ROLE_ADMIN";
                Role adminRole = createNewUserRole(newAdminRoleName);
                // For the first user add the admin role
                roleList.add(adminRole);
            } else {
                roleList.add(userRole);
            }
            user.setRoleList(roleList);
            // A password is required so we set a uuid generated one
            if ("development".equals(env.getProperty("lds.app.instance"))) {
                user.setPassword("pass");
            } else {
                user.setPassword(UUID.randomUUID().toString());
            }
            user.setSubId(subId);
            user.setIssuer(issuer);
            String oidcUpdatedTime = token.getUserInfo().getUpdatedTime();
            // oidc time: "20150701_090039"
            // oidc format: "yyyyMMdd_HHmmss"
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            try {
                Date date = sdf.parse(oidcUpdatedTime);
                user.setLastupdatedAt(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            User savedUser = userService.save(user);

            // update security context
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            enrichAuthoritiesWithStoredAuthorities(user, auth);

            return savedUser;
        }

        @Override
        public void publishEvent(Object event) {
            throw new RuntimeException("Publish event call failed not implemented yet.");
        }

        private void enrichAuthoritiesWithStoredAuthorities(User currentUserInDb, Authentication auth) {
            Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
            final SubjectIssuerGrantedAuthority[] oidcAuthority = new SubjectIssuerGrantedAuthority[1];
            authorities.forEach(authority -> {
                if (authority instanceof SubjectIssuerGrantedAuthority) {
                    // extract the oidc authority information
                    oidcAuthority[0] = (SubjectIssuerGrantedAuthority) authority;
                }
            });

            // create new authorities that includes the authorities stored in the database
            // as well as the oidc authority
            ArrayList<GrantedAuthority> newAuthorities = new ArrayList<GrantedAuthority>();
            newAuthorities.add(oidcAuthority[0]);
            currentUserInDb.getRoleList().forEach(role -> {
                newAuthorities.add(new SimpleGrantedAuthority(role.getName()));
            });
            try {
                Field authoritiesField = AbstractAuthenticationToken.class.getDeclaredField("authorities");
                authoritiesField.setAccessible(true);
                authoritiesField.set(auth, newAuthorities);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
            // update the authority information in the security context
            SecurityContextHolder.getContext().setAuthentication(auth);
        }

        private Role createNewUserRole(String newRoleName) {
            Role newUserRole = new Role();
            newUserRole.setName(newRoleName);
            return roleService.save(newUserRole);
        }
    });

    http.addFilterBefore(oidcFilter, AbstractPreAuthenticatedProcessingFilter.class).csrf()
            .requireCsrfProtectionMatcher(new RequestMatcher() {
                private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");

                private RegexRequestMatcher apiMatcher = new RegexRequestMatcher("/v[0-9]*/.*", null);

                @Override
                public boolean matches(HttpServletRequest request) {
                    // CSRF disabled on allowedMethod
                    if (allowedMethods.matcher(request.getMethod()).matches())
                        return false;

                    // CSRF disabled on api calls
                    if (apiMatcher.matches(request))
                        return false;

                    // CSRF enables for other requests
                    //TODO change later on
                    return false;
                }
            }).and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()).and().logout()
            .logoutSuccessHandler(logoutSuccessHandler()).deleteCookies("JSESSIONID")
            .deleteCookies("sessionID");
}

From source file:com.evolveum.midpoint.web.component.prism.ContainerWrapperFactory.java

public <O extends ObjectType, C extends Containerable> List<ItemWrapper> createProperties(
        ContainerValueWrapper<C> cWrapper, boolean onlyEmpty, Task task) {

    result = new OperationResult(CREATE_PROPERTIES);

    ContainerWrapper<C> containerWrapper = cWrapper.getContainer();
    PrismContainerDefinition<C> definition = containerWrapper.getItemDefinition();

    List<ItemWrapper> properties = new ArrayList<>();

    if (definition == null) {
        LOGGER.error("Couldn't get property list from null definition {}",
                new Object[] { containerWrapper.getItem().getElementName() });
        return properties;
    }/*from   w  w  w  .jav a  2s.  c  om*/

    Collection<? extends ItemDefinition> propertyDefinitions = definition.getDefinitions();
    List<PropertyOrReferenceWrapper> propertyOrReferenceWrappers = new ArrayList<>();
    List<ContainerWrapper<C>> containerWrappers = new ArrayList<>();
    propertyDefinitions.forEach(itemDef -> {

        if (itemDef.isIgnored() || skipProperty(itemDef)) {
            LOGGER.trace("Skipping creating wrapper for: {}", itemDef);
            return;
        }

        if (itemDef.isExperimental()
                && !WebModelServiceUtils.isEnableExperimentalFeature(task, modelServiceLocator)) {
            LOGGER.trace(
                    "Skipping creating wrapper for {} because it is experimental a experimental features are not enabled.",
                    itemDef.getName());
            return;
        }

        LOGGER.trace("Creating wrapper for {}", itemDef);
        try {
            createPropertyOrReferenceWrapper(itemDef, cWrapper, propertyOrReferenceWrappers, onlyEmpty,
                    cWrapper.getPath());
            createContainerWrapper(itemDef, cWrapper, containerWrappers, onlyEmpty, task);
        } catch (Exception e) {
            LoggingUtils.logUnexpectedException(LOGGER, "something strange happened: " + e.getMessage(), e);
            System.out.println(e.getMessage());
            throw new TunnelException(e);
        }

    });

    Collections.sort(propertyOrReferenceWrappers, new ItemWrapperComparator());
    Collections.sort(containerWrappers, new ItemWrapperComparator());

    properties.addAll(propertyOrReferenceWrappers);
    properties.addAll(containerWrappers);

    result.recomputeStatus();
    result.recordSuccessIfUnknown();

    return properties;
}

From source file:org.teiid.spring.autoconfigure.TeiidServer.java

private ModelMetaData buildModelFromDataSource(String dsBeanName, String driverName, ApplicationContext context,
        boolean createInitTable) throws AdminException {

    ModelMetaData model = new ModelMetaData();
    model.setName(dsBeanName);//from  ww w .  j  a v  a  2 s . com
    model.setModelType(Model.Type.PHYSICAL);

    // note these can be overridden by specific ones in the configuration
    // TODO: need come up most sensible properties for this.
    model.addProperty("importer.useQualifiedName", "false");
    model.addProperty("importer.tableTypes", "TABLE,VIEW");

    SourceMappingMetadata source = new SourceMappingMetadata();
    source.setName(dsBeanName);
    source.setConnectionJndiName(dsBeanName);

    String translatorName = ExternalSource.findTransaltorNameFromDriverName(driverName);
    source.setTranslatorName(translatorName);
    String dialect = ExternalSource.findDialectFromDriverName(driverName);
    if (dialect != null) {
        model.addProperty(DIALECT, dialect);
    }

    // load the translator class
    addTranslator(translatorName);

    // add the importer properties from the configuration
    // note that above defaults can be overridden with this too.
    Collection<? extends PropertyDefinition> importProperties = getAdmin()
            .getTranslatorPropertyDefinitions(source.getTranslatorName(), TranlatorPropertyType.IMPORT);
    importProperties.forEach(prop -> {
        String key = prop.getName();
        String value = context.getEnvironment().getProperty("spring.datasource." + dsBeanName + "." + key);
        if (value == null) {
            value = context.getEnvironment().getProperty("spring.xa.datasource." + dsBeanName + "." + key);
        }
        if (value != null) {
            model.addProperty(key, value);
        }
    });

    model.addSourceMapping(source);

    // This is to avoid failing on empty schema
    if (createInitTable) {
        model.addSourceMetadata("NATIVE", "");
        model.addSourceMetadata("DDL", "create foreign table dual(id integer);");
    }
    return model;
}

From source file:io.mindmaps.loader.DistributedLoader.java

public DistributedLoader(String graphNameInit, Collection<String> hosts) {
    ConfigProperties prop = ConfigProperties.getInstance();
    batchSize = prop.getPropertyAsInt(ConfigProperties.BATCH_SIZE_PROPERTY);
    graphName = graphNameInit;//  ww  w  . j  a v a  2  s  .  c  o m
    batch = new HashSet<>();
    hostsArray = hosts.toArray(new String[hosts.size()]);
    currentHost = 0;
    pollingFrequency = 30000;

    threadsNumber = prop.getPropertyAsInt(ConfigProperties.NUM_THREADS_PROPERTY) * 3;

    // create availability map
    availability = new HashMap<>();
    hosts.forEach(h -> availability.put(h, new Semaphore(threadsNumber)));

    jobsTerminated = new HashMap<>();
    hosts.forEach(h -> jobsTerminated.put(h, 0));
}

From source file:de.acosix.alfresco.utility.common.spring.BeanDefinitionFromPropertiesPostProcessor.java

protected void compressPaddedLists(final Collection<ManagedList<?>> paddedLists) {
    paddedLists.forEach(list -> {
        final Iterator<?> iterator = list.iterator();
        while (iterator.hasNext()) {
            if (iterator.next() == null) {
                iterator.remove();/*from w w w .ja va2  s .  c  om*/
            }
        }
    });
}

From source file:org.lanternpowered.server.data.MemoryDataView.java

@SuppressWarnings("rawtypes")
private ImmutableList<Object> ensureSerialization(Collection<?> collection) {
    ImmutableList.Builder<Object> objectBuilder = ImmutableList.builder();
    collection.forEach(element -> {
        if (element instanceof Collection) {
            objectBuilder.add(ensureSerialization((Collection) element));
        } else if (element instanceof DataSerializable) {
            objectBuilder.add(((DataSerializable) element).toContainer());
        } else {//w  w  w .j  a v a 2 s .co m
            objectBuilder.add(element);
        }
    });
    return objectBuilder.build();

}