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

The following examples show how to use java.util.ArrayList#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: P2PDataStorage.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
@VisibleForTesting
void removeExpiredEntries() {
    // The moment when an object becomes expired will not be synchronous in the network and we could
    // get add network_messages after the object has expired. To avoid repeated additions of already expired
    // object when we get it sent from new peers, we don’t remove the sequence number from the map.
    // That way an ADD message for an already expired data will fail because the sequence number
    // is equal and not larger as expected.
    ArrayList<Map.Entry<ByteArray, ProtectedStorageEntry>> toRemoveList =
            map.entrySet().stream()
                    .filter(entry -> entry.getValue().isExpired(this.clock))
                    .collect(Collectors.toCollection(ArrayList::new));

    // Batch processing can cause performance issues, so do all of the removes first, then update the listeners
    // to let them know about the removes.
    toRemoveList.forEach(toRemoveItem -> {
        log.debug("We found an expired data entry. We remove the protectedData:\n\t" +
                Utilities.toTruncatedString(toRemoveItem.getValue()));
    });
    removeFromMapAndDataStore(toRemoveList);

    if (sequenceNumberMap.size() > this.maxSequenceNumberMapSizeBeforePurge)
        sequenceNumberMap.setMap(getPurgedSequenceNumberMap(sequenceNumberMap.getMap()));
}
 
Example 2
Source File: AmqpTransferTagGeneratorTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Ignore("Used to test performance")
@Test
public void testTagGeneratorOverTime() {
    final AmqpTransferTagGenerator tagGen = new AmqpTransferTagGenerator(true);
    final int tagLoop = AmqpTransferTagGenerator.DEFAULT_TAG_POOL_SIZE;
    final ArrayList<byte[]> tags = new ArrayList<>(tagLoop);

    for (int i = 0; i < Short.MAX_VALUE * 16; ++i) {
        // Checkout all the tags the pool will create
        for (int j = 0; j < tagLoop; ++j) {
            tags.add(tagGen.getNextTag());
        }

        // Return them and then clear
        tags.forEach((tag) -> tagGen.returnTag(tag));
        tags.clear();
    }
}
 
Example 3
Source File: CalendarDateVerificationServiceTest.java    From gtfs-validator with MIT License 5 votes vote down vote up
@Test
public void serviceIdsForDateWithMultipleServiceIDs(){
	Date day = new Date(1427947200000L);
	Calendar d = new GregorianCalendar();
	d.setTime(day);
	d.setTimeZone(cdvs.getTz());
	
	ArrayList<AgencyAndId> idsOnWeekday = cdvs.getServiceIdsForDates().get(d);
	idsOnWeekday.forEach(t -> System.out.println(t.getId()));
	Assert.assertTrue(idsOnWeekday.size() > 1);
}
 
Example 4
Source File: ArrayListTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_forEach_NPE() throws Exception {
    ArrayList<Integer> list = new ArrayList<>();
    try {
        list.forEach(null);
        fail();
    } catch(NullPointerException expected) {}
}
 
Example 5
Source File: DanmakuThreadFactory.java    From BakaDanmaku with MIT License 5 votes vote down vote up
/**
 * 重启所有线程 同样可以用于初始化时线程的启动
 */
