Search in sources :

Example 11 with BiFunction

use of java.util.function.BiFunction in project riposte by Nike-Inc.

the class RequestFilterHandlerTest method doChannelRead_delegates_to_handleFilterLogic_with_last_chunk_method_references_when_msg_is_LastHttpContent.

@DataProvider(value = { "CONTINUE", "DO_NOT_FIRE_CONTINUE_EVENT" }, splitBy = "\\|")
@Test
public void doChannelRead_delegates_to_handleFilterLogic_with_last_chunk_method_references_when_msg_is_LastHttpContent(PipelineContinuationBehavior expectedPipelineContinuationBehavior) throws Exception {
    // given
    doReturn(expectedPipelineContinuationBehavior).when(handlerSpy).handleFilterLogic(any(), any(), any(), any());
    // when
    PipelineContinuationBehavior result = handlerSpy.doChannelRead(ctxMock, lastChunkMsgMock);
    // then
    assertThat(result).isEqualTo(expectedPipelineContinuationBehavior);
    ArgumentCaptor<BiFunction> normalFilterCallCaptor = ArgumentCaptor.forClass(BiFunction.class);
    ArgumentCaptor<BiFunction> shortCircuitFilterCallCaptor = ArgumentCaptor.forClass(BiFunction.class);
    verify(handlerSpy).handleFilterLogic(eq(ctxMock), eq(lastChunkMsgMock), normalFilterCallCaptor.capture(), shortCircuitFilterCallCaptor.capture());
    BiFunction<RequestAndResponseFilter, RequestInfo, RequestInfo> normalFilterCall = normalFilterCallCaptor.getValue();
    BiFunction<RequestAndResponseFilter, RequestInfo, Pair<RequestInfo, Optional<ResponseInfo<?>>>> shortCircuitFilterCall = shortCircuitFilterCallCaptor.getValue();
    RequestAndResponseFilter filterForNormalCallMock = mock(RequestAndResponseFilter.class);
    normalFilterCall.apply(filterForNormalCallMock, requestInfoMock);
    verify(filterForNormalCallMock).filterRequestLastChunkWithFullPayload(requestInfoMock, ctxMock);
    RequestAndResponseFilter filterForShortCircuitCallMock = mock(RequestAndResponseFilter.class);
    shortCircuitFilterCall.apply(filterForShortCircuitCallMock, requestInfoMock);
    verify(filterForShortCircuitCallMock).filterRequestLastChunkWithOptionalShortCircuitResponse(requestInfoMock, ctxMock);
}
Also used : ResponseInfo(com.nike.riposte.server.http.ResponseInfo) LastOutboundMessageSendFullResponseInfo(com.nike.riposte.server.channelpipeline.message.LastOutboundMessageSendFullResponseInfo) PipelineContinuationBehavior(com.nike.riposte.server.handler.base.PipelineContinuationBehavior) BiFunction(java.util.function.BiFunction) RequestAndResponseFilter(com.nike.riposte.server.http.filter.RequestAndResponseFilter) RequestInfo(com.nike.riposte.server.http.RequestInfo) Pair(com.nike.internal.util.Pair) DataProvider(com.tngtech.java.junit.dataprovider.DataProvider) Test(org.junit.Test)

Example 12 with BiFunction

use of java.util.function.BiFunction in project riposte by Nike-Inc.

the class RequestFilterHandlerTest method doChannelRead_delegates_to_handleFilterLogic_with_first_chunk_method_references_when_msg_is_HttpRequest.

