Java Code Examples for java.util.Set#forEach()

The following examples show how to use java.util.Set#forEach() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaggagePropagationTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void clear_and_add() {
  SingleBaggageField requestIdConfig = SingleBaggageField.newBuilder(vcapRequestId)
    .addKeyName("request-id")
    .addKeyName("request_id")
    .build();

  SingleBaggageField traceIdConfig = SingleBaggageField.remote(amznTraceId);
  BaggagePropagation.FactoryBuilder builder = newFactoryBuilder(B3Propagation.FACTORY)
    .add(requestIdConfig)
    .add(traceIdConfig);

  Set<BaggagePropagationConfig> configs = builder.configs();

  builder.clear();

  configs.forEach(builder::add);

  assertThat(builder)
    .usingRecursiveComparison()
    .isEqualTo(newFactoryBuilder(B3Propagation.FACTORY)
      .add(requestIdConfig)
      .add(traceIdConfig));
}
 
Example 2
Source File: PerformanceView.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private void addDynamicVisualisationSelection(IMenuManager menuManager) {
	if (defaultMenuItems == null) {
		// first call: remember default menu items (as contributed by extensions in plugin.xml)
		defaultMenuItems = menuManager.getItems();
	} else {
		// later calls: clear menu & restore the default menu items
		menuManager.removeAll();
		Stream.of(defaultMenuItems).forEach(item -> menuManager.add(item));
	}

	Set<String> collectorsKeys = CollectedDataAccess.getCollectorsKeys();
	trashUnreachableVisualisations(collectorsKeys);

	// add actions to the menu
	menuManager.add(new Separator());
	collectorsKeys
			.forEach(collectorName -> menuManager.add(createDynamicAction(collectorName, this::selectDataSource)));
}
 
Example 3
Source File: GraphManager.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
private void closeTx(final Set<String> graphSourceNamesToCloseTxOn,
                     final Transaction.Status tx) {
    final Set<Graph> graphsToCloseTxOn = new HashSet<>();

    graphSourceNamesToCloseTxOn.forEach(name -> {
        if (this.graphs.containsKey(name)) {
            graphsToCloseTxOn.add(this.graphs.get(name));
        }
    });

    graphsToCloseTxOn.forEach(graph -> {
        if (graph.features().graph().supportsTransactions() &&
            graph.tx().isOpen()) {
            if (tx == Transaction.Status.COMMIT) {
                graph.tx().commit();
            } else {
                graph.tx().rollback();
            }
        }
    });
}
 
Example 4
Source File: ConcurrentSortedLongPairSetTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testIteration() {
    LongPairSet set = new ConcurrentSortedLongPairSet(16);

    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            set.add(i, j);
        }
    }

    for (int i = 0; i < 10; i++) {
        final int firstKey = i;
        Set<LongPair> longSetResult = set.items(10);
        assertEquals(longSetResult.size(), 10);
        longSetResult.forEach(longPair -> {
            assertEquals(firstKey, longPair.first);
        });
        set.removeIf((item1, item2) -> item1 == firstKey);
    }

}
 
Example 5
Source File: ElasticsearchUtil.java    From adaptive-alerting with Apache License 2.0 6 votes vote down vote up
@Generated
public void updateIndexMappings(Set<String> newFieldMappings, String indexName, String docType) {
    PutMappingRequest request = new PutMappingRequest(indexName);

    Map<String, Object> type = new HashMap<>();
    type.put("type", "keyword");

    Map<String, Object> properties = new HashMap<>();
    newFieldMappings.forEach(field -> {
        properties.put(field, type);
    });

    Map<String, Object> jsonMap = new HashMap<>();
    jsonMap.put("properties", properties);
    request.source(jsonMap);
    request.type(docType);

    try {
        legacyElasticSearchClient.indices().putMapping(request, RequestOptions.DEFAULT);
    } catch (IOException e) {
        log.error("Error updating mappings", e);
        throw new RuntimeException(e);
    }
}
 
Example 6
Source File: ConstructGraphTestUtils.java    From rya with Apache License 2.0 5 votes vote down vote up
public VisibilityStatementSet(Set<RyaStatement> statements) {
    this.statements = new HashSet<>();
    statements.forEach(x -> {
        this.statements.add(RyaToRdfConversions.convertStatement(x));
        if (visibility == null) {
            if (x.getColumnVisibility() != null) {
                visibility = new String(x.getColumnVisibility());
            } else {
                this.visibility = "";
            }
        }
    });
}
 