public static void restartThreads() {
    // 获得所有的 platforms
    String[] _platforms = BakaDanmakuConfig.livePlatform.platform.split(",");
    for (int i = 0; i < _platforms.length; i++) {
        _platforms[i] = _platforms[i].trim(); // 剔除行首行尾空格
    }

    // 获得所有的平台
    ArrayList<String> platforms = new ArrayList<>(Arrays.asList(_platforms));
    // 获得正在运行的弹幕线程
    ArrayList<String> running = getRunningDanmakuThread();

    // 创建一个 restart 数据,存入刚刚正在运行的弹幕线程列表
    ArrayList<String> restart = new ArrayList<>(running);
    // 获得两者的交集
    restart.retainAll(platforms);

    // 创建一个 toStop 数据,存入刚刚正在运行的弹幕线程列表
    ArrayList<String> toStop = new ArrayList<>(running);
    // 获得两者的差集
    toStop.removeAll(platforms);

    // 创建一个 toStart 数据,存入所有的平台列表
    ArrayList<String> toStart = new ArrayList<>(platforms);
    // 获得两者的差集
    toStart.removeAll((getRunningDanmakuThread()));

    // restart 部分,依次进行停止、并重启
    restart.forEach((platform) -> stopThread(platform, true));
    // toStop 部分,依次进行停止
    toStop.forEach(DanmakuThreadFactory::stopThread);
    // toStart 部分,依次进行开启
    toStart.forEach(DanmakuThreadFactory::runThread);
}
 
Example 6
Source File: ModuleSink.java    From Logistics-Pipes-2 with MIT License 5 votes vote down vote up
@Override
public boolean execute(TileRoutedPipe te) {
	if(!hasRegistered) {
		if(te.hasInventory() && te.hasNetwork()) {
			ArrayList<Item> types = te.getItemTypesInInventory(te.getNetwork().getDirectionForDestination(te.nodeID));
			if(!types.isEmpty()) {
				types.forEach(p -> {
					te.getNetwork().registerItemStorage(new Tuple<UUID, Item>(te.nodeID, p));
				});
				hasRegistered=true;
			}
		}
	}
	return true;
}
 
Example 7
Source File: TaskListModel.java    From AlipayOrdersSupervisor-GUI with MIT License 5 votes vote down vote up
private TaskListModel() {
    observers = new ArrayList<>();
    tasks = new ArrayList<>();
    String savedTasksString = Settings.getInstance().getTasks();
    if (!StringUtils.isEmpty(savedTasksString)) {
        Gson gson = new Gson();
        ArrayList<String> tasksStrings = gson.fromJson(savedTasksString, ArrayList.class);
        tasksStrings.forEach(s -> {
            tasks.add(gson.fromJson(s, new TypeToken<ApsvTask>() {
            }.getType()));
        });
    }
}
 
Example 8
Source File: T3.java    From cs-summary-reflection with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    ListNode listNode1 = new ListNode(1);
    ListNode listNode2 = new ListNode(2);
    ListNode listNode3 = new ListNode(3);

    listNode1.next = listNode2;
    listNode2.next = listNode3;

    ArrayList<Integer> arrayList = printListFromTailToHead1(listNode1);
    arrayList.forEach(System.out::println);
}
 
Example 9
Source File: StreamSegmentReadIndex.java    From pravega with Apache License 2.0 5 votes vote down vote up
@Override
public boolean updateGenerations(int currentGeneration, int oldestGeneration) {
    Exceptions.checkNotClosed(this.closed, this);

    // Update the current generation with the provided info.
    this.summary.setCurrentGeneration(currentGeneration);

    // Identify & collect those entries that can be removed, then remove them from the index.
    ArrayList<ReadIndexEntry> toRemove = new ArrayList<>();
    synchronized (this.lock) {
        this.indexEntries.forEach(entry -> {
            // We can only evict if both these conditions are met:
            // 1. The entry is a Cache Entry (Redirect entries cannot be removed).
            // 2. Every single byte in the entry has to exist in Storage.
            // In addition, we are free to evict (regardless of Generation, but still subject to the above rules) if
            // every single byte in the entry has been truncated out.
            long lastOffset = entry.getLastStreamSegmentOffset();
            boolean canRemove = entry.isDataEntry()
                    && lastOffset < this.metadata.getStorageLength()
                    && (entry.getGeneration() < oldestGeneration || lastOffset < this.metadata.getStartOffset());
            if (canRemove) {
                toRemove.add(entry);
            }
        });

        // Remove from the index and from the cache.
        toRemove.forEach(e -> this.indexEntries.remove(e.key()));
    }

    // Update the summary (no need for holding the lock here; we are not modifying the index).
    toRemove.forEach(e -> {
        deleteData(e);
        this.summary.removeOne(e.getGeneration());
    });

    return !toRemove.isEmpty();
}
 
