com.consol.citrus.message.Message Java Examples

The following examples show how to use com.consol.citrus.message.Message. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SoapMessageHelper.java    From citrus-simulator with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new SOAP message representation from given payload resource. Constructs a SOAP envelope
 * with empty header and payload as body.
 *
 * @param message
 * @return
 * @throws IOException
 */
public Message createSoapMessage(Message message) {
    try {
        String payload = message.getPayload().toString();

        LOG.info("Creating SOAP message from payload: " + payload);

        WebServiceMessage soapMessage = soapMessageFactory.createWebServiceMessage();
        transformerFactory.newTransformer().transform(
                new StringSource(payload), soapMessage.getPayloadResult());

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        soapMessage.writeTo(bos);

        return new SoapMessage(new String(bos.toByteArray()), message.getHeaders());
    } catch (Exception e) {
        throw new CitrusRuntimeException("Failed to create SOAP message from payload resource", e);
    }
}
 
Example #2
Source File: SoapMessageHelper.java    From citrus-simulator with Apache License 2.0 6 votes vote down vote up
/**
 * Method reads SOAP body element from SOAP Envelope and transforms body payload to String.
 *
 * @param request
 * @return
 * @throws javax.xml.soap.SOAPException
 * @throws java.io.IOException
 * @throws javax.xml.transform.TransformerException
 */
public String getSoapBody(Message request) throws SOAPException, IOException, TransformerException {
    MessageFactory msgFactory = MessageFactory.newInstance();
    MimeHeaders mimeHeaders = new MimeHeaders();
    mimeHeaders.addHeader("Content-Type", "text/xml; charset=" + Charset.forName(System.getProperty("citrus.file.encoding", "UTF-8")));

    SOAPMessage message = msgFactory.createMessage(mimeHeaders, new ByteArrayInputStream(request.getPayload().toString().getBytes(System.getProperty("citrus.file.encoding", "UTF-8"))));
    SOAPBody soapBody = message.getSOAPBody();

    Document body = soapBody.extractContentAsDocument();

    StringResult result = new StringResult();
    transformerFactory.newTransformer().transform(new DOMSource(body), result);

    return result.toString();
}
 
Example #3
Source File: WebSocketPushEventsListenerTest.java    From citrus-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void testOnInboundMessage() throws Exception {
    Message inbound = new DefaultMessage("Hello Citrus!");

    reset(restTemplate, context);
    when(restTemplate.exchange(eq("http://localhost:8080/api/connector/message/inbound?processId=MySampleTest"), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))).thenAnswer(invocation -> {
        HttpEntity request = (HttpEntity) invocation.getArguments()[2];

        Assert.assertEquals(request.getBody().toString(), inbound.toString());

        return ResponseEntity.ok().build();
    });

    when(context.getVariables()).thenReturn(Collections.singletonMap(Citrus.TEST_NAME_VARIABLE, "MySampleTest"));
    when(context.getVariable(Citrus.TEST_NAME_VARIABLE)).thenReturn("MySampleTest");

    pushMessageListener.onInboundMessage(inbound, context);
    verify(restTemplate).exchange(eq("http://localhost:8080/api/connector/message/inbound?processId=MySampleTest"), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class));
}
 
Example #4
Source File: WebSocketPushEventsListenerTest.java    From citrus-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void testOnOutboundMessage() throws Exception {
    Message outbound = new DefaultMessage("Hello Citrus!");

    reset(restTemplate, context);
    when(restTemplate.exchange(eq("http://localhost:8080/api/connector/message/outbound?processId=MySampleTest"), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))).thenAnswer(invocation -> {
        HttpEntity request = (HttpEntity) invocation.getArguments()[2];

        Assert.assertEquals(request.getBody().toString(), outbound.toString());

        return ResponseEntity.ok().build();
    });

    when(context.getVariables()).thenReturn(Collections.singletonMap(Citrus.TEST_NAME_VARIABLE, "MySampleTest"));
    when(context.getVariable(Citrus.TEST_NAME_VARIABLE)).thenReturn("MySampleTest");

    pushMessageListener.onOutboundMessage(outbound, context);
    verify(restTemplate).exchange(eq("http://localhost:8080/api/connector/message/outbound?processId=MySampleTest"), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class));
}
 
