Search in sources :

Example 41 with BiConsumer

use of java.util.function.BiConsumer in project rom-manager by Jakz.

the class Scanner method scanForRoms.

public void scanForRoms(boolean total) throws IOException {
    ignoredPaths.clear();
    foundFiles.clear();
    clones.clear();
    if (total) {
        logger.i(LogTarget.romset(set), "Scanning for roms");
        set.resetStatus();
    } else {
        logger.i(LogTarget.romset(set), "Scanning for new roms");
        set.romStream().filter(r -> r.isPresent()).map(r -> r.handle().path()).forEach(ignoredPaths::add);
    }
    ignoredPaths.addAll(settings.getIgnoredPaths());
    Path folder = settings.romsPath;
    if (!canProceedWithScan())
        return;
    FolderScanner folderScanner = new FolderScanner(ignoredPaths, true);
    final Set<Path> pathsToScan = folderScanner.scan(folder);
    List<VerifierEntry> foundEntries = Collections.synchronizedList(new ArrayList<>());
    /* scanning task */
    {
        Operation<Path, List<VerifierEntry>> operation = path -> {
            logger.d(LogTarget.file(path), "> Scanning %s", path.getFileName().toString());
            try {
                return scanner.scanFile(path);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } catch (RuntimeException e) {
                logger.e(LogTarget.file(path), "Exception while scanning %s", path.toString());
                e.printStackTrace();
                if (!SevenZip.isInitializedSuccessfully()) {
                    Throwable ee = SevenZip.getLastInitializationException();
                    ee.printStackTrace();
                }
                return null;
            }
        };
        BiConsumer<Long, Float> guiProgress = (i, f) -> {
            Main.progress.update(f, "Scanning " + i + " of " + pathsToScan.size() + "...");
        };
        Consumer<List<VerifierEntry>> callback = results -> {
            foundEntries.addAll(results);
        };
        Runnable onComplete = () -> {
            SwingUtilities.invokeLater(() -> {
                Main.progress.finished();
                List<VerifierEntry> transformedEntries = foundEntries.stream().collect(Collectors.toList());
                HandleSet handleSet = new HandleSet(transformedEntries);
                HandleSet.Stats stats = handleSet.stats();
                logger.i(LogTarget.romset(set), "Found %d potential matches (%d binary, %d inside archives, %d nested inside %d archives).", stats.totalHandles, stats.binaryCount, stats.archivedCount, stats.nestedArchiveInnerCount, stats.nestedArchiveCount);
                transformedEntries.forEach(h -> logger.d(LogTarget.romset(set), "> %s", h.toString()));
                Runnable verifyTask = verifyTask(transformedEntries, total);
                verifyTask.run();
            });
        };
        AsyncGuiPoolWorker<Path, List<VerifierEntry>> worker = new AsyncGuiPoolWorker<>(operation, guiProgress, 1);
        SwingUtilities.invokeLater(() -> {
            Main.progress.show(Main.mainFrame, "Scanning " + pathsToScan.size() + " files", () -> worker.cancel());
        });
        worker.compute(pathsToScan, callback, onComplete);
    }
}
Also used : IntStream(java.util.stream.IntStream) Game(com.github.jakz.romlib.data.game.Game) Dialogs(jack.rm.gui.Dialogs) MyGameSetFeatures(jack.rm.data.romset.MyGameSetFeatures) ScannerPlugin(jack.rm.plugins.types.ScannerPlugin) Function(java.util.function.Function) TreeSet(java.util.TreeSet) Handle(com.pixbits.lib.io.archive.handles.Handle) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) GameSet(com.github.jakz.romlib.data.set.GameSet) SwingUtilities(javax.swing.SwingUtilities) HandleSet(com.pixbits.lib.io.archive.HandleSet) StreamException(com.pixbits.lib.functional.StreamException) Log(com.pixbits.lib.log.Log) BiConsumer(java.util.function.BiConsumer) Rom(com.github.jakz.romlib.data.game.Rom) Path(java.nio.file.Path) Files(java.nio.file.Files) LogSource(jack.rm.log.LogSource) LogTarget(jack.rm.log.LogTarget) Operation(com.pixbits.lib.concurrent.Operation) PluginRealType(jack.rm.plugins.PluginRealType) Set(java.util.Set) FormatSupportPlugin(jack.rm.plugins.types.FormatSupportPlugin) IOException(java.io.IOException) GameStatus(com.github.jakz.romlib.data.game.GameStatus) Collectors(java.util.stream.Collectors) ExecutionException(java.util.concurrent.ExecutionException) Consumer(java.util.function.Consumer) FolderScanner(com.pixbits.lib.io.FolderScanner) List(java.util.List) Logger(com.pixbits.lib.log.Logger) VerifierPlugin(jack.rm.plugins.types.VerifierPlugin) SevenZip(net.sf.sevenzipjbinding.SevenZip) Collections(java.util.Collections) VerifierEntry(com.pixbits.lib.io.archive.VerifierEntry) Main(jack.rm.Main) AsyncGuiPoolWorker(com.pixbits.lib.concurrent.AsyncGuiPoolWorker) Settings(jack.rm.data.romset.Settings) Path(java.nio.file.Path) Operation(com.pixbits.lib.concurrent.Operation) IOException(java.io.IOException) AsyncGuiPoolWorker(com.pixbits.lib.concurrent.AsyncGuiPoolWorker) VerifierEntry(com.pixbits.lib.io.archive.VerifierEntry) BiConsumer(java.util.function.BiConsumer) Consumer(java.util.function.Consumer) FolderScanner(com.pixbits.lib.io.FolderScanner) BiConsumer(java.util.function.BiConsumer) HandleSet(com.pixbits.lib.io.archive.HandleSet)