Example 10
Source File: FileBasedProjectPersistor.java    From tcMenu with Apache License 2.0 5 votes vote down vote up
@Override
public JsonElement serialize(ArrayList<PersistedMenu> src, Type type, JsonSerializationContext ctx) {
    if (src == null) {
        return null;
    }
    JsonArray arr = new JsonArray();
    src.forEach((itm) -> {
        JsonObject ele = new JsonObject();
        ele.addProperty(PARENT_ID, itm.getParentId());
        ele.addProperty(TYPE_ID, itm.getType());
        ele.add(ITEM_ID, ctx.serialize(itm.getItem()));
        arr.add(ele);
    });
    return arr;
}
 
Example 11
Source File: DebugPipeNetInfoProvider.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void addProbeInfo(ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data) {
    if (mode == ProbeMode.DEBUG && ConfigHolder.debug) {
        TileEntity tileEntity = world.getTileEntity(data.getPos());
        if (tileEntity instanceof MetaTileEntityHolder) {
            MetaTileEntity metaTileEntity = ((MetaTileEntityHolder) tileEntity).getMetaTileEntity();
            if (metaTileEntity != null) {
                ArrayList<String> arrayList = new ArrayList<>();
                arrayList.add("MetaTileEntity Id: " + metaTileEntity.metaTileEntityId);
                metaTileEntity.addDebugInfo(arrayList);
                arrayList.forEach(probeInfo::text);
            }
        }
        if (tileEntity instanceof TileEntityPipeBase) {
            IPipeTile<?, ?> pipeTile = (IPipeTile<?, ?>) tileEntity;
            BlockPipe<?, ?, ?> blockPipe = pipeTile.getPipeBlock();
            PipeNet<?> pipeNet = blockPipe.getWorldPipeNet(world).getNetFromPos(data.getPos());
            if (pipeNet != null) {
                probeInfo.text("Net: " + pipeNet.hashCode());
                probeInfo.text("Node Info: ");
                StringBuilder builder = new StringBuilder();
                Map<BlockPos, ? extends Node<?>> nodeMap = pipeNet.getAllNodes();
                Node<?> node = nodeMap.get(data.getPos());
                builder.append("{").append("active: ").append(node.isActive)
                    .append(", mark: ").append(node.mark)
                    .append(", blocked: ").append(node.blockedConnections).append("}");
                probeInfo.text(builder.toString());
            }
            probeInfo.text("tile blocked: " + pipeTile.getBlockedConnections());
            if (blockPipe instanceof BlockFluidPipe) {
                if (pipeTile instanceof TileEntityFluidPipeTickable) {
                    probeInfo.text("tile active: " + ((TileEntityFluidPipeTickable) pipeTile).isActive());
                }
            }
        }
    }
}
 
