Search in sources :

Example 16 with IntSupplier

use of java.util.function.IntSupplier in project alf.io by alfio-event.

the class WaitingQueueManager method distributeAvailableSeats.

private Stream<Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime>> distributeAvailableSeats(Event event, Ticket.TicketStatus status, IntSupplier availableSeatSupplier) {
    int availableSeats = availableSeatSupplier.getAsInt();
    int eventId = event.getId();
    log.debug("processing {} subscribers from waiting list", availableSeats);
    List<TicketCategory> unboundedCategories = ticketCategoryRepository.findUnboundedOrderByExpirationDesc(eventId);
    Iterator<Ticket> tickets = ticketRepository.selectWaitingTicketsForUpdate(eventId, status.name(), availableSeats).stream().filter(t -> t.getCategoryId() != null || !unboundedCategories.isEmpty()).iterator();
    int expirationTimeout = configurationManager.getFor(WAITING_QUEUE_RESERVATION_TIMEOUT, ConfigurationLevel.event(event)).getValueAsIntOrDefault(4);
    ZonedDateTime expiration = event.now(clockProvider).plusHours(expirationTimeout).with(WorkingDaysAdjusters.defaultWorkingDays());
    if (!tickets.hasNext()) {
        log.warn("Unable to assign tickets, returning an empty stream");
        return Stream.empty();
    }
    return waitingQueueRepository.loadWaiting(eventId, availableSeats).stream().map(wq -> Pair.of(wq, tickets.next())).map(pair -> {
        TicketReservationModification ticketReservation = new TicketReservationModification();
        ticketReservation.setQuantity(1);
        Integer categoryId = Optional.ofNullable(pair.getValue().getCategoryId()).orElseGet(() -> findBestCategory(unboundedCategories, pair.getKey()).orElseThrow(RuntimeException::new).getId());
        ticketReservation.setTicketCategoryId(categoryId);
        return Pair.of(pair.getLeft(), new TicketReservationWithOptionalCodeModification(ticketReservation, Optional.empty()));
    }).map(pair -> Triple.of(pair.getKey(), pair.getValue(), expiration));
}
Also used : java.util(java.util) TicketReservationModification(alfio.model.modification.TicketReservationModification) TicketCategoryRepository(alfio.repository.TicketCategoryRepository) ConfigurationLevel(alfio.manager.system.ConfigurationLevel) AffectedRowCountAndKey(ch.digitalfondue.npjt.AffectedRowCountAndKey) MessageSourceManager(alfio.manager.i18n.MessageSourceManager) WaitingQueueRepository(alfio.repository.WaitingQueueRepository) ZonedDateTime(java.time.ZonedDateTime) ConfigurationManager(alfio.manager.system.ConfigurationManager) alfio.util(alfio.util) Pair(org.apache.commons.lang3.tuple.Pair) Triple(org.apache.commons.lang3.tuple.Triple) IntSupplier(java.util.function.IntSupplier) EventUtil.determineAvailableSeats(alfio.util.EventUtil.determineAvailableSeats) OrganizationRepository(alfio.repository.user.OrganizationRepository) TicketRepository(alfio.repository.TicketRepository) TicketReservationWithOptionalCodeModification(alfio.model.modification.TicketReservationWithOptionalCodeModification) Organization(alfio.model.user.Organization) EventRepository(alfio.repository.EventRepository) Collectors(java.util.stream.Collectors) DuplicateKeyException(org.springframework.dao.DuplicateKeyException) Component(org.springframework.stereotype.Component) Validate(org.apache.commons.lang3.Validate) Stream(java.util.stream.Stream) alfio.model(alfio.model) Log4j2(lombok.extern.log4j.Log4j2) AllArgsConstructor(lombok.AllArgsConstructor) ConfigurationKeys(alfio.model.system.ConfigurationKeys) TicketReservationWithOptionalCodeModification(alfio.model.modification.TicketReservationWithOptionalCodeModification) ZonedDateTime(java.time.ZonedDateTime) TicketReservationModification(alfio.model.modification.TicketReservationModification)

Example 17 with IntSupplier

use of java.util.function.IntSupplier in project ambry by linkedin.

the class Utils method partitionList.

