Search in sources :

Example 26 with Message

use of org.mule.runtime.api.message.Message in project mule by mulesoft.

the class DefaultRouterResultsHandlerTestCase method aggregateMultipleMuleMessageCollections.

@Test
public void aggregateMultipleMuleMessageCollections() {
    Message message1 = Message.of("test event A");
    CoreEvent event1 = InternalEvent.builder(context).message(message1).addVariable("key1", "value1").build();
    Message message2 = Message.of("test event B");
    Message message3 = Message.of("test event C");
    Message message4 = Message.of("test event D");
    Message message5 = Message.of("test event E");
    List<Message> list = new ArrayList<>();
    list.add(message2);
    list.add(message3);
    Message messageCollection = Message.of(list);
    CoreEvent event2 = InternalEvent.builder(context).message(messageCollection).addVariable("key2", "value2").build();
    List<InternalMessage> list2 = new ArrayList<>();
    list.add(message4);
    list.add(message5);
    Message messageCollection2 = Message.of(list2);
    CoreEvent event3 = InternalEvent.builder(context).message(messageCollection2).addVariable("key3", "value3").build();
    List<CoreEvent> events = new ArrayList<>();
    events.add(event2);
    events.add(event3);
    CoreEvent result = resultsHandler.aggregateResults(events, event1);
    assertNotNull(result);
    assertEquals(2, ((List<InternalMessage>) result.getMessage().getPayload().getValue()).size());
    assertTrue(result.getMessage().getPayload().getValue() instanceof List<?>);
    assertEquals(messageCollection, ((List<InternalMessage>) result.getMessage().getPayload().getValue()).get(0));
    assertEquals(messageCollection2, ((List<InternalMessage>) result.getMessage().getPayload().getValue()).get(1));
    // Because a new MuleMessageCollection is created, propagate properties from
    // original event
    assertThat(result.getVariables().get("key1").getValue(), equalTo("value1"));
    assertThat(result.getVariables().get("key2").getValue(), equalTo("value2"));
    assertThat(result.getVariables().get("key3").getValue(), equalTo("value3"));
    // Root id
    assertThat(result.getCorrelationId(), equalTo(event1.getCorrelationId()));
}
Also used : InternalMessage(org.mule.runtime.core.internal.message.InternalMessage) Message(org.mule.runtime.api.message.Message) InternalMessage(org.mule.runtime.core.internal.message.InternalMessage) CoreEvent(org.mule.runtime.core.api.event.CoreEvent) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 27 with Message

use of org.mule.runtime.api.message.Message in project mule by mulesoft.

the class FirstSuccessfulTestCase method getPayload.

private String getPayload(Processor mp, MuleSession session, String message) throws Exception {
    Message msg = of(message);
    try {
        CoreEvent event = mp.process(this.<PrivilegedEvent.Builder>getEventBuilder().message(msg).session(session).build());
        Message returnedMessage = event.getMessage();
        if (event.getError().isPresent()) {
            return EXCEPTION_SEEN;
        } else {
            return getPayloadAsString(returnedMessage);
        }
    } catch (Exception ex) {
        return EXCEPTION_SEEN;
    }
}
Also used : Message(org.mule.runtime.api.message.Message) InternalMessage(org.mule.runtime.core.internal.message.InternalMessage) CoreEvent(org.mule.runtime.core.api.event.CoreEvent) MuleContextUtils.eventBuilder(org.mule.tck.util.MuleContextUtils.eventBuilder) CouldNotRouteOutboundMessageException(org.mule.runtime.core.privileged.routing.CouldNotRouteOutboundMessageException) MuleException(org.mule.runtime.api.exception.MuleException) DefaultMuleException(org.mule.runtime.api.exception.DefaultMuleException)

Example 28 with Message

use of org.mule.runtime.api.message.Message in project mule by mulesoft.

the class InvokerMessageProcessor method evaluateExpressionCandidate.