Example 7
Source File: ValidationWriters.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
public ValidationWriters(String networkId, Set<ValidationType> validationTypes, Path folder, ValidationConfig config) {
    validationTypes.forEach(validationType -> {
        try {
            Writer writer = Files.newBufferedWriter(validationType.getOutputFile(folder), StandardCharsets.UTF_8);
            writersMap.put(validationType, writer);
            validationWritersMap.put(validationType, ValidationUtils.createValidationWriter(networkId, config, writer, validationType));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    });
}
 
Example 8
Source File: WorkflowTaskTypeConstraintTest.java    From conductor with Apache License 2.0 5 votes vote down vote up
private List<String> getErrorMessages(WorkflowTask workflowTask) {
    Set<ConstraintViolation<WorkflowTask>> result = validator.validate(workflowTask);
    List<String> validationErrors = new ArrayList<>();
    result.forEach(e -> validationErrors.add(e.getMessage()));

    return validationErrors;
}
 
Example 9
Source File: StatusService.java    From galeb with Apache License 2.0 5 votes vote down vote up
public Map<Long, Status> status(AbstractEntity entity) {
	if (entity instanceof Environment) {
		boolean exists = changesService.hasByEnvironmentId(entity.getId());
		return Collections.singletonMap(entity.getId(), exists ? Status.PENDING : Status.OK);
	}
	final Set<Environment> allEnvironments = entity.getAllEnvironments();
	if (allEnvironments == null || allEnvironments.isEmpty()) {
		if (!(entity instanceof Rule)) {
			LOGGER.error(entity.getClass().getSimpleName() + " ID " + entity.getId() + " is INCONSISTENT. allEnvironments is NULL or Empty");
		}
		return Collections.emptyMap();
    }
    final Boolean isQuarantine;
    if ((isQuarantine = entity.isQuarantine()) != null && isQuarantine) {
        return allEnvironments.stream().collect(Collectors.toMap(Environment::getId, e -> Status.DELETED));
    }
    if (entity instanceof Target && targetHasEnvUnregistered((Target) entity, allEnvironments)) {
        return allEnvironments.stream().collect(Collectors.toMap(Environment::getId, e -> Status.PENDING));
    }
    Set<Long> allEnvironmentsWithChanges = changesService.listEnvironmentIds(entity);
    Set<Long> allEnvironmentIdsEntity = allEnvironments.stream().map(Environment::getId).collect(Collectors.toSet());
    allEnvironmentIdsEntity.removeAll(allEnvironmentsWithChanges);

    Map<Long, Status> mapStatus = new HashMap<>();
    allEnvironmentIdsEntity.forEach(e -> mapStatus.put(e, Status.OK));
    allEnvironmentsWithChanges.forEach(e -> mapStatus.put(e, Status.PENDING));

    return mapStatus;
}
 
Example 10
Source File: RoutesAnswererUtil.java    From batfish with Apache License 2.0 5 votes vote down vote up
/**
 * Filters a {@link Table} of {@link Bgpv4Route}s to produce a {@link Multiset} of rows
 *
 * @param bgpRoutes {@link Table} of all {@link Bgpv4Route}s
 * @param ribProtocol {@link RibProtocol}, either {@link RibProtocol#BGP}
 * @param matchingNodes {@link Set} of nodes from which {@link Bgpv4Route}s are to be selected
 * @param network {@link Prefix} of the network used to filter the routes
 * @param protocolSpec {@link RoutingProtocolSpecifier} used to filter the {@link Bgpv4Route}s
 * @param vrfRegex Regex used to filter the routes based on {@link org.batfish.datamodel.Vrf}
 * @return {@link Multiset} of {@link Row}s representing the routes
 */
static Multiset<Row> getBgpRibRoutes(
    Table<String, String, Set<Bgpv4Route>> bgpRoutes,
    RibProtocol ribProtocol,
    Set<String> matchingNodes,
    @Nullable Prefix network,
    RoutingProtocolSpecifier protocolSpec,
    String vrfRegex) {
  Multiset<Row> rows = HashMultiset.create();
  Map<String, ColumnMetadata> columnMetadataMap = getTableMetadata(ribProtocol).toColumnMap();
  Pattern compiledVrfRegex = Pattern.compile(vrfRegex);
  matchingNodes.forEach(
      hostname ->
          bgpRoutes
              .row(hostname)
              .forEach(
                  (vrfName, routes) -> {
                    if (compiledVrfRegex.matcher(vrfName).matches()) {
                      routes.stream()
                          .filter(
                              route ->
                                  (network == null || network.equals(route.getNetwork()))
                                      && protocolSpec
                                          .getProtocols()
                                          .contains(route.getProtocol()))
                          .forEach(
                              route ->
                                  rows.add(
                                      bgpRouteToRow(
                                          hostname, vrfName, route, columnMetadataMap)));
                    }
                  }));
  return rows;
}
 
Example 11
Source File: MessageServer.java    From seppb with MIT License 5 votes vote down vote up
/**
 * 为每个用户推送
 *
 * @param userId
 */
@Override
public void pushByT(String userId) {
	Set<WebSocketSession> sessions = GlobalCache.getUserSessionMap().get(userId);
	sessions.forEach(session -> pushBySession(session, userId));
	messageService.updateSendStatusByUser(Integer.parseInt(userId), 1);

	// 告警消息一直保持,不消除
	// warningService.updateWarningMessageSendStatus(Integer.parseInt(userId), 1);
}
 
Example 12
Source File: AbstractModelFactory.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Model createModel(@Nonnull Set<Namespace> namespaces, @Nonnull Collection<@Nonnull ? extends Statement> c) {
    Model finalModel = createModel();
    finalModel.addAll(c);
    namespaces.forEach(finalModel::setNamespace);
    return finalModel;
}
 
Example 13
Source File: BrainUtil.java    From spring-boot-chatbot with MIT License 5 votes vote down vote up
public static <T extends AbstractBrainCell> String explainDetail(Set<BrainFactory.BrainCellInfo<T>> entrySet) {
    StringBuilder stringBuilder = new StringBuilder();
    entrySet
            .forEach(info -> {
                        stringBuilder.append(info.toString());
                        stringBuilder.append("\n");
                    }
            );
    return stringBuilder.toString();
}
 
Example 14
Source File: ResourceManagerPartitionTrackerImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
private Map<ResourceID, Set<IntermediateDataSetID>> prepareReleaseCalls(Set<IntermediateDataSetID> dataSetsToRelease) {
	final Map<ResourceID, Set<IntermediateDataSetID>> releaseCalls = new HashMap<>();
	dataSetsToRelease.forEach(dataSetToRelease -> {
		final Set<ResourceID> hostingTaskExecutors = getHostingTaskExecutors(dataSetToRelease);
		hostingTaskExecutors.forEach(hostingTaskExecutor -> insert(hostingTaskExecutor, dataSetToRelease, releaseCalls));
	});
	return releaseCalls;
}
 
Example 15
Source File: ConstructGraphTestUtils.java    From rya with Apache License 2.0 4 votes vote down vote up
public static void subGraphsEqualIgnoresBlankNode(Set<RyaSubGraph> subgraph1, Set<RyaSubGraph> subgraph2) {
    Map<Integer, RyaSubGraph> subGraphMap = new HashMap<>();
    subgraph1.forEach(x->subGraphMap.put(getKey(x), x));
    subgraph2.forEach(x->ryaStatementsEqualIgnoresBlankNode(x.getStatements(), subGraphMap.get(getKey(x)).getStatements()));
}
 
Example 16
Source File: DefaultPersistenceUnitManager.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private void scanPackage(SpringPersistenceUnitInfo scannedUnit, String pkg) {
	if (this.componentsIndex != null) {
		Set<String> candidates = new HashSet<>();
		for (AnnotationTypeFilter filter : entityTypeFilters) {
			candidates.addAll(this.componentsIndex.getCandidateTypes(pkg, filter.getAnnotationType().getName()));
		}
		candidates.forEach(scannedUnit::addManagedClassName);
		Set<String> managedPackages = this.componentsIndex.getCandidateTypes(pkg, "package-info");
		managedPackages.forEach(scannedUnit::addManagedPackage);
		return;
	}

	try {
		String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
				ClassUtils.convertClassNameToResourcePath(pkg) + CLASS_RESOURCE_PATTERN;
		Resource[] resources = this.resourcePatternResolver.getResources(pattern);
		MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
		for (Resource resource : resources) {
			if (resource.isReadable()) {
				MetadataReader reader = readerFactory.getMetadataReader(resource);
				String className = reader.getClassMetadata().getClassName();
				if (matchesFilter(reader, readerFactory)) {
					scannedUnit.addManagedClassName(className);
					if (scannedUnit.getPersistenceUnitRootUrl() == null) {
						URL url = resource.getURL();
						if (ResourceUtils.isJarURL(url)) {
							scannedUnit.setPersistenceUnitRootUrl(ResourceUtils.extractJarFileURL(url));
						}
					}
				}
				else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {
					scannedUnit.addManagedPackage(
							className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length()));
				}
			}
		}
	}
	catch (IOException ex) {
		throw new PersistenceException("Failed to scan classpath for unlisted entity classes", ex);
	}
}
 
