Example usage for java.util Set forEach

List of usage examples for java.util Set forEach

Introduction

In this page you can find the example usage for java.util Set 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:ai.grakn.graql.internal.analytics.CommonOLAP.java

/**
 * Store <code>persistentProperties</code> and any hard coded fields in an apache config object for propagation to
 * spark executors.// w  w w .ja va 2  s.c o m
 *
 * @param configuration the apache config object that will be propagated
 */
public void storeState(final Configuration configuration) {
    // clear properties from vertex program
    Set<String> oldKeys = new HashSet<>();
    configuration.subset(PREFIX_SELECTED_TYPE_KEY).getKeys()
            .forEachRemaining(key -> oldKeys.add(PREFIX_SELECTED_TYPE_KEY + "." + key));
    oldKeys.forEach(configuration::clearProperty);

    // store selectedTypes
    selectedTypes.forEach(typeId -> configuration.addProperty(PREFIX_SELECTED_TYPE_KEY + "." + typeId, typeId));

    // store user specified properties
    persistentProperties.forEach(
            (key, value) -> configuration.addProperty(PREFIX_PERSISTENT_PROPERTIES + "." + key, value));
}

From source file:io.gravitee.gateway.resource.internal.ResourceManagerImpl.java

private void initialize() {
    ResourcePluginManager rpm = applicationContext.getBean(ResourcePluginManager.class);
    ResourceClassLoaderFactory rclf = applicationContext.getBean(ResourceClassLoaderFactory.class);
    ResourceConfigurationFactory rcf = applicationContext.getBean(ResourceConfigurationFactory.class);
    ReactorHandler rh = applicationContext.getBean(ReactorHandler.class);
    Reactable reactable = rh.reactable();

    Set<Resource> resourceDeps = reactable.dependencies(Resource.class);

    resourceDeps.forEach(resource -> {
        final ResourcePlugin resourcePlugin = rpm.get(resource.getType());
        if (resourcePlugin == null) {
            logger.error("Resource [{}] can not be found in plugin registry", resource.getType());
            throw new IllegalStateException(
                    "Resource [" + resource.getType() + "] can not be found in plugin registry");
        }/*w  w w. j av  a 2  s . c o  m*/

        PluginClassLoader resourceClassLoader = rclf.getOrCreateClassLoader(resourcePlugin, rh.classloader());
        logger.debug("Loading resource {} for {}", resource.getName(), rh);

        try {
            Class<? extends io.gravitee.resource.api.Resource> resourceClass = (Class<? extends io.gravitee.resource.api.Resource>) ClassUtils
                    .forName(resourcePlugin.resource().getName(), resourceClassLoader);
            Map<Class<?>, Object> injectables = new HashMap<>();

            if (resourcePlugin.configuration() != null) {
                Class<? extends ResourceConfiguration> resourceConfigurationClass = (Class<? extends ResourceConfiguration>) ClassUtils
                        .forName(resourcePlugin.configuration().getName(), resourceClassLoader);
                injectables.put(resourceConfigurationClass,
                        rcf.create(resourceConfigurationClass, resource.getConfiguration()));
            }

            io.gravitee.resource.api.Resource resourceInstance = new ResourceFactory().create(resourceClass,
                    injectables);
            resources.put(resource.getName(), resourceInstance);
        } catch (Exception ex) {
            logger.error("Unable to create resource", ex);
            if (resourceClassLoader != null) {
                try {
                    resourceClassLoader.close();
                } catch (IOException ioe) {
                    logger.error("Unable to close classloader for resource", ioe);
                }
            }
        }
    });
}

From source file:it.damore.solr.importexport.App.java

/**
 * @param client/*  w  w w.  j a  v  a2s . co m*/
 * @param outputFile
 * @throws SolrServerException
 * @throws IOException
 */