Example 42 with BiConsumer

use of java.util.function.BiConsumer in project hazelcast-jet by hazelcast.

the class SplitBrainTest method when_quorumIsLostOnMinority_then_jobRestartsUntilMerge.

@Test
public void when_quorumIsLostOnMinority_then_jobRestartsUntilMerge() {
    int firstSubClusterSize = 3;
    int secondSubClusterSize = 2;
    int clusterSize = firstSubClusterSize + secondSubClusterSize;
    StuckProcessor.executionStarted = new CountDownLatch(clusterSize * PARALLELISM);
    Job[] jobRef = new Job[1];
    Consumer<JetInstance[]> beforeSplit = instances -> {
        MockPS processorSupplier = new MockPS(StuckProcessor::new, clusterSize);
        DAG dag = new DAG().vertex(new Vertex("test", processorSupplier));
        jobRef[0] = instances[0].newJob(dag, new JobConfig().setSplitBrainProtection(true));
        assertOpenEventually(StuckProcessor.executionStarted);
    };
    Future[] minorityJobFutureRef = new Future[1];
    BiConsumer<JetInstance[], JetInstance[]> onSplit = (firstSubCluster, secondSubCluster) -> {
        StuckProcessor.proceedLatch.countDown();
        assertTrueEventually(() -> assertEquals(clusterSize + firstSubClusterSize, MockPS.initCount.get()));
        long jobId = jobRef[0].getId();
        assertTrueEventually(() -> {
            JetService service = getJetService(firstSubCluster[0]);
            assertEquals(COMPLETED, service.getJobCoordinationService().getJobStatus(jobId));
        });
        JetService service2 = getJetService(secondSubCluster[0]);
        assertTrueEventually(() -> {
            assertEquals(STARTING, service2.getJobCoordinationService().getJobStatus(jobId));
        });
        MasterContext masterContext = service2.getJobCoordinationService().getMasterContext(jobId);
        assertNotNull(masterContext);
        minorityJobFutureRef[0] = masterContext.completionFuture();
        assertTrueAllTheTime(() -> {
            assertEquals(STARTING, service2.getJobCoordinationService().getJobStatus(jobId));
        }, 20);
    };
    Consumer<JetInstance[]> afterMerge = instances -> {
        assertTrueEventually(() -> {
            assertEquals(clusterSize + firstSubClusterSize, MockPS.initCount.get());
            assertEquals(clusterSize + firstSubClusterSize, MockPS.closeCount.get());
        });
        assertEquals(clusterSize, MockPS.receivedCloseErrors.size());
        MockPS.receivedCloseErrors.forEach(t -> assertTrue(t instanceof TopologyChangedException));
        try {
            minorityJobFutureRef[0].get();
            fail();
        } catch (CancellationException ignored) {
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    };
    testSplitBrain(firstSubClusterSize, secondSubClusterSize, beforeSplit, onSplit, afterMerge);
}
Also used : MasterContext(com.hazelcast.jet.impl.MasterContext) JetInstance(com.hazelcast.jet.JetInstance) RunWith(org.junit.runner.RunWith) HazelcastSerialClassRunner(com.hazelcast.test.HazelcastSerialClassRunner) Future(java.util.concurrent.Future) STARTING(com.hazelcast.jet.core.JobStatus.STARTING) BiConsumer(java.util.function.BiConsumer) Assert.fail(org.junit.Assert.fail) ExpectedException(org.junit.rules.ExpectedException) Job(com.hazelcast.jet.Job) JobRepository(com.hazelcast.jet.impl.JobRepository) JetConfig(com.hazelcast.jet.config.JetConfig) MAX_BACKUP_COUNT(com.hazelcast.spi.partition.IPartition.MAX_BACKUP_COUNT) MockPS(com.hazelcast.jet.core.TestProcessors.MockPS) CancellationException(java.util.concurrent.CancellationException) RESTARTING(com.hazelcast.jet.core.JobStatus.RESTARTING) Assert.assertNotNull(org.junit.Assert.assertNotNull) JobConfig(com.hazelcast.jet.config.JobConfig) StuckProcessor(com.hazelcast.jet.core.TestProcessors.StuckProcessor) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) JetService(com.hazelcast.jet.impl.JetService) COMPLETED(com.hazelcast.jet.core.JobStatus.COMPLETED) JobRecord(com.hazelcast.jet.impl.JobRecord) Assert.assertEquals(org.junit.Assert.assertEquals) MockPS(com.hazelcast.jet.core.TestProcessors.MockPS) JetService(com.hazelcast.jet.impl.JetService) CountDownLatch(java.util.concurrent.CountDownLatch) JobConfig(com.hazelcast.jet.config.JobConfig) ExpectedException(org.junit.rules.ExpectedException) CancellationException(java.util.concurrent.CancellationException) CancellationException(java.util.concurrent.CancellationException) Future(java.util.concurrent.Future) Job(com.hazelcast.jet.Job) MasterContext(com.hazelcast.jet.impl.MasterContext) Test(org.junit.Test)