Example 12
Source File: ClassDefJava.java    From Concurnas with MIT License 5 votes vote down vote up
@Override
public ArrayList<Sixple<String, Type, Boolean, AccessModifier, Boolean, String>> getAllFieldsDefined() {
	ArrayList<Sixple<String, Type, Boolean, AccessModifier, Boolean, String>> ret = new ArrayList<Sixple<String, Type, Boolean, AccessModifier, Boolean, String>>();
	
	if(this.isTrait) {
		Annotations annots = this.getAnnotations();
		if(null != annots) {
			Annotation annot = annots.getAnnotation("com.concurnas.lang.Trait");
			if(null != annot) {
				for(Pair<String, Expression> inst : annot.manyArgs) {
					if(inst.getA().equals("traitFields")) {
						Object traitFields = inst.getB().getFoldedConstant();
						if(traitFields instanceof TraitField[]) {
							for(TraitField tf : (TraitField[])traitFields) {
								String fname = tf.fieldName();
								boolean isAbastract = tf.isAbstract();
								Type tt = TraitFieldEncoderDecoder.decode(tf.fieldType()); 
								AccessModifier am = AccessModifier.getAccessModifier(tf.accessModifier());
								
								ret.add(new Sixple<String, Type, Boolean, AccessModifier, Boolean, String>(fname, tt, isAbastract, am, false, null));
							}
							return ret;
						}
					}
				}
			}
		}
	}
	
	ArrayList<Fiveple<String, Type, Boolean, String, AccessModifier>> allfields = CompiledClassUtils.getAllFields(cls, nameToGenericMap);
	
	allfields.forEach(a -> ret.add(new Sixple<String, Type, Boolean, AccessModifier, Boolean, String>(a.getA(), a.getB(), false, a.getE(), a.getC(), a.getD())));
	
	return ret;
}
 
Example 13
Source File: OfferBookViewModelTest.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private PaymentAccount getSepaAccount(String currencyCode,
                                      String countryCode,
                                      String bic,
                                      ArrayList<String> countryCodes) {
    CountryBasedPaymentAccount paymentAccount = new SepaAccount();
    paymentAccount.setSingleTradeCurrency(new FiatCurrency(currencyCode));
    paymentAccount.setCountry(new Country(countryCode, null, null));
    ((SepaAccountPayload) paymentAccount.getPaymentAccountPayload()).setBic(bic);
    countryCodes.forEach(((SepaAccountPayload) paymentAccount.getPaymentAccountPayload())::addAcceptedCountry);
    return paymentAccount;
}
 
Example 14
Source File: StateDescriptorTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerializerLazyInitializeInParallel() throws Exception {
	final String name = "testSerializerLazyInitializeInParallel";
	// use PojoTypeInfo which will create a new serializer when createSerializer is invoked.
	final TestStateDescriptor<String> desc =
		new TestStateDescriptor<>(name, new PojoTypeInfo<>(String.class, new ArrayList<>()));
	final int threadNumber = 20;
	final ArrayList<CheckedThread> threads = new ArrayList<>(threadNumber);
	final ExecutionConfig executionConfig = new ExecutionConfig();
	final ConcurrentHashMap<Integer, TypeSerializer<String>> serializers = new ConcurrentHashMap<>();
	for (int i = 0; i < threadNumber; i++) {
		threads.add(new CheckedThread() {
			@Override
			public void go() {
				desc.initializeSerializerUnlessSet(executionConfig);
				TypeSerializer<String> serializer = desc.getOriginalSerializer();
				serializers.put(System.identityHashCode(serializer), serializer);
			}
		});
	}
	threads.forEach(Thread::start);
	for (CheckedThread t : threads) {
		t.sync();
	}
	assertEquals("Should use only one serializer but actually: " + serializers, 1, serializers.size());
	threads.clear();
}
 
Example 15
Source File: MessagesConsumer.java    From ns-usbloader with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void handle(long l) {
    ArrayList<String> messages = new ArrayList<>();
    int msgRecieved = msgQueue.drainTo(messages);
    if (msgRecieved > 0)
        messages.forEach(logsArea::appendText);

    ArrayList<Double> progress = new ArrayList<>();
    int progressRecieved = progressQueue.drainTo(progress);
    if (progressRecieved > 0) {
        progress.forEach(prg -> {
            if (prg != 1.0)
                progressBar.setProgress(prg);
            else
                progressBar.setProgress(ProgressIndicator.INDETERMINATE_PROGRESS);
        });
    }

    if (isInterrupted) {                                                // It's safe 'cuz it's could't be interrupted while HashMap populating
        MediatorControl.getInstance().setBgThreadActive(false, appModuleType);
        progressBar.setProgress(0.0);

        if (statusMap.size() > 0)
            for (String key : statusMap.keySet())
                tableViewController.setFileStatus(key, statusMap.get(key));
        this.stop();
    }
}
 