private static void readAllDocuments(HttpSolrClient client, File outputFile)
        throws SolrServerException, IOException {

    SolrQuery solrQuery = new SolrQuery();
    solrQuery.setQuery("*:*");
    if (config.getFilterQuery() != null) {
        solrQuery.addFilterQuery(config.getFilterQuery());
    }
    solrQuery.setRows(0);

    solrQuery.addSort(config.getUniqueKey(), ORDER.asc); // Pay attention to this line

    String cursorMark = CursorMarkParams.CURSOR_MARK_START;

    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

    // objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
    DateFormat df = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:sss'Z'");
    objectMapper.setDateFormat(df);
    objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);

    QueryResponse r = client.query(solrQuery);

    long nDocuments = r.getResults().getNumFound();
    logger.info("Found " + nDocuments + " documents");

    if (!config.getDryRun()) {
        logger.info("Creating " + config.getFileName());

        Set<SkipField> skipFieldsEquals = config.getSkipFieldsSet().stream()
                .filter(s -> s.getMatch() == MatchType.EQUAL).collect(Collectors.toSet());
        Set<SkipField> skipFieldsStartWith = config.getSkipFieldsSet().stream()
                .filter(s -> s.getMatch() == MatchType.STARTS_WITH).collect(Collectors.toSet());
        Set<SkipField> skipFieldsEndWith = config.getSkipFieldsSet().stream()
                .filter(s -> s.getMatch() == MatchType.ENDS_WITH).collect(Collectors.toSet());

        try (PrintWriter pw = new PrintWriter(outputFile)) {
            solrQuery.setRows(200);
            boolean done = false;
            while (!done) {
                solrQuery.set(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark);
                QueryResponse rsp = client.query(solrQuery);
                String nextCursorMark = rsp.getNextCursorMark();

                for (SolrDocument d : rsp.getResults()) {
                    skipFieldsEquals.forEach(f -> d.removeFields(f.getText()));
                    if (skipFieldsStartWith.size() > 0 || skipFieldsEndWith.size() > 0) {
                        Map<String, Object> collect = d.entrySet().stream()
                                .filter(e -> !skipFieldsStartWith.stream()
                                        .filter(f -> e.getKey().startsWith(f.getText())).findFirst()
                                        .isPresent())
                                .filter(e -> !skipFieldsEndWith.stream()
                                        .filter(f -> e.getKey().endsWith(f.getText())).findFirst().isPresent())
                                .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
                        pw.write(objectMapper.writeValueAsString(collect));
                    } else {
                        pw.write(objectMapper.writeValueAsString(d));
                    }
                    pw.write("\n");
                }
                if (cursorMark.equals(nextCursorMark)) {
                    done = true;
                }

                cursorMark = nextCursorMark;
            }

        }
    }

}

From source file:com.adobe.acs.commons.mcp.impl.ControlledProcessManagerImpl.java

@Override
public void haltActiveProcesses() {
    Set<ProcessInstance> instances = new HashSet<>(activeProcesses.values());
    activeProcesses.clear();//ww w  .ja  v  a 2  s  . c  om
    instances.forEach(ProcessInstance::halt);
}

From source file:org.ff4j.hbase.mapper.HBasePropertyMapper.java

/** {@inheritDoc} */
public Property<?> fromStore(Result result) {
    String propName = Bytes.toString(result.getValue(B_FEATURES_CF_PROPERTIES, B_COL_PROPERTY_ID));
    String propType = Bytes.toString(result.getValue(B_FEATURES_CF_PROPERTIES, B_COL_PROPERTY_CLAZZ));
    String propVal = Bytes.toString(result.getValue(B_FEATURES_CF_PROPERTIES, B_COL_PROPERTY_VALUE));
    Property<?> prop = PropertyFactory.createProperty(propName, propType, propVal);
    String desc = Bytes.toString(result.getValue(B_FEATURES_CF_PROPERTIES, B_COL_PROPERTY_DESCRIPTION));
    prop.setDescription(desc);// w ww  .  j  a  v  a  2  s. c  om
    Set<String> fixedValues = FeatureJsonParser
            .parsePermissions(Bytes.toString(result.getValue(B_FEATURES_CF_PROPERTIES, B_COL_PROPERTY_FIXED)));
    if (fixedValues != null) {
        fixedValues.forEach(prop::add2FixedValueFromString);
    }
    return prop;
}

From source file:org.libreplan.business.hibernate.notification.HibernateDatabaseModificationsListener.java

private void dispatch(Set<NotBlockingAutoUpdatedSnapshot<?>> toBeDispatched) {
    toBeDispatched.forEach(this::dispatch);
}

From source file:com.rockagen.gnext.service.spring.security.extension.ExTokenAuthentication.java

/**
 * Get {@link org.springframework.security.core.userdetails.UserDetails} from token
 *
 * @param token token/*from w  w w  .j a  v  a  2  s.c om*/
 * @return {@link org.springframework.security.core.userdetails.UserDetails} if token authenticated,otherwise return null
 */