Example 43 with BiConsumer

use of java.util.function.BiConsumer in project hazelcast-jet by hazelcast.

the class SplitBrainTest method when_quorumIsLostOnBothSides_then_jobRestartsUntilMerge.

@Test
public void when_quorumIsLostOnBothSides_then_jobRestartsUntilMerge() {
    int firstSubClusterSize = 2;
    int secondSubClusterSize = 2;
    int clusterSize = firstSubClusterSize + secondSubClusterSize;
    StuckProcessor.executionStarted = new CountDownLatch(clusterSize * PARALLELISM);
    Job[] jobRef = new Job[1];
    Consumer<JetInstance[]> beforeSplit = instances -> {
        MockPS processorSupplier = new MockPS(StuckProcessor::new, clusterSize);
        DAG dag = new DAG().vertex(new Vertex("test", processorSupplier));
        jobRef[0] = instances[0].newJob(dag, new JobConfig().setSplitBrainProtection(true));
        assertOpenEventually(StuckProcessor.executionStarted);
    };
    BiConsumer<JetInstance[], JetInstance[]> onSplit = (firstSubCluster, secondSubCluster) -> {
        StuckProcessor.proceedLatch.countDown();
        long jobId = jobRef[0].getId();
        assertTrueEventually(() -> {
            JetService service1 = getJetService(firstSubCluster[0]);
            JetService service2 = getJetService(secondSubCluster[0]);
            assertEquals(RESTARTING, service1.getJobCoordinationService().getJobStatus(jobId));
            assertEquals(STARTING, service2.getJobCoordinationService().getJobStatus(jobId));
        });
        assertTrueAllTheTime(() -> {
            JetService service1 = getJetService(firstSubCluster[0]);
            JetService service2 = getJetService(secondSubCluster[0]);
            assertEquals(RESTARTING, service1.getJobCoordinationService().getJobStatus(jobId));
            assertEquals(STARTING, service2.getJobCoordinationService().getJobStatus(jobId));
        }, 20);
    };
    Consumer<JetInstance[]> afterMerge = instances -> {
        assertTrueEventually(() -> {
            assertEquals(clusterSize * 2, MockPS.initCount.get());
            assertEquals(clusterSize * 2, MockPS.closeCount.get());
        });
        assertEquals(clusterSize, MockPS.receivedCloseErrors.size());
        MockPS.receivedCloseErrors.forEach(t -> assertTrue(t instanceof TopologyChangedException));
    };
    testSplitBrain(firstSubClusterSize, secondSubClusterSize, beforeSplit, onSplit, afterMerge);
}
Also used : MasterContext(com.hazelcast.jet.impl.MasterContext) JetInstance(com.hazelcast.jet.JetInstance) RunWith(org.junit.runner.RunWith) HazelcastSerialClassRunner(com.hazelcast.test.HazelcastSerialClassRunner) Future(java.util.concurrent.Future) STARTING(com.hazelcast.jet.core.JobStatus.STARTING) BiConsumer(java.util.function.BiConsumer) Assert.fail(org.junit.Assert.fail) ExpectedException(org.junit.rules.ExpectedException) Job(com.hazelcast.jet.Job) JobRepository(com.hazelcast.jet.impl.JobRepository) JetConfig(com.hazelcast.jet.config.JetConfig) MAX_BACKUP_COUNT(com.hazelcast.spi.partition.IPartition.MAX_BACKUP_COUNT) MockPS(com.hazelcast.jet.core.TestProcessors.MockPS) CancellationException(java.util.concurrent.CancellationException) RESTARTING(com.hazelcast.jet.core.JobStatus.RESTARTING) Assert.assertNotNull(org.junit.Assert.assertNotNull) JobConfig(com.hazelcast.jet.config.JobConfig) StuckProcessor(com.hazelcast.jet.core.TestProcessors.StuckProcessor) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) JetService(com.hazelcast.jet.impl.JetService) COMPLETED(com.hazelcast.jet.core.JobStatus.COMPLETED) JobRecord(com.hazelcast.jet.impl.JobRecord) Assert.assertEquals(org.junit.Assert.assertEquals) MockPS(com.hazelcast.jet.core.TestProcessors.MockPS) JetService(com.hazelcast.jet.impl.JetService) CountDownLatch(java.util.concurrent.CountDownLatch) JobConfig(com.hazelcast.jet.config.JobConfig) Job(com.hazelcast.jet.Job) Test(org.junit.Test)