Example 16
Source File: CachingCryptoMaterialsManager.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
private byte[] getCacheIdentifier(DecryptionMaterialsRequest req) {
    try {
        MessageDigest digest = MessageDigest.getInstance(CACHE_ID_HASH_ALGORITHM);
        byte[] hashOfContext = digest.digest(EncryptionContextSerializer.serialize(req.getEncryptionContext()));

        ArrayList<byte[]> keyBlobHashes = new ArrayList<>(req.getEncryptedDataKeys().size());

        for (KeyBlob blob : req.getEncryptedDataKeys()) {
            keyBlobHashes.add(digest.digest(blob.toByteArray()));
        }
        keyBlobHashes.sort(new Utils.ComparingByteArrays());

        // Now starting the digest of the actual cache identifier
        digest.update(partitionIdHash);
        updateDigestWithAlgorithm(digest, req.getAlgorithm());

        keyBlobHashes.forEach(digest::update);

        // This all-zero sentinel field indicates the end of the key blob hashes.
        digest.update(new byte[digest.getDigestLength()]);
        digest.update(hashOfContext);

        return digest.digest();
    } catch (GeneralSecurityException e) {
        throw new AwsCryptoException(e);
    }
}
 
Example 17
Source File: NettyConnection.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Override
public final void fireReady(final boolean ready) {
   ArrayList<ReadyListener> readyToCall = localListenersPool.get();
   if (readyToCall != null) {
      localListenersPool.set(null);
   }
   synchronized (readyListeners) {
      this.ready = ready;

      if (ready) {
         final int size = this.readyListeners.size();
         if (readyToCall != null) {
            readyToCall.ensureCapacity(size);
         }
         try {
            for (int i = 0; i < size; i++) {
               final ReadyListener readyListener = readyListeners.get(i);
               if (readyListener == null) {
                  break;
               }
               if (readyToCall == null) {
                  readyToCall = new ArrayList<>(size);
               }
               readyToCall.add(readyListener);
            }
         } finally {
            readyListeners.clear();
         }
      }
   }
   if (readyToCall != null) {
      try {
         readyToCall.forEach(readyListener -> {
            try {
               readyListener.readyForWriting();
            } catch (Throwable logOnly) {
               ActiveMQClientLogger.LOGGER.failedToSetChannelReadyForWriting(logOnly);
            }
         });
      } catch (Throwable t) {
         ActiveMQClientLogger.LOGGER.failedToSetChannelReadyForWriting(t);
      } finally {
         readyToCall.clear();
         if (localListenersPool.get() != null) {
            localListenersPool.set(readyToCall);
         }
      }
   }
}
 
Example 18
Source File: X3DSegmentLayout.java    From Getaviz with Apache License 2.0 4 votes vote down vote up
private void updateDiskSegment(ArrayList<DiskSegment> segments, double height, double width, double factor) {
    segments.forEach(segment -> calculateCrossSection(segment, width, height));
    calculateSpines(segments, factor);
}
 