/**
 * Partition the input list into a List of smaller sublists, each one limited to the specified batch size. This method
 * copy elements, so changes to the so changes to the original list will be reflected in the returned list.
 * Method inspired by the Guava utility Lists.partition(List<T> list, int size).
 * @param inputList the input list to partition.
 * @param batchSize the maximum size of the returned sublists.
 * @return the partitioned list of sublists.
 */
public static <T> List<List<T>> partitionList(List<T> inputList, int batchSize) {
    Objects.requireNonNull(inputList, "Input list cannot be null");
    if (batchSize < 1) {
        throw new IllegalArgumentException("Invalid batchSize: " + batchSize);
    }
    IntSupplier numBatches = () -> (inputList.size() + batchSize - 1) / batchSize;
    IntFunction<List<T>> batchFetcher = index -> {
        int start = index * batchSize;
        int end = Math.min(start + batchSize, inputList.size());
        return inputList.subList(start, end);
    };
    return new ListView<>(numBatches, batchFetcher);
}
Also used : RandomAccessFile(java.io.RandomAccessFile) Arrays(java.util.Arrays) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) LoggerFactory(org.slf4j.LoggerFactory) AbstractList(java.util.AbstractList) Random(java.util.Random) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ThreadFactory(java.util.concurrent.ThreadFactory) Path(java.nio.file.Path) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) Collection(java.util.Collection) Set(java.util.Set) CompletionException(java.util.concurrent.CompletionException) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) Collectors(java.util.stream.Collectors) FileNotFoundException(java.io.FileNotFoundException) StandardCharsets(java.nio.charset.StandardCharsets) Objects(java.util.Objects) FileVisitResult(java.nio.file.FileVisitResult) List(java.util.List) Stream(java.util.stream.Stream) Modifier(java.lang.reflect.Modifier) EventExecutor(io.netty.util.concurrent.EventExecutor) DataInputStream(java.io.DataInputStream) Constructor(java.lang.reflect.Constructor) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) RandomAccess(java.util.RandomAccess) ByteBuf(io.netty.buffer.ByteBuf) Charset(java.nio.charset.Charset) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) IntSupplier(java.util.function.IntSupplier) IntFunction(java.util.function.IntFunction) ReadableByteChannel(java.nio.channels.ReadableByteChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) Properties(java.util.Properties) Logger(org.slf4j.Logger) SingleThreadEventExecutor(io.netty.util.concurrent.SingleThreadEventExecutor) Files(java.nio.file.Files) Channels(java.nio.channels.Channels) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) InputStreamReader(java.io.InputStreamReader) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Paths(java.nio.file.Paths) BufferedReader(java.io.BufferedReader) FileChannel(java.nio.channels.FileChannel) InputStream(java.io.InputStream) IntSupplier(java.util.function.IntSupplier) AbstractList(java.util.AbstractList) List(java.util.List) ArrayList(java.util.ArrayList)

Example 18 with IntSupplier

use of java.util.function.IntSupplier in project aeron by real-logic.

the class SendSelectReceiveUdpPing method run.