Example 17
Source File: HashSetIterationTest.java    From hellokoding-courses with MIT License 4 votes vote down vote up
@Test
public void iterateWithForEachConsumer() {
    Set<Integer> set = new HashSet<>(Set.of(3, 1, 2));

    set.forEach(ele -> System.out.printf("%d ", ele));
}
 
Example 18
Source File: RoutesAnswererUtil.java    From batfish with Apache License 2.0 4 votes vote down vote up
/**
 * Given a {@link Table} of {@link Bgpv4Route}s indexed by Node name and VRF name, applies given
 * filters and groups the routes by {@link RouteRowKey} and sub-groups them further by {@link
 * RouteRowSecondaryKey} and for the routes in same sub-groups, sorts them according to {@link
 * RouteRowAttribute}
 *
 * @param bgpRoutes {@link Table} of BGP routes with rows per node and columns per VRF * @param
 *     ribs {@link Map} of the RIBs
 * @param matchingNodes {@link Set} of nodes to be matched
 * @param vrfRegex Regex to filter the VRF
 * @param network {@link Prefix}
 * @param protocolRegex Regex to filter the protocols of the routes
 * @return {@link Map} of {@link RouteRowKey}s to corresponding sub{@link Map}s of {@link
 *     RouteRowSecondaryKey} to {@link SortedSet} of {@link RouteRowAttribute}s
 */
