Search in sources :

Example 26 with BiFunction

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

the class SpringLdapProducer method process.

/**
     * Performs the LDAP operation defined in SpringLdapEndpoint that created
     * this producer. The in-message in the exchange must be a map, containing
     * the following entries:
     * 
     * <pre>
     * key: "dn" - base DN for the LDAP operation
     * key: "filter" - necessary for the search operation only; LDAP filter for the search operation,
     * see <a http://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol>http://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol</a>
     * key: "attributes" - necessary for the bind operation only; an instance of javax.naming.directory.Attributes,
     * containing the information necessary to create an LDAP node.
     * key: "password" - necessary for the authentication operation only;
     * key: "modificationItems" - necessary for the modify_attributes operation only;
     * key: "function" - necessary for the function_driven operation only; provides a flexible hook into the {@link LdapTemplate} to call any method
     * key: "request" - necessary for the function_driven operation only; passed into the "function" to enable the client to bind parameters that need to be passed into the {@link LdapTemplate}
     * </pre>
     * 
     * The keys are defined as final fields above.
     */
@Override
public void process(Exchange exchange) throws Exception {
    @SuppressWarnings("unchecked") Map<String, Object> body = exchange.getIn().getBody(Map.class);
    LdapOperation operation = endpoint.getOperation();
    if (null == operation) {
        throw new UnsupportedOperationException("LDAP operation must not be empty, but you provided an empty operation");
    }
    String dn = (String) body.get(DN);
    if (operation != LdapOperation.FUNCTION_DRIVEN && (StringUtils.isBlank(dn))) {
        throw new UnsupportedOperationException("DN must not be empty, but you provided an empty DN");
    }
    LdapOperations ldapTemplate = endpoint.getLdapTemplate();
    switch(operation) {
        case SEARCH:
            String filter = (String) body.get(FILTER);
            exchange.getIn().setBody(ldapTemplate.search(dn, filter, endpoint.scopeValue(), mapper));
            break;
        case BIND:
            Attributes attributes = (Attributes) body.get(ATTRIBUTES);
            ldapTemplate.bind(dn, null, attributes);
            break;
        case UNBIND:
            ldapTemplate.unbind(dn);
            break;
        case AUTHENTICATE:
            ldapTemplate.authenticate(LdapQueryBuilder.query().base(dn).filter((String) body.get(FILTER)), (String) body.get(PASSWORD));
            break;
        case MODIFY_ATTRIBUTES:
            ModificationItem[] modificationItems = (ModificationItem[]) body.get(MODIFICATION_ITEMS);
            ldapTemplate.modifyAttributes(dn, modificationItems);
            break;
        case FUNCTION_DRIVEN:
            BiFunction<LdapOperations, Object, ?> ldapOperationFunction = (BiFunction<LdapOperations, Object, ?>) body.get(FUNCTION);
            Object ldapOperationRequest = body.get(REQUEST);
            exchange.getIn().setBody(ldapOperationFunction.apply(ldapTemplate, ldapOperationRequest));
            break;
        default:
            throw new UnsupportedOperationException("Bug in the Spring-LDAP component. Despite of all assertions, you managed to call an unsupported operation '" + operation + "'");
    }
}
Also used : ModificationItem(javax.naming.directory.ModificationItem) BiFunction(java.util.function.BiFunction) LdapOperations(org.springframework.ldap.core.LdapOperations) Attributes(javax.naming.directory.Attributes)

Example 27 with BiFunction

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

the class SpringLdapProducerTest method testFunctionDriven.