@DataProvider(value = { "CONTINUE", "DO_NOT_FIRE_CONTINUE_EVENT" }, splitBy = "\\|")
@Test
public void doChannelRead_delegates_to_handleFilterLogic_with_first_chunk_method_references_when_msg_is_HttpRequest(PipelineContinuationBehavior expectedPipelineContinuationBehavior) throws Exception {
    // given
    doReturn(expectedPipelineContinuationBehavior).when(handlerSpy).handleFilterLogic(any(), any(), any(), any());
    // when
    PipelineContinuationBehavior result = handlerSpy.doChannelRead(ctxMock, firstChunkMsgMock);
    // then
    assertThat(result).isEqualTo(expectedPipelineContinuationBehavior);
    ArgumentCaptor<BiFunction> normalFilterCallCaptor = ArgumentCaptor.forClass(BiFunction.class);
    ArgumentCaptor<BiFunction> shortCircuitFilterCallCaptor = ArgumentCaptor.forClass(BiFunction.class);
    verify(handlerSpy).handleFilterLogic(eq(ctxMock), eq(firstChunkMsgMock), normalFilterCallCaptor.capture(), shortCircuitFilterCallCaptor.capture());
    BiFunction<RequestAndResponseFilter, RequestInfo, RequestInfo> normalFilterCall = normalFilterCallCaptor.getValue();
    BiFunction<RequestAndResponseFilter, RequestInfo, Pair<RequestInfo, Optional<ResponseInfo<?>>>> shortCircuitFilterCall = shortCircuitFilterCallCaptor.getValue();
    RequestAndResponseFilter filterForNormalCallMock = mock(RequestAndResponseFilter.class);
    normalFilterCall.apply(filterForNormalCallMock, requestInfoMock);
    verify(filterForNormalCallMock).filterRequestFirstChunkNoPayload(requestInfoMock, ctxMock);
    RequestAndResponseFilter filterForShortCircuitCallMock = mock(RequestAndResponseFilter.class);
    shortCircuitFilterCall.apply(filterForShortCircuitCallMock, requestInfoMock);
    verify(filterForShortCircuitCallMock).filterRequestFirstChunkWithOptionalShortCircuitResponse(requestInfoMock, ctxMock);
}
Also used : ResponseInfo(com.nike.riposte.server.http.ResponseInfo) LastOutboundMessageSendFullResponseInfo(com.nike.riposte.server.channelpipeline.message.LastOutboundMessageSendFullResponseInfo) PipelineContinuationBehavior(com.nike.riposte.server.handler.base.PipelineContinuationBehavior) BiFunction(java.util.function.BiFunction) RequestAndResponseFilter(com.nike.riposte.server.http.filter.RequestAndResponseFilter) RequestInfo(com.nike.riposte.server.http.RequestInfo) Pair(com.nike.internal.util.Pair) DataProvider(com.tngtech.java.junit.dataprovider.DataProvider) Test(org.junit.Test)

Example 13 with BiFunction

use of java.util.function.BiFunction in project riposte by Nike-Inc.

the class AsyncNettyHelperTest method biFunctionWithTracingAndMdc_pair_works_as_expected.

@Test
public void biFunctionWithTracingAndMdc_pair_works_as_expected() {
    // given
    Pair<Deque<Span>, Map<String, String>> setupInfo = generateTracingAndMdcInfo();
    // when
    BiFunction result = AsyncNettyHelper.biFunctionWithTracingAndMdc(biFunctionMock, setupInfo);
    // then
    verifyBiFunctionWithTracingAndMdcSupport(result, biFunctionMock, setupInfo.getLeft(), setupInfo.getRight());
}
Also used : BiFunction(java.util.function.BiFunction) Deque(java.util.Deque) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Example 14 with BiFunction

use of java.util.function.BiFunction in project aries by apache.

the class AbstractPushStreamImpl method window.