@SuppressWarnings("unchecked")
protected Object evaluateExpressionCandidate(Object expressionCandidate, CoreEvent event) throws TransformerException {
    if (expressionCandidate instanceof Collection<?>) {
        Collection<Object> collectionTemplate = (Collection<Object>) expressionCandidate;
        Collection<Object> newCollection = new ArrayList<>();
        for (Object object : collectionTemplate) {
            newCollection.add(evaluateExpressionCandidate(object, event));
        }
        return newCollection;
    } else if (expressionCandidate instanceof Map<?, ?>) {
        Map<Object, Object> mapTemplate = (Map<Object, Object>) expressionCandidate;
        Map<Object, Object> newMap = new HashMap<>();
        for (Entry<Object, Object> entry : mapTemplate.entrySet()) {
            newMap.put(evaluateExpressionCandidate(entry.getKey(), event), evaluateExpressionCandidate(entry.getValue(), event));
        }
        return newMap;
    } else if (expressionCandidate instanceof String[]) {
        String[] stringArrayTemplate = (String[]) expressionCandidate;
        Object[] newArray = new String[stringArrayTemplate.length];
        for (int j = 0; j < stringArrayTemplate.length; j++) {
            newArray[j] = evaluateExpressionCandidate(stringArrayTemplate[j], event);
        }
        return newArray;
    }
    if (expressionCandidate instanceof String) {
        Object arg;
        String expression = (String) expressionCandidate;
        // everything to a string
        if (expression.startsWith(patternInfo.getPrefix()) && expression.endsWith(patternInfo.getSuffix()) && expression.lastIndexOf(patternInfo.getPrefix()) == 0) {
            arg = expressionManager.evaluate(expression, event, getLocation()).getValue();
        } else {
            arg = expressionManager.parse(expression, event, getLocation());
        }
        // If expression evaluates to a Message then use it's payload
        if (arg instanceof Message) {
            arg = ((Message) arg).getPayload().getValue();
        }
        return arg;
    } else {
        // Not an expression so use object itself
        return expressionCandidate;
    }
}
Also used : Message(org.mule.runtime.api.message.Message) ArrayList(java.util.ArrayList) Entry(java.util.Map.Entry) Collection(java.util.Collection) CoreMessages.methodWithParamsNotFoundOnObject(org.mule.runtime.core.api.config.i18n.CoreMessages.methodWithParamsNotFoundOnObject) CoreMessages.methodWithNumParamsNotFoundOnObject(org.mule.runtime.core.api.config.i18n.CoreMessages.methodWithNumParamsNotFoundOnObject) HashMap(java.util.HashMap) Map(java.util.Map)

Example 29 with Message

use of org.mule.runtime.api.message.Message in project mule by mulesoft.

the class CompositeSourcePolicy method processNextOperation.

/**
 * Executes the flow.
 *
 * If there's a {@link SourcePolicyParametersTransformer} provided then it will use it to convert the source response or source
 * failure response from the parameters back to a {@link Message} that can be routed through the policy chain which later will
 * be convert back to response or failure response parameters thus allowing the policy chain to modify the response.. That
 * message will be the result of the next-operation of the policy.
 *
 * If no {@link SourcePolicyParametersTransformer} is provided, then the same response from the flow is going to be routed as
 * response of the next-operation of the policy chain. In this case, the same response from the flow is going to be used to
 * generate the response or failure response for the source so the policy chain is not going to be able to modify the response
 * sent by the source.
 *
 * When the flow execution fails, it will create a {@link FlowExecutionException} instead of a regular
 * {@link MessagingException} to signal that the failure was through the the flow exception and not the policy logic.
 */
