interceptSendToEndpoint не перехватывает http-запрос в Route, используя Camel и Springboot - PullRequest
0 голосов
/ 30 апреля 2019

Я пытаюсь написать модульный тест для моего маршрута, который получает сообщение, выполняет внешний вызов веб-службы и затем обрабатывает ответ.Тем не менее, я не могу посмеяться над внешним вызовом веб-службы.Я попробовал следующее:

@RunWith(CamelSpringBootRunner.class)
@SpringBootTest
@DirtiesContext(classMode = 
DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@MockEndpoints
@UseAdviceWith
public class TypeServiceRoutersTest
{

@Autowired
private CamelContext camelContext;

@Autowired
private GetTypesProcess getTypesProcess;

@Produce(uri = "direct:start")
private ProducerTemplate incomingJmsRequestMessage;

@EndpointInject(uri = "mock:JMSReplyTo")
private MockEndpoint jmsReplyTo;

@Before
public void setUp()throws Exception{

    camelContext.getRouteDefinition("Build XML Response").adviceWith(camelContext,
            new AdviceWithRouteBuilder() {
                @Override
                public void configure() throws Exception {
                    weaveAddLast().to("mock:JMSReplyTo");
                }
            });

    camelContext.getRouteDefinition("Build & Send Http Request").adviceWith(camelContext,
            new AdviceWithRouteBuilder() {
                @Override
                public void configure() throws Exception {
                    interceptSendToEndpoint("http://*")
                            .skipSendToOriginalEndpoint()
                            .setBody("Hello");

    camelContext.start();
}

@Test
@DirtiesContext
public void RouteFlowTest() throws Exception{

    Map<String,Object> jmsHeaders = new HashMap<>();
    jmsHeaders.put("Auth","helloWorld");
    jmsHeaders.put("JMSReplyTo","sample");

    String jmsBody = "Hi"
    incomingJmsRequestMessage.sendBodyAndHeaders("direct:start", jmsBody, jmsHeaders);

    jmsReplyTo.expectedMessageCount(1);

    jmsReplyTo.assertIsSatisfied();


}

@After
public void cleanUpCamelContext() throws Exception{
    camelContext.stop();
}

}

Мой маршрут выглядит следующим образом:

@Override
public void configure() throws Exception {

    onException(Exception.class)
            .handled(true)
            .log(LoggingLevel.INFO,log,"${exception.stacktrace}")
            .bean(getTypesProcess,"processFailure")
            .end();

    from("{{jms.input.queue}}"+"?exchangePattern=InOut").routeId("Receive JMS Message")
        .log(LoggingLevel.INFO,log,"New message received on Queue")
        .to("direct:start");


    from("direct:start").routeId("Build & Send Http Request")
            .bean(getTypesProcess,"processRequest")
            .log(LoggingLevel.DEBUG,log,"Processed Request and built http request")
            .to("{{http.endpoints.GetTypes}}")
            .to("direct:processResponse");

    from("direct:processResponse").routeId("Build XML Response")
            .convertBodyTo(String.class)
            .bean(getTypesProcess, "processResponse");

}

Но когда я запускаю свой тест, звонок в веб-службу все ещеполучает запуск:

.to("{{http.endpoints.GetTypes}}")

В результате мой тест не удается из-за 403 от веб-службы.Я не уверен, что я сделал неправильно?

В журналах указано, что маршрут был изменен, но также показано, что вызывается конечная точка:

2019-04-30 14:44:13.938  INFO 1007 --- [           main] org.apache.camel.model.RouteDefinition   : Adviced route before/after as XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<route xmlns="http://camel.apache.org/schema/spring" customId="true" id="Build Send Http Request">
    <from uri="direct:start"/>
    <onException>
        <log loggingLevel="INFO" message="${exception.stacktrace}"/>
        <bean method="processFailure"/>
    </onException>
    <bean method="processRequest"/>
    <log loggingLevel="DEBUG" message="Processed Request and built http request"/>
    <to uri="http://help.co.za:10108"/>
    <to uri="direct:processResponse"/>
</route>

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<route xmlns="http://camel.apache.org/schema/spring" customId="true" id="Build Send Http Request">
    <from uri="direct:start"/>
    <onException>
        <log loggingLevel="INFO" message="${exception.stacktrace}"/>
        <bean method="processFailure"/>
    </onException>
    <interceptSendToEndpoint skipSendToOriginalEndpoint="true" uri="http*">
        <setBody>
            <simple>Hello</simple>
        </setBody>
    </interceptSendToEndpoint>
    <bean method="processRequest"/>
    <log loggingLevel="DEBUG" message="Processed Request and built http request"/>
    <to uri="http://help.co.za:10108"/>
    <to uri="direct:processResponse"/>
</route>

2019-04-30 14:44:13.940  INFO 1007 --- [           main] o.a.camel.spring.SpringCamelContext      : Apache Camel 2.23.2 (CamelContext: camel-1) is starting
2019-04-30 14:44:13.941  INFO 1007 --- [           main] o.a.c.m.ManagedManagementStrategy        : JMX is enabled
2019-04-30 14:44:14.120  INFO 1007 --- [           main] .c.i.InterceptSendToMockEndpointStrategy : Adviced endpoint [http://help.co.za:10108] with mock endpoint [mock:http:help.co.za:10108]
2019-04-30 14:44:14.125  INFO 1007 --- [           main] .c.i.InterceptSendToMockEndpointStrategy : Adviced endpoint [direct://processResponse] with mock endpoint [mock:direct:processResponse]
2019-04-30 14:44:14.151  INFO 1007 --- [           main] .c.i.InterceptSendToMockEndpointStrategy : Adviced endpoint [jms://queue.sample?exchangePattern=InOut] with mock endpoint [mock:jms:queue.sample]
2019-04-30 14:44:14.165  INFO 1007 --- [           main] o.a.camel.spring.SpringCamelContext      : StreamCaching is not in use. If using streams then its recommended to enable stream caching. See more details at http://camel.apache.org/stream-caching.html
2019-04-30 14:44:14.259  INFO 1007 --- [           main] o.a.camel.spring.SpringCamelContext      : Route: Build Send Http Request started and consuming from: direct://start
2019-04-30 14:44:14.259  INFO 1007 --- [           main] o.a.camel.spring.SpringCamelContext      : Route: Build XML Response started and consuming from: direct://processResponse
2019-04-30 14:44:14.291  INFO 1007 --- [           main] o.a.camel.spring.SpringCamelContext      : Route: Receive JMS Message started and consuming from: jms://queue.sample?exchangePattern=InOut
2019-04-30 14:44:14.293  INFO 1007 --- [           main] o.a.camel.spring.SpringCamelContext      : Route: route1 started and consuming from: direct://jmsMessage
2019-04-30 14:44:14.294  INFO 1007 --- [           main] o.a.camel.spring.SpringCamelContext      : Route: route2 started and consuming from: direct://jsonResponse
2019-04-30 14:44:14.294  INFO 1007 --- [           main] o.a.camel.spring.SpringCamelContext      : Total 5 routes, of which 5 are started
2019-04-30 14:44:14.295  INFO 1007 --- [           main] o.a.camel.spring.SpringCamelContext      : Apache Camel 2.23.2 (CamelContext: camel-1) started in 0.355 seconds
2019-04-30 14:44:14.478  INFO 1007 --- [           main] c.i.o.r.OP_GetTypes.TypeServiceRouter    : org.apache.camel.http.common.HttpOperationFailedException: HTTP operation failed invoking http://help.co.za:10108/ with statusCode: 404
    at org.apache.camel.component.http.HttpProducer.populateHttpOperationFailedException(HttpProducer.java:273)```

1 Ответ

0 голосов
/ 30 апреля 2019

Попробуйте изменить аргумент на interceptSendToEndpoint, как показано ниже.

interceptSendToEndpoint("http://.*")

Похоже, что RegEx не совпадает с конечной точкой http, так как один только символ * не совпадает. Но .* соответствует всем символам после http://

...