public UserDetails getUserDetailsFromToken(String token) {
    if (authenticated(token)) {
        // Load user
        Optional<AuthUser> user = authUserServ.load(Token.getUidFromToken(token));
        if (user.filter(AuthUser::enabled).isPresent()) {
            List<GrantedAuthority> authorities = new LinkedList<>();
            Set<AuthGroup> groups = user.get().getGroups();
            if (groups != null && groups.size() > 0) {
                groups.forEach(x -> x.getRoles()
                        .forEach(y -> authorities.add(new SimpleGrantedAuthority(y.getName().trim()))));
            }
            return new User(user.get().getUid(), "***", authorities);
        }
    }
    return null;
}

From source file:com.evolveum.midpoint.repo.sql.helpers.NameResolutionHelper.java

public void resolveNamesIfRequested(Session session, List<? extends PrismContainerValue> containerValues,
        Collection<SelectorOptions<GetOperationOptions>> options) {

    List<ItemPath> pathsToResolve = getPathsToResolve(options);
    if (pathsToResolve.isEmpty()) {
        return;//from w  w  w. j  a  v  a 2 s .  c o  m
    }

    final Set<String> oidsToResolve = new HashSet<>();
    Visitor oidExtractor = visitable -> {
        if (visitable instanceof PrismReferenceValue) {
            PrismReferenceValue value = (PrismReferenceValue) visitable;
            if (!ItemPath.containsSubpathOrEquivalent(pathsToResolve, value.getPath())) {
                return;
            }
            if (value.getTargetName() != null) { // just for sure
                return;
            }
            if (value.getObject() != null) { // improbable but possible
                value.setTargetName(value.getObject().getName());
                return;
            }
            if (value.getOid() == null) { // shouldn't occur as well
                return;
            }
            oidsToResolve.add(value.getOid());
        }
    };
    Set<PrismContainerValue> roots = containerValues.stream().map(pcv -> pcv.getRootValue())
            .collect(Collectors.toSet());
    roots.forEach(root -> root.accept(oidExtractor));

    Map<String, PolyString> oidNameMap = new HashMap<>();
    List<String> batch = new ArrayList<>();
    for (Iterator<String> iterator = oidsToResolve.iterator(); iterator.hasNext();) {
        batch.add(iterator.next());
        if (batch.size() >= MAX_OIDS_TO_RESOLVE_AT_ONCE || !iterator.hasNext()) {
            Query query = session.getNamedQuery("resolveReferences");
            query.setParameterList("oid", batch);

            @SuppressWarnings({ "unchecked", "raw" })
            List<Object[]> results = query.list(); // returns oid + name
            for (Object[] result : results) {
                String oid = (String) result[0];
                RPolyString name = (RPolyString) result[1];
                oidNameMap.put(oid, new PolyString(name.getOrig(), name.getNorm()));
            }
            batch.clear();
        }
    }
    if (!oidNameMap.isEmpty()) {
        Visitor nameSetter = visitable -> {
            if (visitable instanceof PrismReferenceValue) {
                PrismReferenceValue value = (PrismReferenceValue) visitable;
                if (value.getTargetName() == null && value.getOid() != null) {
                    value.setTargetName(oidNameMap.get(value.getOid()));
                }
            }
        };
        roots.forEach(root -> root.accept(nameSetter));
    }
}

From source file:ddf.catalog.data.impl.MetacardTypeImpl.java

private List<String> addAttributeDescriptors(List<String> attributeNames,
        Set<AttributeDescriptor> attributeDescriptors) {
    attributeDescriptors.forEach(attributeDescriptor -> {
        if (!attributeNames.contains(attributeDescriptor.getName())) {
            descriptors.put(attributeDescriptor.getName(), attributeDescriptor);
            attributeNames.add(attributeDescriptor.getName());
        }//from w w  w.j  a  v  a  2s . c  om
    });
    return attributeNames;
}

From source file:com.netflix.genie.web.tasks.leader.ClusterCheckerTask.java

private void updateJobsToFailedOnHost(final String host) {
    final Set<Job> jobs = jobSearchService.getAllActiveJobsOnHost(host);
    jobs.forEach(job -> {
        try {// ww w.ja v a2s  . co m
            jobPersistenceService.setJobCompletionInformation(
                    job.getId().orElseThrow(IllegalArgumentException::new), JobExecution.LOST_EXIT_CODE,
                    JobStatus.FAILED,
                    "Genie leader can't reach node running job. Assuming node and job are lost.", null, null);
            lostJobsCounter.increment();
        } catch (final GenieException ge) {
            log.error("Unable to update job {} to failed due to exception", job.getId(), ge);
            unableToUpdateJobCounter.increment();
        }
    });
}