Example 19
Source File: CollectionDatasourceTest.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("IncorrectCreateEntity")
public void testSuspendListeners() {
    ArrayList<TestMasterEntity> itemsToRemove = new ArrayList<>(2);
    itemsToRemove.add(new TestMasterEntity());
    itemsToRemove.add(new TestMasterEntity());

    ArrayList<TestMasterEntity> itemsToAdd = new ArrayList<>(3);
    itemsToAdd.add(new TestMasterEntity());
    itemsToAdd.add(new TestMasterEntity());
    itemsToAdd.add(new TestMasterEntity());

    CollectionDatasourceImpl<TestMasterEntity, UUID> cds = new CollectionDatasourceImpl<>();
    cds.setMetaClass(metadata.getClassNN(TestMasterEntity.class));
    cds.setRefreshMode(CollectionDatasource.RefreshMode.NEVER);
    cds.valid();

    TestMasterEntity entity = new TestMasterEntity();
    cds.data.put(entity.getId(), entity);
    itemsToRemove.forEach(testMasterEntity -> cds.data.put(testMasterEntity.getId(), testMasterEntity));

    ArrayList<CollectionDatasource.Operation> operations = new ArrayList<>(2);
    ArrayList<TestMasterEntity> removedItems = new ArrayList<>();
    ArrayList<TestMasterEntity> addedItems = new ArrayList<>();

    cds.addCollectionChangeListener(e -> {
        assertFalse(cds.listenersSuspended, "CollectionChange listener worked, when they they are suspended");
        if (CollectionDatasource.Operation.ADD.equals(e.getOperation())) {
            addedItems.clear();
            addedItems.addAll(e.getItems());
        } else if (CollectionDatasource.Operation.REMOVE.equals(e.getOperation())) {
            removedItems.clear();
            removedItems.addAll(e.getItems());
        }
        operations.add(e.getOperation());
    });

    cds.suspendListeners();
    itemsToRemove.forEach(cds::removeItem);
    itemsToAdd.forEach(cds::addItem);
    cds.resumeListeners();

    assertEquals(2, operations.size());
    assertTrue(operations.get(0).equals(CollectionDatasource.Operation.REMOVE)
            && operations.get(1).equals(CollectionDatasource.Operation.ADD), "Not right order of operations");
    assertTrue(removedItems.containsAll(itemsToRemove), "Not all removed items passed on resume");
    assertTrue(addedItems.containsAll(itemsToAdd), "Not all added items passed on resume");
}
 
Example 20
Source File: TradesChartsViewModelTest.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
@Ignore
    @Test
    public void testItemLists() throws ParseException {
        // Helper class to add historic trades
        class Trade {
            Trade(String date, String size, String price, String cc) {
                try {
                    this.date = dateFormat.parse(date);
                } catch (ParseException p) {
                    this.date = new Date();
                }
                this.size = size;
                this.price = price;
                this.cc = cc;
            }

            Date date;
            String size;
            String price;
            String cc;
        }

        // Trade EUR
        model.selectedTradeCurrencyProperty.setValue(new FiatCurrency("EUR"));

        ArrayList<Trade> trades = new ArrayList<>();

        // Set predetermined time to use as "now" during test
        Date test_time = dateFormat.parse("2018-01-01T00:00:05");  // Monday
/*        new MockUp<System>() {
            @Mock
            long currentTimeMillis() {
                return test_time.getTime();
            }
        };*/

        // Two trades 10 seconds apart, different YEAR, MONTH, WEEK, DAY, HOUR, MINUTE_10
        trades.add(new Trade("2017-12-31T23:59:52", "1", "100", "EUR"));
        trades.add(new Trade("2018-01-01T00:00:02", "1", "110", "EUR"));
        Set<TradeStatistics2> set = new HashSet<>();
        trades.forEach(t ->
                set.add(new TradeStatistics2(offer, Price.parse(t.cc, t.price), Coin.parseCoin(t.size), t.date, null, null))
        );
        ObservableSet<TradeStatistics2> tradeStats = FXCollections.observableSet(set);

        // Run test for each tick type
        for (TradesChartsViewModel.TickUnit tick : TradesChartsViewModel.TickUnit.values()) {
/*            new Expectations() {{
                tradeStatisticsManager.getObservableTradeStatisticsSet();
                result = tradeStats;
            }};*/

            // Trigger chart update
            model.setTickUnit(tick);
            assertEquals(model.selectedTradeCurrencyProperty.get().getCode(), tradeStats.iterator().next().getCurrencyCode());
            assertEquals(2, model.priceItems.size());
            assertEquals(2, model.volumeItems.size());
        }
    }