static Map<RouteRowKey, Map<RouteRowSecondaryKey, SortedSet<RouteRowAttribute>>> groupBgpRoutes(
    Table<String, String, Set<Bgpv4Route>> bgpRoutes,
    Set<String> matchingNodes,
    String vrfRegex,
    @Nullable Prefix network,
    String protocolRegex) {
  Map<RouteRowKey, Map<RouteRowSecondaryKey, SortedSet<RouteRowAttribute>>> routesGroups =
      new HashMap<>();
  Pattern compiledProtocolRegex = Pattern.compile(protocolRegex, Pattern.CASE_INSENSITIVE);
  Pattern compiledVrfRegex = Pattern.compile(vrfRegex);
  matchingNodes.forEach(
      hostname ->
          bgpRoutes
              .row(hostname)
              .forEach(
                  (vrfName, routes) -> {
                    if (compiledVrfRegex.matcher(vrfName).matches()) {
                      routes.stream()
                          .filter(
                              route ->
                                  (network == null || network.equals(route.getNetwork()))
                                      && compiledProtocolRegex
                                          .matcher(route.getProtocol().protocolName())
                                          .matches())
                          .forEach(
                              route ->
                                  routesGroups
                                      .computeIfAbsent(
                                          new RouteRowKey(hostname, vrfName, route.getNetwork()),
                                          k -> new HashMap<>())
                                      .computeIfAbsent(
                                          new RouteRowSecondaryKey(
                                              route.getNextHopIp(),
                                              route.getProtocol().protocolName()),
                                          k -> new TreeSet<>())
                                      .add(
                                          RouteRowAttribute.builder()
                                              .setOriginProtocol(
                                                  route.getSrcProtocol() != null
                                                      ? route.getSrcProtocol().protocolName()
                                                      : null)
                                              .setAdminDistance(route.getAdministrativeCost())
                                              .setMetric(route.getMetric())
                                              .setAsPath(route.getAsPath())
                                              .setLocalPreference(route.getLocalPreference())
                                              .setCommunities(
                                                  route.getCommunities().stream()
                                                      .map(Community::toString)
                                                      .collect(toImmutableList()))
                                              .setOriginType(route.getOriginType())
                                              .setTag(
                                                  route.getTag() == Route.UNSET_ROUTE_TAG
                                                      ? null
                                                      : route.getTag())
                                              .build()));
                    }
                  }));

  return routesGroups;
}
 
