下面列出了java.util.HashSet#forEach ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Gets all values for all definitions. If there is no value for a definition {@code null} is added to the map.
*
* @return all values by definition
*/
@Override
public Map<SettingDefinition<?>, SettingValue<?>> getSettings() {
Set<SettingValue<?>> values = this.settingsManagerDao.getSettingValues();
Map<SettingDefinition<?>, SettingValue<?>> settingsByDefinition = new HashMap<>(values.size());
values.forEach(value -> {
final SettingDefinition<?> definition = getDefinitionByKey(value.getKey());
if (definition == null) {
LOG.warn("No definition for '{}' found.", value.getKey());
} else {
settingsByDefinition.put(definition, value);
}
});
HashSet<SettingDefinition<?>> nullValues = new HashSet<>(getSettingDefinitions());
nullValues.removeAll(settingsByDefinition.keySet());
nullValues.forEach(s -> settingsByDefinition.put(s, null));
return settingsByDefinition;
}
/**
* This method combines the list of usernames on local players friend/ignore list into a comma delimited string
* and then copies it to the clipboard.
*/
private void friendIgnoreToClipboard()
{
StringBuilder friendsList = new StringBuilder();
NameableContainer<Friend> friendContainer = client.getFriendContainer();
NameableContainer<Ignore> ignoreContainer = client.getIgnoreContainer();
String[] friendsIgnores = ArrayUtils.addAll(Arrays.stream(friendContainer.getMembers()).map(Nameable::getName).toArray(String[]::new),
Arrays.stream(ignoreContainer.getMembers()).map(Nameable::getName).toArray(String[]::new));
HashSet<String> names = new HashSet<>(Arrays.asList(friendsIgnores));
names.forEach(n -> friendsList.append(n.toLowerCase()).append(","));
StringSelection namesSelection = new StringSelection(friendsList.toString());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(namesSelection, namesSelection);
}
public void init(P2PService p2PService,
BtcWalletService btcWalletService,
BsqWalletService bsqWalletService,
TradeWalletService tradeWalletService,
TradeManager tradeManager,
OpenOfferManager openOfferManager,
ReferralIdService referralIdService,
User user,
FilterManager filterManager,
AccountAgeWitnessService accountAgeWitnessService,
KeyRing keyRing,
boolean useSavingsWallet,
Coin fundsNeededForTrade) {
Log.traceCall();
processModel.onAllServicesInitialized(offer,
tradeManager,
openOfferManager,
p2PService,
btcWalletService,
bsqWalletService,
tradeWalletService,
referralIdService,
user,
filterManager,
accountAgeWitnessService,
keyRing,
useSavingsWallet,
fundsNeededForTrade);
createTradeProtocol();
// If we have already received a msg we apply it.
// removeDecryptedMsgWithPubKey will be called synchronous after apply. We don't have threaded context
// or async calls there.
// Clone to avoid ConcurrentModificationException. We remove items at the applyMailboxMessage call...
HashSet<DecryptedMessageWithPubKey> set = new HashSet<>(decryptedMessageWithPubKeySet);
set.forEach(msg -> tradeProtocol.applyMailboxMessage(msg, this));
}
private void selectTorrentToDelete(){
HashSet<Torrents> completedTorrents = new HashSet<>();
for (Client c : clients) {
try {
c.acquireTorrents(Client.TorrentState.COMPLETED);
} catch (IOException e) {
e.printStackTrace();
}
completedTorrents.addAll(c.getCompletedTorrents());
}
this.torrentToDelete = new Torrents(1577808000, 1577808000, 0, 1048576000);
float expectUp =Float.parseFloat(properties.getProperty("expect_torrent_up"));
switch (properties.getProperty("delete_rule")){
default:
case "act":
completedTorrents.forEach(torrent -> {
if (torrent.getUpspeed() / (double)1048576 < expectUp && torrent.getLast_activity() < this.torrentToDelete.getLast_activity()) this.torrentToDelete = torrent;
});
break;
case "add":
completedTorrents.forEach(torrent -> {
if (torrent.getUpspeed() / (double)1048576 < expectUp && torrent.getAdded_on() < this.torrentToDelete.getAdded_on()) this.torrentToDelete = torrent;
});
break;
case "slow":
completedTorrents.forEach(torrent -> {
if (torrent.getUpspeed() / (double)1048576 < expectUp && torrent.getUpspeed() < this.torrentToDelete.getUpspeed()) this.torrentToDelete = torrent;
});
break;
case "large":
completedTorrents.forEach(torrent -> {
if (torrent.getUpspeed() / (double)1048576 < expectUp && torrent.getTotal_size() > this.torrentToDelete.getTotal_size()) this.torrentToDelete = torrent;
});
break;
}
this.torrentToDelete.setClients(Client.Clients.QBITTORRENT);
}
@Test
public void testEquivalence_DifferentRelationInequivalentVariants(){
HashSet<String> queries = Sets.newHashSet(
"{ $x isa binary; };",
"{ ($y) isa binary; };",
"{ ($x, $y); };",
"{ ($x, $y) isa binary; };",
"{ (baseRole1: $x, baseRole2: $y) isa binary; };",
"{ (role: $y, baseRole2: $z) isa binary; };",
"{ (role: $y, baseRole2: $z) isa $type; };",
"{ (role: $y, baseRole2: $z) isa $type; $type type binary; };",
"{ (role: $x, role: $x, baseRole2: $z) isa binary; };",
"{ $x ($y, $z) isa binary; };",
"{ $x (baseRole1: $y, baseRole2: $z) isa binary; };"
);
queries.forEach(qA -> {
queries.stream()
.filter(qB -> !qA.equals(qB))
.forEach(qB -> {
equivalence(qA, qB, false, ReasonerQueryEquivalence.AlphaEquivalence, reasonerQueryFactory);
equivalence(qA, qB, false, ReasonerQueryEquivalence.StructuralEquivalence, reasonerQueryFactory);
});
});
}
@Test
public void testIterationWithConcurrentClearedCacheException() {
try (CacheManager cacheManager = createTestCacheManager()) {
Cache<Long, byte[]> cache = cacheManager.getCache(testName.getMethodName(), Long.class, byte[].class);
byte[] data = new byte[10 * 1024];
Set<Long> initialKeySet = new HashSet<>();
range(0, 20).forEach(k -> {
cache.put(k, data);
initialKeySet.add(k);
});
Iterator<Cache.Entry<Long, byte[]>> iterator = cache.iterator();
cache.clear();
HashSet<Long> foundKeys = new HashSet<>();
try {
while (true) {
assertThat(foundKeys.add(iterator.next().getKey()), is(true));
}
} catch (NoSuchElementException e) {
//expected
}
foundKeys.forEach(k -> assertThat(k, isIn(initialKeySet)));
}
}
public void test_forEach() throws Exception {
HashSet<Integer> hs = new HashSet<>();
hs.add(0);
hs.add(1);
hs.add(2);
HashSet<Integer> output = new HashSet<>();
hs.forEach(k -> output.add(k));
assertEquals(hs, output);
}
public void test_forEach_NPE() throws Exception {
HashSet<String> set = new HashSet<>();
try {
set.forEach(null);
fail();
} catch(NullPointerException expected) {}
}
public void test_forEach_CME() throws Exception {
HashSet<String> set = new HashSet<>();
set.add("one");
set.add("two");
try {
set.forEach(new java.util.function.Consumer<String>() {
@Override
public void accept(String k) {set.add("foo");}
});
fail();
} catch(ConcurrentModificationException expected) {}
}
/**
* Update Flow route registry and push refresh to UIs (concrete parameter
* types as {@link org.hotswap.agent.command.ReflectionCommand} determines
* the method from actual argument types).
*
* @param addedClasses
* returns classes that have been added or modified
* @param modifiedClasses
* returns classes that have been deleted
*/
public void updateRoutes(HashSet<Class<?>> addedClasses,
HashSet<Class<?>> modifiedClasses) {
assert (vaadinServlet != null);
LOGGER.debug("The following classes were added:");
addedClasses.forEach(clazz -> LOGGER.debug("+ {}", clazz));
LOGGER.debug("The following classes were modified:");
modifiedClasses.forEach(clazz -> LOGGER.debug("# {}", clazz));
Method getInstanceMethod = null;
Object getInstanceMethodParam = null;
try {
// Vaadin 14.2+
getInstanceMethod = ApplicationRouteRegistry.class.getMethod("getInstance", VaadinContext.class);
getInstanceMethodParam = vaadinServlet.getService().getContext();
} catch (NoSuchMethodException ex1) {
// In Vaadin 14.1, this method instead takes a ServletContext parameter
LOGGER.debug("ApplicationRouteRegistry::getInstance(VaadinContext) not found");
try {
getInstanceMethod = ApplicationRouteRegistry.class.getMethod("getInstance", ServletContext.class);
getInstanceMethodParam = vaadinServlet.getServletContext();
} catch (NoSuchMethodException ex2) {
// In Vaadin 14.1, this method takes a ServletContext parameter
LOGGER.warning("Unable to obtain ApplicationRouteRegistry instance; routes are not updated ");
return;
}
}
try {
ApplicationRouteRegistry registry = (ApplicationRouteRegistry)
getInstanceMethod.invoke(null, getInstanceMethodParam);
updateRouteRegistry(registry, addedClasses, modifiedClasses,
Collections.emptySet());
} catch (IllegalAccessException | InvocationTargetException ex) {
LOGGER.warning("Unable to obtain ApplicationRouteRegistry instance; routes are not updated:", ex);
}
}
public boolean updateDepGraph(Block lexedAndParsedAST, TheScopeFrame scopeFrame) {
//update graph
depMap = new HashMap<String, HashSet<REPLTopLevelComponent>>();
topLevelImportStar = new HashSet<ImportStarUtil.PackageOrClass>();
if(null != topLevelNames) {
prevtopLevelItems.putAll(topLevelNames);
}
topLevelNames = new HashMap<String, HashSet<Pair<Type, HashSet<Type>>>>();
super.visit(lexedAndParsedAST);
//now check for changes: topLevelItems vs prevtopLevelItems
HashSet<REPLTopLevelComponent> componentsToRefresh = new HashSet<REPLTopLevelComponent>();
for(String topLevelItem : topLevelNames.keySet()) {
HashSet<REPLTopLevelComponent> toAdd=null;
if(prevtopLevelItems.containsKey(topLevelItem)) {
HashSet<Pair<Type, HashSet<Type>>> newTypes = topLevelNames.get(topLevelItem);
HashSet<Pair<Type, HashSet<Type>>> oldTypes = prevtopLevelItems.get(topLevelItem);
if(!newTypes.equals(oldTypes)){//if there are changes then dependencies
toAdd = depMap.get(topLevelItem);
}
}else {//new so add all deps
toAdd = depMap.get(topLevelItem);
}
if(null != toAdd) {
componentsToRefresh.addAll(toAdd);
}
}
/*{//handle deleted items:
HashSet<String> delItems = new HashSet<String>(scopeFrame.getAllItemsDeleted());
delItems.removeAll(prevDeletedItems);//remove previous onces otherwise we have inf loop
for(String deled : delItems) {
HashSet<REPLTopLevelComponent> toAdd = depMap.get(deled);
if(null != toAdd) {
componentsToRefresh.addAll(toAdd);
}
}
prevDeletedItems = new HashSet<String>(prevDeletedItems);
prevDeletedItems.addAll(delItems);
}*/
if(!topLevelImportStar.isEmpty()) {
//only process new items since last iteration
HashSet<ImportStarUtil.PackageOrClass> toproc = new HashSet<ImportStarUtil.PackageOrClass>(topLevelImportStar);
toproc.removeAll(prevtopLevelImportStar);
for(ImportStarUtil.PackageOrClass inst : toproc) {
//see if any dependencies from any non-already-included dependencies can be satisfied by this instance, if so tag them for inclusion
for(String dep : depMap.keySet()) {
if(null != dep && !dep.contains(".")) {
if(null != inst.getResource(dep)) {
componentsToRefresh.addAll(depMap.get(dep));
}
}
}
}
prevtopLevelImportStar = topLevelImportStar;
}
if(!componentsToRefresh.isEmpty()) {
componentsToRefresh.forEach(a -> {
if(!a.getErrors()) {
a.setSupressErrors(false);//no errors before, so check for them again
}
if(a.canSkip()) {
a.setSkippable(false);
this.replState.topLevelItemsToSkip.remove(new REPLComponentWrapper(a));
}
});
itemsModifiedThisSession.addAll(componentsToRefresh);
return true;
}else {
return false;
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onTableEnchant(EnchantItemEvent event) {
if (!MineTinker.getPlugin().getConfig().getBoolean("ConvertEnchantmentsOnEnchant", true)) return;
if (!ToolType.ALL.contains(event.getItem().getType())) { //Something different (like a book)
return;
}
if (!(modManager.isToolViable(event.getItem()) || modManager.isWandViable(event.getItem())
|| modManager.isArmorViable(event.getItem()))) { //not a MineTinker Tool
return;
}
boolean free = !MineTinker.getPlugin().getConfig().getBoolean("EnchantingCostsSlots", true);
Map<Enchantment, Integer> enchants = event.getEnchantsToAdd();
HashSet<Enchantment> toremove = new HashSet<>();
for (Map.Entry<Enchantment, Integer> entry : enchants.entrySet()) {
Modifier modifier = modManager.getModifierFromEnchantment(entry.getKey());
// The modifier may be disabled
if (modifier != null && modifier.isAllowed()) {
for (int i = 0; i < entry.getValue(); i++) {
//Adding necessary slots
if (free)
modManager.setFreeSlots(event.getItem(), modManager.getFreeSlots(event.getItem()) + modifier.getSlotCost());
if (!modManager.addMod(event.getEnchanter(), event.getItem(), modifier,
false, false, true)) {
//Remove slots as they were not needed
if (free)
modManager.setFreeSlots(event.getItem(), modManager.getFreeSlots(event.getItem()) - modifier.getSlotCost());
if (MineTinker.getPlugin().getConfig().getBoolean("RefundLostEnchantmentsAsItems", true)) {
for (; i < entry.getValue(); i++) { //Drop lost enchantments due to some error in addMod
if (event.getEnchanter().getInventory().addItem(modifier.getModItem()).size() != 0) { //adds items to (full) inventory
event.getEnchanter().getWorld().dropItem(event.getEnchanter().getLocation(), modifier.getModItem());
} // no else as it gets added in if-clause
}
}
break;
}
}
toremove.add(entry.getKey());
}
}
toremove.forEach(enchants::remove);
if (enchants.size() == 0) { //This Map should never be empty as the
enchants.put(fakeEnchant, 1);
Bukkit.getScheduler().runTaskLater(MineTinker.getPlugin(), () -> event.getItem().removeEnchantment(fakeEnchant), 1);
}
}
public void updateSubdivideList(){
splitBy = new HashSet();
splitBy.addAll(subdivideListProperty);
splitBy.forEach(s -> {System.out.println("AwardCategory subdivide category: " + s);});
}
public void encryptCheckThread() {
try {
while (stopRequest.getCount() > 0) {
maybeBarrier();
byte[] ref = new byte[2];
ThreadLocalRandom.current().nextBytes(ref);
ConcurrentHashMap<CacheTestFixtures.SentinelKey, Object> allowedKeys
= possibleEncrypts.computeIfAbsent(ByteBuffer.wrap(ref),
ignored -> new ConcurrentHashMap<>());
synchronized (allowedKeys) {
HashSet<CacheTestFixtures.SentinelKey> foundKeys = new HashSet<>();
CryptoMaterialsCache.EncryptCacheEntry ece = cache.getEntryForEncrypt(ref, UsageStats.ZERO);
if (ece != null) {
foundKeys.add((CacheTestFixtures.SentinelKey)ece.getResult().getCleartextDataKey());
}
if (foundKeys.isEmpty()) {
inc("encrypt check: empty foundRefs");
} else {
inc("encrypt check: non-empty foundRefs");
}
foundKeys.forEach(foundKey -> {
if (!allowedKeys.containsKey(foundKey)) {
fail("encrypt check: unexpected key; " + allowedKeys + " " + foundKeys);
}
});
allowedKeys.keySet().forEach(allowedKey -> {
if (!foundKeys.contains(allowedKey)) {
inc("encrypt check: prune");
// safe since this is a concurrent map
allowedKeys.remove(allowedKey);
}
});
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Generate serde configuration for provided tables
*
* @param tableDescriptors table descriptors, for which serde configuration to be generated
* @return serde configuration for tables
*/
public static Map<String, String> generateSerdeConfig(List<TableDescriptor> tableDescriptors) {
Map<String, String> serdeConfigs = new HashMap<>();
// Collect key and msg serde instances for all the tables
Map<String, Serde> tableKeySerdes = new HashMap<>();
Map<String, Serde> tableValueSerdes = new HashMap<>();
HashSet<Serde> serdes = new HashSet<>();
tableDescriptors.stream()
.filter(d -> d instanceof LocalTableDescriptor)
.forEach(d -> {
LocalTableDescriptor ld = (LocalTableDescriptor) d;
tableKeySerdes.put(ld.getTableId(), ld.getSerde().getKeySerde());
tableValueSerdes.put(ld.getTableId(), ld.getSerde().getValueSerde());
});
serdes.addAll(tableKeySerdes.values());
serdes.addAll(tableValueSerdes.values());
// Generate serde names
SerializableSerde<Serde> serializableSerde = new SerializableSerde<>();
Base64.Encoder base64Encoder = Base64.getEncoder();
Map<Serde, String> serdeUUIDs = new HashMap<>();
serdes.forEach(serde -> {
String serdeName = serdeUUIDs.computeIfAbsent(serde,
s -> serde.getClass().getSimpleName() + "-" + UUID.randomUUID().toString());
serdeConfigs.putIfAbsent(String.format(SerializerConfig.SERDE_SERIALIZED_INSTANCE, serdeName),
base64Encoder.encodeToString(serializableSerde.toBytes(serde)));
});
// Set key and msg serdes for tables to the serde names generated above
tableKeySerdes.forEach((tableId, serde) -> {
String keySerdeConfigKey = String.format(JavaTableConfig.STORE_KEY_SERDE, tableId);
serdeConfigs.put(keySerdeConfigKey, serdeUUIDs.get(serde));
});
tableValueSerdes.forEach((tableId, serde) -> {
String valueSerdeConfigKey = String.format(JavaTableConfig.STORE_MSG_SERDE, tableId);
serdeConfigs.put(valueSerdeConfigKey, serdeUUIDs.get(serde));
});
return serdeConfigs;
}
public void init(P2PService p2PService,
BtcWalletService btcWalletService,
BsqWalletService bsqWalletService,
TradeWalletService tradeWalletService,
DaoFacade daoFacade,
TradeManager tradeManager,
OpenOfferManager openOfferManager,
ReferralIdService referralIdService,
User user,
FilterManager filterManager,
AccountAgeWitnessService accountAgeWitnessService,
TradeStatisticsManager tradeStatisticsManager,
ArbitratorManager arbitratorManager,
MediatorManager mediatorManager,
RefundAgentManager refundAgentManager,
KeyRing keyRing,
boolean useSavingsWallet,
Coin fundsNeededForTrade) {
processModel.onAllServicesInitialized(checkNotNull(offer, "offer must not be null"),
tradeManager,
openOfferManager,
p2PService,
btcWalletService,
bsqWalletService,
tradeWalletService,
daoFacade,
referralIdService,
user,
filterManager,
accountAgeWitnessService,
tradeStatisticsManager,
arbitratorManager,
mediatorManager,
refundAgentManager,
keyRing,
useSavingsWallet,
fundsNeededForTrade);
arbitratorManager.getDisputeAgentByNodeAddress(arbitratorNodeAddress).ifPresent(arbitrator -> {
arbitratorBtcPubKey = arbitrator.getBtcPubKey();
arbitratorPubKeyRing = arbitrator.getPubKeyRing();
persist();
});
mediatorManager.getDisputeAgentByNodeAddress(mediatorNodeAddress).ifPresent(mediator -> {
mediatorPubKeyRing = mediator.getPubKeyRing();
persist();
});
refundAgentManager.getDisputeAgentByNodeAddress(refundAgentNodeAddress).ifPresent(refundAgent -> {
refundAgentPubKeyRing = refundAgent.getPubKeyRing();
persist();
});
createTradeProtocol();
// If we have already received a msg we apply it.
// removeDecryptedMsgWithPubKey will be called synchronous after apply. We don't have threaded context
// or async calls there.
// Clone to avoid ConcurrentModificationException. We remove items at the applyMailboxMessage call...
HashSet<DecryptedMessageWithPubKey> set = new HashSet<>(decryptedMessageWithPubKeySet);
set.forEach(msg -> tradeProtocol.applyMailboxMessage(msg, this));
}
@Test
public void simpleMultiplePsubTest(TestContext should) {
final Async test = should.async();
final AtomicInteger psubscribeCnt = new AtomicInteger(0);
final AtomicInteger pmessageCnt = new AtomicInteger(0);
sub.handler(message -> {
System.out.println(message);
should.assertTrue(message.type() == ResponseType.MULTI);
if (message.get(0).toString().equals("pmessage")) {
should.assertEquals(4, message.size());
pmessageCnt.incrementAndGet();
}
if (message.get(0).toString().equals("psubscribe")) {
should.assertEquals(3, message.size());
psubscribeCnt.incrementAndGet();
}
if (psubscribeCnt.get() + pmessageCnt.get() == 12) {
test.complete();
}
});
String REDIS_KEYSPACE_EVENT_CHANNEL_SET = "[email protected]__:";
HashSet<String> patterns = new HashSet<String>() {{
add(REDIS_KEYSPACE_EVENT_CHANNEL_SET + "A*");
add(REDIS_KEYSPACE_EVENT_CHANNEL_SET + "B*");
add(REDIS_KEYSPACE_EVENT_CHANNEL_SET + "C*");
add(REDIS_KEYSPACE_EVENT_CHANNEL_SET + "D*");
add(REDIS_KEYSPACE_EVENT_CHANNEL_SET + "E*");
add(REDIS_KEYSPACE_EVENT_CHANNEL_SET + "F*");
}};
Request psub_request = cmd(PSUBSCRIBE);
// Add all patterns to subscribe to
patterns.forEach(psub_request::arg);
sub.send(psub_request, subscribe -> {
should.assertTrue(subscribe.succeeded());
rule.vertx().setTimer(100L, t -> patterns.forEach(p -> pub.send(cmd(PUBLISH).arg(p).arg(System.nanoTime()), publish -> {
should.assertTrue(publish.succeeded());
should.assertNotNull(publish.result());
})));
});
}