Example 44 with BiConsumer

use of java.util.function.BiConsumer in project eventuate-tram-core by eventuate-tram.

the class MessageConsumerKafkaImpl method subscribe.

@Override
public void subscribe(String subscriberId, Set<String> channels, MessageHandler handler) {
    BiConsumer<ConsumerRecord<String, String>, BiConsumer<Void, Throwable>> kcHandler = (record, callback) -> {
        Message m = toMessage(record);
        // TODO If we do that here then remove TT from higher-levels
        transactionTemplate.execute(ts -> {
            if (duplicateMessageDetector.isDuplicate(subscriberId, m.getId())) {
                logger.trace("Duplicate message {} {}", subscriberId, m.getId());
                callback.accept(null, null);
                return null;
            }
            try {
                logger.trace("Invoking handler {} {}", subscriberId, m.getId());
                handler.accept(m);
            } catch (Throwable t) {
                logger.trace("Got exception {} {}", subscriberId, m.getId());
                logger.trace("Got exception ", t);
                callback.accept(null, t);
                return null;
            }
            logger.trace("handled message {} {}", subscriberId, m.getId());
            callback.accept(null, null);
            return null;
        });
    };
    EventuateKafkaConsumer kc = new EventuateKafkaConsumer(subscriberId, kcHandler, new ArrayList<>(channels), bootstrapServers);
    consumers.add(kc);
    kc.start();
}
Also used : Logger(org.slf4j.Logger) MessageImpl(io.eventuate.tram.messaging.common.MessageImpl) LoggerFactory(org.slf4j.LoggerFactory) EventuateKafkaConsumer(io.eventuate.local.java.kafka.consumer.EventuateKafkaConsumer) MessageHandler(io.eventuate.tram.messaging.consumer.MessageHandler) Autowired(org.springframework.beans.factory.annotation.Autowired) Set(java.util.Set) JSonMapper(io.eventuate.javaclient.commonimpl.JSonMapper) Message(io.eventuate.tram.messaging.common.Message) ArrayList(java.util.ArrayList) List(java.util.List) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) BiConsumer(java.util.function.BiConsumer) MessageConsumer(io.eventuate.tram.messaging.consumer.MessageConsumer) Message(io.eventuate.tram.messaging.common.Message) EventuateKafkaConsumer(io.eventuate.local.java.kafka.consumer.EventuateKafkaConsumer) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) BiConsumer(java.util.function.BiConsumer)

Example 45 with BiConsumer

use of java.util.function.BiConsumer in project bitfinex-v2-wss-api-java by jnidzwetzki.

the class IntegrationTest method testExecutedTradesStream.

/**
 * Test executed trades stream
 */