Example 19
Source File: RestApiError.java    From spring-boot with Apache License 2.0 4 votes vote down vote up
void addValidationErrors(Set<ConstraintViolation<?>> constraintViolations) {
    constraintViolations.forEach(this::addValidationError);
}
 
Example 20
Source File: GradleDependencyAdapter.java    From thorntail with Apache License 2.0 4 votes vote down vote up
/**
 * Get the dependencies via the Gradle IDEA model.
 *
 * @param connection the Gradle project connection.
 * @return the computed dependencies.
 */
private DeclaredDependencies getDependenciesViaIdeaModel(ProjectConnection connection) {
    DeclaredDependencies declaredDependencies = new DeclaredDependencies();

    // 1. Get the IdeaProject model from the Gradle connection.
    IdeaProject prj = connection.getModel(IdeaProject.class);
    prj.getModules().forEach(this::computeProjectDependencies);

    // 2. Find the IdeaModule that maps to the project that we are looking at.
    Optional<? extends IdeaModule> prjModule = prj.getModules().stream()
            .filter(m -> m.getGradleProject().getProjectDirectory().toPath().equals(rootPath))
            .findFirst();


    // We need to return the following collection of dependencies,
    // 1. For the current project, return all artifacts that are marked as ["COMPILE", "TEST"]
    // 2. From the upstream-projects, add all dependencies that are marked as ["COMPILE"]
    // 3. For the current project, iterate through each dependencies marked as ["PROVIDED"] and do the following,
    //      a.) Check if they are already available from 1 & 2. If yes, then nothing to do here.
    //      b.) Check if this entry is defined as ["TEST"] in the upstream-projects. If yes, then include it.
    //          -- The reason for doing this is because of the optimization that Gradle does on the IdeaModule library set.
    Set<ArtifactSpec> collectedDependencies = new HashSet<>();
    prjModule.ifPresent(m -> {
        Map<String, Set<ArtifactSpec>> currentPrjDeps = ARTIFACT_DEPS_OF_PRJ.get(m.getName());
        Set<String> upstreamProjects = PRJ_DEPS_OF_PRJ.getOrDefault(m.getName(), emptySet());

        collectedDependencies.addAll(currentPrjDeps.getOrDefault(DEP_SCOPE_COMPILE, emptySet()));
        collectedDependencies.addAll(currentPrjDeps.getOrDefault(DEP_SCOPE_TEST, emptySet()));

        upstreamProjects.forEach(moduleName -> {
            Map<String, Set<ArtifactSpec>> moduleDeps = ARTIFACT_DEPS_OF_PRJ.getOrDefault(moduleName, emptyMap());
            collectedDependencies.addAll(moduleDeps.getOrDefault(DEP_SCOPE_COMPILE, emptySet()));
        });

        Set<ArtifactSpec> providedScopeDeps = currentPrjDeps.getOrDefault(DEP_SCOPE_PROVIDED, emptySet());
        providedScopeDeps.removeAll(collectedDependencies);

        if (!providedScopeDeps.isEmpty()) {
            List<ArtifactSpec> testScopedLibs = new ArrayList<>();

            upstreamProjects.forEach(moduleName -> testScopedLibs.addAll(
                    ARTIFACT_DEPS_OF_PRJ.getOrDefault(moduleName, emptyMap())
                            .getOrDefault(DEP_SCOPE_TEST, emptySet())));
            providedScopeDeps.stream().filter(testScopedLibs::contains).forEach(collectedDependencies::add);
        }

    });

    collectedDependencies.forEach(declaredDependencies::add);
    return declaredDependencies;
}