Example #5
Source File: WebSocketPushEventsListenerTest.java    From citrus-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoContext() throws Exception {
    Message inbound = new DefaultMessage("Hello Citrus!");

    reset(restTemplate, context);
    when(restTemplate.exchange(eq("http://localhost:8080/api/connector/message/inbound?processId="), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))).thenAnswer(invocation -> {
        HttpEntity request = (HttpEntity) invocation.getArguments()[2];

        Assert.assertEquals(request.getBody().toString(), inbound.toString());

        return ResponseEntity.ok().build();
    });

    pushMessageListener.onInboundMessage(inbound, null);
    pushMessageListener.onInboundMessage(inbound, context);

    verify(restTemplate, times(2)).exchange(eq("http://localhost:8080/api/connector/message/inbound?processId="), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class));
}
 
Example #6
Source File: ContentBasedJsonPathScenarioMapper.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public String extractMappingKey(Message request) {
    if (!StringUtils.hasText(request.getPayload(String.class))) {
        return null;
    }

    Optional<String> v = keyExtractors.stream()
            .map(keyExtractor -> lookupScenarioName(request, keyExtractor))
            .filter(Optional::isPresent)
            .map(Optional::get)
            .filter(mappingKeyFilter)
            .findFirst();
    return v.orElse(null);
}
 
Example #7
Source File: ContentBasedXPathScenarioMapper.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public String extractMappingKey(Message request) {
    if (!StringUtils.hasText(request.getPayload(String.class))) {
        return null;
    }

    Optional<String> v = keyExtractors.stream()
            .map(keyExtractor -> lookupScenarioName(request, keyExtractor))
            .filter(Optional::isPresent)
            .map(Optional::get)
            .filter(mappingKeyFilter)
            .findFirst();
    return v.orElse(null);
}
 
Example #8
Source File: ContentBasedJsonPathScenarioMapper.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
/**
 * Look up scenario name for given request.
 *
 * @param request
 * @param keyExtractor
 * @return
 */
private Optional<String> lookupScenarioName(Message request, JsonPayloadMappingKeyExtractor keyExtractor) {
    try {
        final String mappingKey = keyExtractor.getMappingKey(request);
        LOG.debug("Scenario-name lookup returned: {}", mappingKey);
        return Optional.of(mappingKey);
    } catch (RuntimeException e) {
        LOG.trace("Scenario-name lookup failed", e);
    }

    LOG.debug("Scenario-name lookup returned: <no-match>");
    return Optional.empty();
}
 
Example #9
Source File: ScenarioMappers.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public String getMappingKey(Message message) {
    return scenarioMapperList.stream()
            .map(mapper -> {
                if (mapper instanceof AbstractScenarioMapper) {
                    ((AbstractScenarioMapper) mapper).setUseDefaultMapping(false);
                }

                try {
                    return Optional.ofNullable(mapper.extractMappingKey(message));
                } catch (Exception e) {
                    return Optional.<String>empty();
                }
            })
            .filter(Optional::isPresent)
            .map(Optional::get)
            .filter(StringUtils::hasLength)
            .filter(key -> scenarioList.parallelStream()
                    .anyMatch(scenario -> {
                        if (scenario instanceof HttpOperationScenario) {
                            return Optional.ofNullable(((HttpOperationScenario) scenario).getOperation())
                                            .map(Operation::getOperationId)
                                            .orElse("")
                                            .equals(key);
                        }

                        return Optional.ofNullable(AnnotationUtils.findAnnotation(scenario.getClass(), Scenario.class))
                                                                    .map(Scenario::value)
                                                                    .orElse("")
                                                                    .equals(key);
                    }))
            .findFirst()
            .orElseGet(() -> super.getMappingKey(message));
}
 
Example #10
Source File: PetstoreConfiguration.java    From yaks with Apache License 2.0 5 votes vote down vote up
@Bean
public EndpointAdapter handlePostRequestAdapter() {
    return new StaticEndpointAdapter() {
        @Override
        protected Message handleMessageInternal(Message message) {
            return new HttpMessage()
                    .contentType(MediaType.APPLICATION_JSON_VALUE)
                    .status(HttpStatus.CREATED);
        }
    };
}
 
Example #11
Source File: ContentBasedXPathScenarioMapper.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
/**
 * Look up scenario name for given request.
 *
 * @param request
 * @param keyExtractor
 * @return
 */
