Search in sources :

Example 1 with Builder

use of org.mule.runtime.core.api.event.CoreEvent.Builder in project mule by mulesoft.

the class SplitterTestCase method assertRouted.

private void assertRouted(Object payload, int count, boolean counted) throws Exception, MuleException {
    MuleSession session = new DefaultMuleSession();
    Map<String, Serializable> inboundProps = new HashMap<>();
    inboundProps.put("inbound1", "1");
    inboundProps.put("inbound2", 2);
    inboundProps.put("inbound3", session);
    Map<String, Serializable> outboundProps = new HashMap<>();
    outboundProps.put("outbound1", "3");
    outboundProps.put("outbound2", 4);
    outboundProps.put("outbound3", session);
    Map<String, Object> invocationProps = new HashMap<>();
    invocationProps.put("invoke1", "5");
    invocationProps.put("invoke2", 6);
    invocationProps.put("invoke3", session);
    Set<Integer> expectedSequences = new HashSet<>();
    for (int i = 1; i <= count; i++) {
        expectedSequences.add(i);
    }
    Message toSplit = InternalMessage.builder().value(payload).inboundProperties(inboundProps).outboundProperties(outboundProps).build();
    Splitter splitter = new Splitter();
    Grabber grabber = new Grabber();
    splitter.setMuleContext(muleContext);
    splitter.setListener(grabber);
    splitter.initialise();
    final Builder eventBuilder = this.<PrivilegedEvent.Builder>getEventBuilder().message(toSplit).session(session);
    for (Map.Entry<String, Object> entry : invocationProps.entrySet()) {
        eventBuilder.addVariable(entry.getKey(), entry.getValue());
    }
    CoreEvent event = eventBuilder.build();
    splitter.process(event);
    List<CoreEvent> splits = grabber.getEvents();
    assertEquals(count, splits.size());
    Set<Object> actualSequences = new HashSet<>();
    assertSplitParts(count, counted, inboundProps, outboundProps, invocationProps, splits, actualSequences);
    assertEquals(expectedSequences, actualSequences);
}
Also used : Serializable(java.io.Serializable) Message(org.mule.runtime.api.message.Message) InternalMessage(org.mule.runtime.core.internal.message.InternalMessage) HashMap(java.util.HashMap) Builder(org.mule.runtime.core.api.event.CoreEvent.Builder) MuleSession(org.mule.runtime.core.privileged.event.MuleSession) DefaultMuleSession(org.mule.runtime.core.privileged.event.DefaultMuleSession) CoreEvent(org.mule.runtime.core.api.event.CoreEvent) DefaultMuleSession(org.mule.runtime.core.privileged.event.DefaultMuleSession) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 2 with Builder

use of org.mule.runtime.core.api.event.CoreEvent.Builder in project mule by mulesoft.

the class AbstractForkJoinStrategyTestCase method flowVarsMerged.