@Test
public void testFunctionDriven() throws Exception {
    String dn = "cn=dn";
    Exchange exchange = new DefaultExchange(context);
    Message in = new DefaultMessage();
    Map<String, Object> body = new HashMap<String, Object>();
    body.put(SpringLdapProducer.DN, dn);
    body.put(SpringLdapProducer.REQUEST, dn);
    body.put(SpringLdapProducer.FUNCTION, (BiFunction<LdapOperations, String, Void>) (l, q) -> {
        l.lookup(q);
        return null;
    });
    when(ldapEndpoint.getOperation()).thenReturn(LdapOperation.FUNCTION_DRIVEN);
    processBody(exchange, in, body);
    verify(ldapTemplate).lookup(eq(dn));
}
Also used : Exchange(org.apache.camel.Exchange) DefaultExchange(org.apache.camel.impl.DefaultExchange) DefaultExchange(org.apache.camel.impl.DefaultExchange) DefaultMessage(org.apache.camel.impl.DefaultMessage) ModificationItem(javax.naming.directory.ModificationItem) Message(org.apache.camel.Message) Matchers(org.mockito.Matchers) BiFunction(java.util.function.BiFunction) HashMap(java.util.HashMap) Exchange(org.apache.camel.Exchange) LdapTemplate(org.springframework.ldap.core.LdapTemplate) SearchControls(javax.naming.directory.SearchControls) BasicAttribute(javax.naming.directory.BasicAttribute) LdapOperations(org.springframework.ldap.core.LdapOperations) Matchers.eq(org.mockito.Matchers.eq) Map(java.util.Map) Before(org.junit.Before) LdapQuery(org.springframework.ldap.query.LdapQuery) DefaultExchange(org.apache.camel.impl.DefaultExchange) Matchers.isNull(org.mockito.Matchers.isNull) DirContext(javax.naming.directory.DirContext) BasicAttributes(javax.naming.directory.BasicAttributes) DefaultMessage(org.apache.camel.impl.DefaultMessage) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) Matchers.any(org.mockito.Matchers.any) Mockito(org.mockito.Mockito) AttributesMapper(org.springframework.ldap.core.AttributesMapper) CamelTestSupport(org.apache.camel.test.junit4.CamelTestSupport) Message(org.apache.camel.Message) DefaultMessage(org.apache.camel.impl.DefaultMessage) HashMap(java.util.HashMap) LdapOperations(org.springframework.ldap.core.LdapOperations) Test(org.junit.Test)

Example 28 with BiFunction

use of java.util.function.BiFunction in project torodb by torodb.

the class DefaultOplogApplier method createBatcherFlow.

/**
   * Creates a flow that batches and analyze a input of {@link AnalyzedOplogBatch remote jobs}.
   *
   * This flow tries to accummulate several remote jobs into a bigger one and does not emit until:
   * <ul>
   * <li>A maximum number of operations are batched</li>
   * <li>Or a maximum time has happen since the last emit</li>
   * <li>Or the recived job is not {@link AnalyzedOplogBatch#isReadyForMore()}</li>
   * </ul>
   *
   */