private Optional<String> lookupScenarioName(Message request, XPathPayloadMappingKeyExtractor keyExtractor) {
    try {
        final String mappingKey = keyExtractor.getMappingKey(request);
        LOG.debug("Scenario-name lookup returned: {}", mappingKey);
        return Optional.of(mappingKey);
    } catch (RuntimeException e) {
        LOG.trace("Scenario-name lookup failed", e);
    }

    LOG.debug("Scenario-name lookup returned: <no-match>");
    return Optional.empty();
}
 
Example #12
Source File: AbstractScenarioMapper.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
protected String getMappingKey(Message request) {
    if (properties != null && useDefaultMapping) {
        return properties.getDefaultScenario();
    } else {
        throw new CitrusRuntimeException("Failed to get mapping key");
    }
}
 
Example #13
Source File: ScenarioEndpoint.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public Message receive(TestContext context, long timeout) {
    try {
        Message message = channel.poll(timeout, TimeUnit.MILLISECONDS);
        if (message == null) {
            throw new SimulatorException("Failed to receive scenario inbound message");
        }
        messageReceived(message, context);
        return message;
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new SimulatorException(e);
    }
}
 
Example #14
Source File: ScenarioEndpoint.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public void send(Message message, TestContext context) {
    messageSent(message, context);
    if (responseFutures.isEmpty()) {
        throw new SimulatorException("Failed to process scenario response message - missing response consumer");
    } else {
        responseFutures.pop().complete(message);
    }
}
 
Example #15
Source File: EndpointConsumerInterceptor.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    Object result = methodInvocation.proceed();
    if (isReceiveMethod(methodInvocation)) {
        final Optional<TestContext> testContext = getTestContext(methodInvocation);
        if (testContext.isPresent()) {
            final Optional<Message> message = getMessage(result);
            message.ifPresent(msg -> endpointMessageHandler.handleReceivedMessage(msg, testContext.get()));
        }
    }
    return result;
}
 
Example #16
Source File: EndpointMessageHandler.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
private void saveScenarioMessage(Message message, TestContext context, Direction direction) {
    Optional<Long> executionId = extractExecutionId(context);
    Optional<String> citrusMessageId = extractCitrusMessageId(message);
    if (executionId.isPresent() && citrusMessageId.isPresent()) {
        activityService.saveScenarioMessage(executionId.get(), direction,
                message.getPayload(String.class), citrusMessageId.get(), message.getHeaders());
    }
}
 
Example #17
Source File: EndpointMessageHandler.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
private Optional<String> extractCitrusMessageId(Message message) {
    Object headerValue = message.getHeader(MessageHeaders.ID);
    if (headerValue != null && headerValue instanceof String) {
        String stringHeaderValue = (String) headerValue;
        if (StringUtils.hasText(stringHeaderValue)) {
            return Optional.of(stringHeaderValue);
        }
    }
    return Optional.empty();
}
 
Example #18
Source File: EndpointProducerInterceptor.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    Object result = methodInvocation.proceed();
    if (isSendMethod(methodInvocation)) {
        final Optional<TestContext> testContext = getArgument(methodInvocation, TestContext.class);
        final Optional<Message> message = getArgument(methodInvocation, Message.class);
        if (testContext.isPresent() && message.isPresent()) {
            endpointMessageHandler.handleSentMessage(message.get(), testContext.get());
        }
    }
    return result;
}
 
Example #19
Source File: SimulatorSoapEndpointPoller.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
protected Message processRequestMessage(Message request) {
    try {
        return new SoapMessage(soapMessageHelper.getSoapBody(request), request.getHeaders());
    } catch (Exception e) {
        throw new SimulatorException("Unexpected error while processing SOAP request", e);
    }
}
 
Example #20
Source File: Simulator.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public EndpointAdapter fallbackEndpointAdapter() {
    return new StaticEndpointAdapter() {
        @Override
        protected Message handleMessageInternal(Message message) {
            return new SoapFault()
                    .faultActor("SERVER")
                    .faultCode("{http://localhost:8080/HelloService/v1}HELLO:ERROR-1001")
                    .faultString("Internal server error");
        }
    };
}
 