@Test
@Description("After successful completion of all routes the variables from each route are merged into the result.")
public void flowVarsMerged() throws Throwable {
    final String beforeVarName = "before";
    final String beforeVarValue = "beforeValue";
    final String beforeVar2Name = "before2";
    final String beforeVar2Value = "before2Value";
    final String beforeVar2NewValue = "before2NewValue";
    final String fooVarName = "foo";
    final String fooVarValue = "fooValue1";
    final String fooVar2Name = "foo2";
    final String fooVar2Value1 = "foo2Value1";
    final String fooVar2Value2 = "foo2Value2";
    final String fooVar3Name = "foo3";
    final String fooVar3Value1 = "foo3Value1";
    final Apple fooVar3Value2 = new Apple();
    CoreEvent original = builder(this.<CoreEvent>newEvent()).addVariable(beforeVarName, beforeVarValue).addVariable(beforeVar2Name, beforeVar2Value).build();
    RoutingPair pair1 = of(original, createChain(event -> builder(event).addVariable(beforeVar2Name, beforeVar2NewValue).addVariable(fooVarName, fooVarValue).addVariable(fooVar2Name, fooVar2Value1).addVariable(fooVar3Name, fooVar3Value1).build()));
    RoutingPair pair2 = of(original, createChain(event -> builder(event).addVariable(fooVar2Name, fooVar2Value2).addVariable(fooVar3Name, fooVar3Value2).build()));
    CoreEvent result = invokeStrategyBlocking(strategy, original, asList(pair1, pair2));
    assertThat(result.getVariables().keySet(), hasSize(5));
    assertThat(result.getVariables().keySet(), hasItems(beforeVarName, beforeVar2Name, fooVarName, fooVarName, fooVar2Name, fooVar3Name));
    assertThat(result.getVariables().get(beforeVarName).getValue(), equalTo(beforeVarValue));
    assertThat(result.getVariables().get(beforeVar2Name).getValue(), equalTo(beforeVar2NewValue));
    assertThat(result.getVariables().get(fooVarName).getValue(), equalTo(fooVarValue));
    TypedValue fooVar2 = result.getVariables().get(fooVar2Name);
    assertThat(fooVar2.getDataType(), equalTo(DataType.builder().collectionType(List.class).itemType(String.class).build()));
    assertThat(((List<String>) fooVar2.getValue()), hasItems(fooVar2Value1, fooVar2Value2));
    TypedValue fooVar3 = result.getVariables().get(fooVar3Name);
    assertThat(fooVar3.getDataType(), equalTo(DataType.builder().collectionType(List.class).itemType(Object.class).build()));
    assertThat(((List<Object>) fooVar3.getValue()), hasItems(fooVar3Value1, fooVar3Value2));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) MessageProcessors.newChain(org.mule.runtime.core.privileged.processor.MessageProcessors.newChain) Schedulers.fromExecutorService(reactor.core.scheduler.Schedulers.fromExecutorService) Apple(org.mule.tck.testmodels.fruit.Apple) IntStream.range(java.util.stream.IntStream.range) Message(org.mule.runtime.api.message.Message) MAX_VALUE(java.lang.Integer.MAX_VALUE) TimeoutException(java.util.concurrent.TimeoutException) Matchers.hasItems(org.hamcrest.Matchers.hasItems) CoreEvent.builder(org.mule.runtime.core.api.event.CoreEvent.builder) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) Assert.assertThat(org.junit.Assert.assertThat) RoutingPair(org.mule.runtime.core.internal.routing.ForkJoinStrategy.RoutingPair) Scheduler(org.mule.runtime.api.scheduler.Scheduler) Arrays.asList(java.util.Arrays.asList) After(org.junit.After) Thread.sleep(java.lang.Thread.sleep) MessagingException(org.mule.runtime.core.internal.exception.MessagingException) Flux.fromIterable(reactor.core.publisher.Flux.fromIterable) ForkJoinStrategy(org.mule.runtime.core.internal.routing.ForkJoinStrategy) ReactiveProcessor(org.mule.runtime.core.api.processor.ReactiveProcessor) Message.of(org.mule.runtime.api.message.Message.of) ProcessingStrategy(org.mule.runtime.core.api.processor.strategy.ProcessingStrategy) MessageProcessorChain(org.mule.runtime.core.privileged.processor.chain.MessageProcessorChain) Matchers.any(org.mockito.Matchers.any) List(java.util.List) AbstractMuleContextTestCase(org.mule.tck.junit4.AbstractMuleContextTestCase) Mockito.atMost(org.mockito.Mockito.atMost) ErrorType(org.mule.runtime.api.message.ErrorType) Optional(java.util.Optional) RoutingPair.of(org.mule.runtime.core.internal.routing.ForkJoinStrategy.RoutingPair.of) Mockito.mock(org.mockito.Mockito.mock) CompositeRoutingException(org.mule.runtime.core.privileged.routing.CompositeRoutingException) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) InternalProcessor(org.mule.runtime.core.privileged.processor.InternalProcessor) Callable(java.util.concurrent.Callable) Mockito.spy(org.mockito.Mockito.spy) Processor(org.mule.runtime.core.api.processor.Processor) Function(java.util.function.Function) TIMEOUT(org.mule.runtime.core.api.exception.Errors.ComponentIdentifiers.Handleable.TIMEOUT) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) Feature(io.qameta.allure.Feature) MuleException(org.mule.runtime.api.exception.MuleException) RoutingResult(org.mule.runtime.core.privileged.routing.RoutingResult) Mono.from(reactor.core.publisher.Mono.from) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ExpectedException(org.junit.rules.ExpectedException) CoreMatchers.nullValue(org.hamcrest.CoreMatchers.nullValue) Before(org.junit.Before) CheckedConsumer(org.mule.runtime.core.api.util.func.CheckedConsumer) DataType(org.mule.runtime.api.metadata.DataType) CoreEvent(org.mule.runtime.core.api.event.CoreEvent) Mockito.times(org.mockito.Mockito.times) FORK_JOIN_STRATEGIES(org.mule.test.allure.AllureConstants.ForkJoinStrategiesFeature.FORK_JOIN_STRATEGIES) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) AbstractComponent(org.mule.runtime.api.component.AbstractComponent) TypedValue(org.mule.runtime.api.metadata.TypedValue) Collectors.toList(java.util.stream.Collectors.toList) Mockito.never(org.mockito.Mockito.never) DefaultMuleException(org.mule.runtime.api.exception.DefaultMuleException) Rule(org.junit.Rule) Exceptions.rxExceptionToMuleException(org.mule.runtime.core.api.rx.Exceptions.rxExceptionToMuleException) Description(io.qameta.allure.Description) Apple(org.mule.tck.testmodels.fruit.Apple) CoreEvent(org.mule.runtime.core.api.event.CoreEvent) Arrays.asList(java.util.Arrays.asList) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) RoutingPair(org.mule.runtime.core.internal.routing.ForkJoinStrategy.RoutingPair) TypedValue(org.mule.runtime.api.metadata.TypedValue) Description(io.qameta.allure.Description) Test(org.junit.Test)