private Flow<OplogBatch, AnalyzedStreamElement, NotUsed> createBatcherFlow(ApplierContext context) {
    Predicate<OplogBatch> finishBatchPredicate = (OplogBatch rawBatch) -> !rawBatch.isReadyForMore();
    ToIntFunction<OplogBatch> costFunction = (rawBatch) -> rawBatch.count();
    Supplier<RawStreamElement> zeroFun = () -> RawStreamElement.INITIAL_ELEMENT;
    BiFunction<RawStreamElement, OplogBatch, RawStreamElement> acumFun = (streamElem, newBatch) -> streamElem.concat(newBatch);
    BatchAnalyzer batchAnalyzer = batchAnalyzerFactory.createBatchAnalyzer(context);
    return Flow.of(OplogBatch.class).via(new BatchFlow<>(batchLimits.maxSize, batchLimits.maxPeriod, finishBatchPredicate, costFunction, zeroFun, acumFun)).filter(rawElem -> rawElem.rawBatch != null && !rawElem.rawBatch.isEmpty()).map(rawElem -> {
        List<OplogOperation> rawOps = rawElem.rawBatch.getOps();
        List<AnalyzedOplogBatch> analyzed = batchAnalyzer.apply(rawOps);
        return new AnalyzedStreamElement(rawElem, analyzed);
    });
}
Also used : BatchAnalyzerFactory(com.torodb.mongodb.repl.oplogreplier.batch.BatchAnalyzer.BatchAnalyzerFactory) BiFunction(java.util.function.BiFunction) Flow(akka.stream.javadsl.Flow) Source(akka.stream.javadsl.Source) Supplier(com.google.common.base.Supplier) KillSwitch(akka.stream.KillSwitch) Materializer(akka.stream.Materializer) CompletableFuture(java.util.concurrent.CompletableFuture) UniqueKillSwitch(akka.stream.UniqueKillSwitch) OplogManager(com.torodb.mongodb.repl.OplogManager) BatchAnalyzer(com.torodb.mongodb.repl.oplogreplier.batch.BatchAnalyzer) Inject(javax.inject.Inject) ActorMaterializer(akka.stream.ActorMaterializer) Keep(akka.stream.javadsl.Keep) RunnableGraph(akka.stream.javadsl.RunnableGraph) OplogOperation(com.eightkdata.mongowp.server.api.oplog.OplogOperation) Empty(com.eightkdata.mongowp.server.api.tools.Empty) OplogManagerPersistException(com.torodb.mongodb.repl.OplogManager.OplogManagerPersistException) AnalyzedOplogBatchExecutor(com.torodb.mongodb.repl.oplogreplier.batch.AnalyzedOplogBatchExecutor) ConcurrentToolsFactory(com.torodb.core.concurrent.ConcurrentToolsFactory) AnalyzedOplogBatch(com.torodb.mongodb.repl.oplogreplier.batch.AnalyzedOplogBatch) OplogFetcher(com.torodb.mongodb.repl.oplogreplier.fetcher.OplogFetcher) Shutdowner(com.torodb.core.Shutdowner) Done(akka.Done) CancellationException(java.util.concurrent.CancellationException) FiniteDuration(scala.concurrent.duration.FiniteDuration) Predicate(java.util.function.Predicate) ToIntFunction(java.util.function.ToIntFunction) Sink(akka.stream.javadsl.Sink) Throwables(com.google.common.base.Throwables) CompletionException(java.util.concurrent.CompletionException) KillSwitches(akka.stream.KillSwitches) WriteOplogTransaction(com.torodb.mongodb.repl.OplogManager.WriteOplogTransaction) ExecutionContexts(akka.dispatch.ExecutionContexts) Pair(akka.japi.Pair) TimeUnit(java.util.concurrent.TimeUnit) Duration(scala.concurrent.duration.Duration) List(java.util.List) Logger(org.apache.logging.log4j.Logger) CompletionStage(java.util.concurrent.CompletionStage) NotUsed(akka.NotUsed) BatchFlow(com.torodb.concurrent.akka.BatchFlow) ActorSystem(akka.actor.ActorSystem) Optional(java.util.Optional) LogManager(org.apache.logging.log4j.LogManager) Await(scala.concurrent.Await) AnalyzedOplogBatch(com.torodb.mongodb.repl.oplogreplier.batch.AnalyzedOplogBatch) BatchAnalyzer(com.torodb.mongodb.repl.oplogreplier.batch.BatchAnalyzer) AnalyzedOplogBatch(com.torodb.mongodb.repl.oplogreplier.batch.AnalyzedOplogBatch) OplogOperation(com.eightkdata.mongowp.server.api.oplog.OplogOperation)

Example 29 with BiFunction

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

the class AsyncNettyHelperTest method biFunctionWithTracingAndMdc_separate_args_works_as_expected.

@Test
public void biFunctionWithTracingAndMdc_separate_args_works_as_expected() {
    // given
    Pair<Deque<Span>, Map<String, String>> setupInfo = generateTracingAndMdcInfo();
    // when
    BiFunction result = AsyncNettyHelper.biFunctionWithTracingAndMdc(biFunctionMock, setupInfo.getLeft(), setupInfo.getRight());
    // 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 30 with BiFunction

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

the class AsyncNettyHelperTest method biFunctionWithTracingAndMdc_ctx_works_as_expected.

@Test
public void biFunctionWithTracingAndMdc_ctx_works_as_expected() {
    // given
    Pair<Deque<Span>, Map<String, String>> setupInfo = setupStateWithTracingAndMdcInfo();
    // when
    BiFunction result = AsyncNettyHelper.biFunctionWithTracingAndMdc(biFunctionMock, ctxMock);
    // 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)

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