@Test(timeout = 60000)
public void testExecutedTradesStream() {
    final BitfinexApiBroker bitfinexClient = new BitfinexApiBroker();
    // Await at least 2 callbacks
    final CountDownLatch latch = new CountDownLatch(2);
    try {
        bitfinexClient.connect();
        final BitfinexExecutedTradeSymbol symbol = new BitfinexExecutedTradeSymbol(BitfinexCurrencyPair.BTC_USD);
        final QuoteManager executedTradeManager = bitfinexClient.getQuoteManager();
        final BiConsumer<BitfinexExecutedTradeSymbol, ExecutedTrade> callback = (c, o) -> {
            latch.countDown();
        };
        executedTradeManager.registerExecutedTradeCallback(symbol, callback);
        executedTradeManager.subscribeExecutedTrades(symbol);
        latch.await();
        executedTradeManager.unsubscribeExecutedTrades(symbol);
        Assert.assertTrue(executedTradeManager.removeExecutedTradeCallback(symbol, callback));
        Assert.assertFalse(executedTradeManager.removeExecutedTradeCallback(symbol, callback));
    } catch (Exception e) {
        // Should not happen
        e.printStackTrace();
        Assert.assertTrue(false);
    } finally {
        bitfinexClient.close();
    }
}
Also used : ExecutedTrade(com.github.jnidzwetzki.bitfinex.v2.entity.ExecutedTrade) BitfinexApiBroker(com.github.jnidzwetzki.bitfinex.v2.BitfinexApiBroker) BitfinexTick(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexTick) OrderbookEntry(com.github.jnidzwetzki.bitfinex.v2.entity.OrderbookEntry) OrderBookPrecision(com.github.jnidzwetzki.bitfinex.v2.entity.OrderBookPrecision) Test(org.junit.Test) Timeframe(com.github.jnidzwetzki.bitfinex.v2.entity.Timeframe) BitfinexCandlestickSymbol(com.github.jnidzwetzki.bitfinex.v2.entity.symbol.BitfinexCandlestickSymbol) OrderbookManager(com.github.jnidzwetzki.bitfinex.v2.manager.OrderbookManager) OrderBookFrequency(com.github.jnidzwetzki.bitfinex.v2.entity.OrderBookFrequency) APIException(com.github.jnidzwetzki.bitfinex.v2.entity.APIException) BitfinexCurrencyPair(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexCurrencyPair) OrderbookConfiguration(com.github.jnidzwetzki.bitfinex.v2.entity.OrderbookConfiguration) CountDownLatch(java.util.concurrent.CountDownLatch) RawOrderbookConfiguration(com.github.jnidzwetzki.bitfinex.v2.entity.RawOrderbookConfiguration) BitfinexTickerSymbol(com.github.jnidzwetzki.bitfinex.v2.entity.symbol.BitfinexTickerSymbol) RawOrderbookManager(com.github.jnidzwetzki.bitfinex.v2.manager.RawOrderbookManager) QuoteManager(com.github.jnidzwetzki.bitfinex.v2.manager.QuoteManager) RawOrderbookEntry(com.github.jnidzwetzki.bitfinex.v2.entity.RawOrderbookEntry) BiConsumer(java.util.function.BiConsumer) ExecutedTrade(com.github.jnidzwetzki.bitfinex.v2.entity.ExecutedTrade) Assert(org.junit.Assert) BitfinexExecutedTradeSymbol(com.github.jnidzwetzki.bitfinex.v2.entity.symbol.BitfinexExecutedTradeSymbol) BitfinexExecutedTradeSymbol(com.github.jnidzwetzki.bitfinex.v2.entity.symbol.BitfinexExecutedTradeSymbol) BitfinexApiBroker(com.github.jnidzwetzki.bitfinex.v2.BitfinexApiBroker) CountDownLatch(java.util.concurrent.CountDownLatch) QuoteManager(com.github.jnidzwetzki.bitfinex.v2.manager.QuoteManager) APIException(com.github.jnidzwetzki.bitfinex.v2.entity.APIException) Test(org.junit.Test)

Aggregations

BiConsumer (java.util.function.BiConsumer)264 Test (org.junit.Test)111 List (java.util.List)109 Map (java.util.Map)79 IOException (java.io.IOException)78 ArrayList (java.util.ArrayList)74 Consumer (java.util.function.Consumer)71 HashMap (java.util.HashMap)66 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)54 Collectors (java.util.stream.Collectors)53 CountDownLatch (java.util.concurrent.CountDownLatch)52 Collections (java.util.Collections)46 Set (java.util.Set)46 Collection (java.util.Collection)45 Arrays (java.util.Arrays)44 TimeUnit (java.util.concurrent.TimeUnit)43 Function (java.util.function.Function)43 Assert (org.junit.Assert)43 Optional (java.util.Optional)41 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)35