Example 3 with Builder

use of org.mule.runtime.core.api.event.CoreEvent.Builder in project mule by mulesoft.

the class AbstractExecutableComponent method execute.

@Override
public final CompletableFuture<ExecutionResult> execute(InputEvent inputEvent) {
    CompletableFuture completableFuture = new CompletableFuture();
    CoreEvent.Builder builder = CoreEvent.builder(createEventContext(of(completableFuture)));
    CoreEvent event = builder.message(inputEvent.getMessage()).error(inputEvent.getError().orElse(null)).variables(inputEvent.getVariables()).build();
    return from(MessageProcessors.process(event, getExecutableFunction())).onErrorMap(throwable -> {
        MessagingException messagingException = (MessagingException) throwable;
        CoreEvent messagingExceptionEvent = messagingException.getEvent();
        return new ComponentExecutionException(messagingExceptionEvent.getError().get().getCause(), messagingExceptionEvent);
    }).<ExecutionResult>map(result -> new ExecutionResultImplementation(result, completableFuture)).toFuture();
}
Also used : Optional.of(java.util.Optional.of) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) CoreEvent.builder(org.mule.runtime.core.api.event.CoreEvent.builder) Event(org.mule.runtime.api.event.Event) ExecutionResult(org.mule.runtime.api.component.execution.ExecutionResult) Inject(javax.inject.Inject) MuleContext(org.mule.runtime.core.api.MuleContext) Mono.from(reactor.core.publisher.Mono.from) MessagingException(org.mule.runtime.core.internal.exception.MessagingException) EventContext(org.mule.runtime.api.event.EventContext) Optional.ofNullable(java.util.Optional.ofNullable) I18nMessageFactory.createStaticMessage(org.mule.runtime.api.i18n.I18nMessageFactory.createStaticMessage) CoreEvent(org.mule.runtime.core.api.event.CoreEvent) Publisher(org.reactivestreams.Publisher) EventContextFactory.create(org.mule.runtime.core.api.event.EventContextFactory.create) BaseEventContext(org.mule.runtime.core.privileged.event.BaseEventContext) NullExceptionHandler(org.mule.runtime.core.api.exception.NullExceptionHandler) MuleRuntimeException(org.mule.runtime.api.exception.MuleRuntimeException) ReactiveProcessor(org.mule.runtime.core.api.processor.ReactiveProcessor) InputEvent(org.mule.runtime.api.component.execution.InputEvent) String.format(java.lang.String.format) AbstractComponent(org.mule.runtime.api.component.AbstractComponent) ComponentExecutionException(org.mule.runtime.api.component.execution.ComponentExecutionException) MessageProcessors(org.mule.runtime.core.privileged.processor.MessageProcessors) ExecutableComponent(org.mule.runtime.api.component.execution.ExecutableComponent) Optional(java.util.Optional) DefaultEventContext.child(org.mule.runtime.core.internal.event.DefaultEventContext.child) CompletableFuture(java.util.concurrent.CompletableFuture) CoreEvent(org.mule.runtime.core.api.event.CoreEvent) MessagingException(org.mule.runtime.core.internal.exception.MessagingException) ComponentExecutionException(org.mule.runtime.api.component.execution.ComponentExecutionException)