@Override
protected Publisher<CoreEvent> processNextOperation(CoreEvent event) {
    return just(event).flatMap(request -> from(processWithChildContext(request, flowExecutionProcessor, empty()))).map(flowExecutionResponse -> {
        originalResponseParameters = getParametersProcessor().getSuccessfulExecutionResponseParametersFunction().apply(flowExecutionResponse);
        Message message = getParametersTransformer().map(parametersTransformer -> parametersTransformer.fromSuccessResponseParametersToMessage(originalResponseParameters)).orElseGet(flowExecutionResponse::getMessage);
        return CoreEvent.builder(event).message(message).build();
    }).onErrorMap(MessagingException.class, messagingException -> {
        originalFailureResponseParameters = getParametersProcessor().getFailedExecutionResponseParametersFunction().apply(messagingException.getEvent());
        Message message = getParametersTransformer().map(parametersTransformer -> parametersTransformer.fromFailureResponseParametersToMessage(originalFailureResponseParameters)).orElse(messagingException.getEvent().getMessage());
        MessagingException flowExecutionException = new FlowExecutionException(CoreEvent.builder(messagingException.getEvent()).message(message).build(), messagingException.getCause(), messagingException.getFailingComponent());
        if (messagingException.getInfo().containsKey(INFO_ALREADY_LOGGED_KEY)) {
            flowExecutionException.addInfo(INFO_ALREADY_LOGGED_KEY, messagingException.getInfo().get(INFO_ALREADY_LOGGED_KEY));
        }
        return flowExecutionException;
    }).doOnError(e -> LOGGER.error(e.getMessage(), e));
}
Also used : Optional.empty(java.util.Optional.empty) Logger(org.slf4j.Logger) SourcePolicyParametersTransformer(org.mule.runtime.core.api.policy.SourcePolicyParametersTransformer) INFO_ALREADY_LOGGED_KEY(org.mule.runtime.api.exception.MuleException.INFO_ALREADY_LOGGED_KEY) Message(org.mule.runtime.api.message.Message) CoreEvent(org.mule.runtime.core.api.event.CoreEvent) Publisher(org.reactivestreams.Publisher) HashMap(java.util.HashMap) Either.left(org.mule.runtime.core.api.functional.Either.left) Processor(org.mule.runtime.core.api.processor.Processor) Supplier(java.util.function.Supplier) Either.right(org.mule.runtime.core.api.functional.Either.right) Either(org.mule.runtime.core.api.functional.Either) List(java.util.List) MessageProcessors.processWithChildContext(org.mule.runtime.core.privileged.processor.MessageProcessors.processWithChildContext) Policy(org.mule.runtime.core.api.policy.Policy) MessageProcessors(org.mule.runtime.core.privileged.processor.MessageProcessors) Map(java.util.Map) LoggerFactory.getLogger(org.slf4j.LoggerFactory.getLogger) Mono.from(reactor.core.publisher.Mono.from) Mono.just(reactor.core.publisher.Mono.just) MessagingException(org.mule.runtime.core.internal.exception.MessagingException) Optional(java.util.Optional) Message(org.mule.runtime.api.message.Message) MessagingException(org.mule.runtime.core.internal.exception.MessagingException)

Example 30 with Message

use of org.mule.runtime.api.message.Message in project mule by mulesoft.

the class ParseTemplateProcessor method process.

@Override
public CoreEvent process(CoreEvent event) {
    evaluateCorrectArguments();
    Object result = muleContext.getExpressionManager().parseLogTemplate(content, event, getLocation(), NULL_BINDING_CONTEXT);
    Message resultMessage = Message.builder(event.getMessage()).value(result).nullAttributesValue().build();
    if (target == null) {
        return CoreEvent.builder(event).message(resultMessage).build();
    } else {
        if (targetValue == null) {
            // Return the whole message
            return CoreEvent.builder(event).addVariable(target, resultMessage).build();
        } else {
            // typeValue was defined by the user
            return CoreEvent.builder(event).addVariable(target, muleContext.getExpressionManager().evaluate(targetValue, CoreEvent.builder(event).message(resultMessage).build())).build();
        }
    }
}
Also used : I18nMessageFactory.createStaticMessage(org.mule.runtime.api.i18n.I18nMessageFactory.createStaticMessage) Message(org.mule.runtime.api.message.Message)

Aggregations

Message (org.mule.runtime.api.message.Message)226 Test (org.junit.Test)189 CoreEvent (org.mule.runtime.core.api.event.CoreEvent)104 SmallTest (org.mule.tck.size.SmallTest)68 InternalMessage (org.mule.runtime.core.internal.message.InternalMessage)46 Transformer (org.mule.runtime.core.api.transformer.Transformer)35 DataType (org.mule.runtime.api.metadata.DataType)33 ArrayList (java.util.ArrayList)26 PrivilegedEvent (org.mule.runtime.core.privileged.event.PrivilegedEvent)26 Processor (org.mule.runtime.core.api.processor.Processor)25 List (java.util.List)20 Assert.assertThat (org.junit.Assert.assertThat)19 ExpectedException (org.junit.rules.ExpectedException)19 MuleContextUtils.eventBuilder (org.mule.tck.util.MuleContextUtils.eventBuilder)19 Map (java.util.Map)18 Rule (org.junit.Rule)18 MockConverterBuilder (org.mule.runtime.core.internal.transformer.builder.MockConverterBuilder)18 ExpectedException.none (org.junit.rules.ExpectedException.none)17 MockTransformerBuilder (org.mule.runtime.core.internal.transformer.builder.MockTransformerBuilder)17 TypedValue (org.mule.runtime.api.metadata.TypedValue)16