private void run() throws IOException {
    final Histogram histogram = new Histogram(TimeUnit.SECONDS.toNanos(10), 3);
    final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);
    final DatagramChannel receiveChannel = DatagramChannel.open();
    Common.init(receiveChannel);
    receiveChannel.bind(new InetSocketAddress("localhost", Common.PONG_PORT));
    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);
    final Selector selector = Selector.open();
    final IntSupplier handler = () -> {
        try {
            buffer.clear();
            receiveChannel.receive(buffer);
            final long receivedSequenceNumber = buffer.getLong(0);
            final long timestampNs = buffer.getLong(SIZE_OF_LONG);
            if (receivedSequenceNumber != sequenceNumber) {
                throw new IllegalStateException("data Loss:" + sequenceNumber + " to " + receivedSequenceNumber);
            }
            final long durationNs = System.nanoTime() - timestampNs;
            histogram.recordValue(durationNs);
        } catch (final IOException ex) {
            ex.printStackTrace();
        }
        return 1;
    };
    receiveChannel.register(selector, OP_READ, handler);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    while (running.get()) {
        measureRoundTrip(histogram, SEND_ADDRESS, buffer, sendChannel, selector, running);
        histogram.reset();
        System.gc();
        LockSupport.parkNanos(1000 * 1000 * 1000);
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Histogram(org.HdrHistogram.Histogram) IntSupplier(java.util.function.IntSupplier) InetSocketAddress(java.net.InetSocketAddress) DatagramChannel(java.nio.channels.DatagramChannel) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Selector(java.nio.channels.Selector)

Example 19 with IntSupplier

use of java.util.function.IntSupplier in project DrivenByMoss by git-moss.

the class AbstractControllerSetup method addButton.

/**
 * Create a hardware button proxy, bind a trigger command to it and bind it to the trigger bind
 * type retrieved from {@link #getTriggerBindType(ButtonID)}.
 *
 * @param surface The control surface
 * @param buttonID The ID of the button (for later access)
 * @param label The label of the button
 * @param supplier Callback for retrieving the state of the light
 * @param midiInputChannel The MIDI input channel
 * @param midiOutputChannel The MIDI output channel
 * @param midiControl The MIDI CC or note
 * @param value The specific value of the control to bind to
 * @param command The command to bind
 * @param hasLight True create and add a light
 * @param colorIds The color IDs to map to the states
 */
protected void addButton(final S surface, final ButtonID buttonID, final String label, final TriggerCommand command, final int midiInputChannel, final int midiOutputChannel, final int midiControl, final int value, final boolean hasLight, final IntSupplier supplier, final String... colorIds) {
    final IHwButton button = surface.createButton(buttonID, label);
    button.bind(command);
    if (midiControl < 0)
        return;
    final IMidiInput midiInput = surface.getMidiInput();
    final BindType triggerBindType = this.getTriggerBindType(buttonID);
    if (value == -1)
        button.bind(midiInput, triggerBindType, midiInputChannel, midiControl);
    else
        button.bind(midiInput, triggerBindType, midiInputChannel, midiControl, value);
    if (hasLight) {
        final IntSupplier intSupplier = () -> button.isPressed() ? 1 : 0;
        final IntSupplier supp = supplier == null ? intSupplier : supplier;
        this.addLight(surface, null, buttonID, button, midiOutputChannel, midiControl, supp, colorIds);
    }
}
Also used : IntSupplier(java.util.function.IntSupplier) IMidiInput(de.mossgrabers.framework.daw.midi.IMidiInput) BindType(de.mossgrabers.framework.controller.hardware.BindType) IHwButton(de.mossgrabers.framework.controller.hardware.IHwButton)

Example 20 with IntSupplier

use of java.util.function.IntSupplier in project Java-Tutorial by gpcodervn.

the class SupplierExample3 method main.

public static void main(String[] args) {
    BooleanSupplier bs = NumberUtils::getBooleanValue;
    System.out.println("Boolean Value: " + bs.getAsBoolean());
    IntSupplier dbs = NumberUtils::getIntValue;
    System.out.println("Integer Value: " + dbs.getAsInt());
    LongSupplier ls = NumberUtils::getLongValue;
    System.out.println("Long Value: " + ls.getAsLong());
    DoubleSupplier ds = NumberUtils::getDoubleValue;
    System.out.println("Double Value: " + ds.getAsDouble());
}
Also used : IntSupplier(java.util.function.IntSupplier) DoubleSupplier(java.util.function.DoubleSupplier) LongSupplier(java.util.function.LongSupplier) BooleanSupplier(java.util.function.BooleanSupplier)

Aggregations

IntSupplier (java.util.function.IntSupplier)39 Test (org.junit.Test)13 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 UnitTest (org.apache.geode.test.junit.categories.UnitTest)6 IOException (java.io.IOException)5 ByteBuffer (java.nio.ByteBuffer)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 InetSocketAddress (java.net.InetSocketAddress)4 DatagramChannel (java.nio.channels.DatagramChannel)4 Selector (java.nio.channels.Selector)4 IHwButton (de.mossgrabers.framework.controller.hardware.IHwButton)3 SelectionKey (java.nio.channels.SelectionKey)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Supplier (java.util.function.Supplier)3 Collectors (java.util.stream.Collectors)3 FrameDescriptor (com.oracle.truffle.api.frame.FrameDescriptor)2 ButtonID (de.mossgrabers.framework.controller.ButtonID)2 IHwLight (de.mossgrabers.framework.controller.hardware.IHwLight)2 WeakReference (java.lang.ref.WeakReference)2