Example 4 with Builder

use of org.mule.runtime.core.api.event.CoreEvent.Builder in project mule by mulesoft.

the class AbstractMessageSequenceSplitter method processParts.

protected List<CoreEvent> processParts(MessageSequence<?> seq, CoreEvent originalEvent) throws MuleException {
    List<CoreEvent> resultEvents = new ArrayList<>();
    int correlationSequence = 0;
    MessageSequence<?> messageSequence = seq;
    if (batchSize > 1) {
        messageSequence = new PartitionedMessageSequence<>(seq, batchSize);
    }
    Integer count = messageSequence.size();
    CoreEvent lastResult = null;
    for (; messageSequence.hasNext(); ) {
        correlationSequence++;
        final Builder builder = builder(originalEvent);
        propagateFlowVars(lastResult, builder);
        if (counterVariableName != null) {
            builder.addVariable(counterVariableName, correlationSequence);
        }
        builder.groupCorrelation(Optional.of(count != null ? GroupCorrelation.of(correlationSequence, count) : GroupCorrelation.of(correlationSequence)));
        Object nextValue = messageSequence.next();
        initEventBuilder(nextValue, originalEvent, builder, resolvePropagatedFlowVars(lastResult));
        try {
            // TODO MULE-13052 Migrate Splitter and Foreach implementation to non-blocking
            CoreEvent resultEvent = processToApplyWithChildContext(builder.build(), applyNext());
            if (resultEvent != null) {
                resultEvents.add(builder(originalEvent.getContext(), resultEvent).build());
                lastResult = resultEvent;
            }
        } catch (MessagingException e) {
            if (!filterOnErrorTypeAcceptor.accept(e.getEvent())) {
                throw e;
            }
        } finally {
            if (nextValue instanceof EventBuilderConfigurer) {
                ((EventBuilderConfigurer) nextValue).eventCompleted();
            }
        }
    }
    if (correlationSequence == 1) {
        logger.debug("Splitter only returned a single result. If this is not expected, please check your split expression");
    }
    return resultEvents;
}
Also used : CoreEvent(org.mule.runtime.core.api.event.CoreEvent) MessagingException(org.mule.runtime.core.internal.exception.MessagingException) Builder(org.mule.runtime.core.api.event.CoreEvent.Builder) ArrayList(java.util.ArrayList)

Example 5 with Builder

use of org.mule.runtime.core.api.event.CoreEvent.Builder in project mule by mulesoft.

the class Foreach method apply.