Example #21
Source File: Simulator.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public EndpointAdapter fallbackEndpointAdapter() {
    return new StaticEndpointAdapter() {
        @Override
        protected Message handleMessageInternal(Message message) {
            return new HttpMessage().status(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    };
}
 
Example #22
Source File: Simulator.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public EndpointAdapter fallbackEndpointAdapter() {
    return new StaticEndpointAdapter() {
        @Override
        protected Message handleMessageInternal(Message message) {
            return new HttpMessage().status(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    };
}
 
Example #23
Source File: Simulator.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public EndpointAdapter fallbackEndpointAdapter() {
    return new StaticEndpointAdapter() {
        @Override
        protected Message handleMessageInternal(Message message) {
            return new SoapFault()
                    .faultActor("SERVER")
                    .faultCode("{http://localhost:8080/HelloService/v1}HELLO:ERROR-1001")
                    .faultString("Internal server error");
        }
    };
}
 
Example #24
Source File: PetstoreConfiguration.java    From yaks with Apache License 2.0 5 votes vote down vote up
@Bean
public EndpointAdapter handlePutRequestAdapter() {
    return new StaticEndpointAdapter() {
        @Override
        protected Message handleMessageInternal(Message request) {
            return new HttpMessage()
                    .contentType(MediaType.APPLICATION_JSON_VALUE)
                    .status(HttpStatus.OK);
        }
    };
}
 
Example #25
Source File: XPathPayloadCorrelationHandler.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isHandlerFor(Message message, TestContext context) {
    boolean isIntermediateMessage;
    try {
        isIntermediateMessage = xPathPayloadMappingKeyExtractor.extractMappingKey(message).equals(context.replaceDynamicContentInString(value));
    } catch (RuntimeException e) {
        LOG.debug("Error checking whether message({}) is an intermediate message: {}", message.getId(), e.getMessage());
        isIntermediateMessage = false;
    }
    LOG.debug("Intermediate message({}): {}", message.getId(), isIntermediateMessage);
    return isIntermediateMessage;
}
 
Example #26
Source File: CorrelationHandlerRegistry.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
/**
 * Finds handler in registered handlers that is able to handle given message. When handler is found return true
 * otherwise false.
 * @param request
 * @return
 */
public CorrelationHandler findHandlerFor(Message request) {
    for (Map.Entry<CorrelationHandler, TestContext> handlerEntry : registeredHandlers.entrySet()) {
        if (handlerEntry.getKey().isHandlerFor(request, handlerEntry.getValue())) {
            return handlerEntry.getKey();
        }
    }

    return null;
}
 
Example #27
Source File: PetstoreConfiguration.java    From yaks with Apache License 2.0 5 votes vote down vote up
@Bean
public EndpointAdapter handleDeleteRequestAdapter() {
    return new StaticEndpointAdapter() {
        @Override
        protected Message handleMessageInternal(Message message) {
            return new HttpMessage()
                    .contentType(MediaType.APPLICATION_JSON_VALUE)
                    .status(HttpStatus.NO_CONTENT);
        }
    };
}
 
Example #28
Source File: HttpEndpointConfiguration.java    From yaks with Apache License 2.0 5 votes vote down vote up
@Bean
public EndpointAdapter handlePostRequestAdapter() {
    return new StaticEndpointAdapter() {
        @Override
        protected Message handleMessageInternal(Message message) {
            return new HttpMessage().status(HttpStatus.CREATED);
        }
    };
}
 
Example #29
Source File: HttpEndpointConfiguration.java    From yaks with Apache License 2.0 5 votes vote down vote up
@Bean
public EndpointAdapter handlePutRequestAdapter() {
    return new StaticEndpointAdapter() {
        @Override
        protected Message handleMessageInternal(Message request) {
            return new HttpMessage(request).status(HttpStatus.OK);
        }
    };
}
 
Example #30
Source File: WebSocketPushEventsListener.java    From citrus-admin with Apache License 2.0 5 votes vote down vote up
/**
 * Push message to citrus-admin connector via REST API.
 * @param processId
 * @param message
 * @param direction
 */
protected void pushMessage(String processId, Message message, String direction) {
    try {
        if (!disabled) {
            ResponseEntity<String> response = getRestTemplate().exchange(getConnectorBaseUrl() + String.format("/message/%s?processId=%s", direction, processId), HttpMethod.POST, new HttpEntity<>(message.toString()), String.class);

            if (response.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
                disabled = true;
            }
        }
    } catch (RestClientException e) {
        log.error("Failed to push message to citrus-admin connector", e);
    }
}