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:org.apache.samza.system.hdfs.HdfsSystemAdmin.java

/**
 *
 * Fetch metadata from hdfs system for a set of streams. This has the potential side effect
 * to persist partition description to the staging directory on hdfs if staging directory
 * is not empty. See getStagingDirectory on {@link HdfsConfig}
 *
 * @param streamNames/*w w  w .j  ava 2 s .co m*/
 *          The streams to to fetch metadata for.
 * @return A map from stream name to SystemStreamMetadata for each stream
 *         requested in the parameter set.
 */
@Override
public Map<String, SystemStreamMetadata> getSystemStreamMetadata(Set<String> streamNames) {
    Map<String, SystemStreamMetadata> systemStreamMetadataMap = new HashMap<>();
    streamNames.forEach(streamName -> {
        systemStreamMetadataMap.put(streamName,
                new SystemStreamMetadata(streamName, directoryPartitioner.getPartitionMetadataMap(streamName,
                        obtainPartitionDescriptorMap(stagingDirectory, streamName))));
        if (!partitionDescriptorExists(streamName)) {
            persistPartitionDescriptor(streamName, directoryPartitioner.getPartitionDescriptor(streamName));
        }
    });
    return systemStreamMetadataMap;
}

From source file:org.jboss.pnc.coordinator.test.event.StatusUpdatesTest.java

@Test
@InSequence(10)/*  www  . java 2s  . c o m*/
public void buildSetStatusShouldUpdateWhenAllBuildStatusChangeToCompletedState()
        throws DatastoreException, InterruptedException, CoreException {
    ObjectWrapper<BuildSetStatusChangedEvent> receivedBuildSetStatusChangedEvent = new ObjectWrapper<>();
    Consumer<BuildSetStatusChangedEvent> statusUpdateListener = (event) -> {
        receivedBuildSetStatusChangedEvent.set(event);
    };
    testCDIBuildSetStatusChangedReceiver.addBuildSetStatusChangedEventListener(statusUpdateListener);

    User user = User.Builder.newBuilder().id(1).username("test-user-1").build();
    Set<BuildTask> buildTasks = initializeBuildTaskSet(configurationBuilder, user, (buildConfigSetRecord) -> {
    }).getBuildTasks();
    buildTasks.forEach((bt) -> {
        buildCoordinator.updateBuildTaskStatus(bt, BuildCoordinationStatus.DONE);
        buildCoordinator.completeBuild(bt, createBuildResult());
    });
    this.waitForConditionWithTimeout(() -> buildTasks.stream().allMatch(task -> task.getStatus().isCompleted()),
            4);

    Assert.assertNotNull("Did not receive build set status update.", receivedBuildSetStatusChangedEvent.get());
    Assert.assertEquals(BuildSetStatus.DONE, receivedBuildSetStatusChangedEvent.get().getNewStatus());
}

From source file:io.fabric8.vertx.maven.plugin.utils.IncrementalBuilder.java

public IncrementalBuilder(Set<Path> inclDirs, List<Callable<Void>> chain, Log logger, long watchTimeInterval) {
    this.chain = chain;
    this.logger = logger;
    this.monitor = new FileAlterationMonitor(watchTimeInterval);
    inclDirs.forEach(this::buildObserver);

}

From source file:org.wso2.extension.siddhi.execution.var.models.parametric.ParametricVaRCalculator.java

/**
 * @param symbol Update global co-variance table based on latest event
 *///from ww  w  . ja v a2 s.  c o  m