@Override
public Publisher<CoreEvent> apply(Publisher<CoreEvent> publisher) {
    return from(publisher).doOnNext(event -> {
        if (expression.equals(DEFAULT_SPLIT_EXPRESSION) && Map.class.isAssignableFrom(event.getMessage().getPayload().getDataType().getType())) {
            throw new IllegalArgumentException(MAP_NOT_SUPPORTED_MESSAGE);
        }
    }).flatMap(originalEvent -> {
        // Keep reference to existing rootMessage/count variables in order to restore later to support foreach nesting.
        final Object previousCounterVar = originalEvent.getVariables().containsKey(counterVariableName) ? originalEvent.getVariables().get(counterVariableName).getValue() : null;
        final Object previousRootMessageVar = originalEvent.getVariables().containsKey(rootMessageVariableName) ? originalEvent.getVariables().get(rootMessageVariableName).getValue() : null;
        final CoreEvent requestEvent = builder(originalEvent).addVariable(rootMessageVariableName, originalEvent.getMessage()).build();
        return Mono.from(splitAndProcess(requestEvent)).map(result -> {
            final Builder responseBuilder = builder(result).message(originalEvent.getMessage());
            restoreVariables(previousCounterVar, previousRootMessageVar, responseBuilder);
            return responseBuilder.build();
        }).onErrorMap(MessagingException.class, me -> {
            // Restore variables in case of error also
            CoreEvent.Builder exceptionEventBuilder = builder(me.getEvent());
            restoreVariables(previousCounterVar, previousRootMessageVar, exceptionEventBuilder);
            me.setProcessedEvent(exceptionEventBuilder.build());
            return me;
        });
    });
}
Also used : MessageProcessors.newChain(org.mule.runtime.core.privileged.processor.MessageProcessors.newChain) Message(org.mule.runtime.api.message.Message) Flux.from(reactor.core.publisher.Flux.from) Mono.defer(reactor.core.publisher.Mono.defer) InitialisationException(org.mule.runtime.api.lifecycle.InitialisationException) DataType.fromObject(org.mule.runtime.api.metadata.DataType.fromObject) Processor(org.mule.runtime.core.api.processor.Processor) AtomicReference(java.util.concurrent.atomic.AtomicReference) CoreEvent.builder(org.mule.runtime.core.api.event.CoreEvent.builder) Iterators(com.google.common.collect.Iterators) Collections.singletonList(java.util.Collections.singletonList) Scope(org.mule.runtime.core.privileged.processor.Scope) MuleException(org.mule.runtime.api.exception.MuleException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MessageProcessors.newChildContext(org.mule.runtime.core.privileged.processor.MessageProcessors.newChildContext) Builder(org.mule.runtime.core.api.event.CoreEvent.Builder) Map(java.util.Map) Mono.just(reactor.core.publisher.Mono.just) AbstractMessageProcessorOwner(org.mule.runtime.core.api.processor.AbstractMessageProcessorOwner) MessagingException(org.mule.runtime.core.internal.exception.MessagingException) EventBuilderConfigurer(org.mule.runtime.core.internal.routing.outbound.EventBuilderConfigurer) Mono.empty(reactor.core.publisher.Mono.empty) DEFAULT_SPLIT_EXPRESSION(org.mule.runtime.core.internal.routing.ExpressionSplittingStrategy.DEFAULT_SPLIT_EXPRESSION) EventContext(org.mule.runtime.api.event.EventContext) Iterator(java.util.Iterator) MessageProcessors.processToApply(org.mule.runtime.core.privileged.processor.MessageProcessors.processToApply) Flux.fromIterable(reactor.core.publisher.Flux.fromIterable) Optional.ofNullable(java.util.Optional.ofNullable) MessageProcessors.completeSuccessIfNeeded(org.mule.runtime.core.privileged.processor.MessageProcessors.completeSuccessIfNeeded) CoreEvent(org.mule.runtime.core.api.event.CoreEvent) Publisher(org.reactivestreams.Publisher) BaseEventContext(org.mule.runtime.core.privileged.event.BaseEventContext) Mono(reactor.core.publisher.Mono) Initialisable(org.mule.runtime.api.lifecycle.Initialisable) EventBuilderConfigurerList(org.mule.runtime.core.internal.routing.outbound.EventBuilderConfigurerList) ProcessingStrategy(org.mule.runtime.core.api.processor.strategy.ProcessingStrategy) MessageProcessorChain(org.mule.runtime.core.privileged.processor.chain.MessageProcessorChain) TypedValue(org.mule.runtime.api.metadata.TypedValue) List(java.util.List) Optional(java.util.Optional) EventBuilderConfigurerIterator(org.mule.runtime.core.internal.routing.outbound.EventBuilderConfigurerIterator) MessageProcessors.getProcessingStrategy(org.mule.runtime.core.privileged.processor.MessageProcessors.getProcessingStrategy) Builder(org.mule.runtime.core.api.event.CoreEvent.Builder) CoreEvent(org.mule.runtime.core.api.event.CoreEvent) Builder(org.mule.runtime.core.api.event.CoreEvent.Builder) DataType.fromObject(org.mule.runtime.api.metadata.DataType.fromObject)

Aggregations

CoreEvent (org.mule.runtime.core.api.event.CoreEvent)7 MessagingException (org.mule.runtime.core.internal.exception.MessagingException)6 Optional (java.util.Optional)5 CoreEvent.builder (org.mule.runtime.core.api.event.CoreEvent.builder)5 Optional.ofNullable (java.util.Optional.ofNullable)4 Message (org.mule.runtime.api.message.Message)4 Builder (org.mule.runtime.core.api.event.CoreEvent.Builder)4 List (java.util.List)3 Map (java.util.Map)3 EventContext (org.mule.runtime.api.event.EventContext)3 BaseEventContext (org.mule.runtime.core.privileged.event.BaseEventContext)3 Publisher (org.reactivestreams.Publisher)3 Iterators (com.google.common.collect.Iterators)2 Collections.singletonList (java.util.Collections.singletonList)2 Iterator (java.util.Iterator)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Function (java.util.function.Function)2 AbstractComponent (org.mule.runtime.api.component.AbstractComponent)2 MuleException (org.mule.runtime.api.exception.MuleException)2