@Override
public <R> PushStream<R> window(Supplier<Duration> time, IntSupplier maxEvents, Executor ex, BiFunction<Long, Collection<T>, R> f) {
    AtomicLong timestamp = new AtomicLong();
    AtomicLong counter = new AtomicLong();
    Object lock = new Object();
    AtomicReference<Queue<T>> queueRef = new AtomicReference<Queue<T>>(null);
    // This code is declared as a separate block to avoid any confusion
    // about which instance's methods and variables are in scope
    Consumer<AbstractPushStreamImpl<R>> begin = p -> {
        synchronized (lock) {
            timestamp.lazySet(System.nanoTime());
            long count = counter.get();
            scheduler.schedule(getWindowTask(p, f, time, maxEvents, lock, count, queueRef, timestamp, counter, ex), time.get().toNanos(), NANOSECONDS);
        }
        queueRef.set(getQueueForInternalBuffering(maxEvents.getAsInt()));
    };
    @SuppressWarnings("resource") AbstractPushStreamImpl<R> eventStream = new IntermediatePushStreamImpl<R>(psp, ex, scheduler, this) {

        @Override
        protected void beginning() {
            begin.accept(this);
        }
    };
    AtomicBoolean endPending = new AtomicBoolean(false);
    updateNext((event) -> {
        try {
            if (eventStream.closed.get() == CLOSED) {
                return ABORT;
            }
            Queue<T> queue;
            if (!event.isTerminal()) {
                long elapsed;
                long newCount;
                synchronized (lock) {
                    for (; ; ) {
                        queue = queueRef.get();
                        if (queue == null) {
                            if (endPending.get()) {
                                return ABORT;
                            } else {
                                continue;
                            }
                        } else if (queue.offer(event.getData())) {
                            return CONTINUE;
                        } else {
                            queueRef.lazySet(null);
                            break;
                        }
                    }
                    long now = System.nanoTime();
                    elapsed = now - timestamp.get();
                    timestamp.lazySet(now);
                    newCount = counter.get() + 1;
                    counter.lazySet(newCount);
                    // This is a non-blocking call, and must happen in the
                    // synchronized block to avoid re=ordering the executor
                    // enqueue with a subsequent incoming close operation
                    aggregateAndForward(f, eventStream, event, queue, ex, elapsed);
                }
                // These must happen outside the synchronized block as we
                // call out to user code
                queueRef.set(getQueueForInternalBuffering(maxEvents.getAsInt()));
                scheduler.schedule(getWindowTask(eventStream, f, time, maxEvents, lock, newCount, queueRef, timestamp, counter, ex), time.get().toNanos(), NANOSECONDS);
                return CONTINUE;
            } else {
                long elapsed;
                synchronized (lock) {
                    queue = queueRef.get();
                    queueRef.lazySet(null);
                    endPending.set(true);
                    long now = System.nanoTime();
                    elapsed = now - timestamp.get();
                    counter.lazySet(counter.get() + 1);
                }
                Collection<T> collected = queue == null ? emptyList() : queue;
                ex.execute(() -> {
                    try {
                        eventStream.handleEvent(PushEvent.data(f.apply(Long.valueOf(NANOSECONDS.toMillis(elapsed)), collected)));
                    } catch (Exception e) {
                        close(PushEvent.error(e));
                    }
                });
            }
            ex.execute(() -> eventStream.handleEvent(event.nodata()));
            return ABORT;
        } catch (Exception e) {
            close(PushEvent.error(e));
            return ABORT;
        }
    });
    return eventStream;
}
Also used : Arrays(java.util.Arrays) BiFunction(java.util.function.BiFunction) AbstractQueue(java.util.AbstractQueue) Deferred(org.osgi.util.promise.Deferred) EventType(org.osgi.util.pushstream.PushEvent.EventType) AtomicReferenceArray(java.util.concurrent.atomic.AtomicReferenceArray) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Collector(java.util.stream.Collector) PushStreamBuilder(org.osgi.util.pushstream.PushStreamBuilder) Collections.emptyList(java.util.Collections.emptyList) Predicate(java.util.function.Predicate) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) Collectors(java.util.stream.Collectors) BinaryOperator(java.util.function.BinaryOperator) Promise(org.osgi.util.promise.Promise) PushStreamProvider(org.osgi.util.pushstream.PushStreamProvider) List(java.util.List) Optional(java.util.Optional) Queue(java.util.Queue) ConcurrentModificationException(java.util.ConcurrentModificationException) PushEvent(org.osgi.util.pushstream.PushEvent) LongAdder(java.util.concurrent.atomic.LongAdder) NANOSECONDS(java.util.concurrent.TimeUnit.NANOSECONDS) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PushStream(org.osgi.util.pushstream.PushStream) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) PushEventSource(org.osgi.util.pushstream.PushEventSource) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) LinkedList(java.util.LinkedList) NoSuchElementException(java.util.NoSuchElementException) IntSupplier(java.util.function.IntSupplier) IntFunction(java.util.function.IntFunction) Iterator(java.util.Iterator) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Executor(java.util.concurrent.Executor) Semaphore(java.util.concurrent.Semaphore) State(org.apache.aries.pushstream.AbstractPushStreamImpl.State) Consumer(java.util.function.Consumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) Lock(java.util.concurrent.locks.Lock) PushEventConsumer(org.osgi.util.pushstream.PushEventConsumer) Comparator(java.util.Comparator) Collections(java.util.Collections) AtomicReference(java.util.concurrent.atomic.AtomicReference) ConcurrentModificationException(java.util.ConcurrentModificationException) NoSuchElementException(java.util.NoSuchElementException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicLong(java.util.concurrent.atomic.AtomicLong) AbstractQueue(java.util.AbstractQueue) BlockingQueue(java.util.concurrent.BlockingQueue) Queue(java.util.Queue)

Example 15 with BiFunction

use of java.util.function.BiFunction in project lucene-solr by apache.

the class TestMemoryIndex method testPointValues.

public void testPointValues() throws Exception {
    List<Function<Long, IndexableField>> fieldFunctions = Arrays.asList((t) -> new IntPoint("number", t.intValue()), (t) -> new LongPoint("number", t), (t) -> new FloatPoint("number", t.floatValue()), (t) -> new DoublePoint("number", t.doubleValue()));
    List<Function<Long, Query>> exactQueryFunctions = Arrays.asList((t) -> IntPoint.newExactQuery("number", t.intValue()), (t) -> LongPoint.newExactQuery("number", t), (t) -> FloatPoint.newExactQuery("number", t.floatValue()), (t) -> DoublePoint.newExactQuery("number", t.doubleValue()));
    List<Function<long[], Query>> setQueryFunctions = Arrays.asList((t) -> IntPoint.newSetQuery("number", LongStream.of(t).mapToInt(value -> (int) value).toArray()), (t) -> LongPoint.newSetQuery("number", t), (t) -> FloatPoint.newSetQuery("number", Arrays.asList(LongStream.of(t).mapToObj(value -> (float) value).toArray(Float[]::new))), (t) -> DoublePoint.newSetQuery("number", LongStream.of(t).mapToDouble(value -> (double) value).toArray()));
    List<BiFunction<Long, Long, Query>> rangeQueryFunctions = Arrays.asList((t, u) -> IntPoint.newRangeQuery("number", t.intValue(), u.intValue()), (t, u) -> LongPoint.newRangeQuery("number", t, u), (t, u) -> FloatPoint.newRangeQuery("number", t.floatValue(), u.floatValue()), (t, u) -> DoublePoint.newRangeQuery("number", t.doubleValue(), u.doubleValue()));
    for (int i = 0; i < fieldFunctions.size(); i++) {
        Function<Long, IndexableField> fieldFunction = fieldFunctions.get(i);
        Function<Long, Query> exactQueryFunction = exactQueryFunctions.get(i);
        Function<long[], Query> setQueryFunction = setQueryFunctions.get(i);
        BiFunction<Long, Long, Query> rangeQueryFunction = rangeQueryFunctions.get(i);
        Document doc = new Document();
        for (int number = 1; number < 32; number += 2) {
            doc.add(fieldFunction.apply((long) number));
        }
        MemoryIndex mi = MemoryIndex.fromDocument(doc, analyzer);
        IndexSearcher indexSearcher = mi.createSearcher();
        Query query = exactQueryFunction.apply(5L);
        assertEquals(1, indexSearcher.count(query));
        query = exactQueryFunction.apply(4L);
        assertEquals(0, indexSearcher.count(query));
        query = setQueryFunction.apply(new long[] { 3L, 9L, 19L });
        assertEquals(1, indexSearcher.count(query));
        query = setQueryFunction.apply(new long[] { 2L, 8L, 13L });
        assertEquals(1, indexSearcher.count(query));
        query = setQueryFunction.apply(new long[] { 2L, 8L, 16L });
        assertEquals(0, indexSearcher.count(query));
        query = rangeQueryFunction.apply(2L, 16L);
        assertEquals(1, indexSearcher.count(query));
        query = rangeQueryFunction.apply(24L, 48L);
        assertEquals(1, indexSearcher.count(query));
        query = rangeQueryFunction.apply(48L, 68L);
        assertEquals(0, indexSearcher.count(query));
    }
}
Also used : Query(org.apache.lucene.search.Query) CoreMatchers.is(org.hamcrest.CoreMatchers.is) Arrays(java.util.Arrays) BinaryPoint(org.apache.lucene.document.BinaryPoint) FieldType(org.apache.lucene.document.FieldType) BiFunction(java.util.function.BiFunction) IndexableField(org.apache.lucene.index.IndexableField) SortedNumericDocValuesField(org.apache.lucene.document.SortedNumericDocValuesField) Term(org.apache.lucene.index.Term) PhraseQuery(org.apache.lucene.search.PhraseQuery) StoredField(org.apache.lucene.document.StoredField) DoublePoint(org.apache.lucene.document.DoublePoint) Document(org.apache.lucene.document.Document) TermsEnum(org.apache.lucene.index.TermsEnum) LeafReaderContext(org.apache.lucene.index.LeafReaderContext) NumericDocValuesField(org.apache.lucene.document.NumericDocValuesField) SortedSetDocValuesField(org.apache.lucene.document.SortedSetDocValuesField) ClassicSimilarity(org.apache.lucene.search.similarities.ClassicSimilarity) BytesRef(org.apache.lucene.util.BytesRef) BinaryDocValuesField(org.apache.lucene.document.BinaryDocValuesField) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) StandardCharsets(java.nio.charset.StandardCharsets) SortedNumericDocValues(org.apache.lucene.index.SortedNumericDocValues) MockAnalyzer(org.apache.lucene.analysis.MockAnalyzer) List(java.util.List) FieldInvertState(org.apache.lucene.index.FieldInvertState) SortedDocValuesField(org.apache.lucene.document.SortedDocValuesField) LeafReader(org.apache.lucene.index.LeafReader) LuceneTestCase(org.apache.lucene.util.LuceneTestCase) MockPayloadAnalyzer(org.apache.lucene.analysis.MockPayloadAnalyzer) BinaryDocValues(org.apache.lucene.index.BinaryDocValues) IndexReader(org.apache.lucene.index.IndexReader) BM25Similarity(org.apache.lucene.search.similarities.BM25Similarity) IndexSearcher(org.apache.lucene.search.IndexSearcher) LongPoint(org.apache.lucene.document.LongPoint) StringField(org.apache.lucene.document.StringField) NumericDocValues(org.apache.lucene.index.NumericDocValues) TestUtil(org.apache.lucene.util.TestUtil) CoreMatchers.not(org.hamcrest.CoreMatchers.not) Function(java.util.function.Function) StringContains.containsString(org.junit.internal.matchers.StringContains.containsString) Similarity(org.apache.lucene.search.similarities.Similarity) SortedSetDocValues(org.apache.lucene.index.SortedSetDocValues) IntPoint(org.apache.lucene.document.IntPoint) SortedDocValues(org.apache.lucene.index.SortedDocValues) TermStatistics(org.apache.lucene.search.TermStatistics) Before(org.junit.Before) LongStream(java.util.stream.LongStream) PostingsEnum(org.apache.lucene.index.PostingsEnum) FloatPoint(org.apache.lucene.document.FloatPoint) Analyzer(org.apache.lucene.analysis.Analyzer) IOException(java.io.IOException) Test(org.junit.Test) CollectionStatistics(org.apache.lucene.search.CollectionStatistics) TermQuery(org.apache.lucene.search.TermQuery) Field(org.apache.lucene.document.Field) DocValuesType(org.apache.lucene.index.DocValuesType) TextField(org.apache.lucene.document.TextField) IndexOptions(org.apache.lucene.index.IndexOptions) IndexSearcher(org.apache.lucene.search.IndexSearcher) Query(org.apache.lucene.search.Query) PhraseQuery(org.apache.lucene.search.PhraseQuery) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) TermQuery(org.apache.lucene.search.TermQuery) LongPoint(org.apache.lucene.document.LongPoint) Document(org.apache.lucene.document.Document) BinaryPoint(org.apache.lucene.document.BinaryPoint) DoublePoint(org.apache.lucene.document.DoublePoint) LongPoint(org.apache.lucene.document.LongPoint) IntPoint(org.apache.lucene.document.IntPoint) FloatPoint(org.apache.lucene.document.FloatPoint) IndexableField(org.apache.lucene.index.IndexableField) IntPoint(org.apache.lucene.document.IntPoint) BiFunction(java.util.function.BiFunction) Function(java.util.function.Function) FloatPoint(org.apache.lucene.document.FloatPoint) BiFunction(java.util.function.BiFunction) DoublePoint(org.apache.lucene.document.DoublePoint)

Aggregations

BiFunction (java.util.function.BiFunction)43 HashMap (java.util.HashMap)22 List (java.util.List)22 Map (java.util.Map)22 ArrayList (java.util.ArrayList)18 Test (org.junit.Test)17 Collectors (java.util.stream.Collectors)15 Collections (java.util.Collections)14 Set (java.util.Set)13 Function (java.util.function.Function)13 Arrays (java.util.Arrays)12 Mockito.mock (org.mockito.Mockito.mock)12 IOException (java.io.IOException)11 Collection (java.util.Collection)11 IntStream (java.util.stream.IntStream)11 Before (org.junit.Before)11 Logger (org.apache.logging.log4j.Logger)8 Config (org.apache.samza.config.Config)8 JobConfig (org.apache.samza.config.JobConfig)8 ApplicationRunner (org.apache.samza.runtime.ApplicationRunner)8