private void updateCovarianceTable(String symbol) {
    Set<String> keys = getAssetPool().keySet();
    double[] excessReturns = ((ParametricAsset) getAssetPool().get(symbol)).getExcessReturns();

    keys.forEach((iterateSymbol) -> {

        double[] iterateExcessReturns = ((ParametricAsset) getAssetPool().get(iterateSymbol))
                .getExcessReturns();
        int min;
        double covariance = 0.0;
        if (excessReturns.length > iterateExcessReturns.length) {
            min = iterateExcessReturns.length;
        } else {
            min = excessReturns.length;
        }

        for (int j = 0; j < min; j++) {
            covariance += excessReturns[j] * iterateExcessReturns[j];
        }
        covariance /= (getBatchSize() - 2);

        covarianceTable.put(symbol, iterateSymbol, covariance);
        covarianceTable.put(iterateSymbol, symbol, covariance);
    });

}

From source file:com.wmfsystem.eurekaserver.broadcast.Server.java

public void run() {
    try {/*  w  w w .j a  va2  s .  c  om*/
        socket = new DatagramSocket(DEFAULT_PORT);
    } catch (Exception ex) {
        System.out.println("Problem creating socket on port: " + DEFAULT_PORT);
    }

    packet = new DatagramPacket(new byte[1], 1);

    while (true) {
        try {
            socket.receive(packet);
            System.out.println("Received from: " + packet.getAddress() + ":" + packet.getPort());
            byte[] outBuffer = new java.util.Date().toString().getBytes();
            packet.setData(outBuffer);
            packet.setLength(outBuffer.length);
            socket.setBroadcast(true);
            socket.send(packet);

            Set<InetAddress> localAddress = getLocalAddress();

            Set<String> ips = localAddress.stream().map(ad -> ad.getHostAddress()).collect(Collectors.toSet())
                    .stream().sorted().collect(Collectors.toSet());

            RestTemplate template = new RestTemplate();

            ips.forEach(ip -> {
                template.exchange("http://" + packet.getAddress().getHostAddress().concat(":8000?ip={ip}"),
                        HttpMethod.GET, HttpEntity.EMPTY, Void.class, ip.concat(":8000"));
                try {
                    template.exchange("http://" + packet.getAddress().getHostAddress().concat(":8000?ip={ip}"),
                            HttpMethod.GET, HttpEntity.EMPTY, Void.class, ip.concat(":8000"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            System.out.println("Message ----> " + packet.getAddress().getHostAddress());

        } catch (IOException ie) {
            ie.printStackTrace();
        }
    }
}

From source file:io.gravitee.gateway.policy.impl.DefaultPolicyManager.java

private void initialize() {
    PolicyPluginManager ppm = applicationContext.getBean(PolicyPluginManager.class);
    PolicyClassLoaderFactory pclf = applicationContext.getBean(PolicyClassLoaderFactory.class);
    ReactorHandler rh = applicationContext.getBean(ReactorHandler.class);
    ResourceLifecycleManager rm = applicationContext.getBean(ResourceLifecycleManager.class);
    Reactable reactable = rh.reactable();

    Set<Policy> requiredPlugins = reactable.dependencies(Policy.class);

    requiredPlugins.forEach(policy -> {
        final PolicyPlugin policyPlugin = ppm.get(policy.getName());
        if (policyPlugin == null) {
            logger.error("Policy [{}] can not be found in policy registry", policy.getName());
            throw new IllegalStateException(
                    "Policy [" + policy.getName() + "] can not be found in policy registry");
        }//from  w w w .j  a v  a2  s  .  co  m

        PluginClassLoader policyClassLoader = null;

        // Load dependant resources to enhance policy classloader
        Collection<? extends Resource> resources = rm.getResources();
        if (!resources.isEmpty()) {
            ClassLoader[] resourceClassLoaders = rm.getResources().stream()
                    .map(new Function<Resource, ClassLoader>() {
                        @Override
                        public ClassLoader apply(Resource resource) {
                            return resource.getClass().getClassLoader();
                        }
                    }).toArray(ClassLoader[]::new);

            DelegatingClassLoader parentClassLoader = new DelegatingClassLoader(rh.classloader(),
                    resourceClassLoaders);
            policyClassLoader = pclf.getOrCreateClassLoader(policyPlugin, parentClassLoader);
        } else {
            policyClassLoader = pclf.getOrCreateClassLoader(policyPlugin, rh.classloader());
        }

        logger.debug("Loading policy {} for {}", policy.getName(), rh);

        PolicyMetadataBuilder builder = new PolicyMetadataBuilder();
        builder.setId(policyPlugin.id());

        try {
            // Prepare metadata
            Class<?> policyClass = ClassUtils.forName(policyPlugin.policy().getName(), policyClassLoader);

            builder.setPolicy(policyClass).setMethods(new PolicyMethodResolver().resolve(policyClass));

            if (policyPlugin.configuration() != null) {
                builder.setConfiguration((Class<? extends PolicyConfiguration>) ClassUtils
                        .forName(policyPlugin.configuration().getName(), policyClassLoader));
            }

            // Prepare context if defined
            if (policyPlugin.context() != null) {
                Class<? extends PolicyContext> policyContextClass = (Class<? extends PolicyContext>) ClassUtils
                        .forName(policyPlugin.context().getName(), policyClassLoader);
                // Create policy context instance and initialize context provider (if used)
                PolicyContext context = new PolicyContextFactory(reactable).create(policyContextClass);
                builder.setContext(context);
            }

            RegisteredPolicy registeredPolicy = new RegisteredPolicy();
            registeredPolicy.classLoader = policyClassLoader;
            registeredPolicy.metadata = builder.build();

            policies.put(policy.getName(), registeredPolicy);
        } catch (Exception ex) {
            logger.error("Unable to load policy metadata", ex);

            if (policyClassLoader != null) {
                try {
                    policyClassLoader.close();
                } catch (IOException ioe) {
                    logger.error("Unable to close classloader for policy", ioe);
                }
            }
        }
    });
}

From source file:com.flipkart.flux.resource.StateMachineResource.java

private FsmGraph getGraphData(Long fsmId) throws IOException {
    StateMachine stateMachine = stateMachinesDAO.findById(fsmId);

    if (stateMachine == null) {
        throw new WebApplicationException(Response.Status.NOT_FOUND);
    }// w w w.  j  a v a2 s.  c o  m
    final FsmGraph fsmGraph = new FsmGraph();

    Map<String, Event> stateMachineEvents = eventsDAO.findBySMInstanceId(fsmId).stream()
            .collect(Collectors.<Event, String, Event>toMap(Event::getName, (event -> event)));
    Set<String> allOutputEventNames = new HashSet<>();

    final RAMContext ramContext = new RAMContext(System.currentTimeMillis(), null, stateMachine);
    /* After this operation, we'll have nodes for each state and its corresponding output event along with the output event's dependencies mapped out*/
    for (State state : stateMachine.getStates()) {
        if (state.getOutputEvent() != null) {
            EventDefinition eventDefinition = objectMapper.readValue(state.getOutputEvent(),
                    EventDefinition.class);
            final Event outputEvent = stateMachineEvents.get(eventDefinition.getName());
            final FsmGraphVertex vertex = new FsmGraphVertex(state.getId(), getDisplayName(state.getName()));
            fsmGraph.addVertex(vertex, new FsmGraphEdge(getDisplayName(outputEvent.getName()),
                    outputEvent.getStatus().name(), outputEvent.getEventSource()));
            final Set<State> dependantStates = ramContext.getDependantStates(outputEvent.getName());
            dependantStates.forEach((aState) -> fsmGraph.addOutgoingEdge(vertex, aState.getId()));
            allOutputEventNames.add(outputEvent.getName()); // we collect all output event names and use them below.
        } else {
            fsmGraph.addVertex(new FsmGraphVertex(state.getId(), this.getDisplayName(state.getName())), null);
        }
    }

    /* Handle states with no dependencies, i.e the states that can be triggered as soon as we execute the state machine */
    final Set<State> initialStates = ramContext.getInitialStates(Collections.emptySet());// hackety hack.  We're fooling the context to give us only events that depend on nothing
    if (!initialStates.isEmpty()) {
        final FsmGraphEdge initEdge = new FsmGraphEdge(TRIGGER, Event.EventStatus.triggered.name(), TRIGGER);
        initialStates.forEach((state) -> {
            initEdge.addOutgoingVertex(state.getId());
        });
        fsmGraph.addInitStateEdge(initEdge);
    }
    /* Now we handle events that were not "output-ed" by any state, which means that they were given to the workflow at the time of invocation or supplied externally*/
    final HashSet<String> eventsGivenOnWorkflowTrigger = new HashSet<>(stateMachineEvents.keySet());
    eventsGivenOnWorkflowTrigger.removeAll(allOutputEventNames);
    eventsGivenOnWorkflowTrigger.forEach((workflowTriggeredEventName) -> {
        final Event correspondingEvent = stateMachineEvents.get(workflowTriggeredEventName);
        final FsmGraphEdge initEdge = new FsmGraphEdge(this.getDisplayName(workflowTriggeredEventName),
                correspondingEvent.getStatus().name(), correspondingEvent.getEventSource());
        final Set<State> dependantStates = ramContext.getDependantStates(workflowTriggeredEventName);
        dependantStates.forEach((state) -> initEdge.addOutgoingVertex(state.getId()));
        fsmGraph.addInitStateEdge(initEdge);
    });
    return fsmGraph;
}

From source file:org.springframework.cloud.gateway.filter.factory.RetryGatewayFilterFactory.java

public void reset(ServerWebExchange exchange) {
    // TODO: what else to do to reset SWE?
    Set<String> addedHeaders = exchange.getAttributeOrDefault(CLIENT_RESPONSE_HEADER_NAMES,
            Collections.emptySet());
    addedHeaders.forEach(header -> exchange.getResponse().getHeaders().remove(header));
    exchange.getAttributes().remove(GATEWAY_ALREADY_ROUTED_ATTR);
}

From source file:de.ks.flatadocdb.defaults.ReflectionLuceneDocumentExtractor.java

protected Set<DocField> getFields(Class<?> clazz) {

    if (!cache.containsKey(clazz)) {
        @SuppressWarnings("unchecked")
        Set<Field> allFields = ReflectionUtils.getAllFields(clazz, this::filterField);
        Set<DocField> docFields = allFields.stream().map(this::createDocField).filter(Objects::nonNull)
                .collect(Collectors.toSet());
        docFields.forEach(
                f -> log.debug("Found indexable lucene field {} for {}", f.getField(), clazz.getSimpleName()));
        cache.putIfAbsent(clazz, docFields);
    }//w  ww .  jav a  2  s  .com
    return cache.get(clazz);
}

From source file:se.uu.it.cs.recsys.service.resource.FrequenPatternResource.java

@GET
@Path("/find")
@Produces(MediaType.APPLICATION_JSON)// w  w  w .  ja va  2s  .  c o  m
@ApiOperation(value = "find", notes = "list all frequent patterns", responseContainer = "Map")
public Response listAllFrequentPatterns(@QueryParam("codes") Set<String> codes,
        @QueryParam("minSupport") Integer minSupport) {

    if (codes == null || codes.isEmpty()) {
        return Response.ok().build();
    }

    Set<Integer> courseIds = new HashSet<>();

    codes.forEach(code -> {
        Set<se.uu.it.cs.recsys.persistence.entity.Course> courses = this.courseRepository.findByCode(code);
        Set<Integer> ids = courses.stream().map(entry -> entry.getAutoGenId()).collect(Collectors.toSet());

        courseIds.addAll(ids);
    });

    Map<Set<Integer>, Integer> patterns = this.ruleMiner.getPatterns(courseIds, minSupport);

    Map<Set<Course>, Integer> output = convertToCourse(patterns);

    return Response.ok(output, MediaType.APPLICATION_JSON).build();

}