I have setup my current project to run with Selenium and PhantomJS. (Similar setup to http://www.nuanced.it/2015/05/using-phantomjs-with-phpunit.html)
However I keep on getting following error
{"errorMessage":"Can only set Cookies for the current domain","request":{"headers":{"Accept":"application/json;charset=UTF-8","Content-Length":"135","Content-type":"application/json;charset=UTF-8","Host":"127.0.0.1:8080"},"httpVersion":"1.1","method":"POST","post":"{\"cookie\":{\"name\":\"PHPUNIT_SELENIUM_TEST_ID\",\"value\":\"PepperLeaf\\\\WebBundle\\\\Tests\\\\MyProject\\\\TestFirstTest__testTitle\",\"secure\":false}}","url":"/cookie","urlParsed":{"anchor":"","query":"","file":"cookie","directory":"/","path":"/cookie","relative":"/cookie","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/cookie","queryKey":{},"chunks":["cookie"]},"urlOriginal":"/session/0d022670-4f79-11e5-abbe-01f06bc40b42/cookie"}}
Output from PhantomJS
[INFO - 2015-08-31T00:41:02.249Z] HUB Register - register - Registered with grid hub: http://127.0.0.1:4444/ (ok)
[INFO - 2015-08-31T00:41:43.258Z] Session [0d022670-4f79-11e5-abbe-01f06bc40b42] - page.settings - {"XSSAuditingEnabled":false,"javascriptCanCloseWindows":true,"javascriptCanOpenWindows":true,"javascriptEnabled":true,"loadImages":true,"localToRemoteUrlAccessEnabled":false,"userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.0.0 Safari/538.1","webSecurityEnabled":true}
[INFO - 2015-08-31T00:41:43.258Z] Session [0d022670-4f79-11e5-abbe-01f06bc40b42] - page.customHeaders: - {}
[INFO - 2015-08-31T00:41:43.258Z] Session [0d022670-4f79-11e5-abbe-01f06bc40b42] - Session.negotiatedCapabilities - {"browserName":"phantomjs","version":"2.0.0","driverName":"ghostdriver","driverVersion":"1.2.0","platform":"mac-10.9 (Mavericks)-64bit","javascriptEnabled":true,"takesScreenshot":true,"handlesAlerts":false,"databaseEnabled":false,"locationContextEnabled":false,"applicationCacheEnabled":false,"browserConnectionEnabled":false,"cssSelectorsEnabled":true,"webStorageEnabled":false,"rotatable":false,"acceptSslCerts":false,"nativeEvents":true,"proxy":{"proxyType":"direct"}}
[INFO - 2015-08-31T00:41:43.258Z] SessionManagerReqHand - _postNewSessionCommand - New Session Created: 0d022670-4f79-11e5-abbe-01f06bc40b42
Code that I run on PHPUnit
class TestFirstTest extends \PHPUnit_Extensions_Selenium2TestCase {
/**
* {#inheritDoc}
*/
protected function setUp()
{
$this->setBrowser('phantomjs');
$this->setHost("127.0.0.1");
$this->setPort(8080);
$this->setBrowserUrl('http://www.mywebsite.dev/');
}
public function testTitle()
{
$this->url('/');
$this->assertTitle('Example WWW Page');
}
}
Disclaimer: I'm quite new to front end testing, this is my first go at this. I'm confused why this would be happening as I'm not setting up nor creating any cookies/sessions.
I'm not sure exactly what has caused this problem. However, this is my symfony/phpunit.xml (this is what has caused problems)
<!-- http://www.phpunit.de/manual/current/en/appendixes.configuration.html -->
<phpunit
backupGlobals = "false"
backupStaticAttributes = "false"
colors = "false"
convertErrorsToExceptions = "true"
convertNoticesToExceptions = "true"
convertWarningsToExceptions = "true"
processIsolation = "false"
stopOnFailure = "false"
syntaxCheck = "false"
bootstrap = "../app/bootstrap.php.cache" >
<testsuites>
<testsuite name="PepperLeaf">
<directory>../src/*/*Bundle/Tests</directory>
<directory>../src/*/Bundle/*Bundle/Tests</directory>
</testsuite>
</testsuites>
<php>
<server name="KERNEL_DIR" value="app/" />
<ini name="memory_limit" value="2048M" />
<ini name="xdebug.max_nesting_level" value="500" />
</php>
<filter>
<whitelist addUncoveredFilesFromWhitelist="true">
<directory suffix=".php">../src</directory>
<exclude>
<directory>../src/*/*Bundle/Resources</directory>
<directory>../src/*/*Bundle/Tests</directory>
<directory>../src/*/Bundle/*Bundle/Resources</directory>
<directory>../src/*/Bundle/*Bundle/Tests</directory>
<directory>../src/*/Bundle/*Bundle/FrontTests</directory>
<directory>../src/*/Bundle/*Bundle/DataFixtures</directory>
</exclude>
</whitelist>
</filter>
<logging>
<log type="coverage-html" target="coverage" />
<log type="coverage-xml" target="coverage/xml" />
<log type="coverage-clover" target="logs/clover.xml" />
<log type="coverage-crap4j" target="logs/crap4j.xml" />
<log type="junit" target="logs/junit.xml" logIncompleteSkipped="false" />
</logging>
</phpunit>
This is updated (working phpunit.xml script that WORKS). I'm not sure what exactly caused the problem above.
<?xml version="1.0" encoding="UTF-8"?>
<!-- http://www.phpunit.de/manual/current/en/appendixes.configuration.html -->
<phpunit>
<testsuites>
<testsuite name="PepperLeaf_Frontend">
<directory>../src/*/*Bundle/FrontTests</directory>
</testsuite>
</testsuites>
<php>
<server name="KERNEL_DIR" value="app/" />
<ini name="memory_limit" value="2048M" />
<ini name="xdebug.max_nesting_level" value="500" />
</php>
<filter>
<whitelist addUncoveredFilesFromWhitelist="true">
<directory suffix=".php">../src</directory>
<exclude>
<directory>../src/*/*Bundle/Resources</directory>
<directory>../src/*/*Bundle/Tests</directory>
<directory>../src/*/Bundle/*Bundle/Resources</directory>
<directory>../src/*/Bundle/*Bundle/Tests</directory>
<directory>../src/*/Bundle/*Bundle/DataFixtures</directory>
<directory>../src/*/*Bundle/FrontTests</directory>
</exclude>
</whitelist>
</filter>
</phpunit>
Related
I read through the following documentation but cannot figure out what other configuration I need: https://github.com/logstash/logstash-logback-encoder#header-fields
My config file:
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
<property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}/spring.log}"/>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<customFields>{"app_name":"${APP_NAME:-N/A}","app_version":"${APP_VERSION:-N/A}","hostname":"${HOST:-N/A}","environment":"${environment:-${ENVIRONMENT:-N/A}}"}</customFields>
<includeContext>false</includeContext>
<timeZone>UTC</timeZone>
</encoder>
<encoder class="net.logstash.logback.encoder.LogstashAccessEncoder">
<fieldNames>
<requestHeaders>request_headers</requestHeaders>
</fieldNames>
</encoder>
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE_ROTATION:-${LOG_FILE}%d{yyyy-MM-dd}.%i}</fileNamePattern>
<maxHistory>${LOG_FILE_ROTATION_MAX_HISTORY:-1}</maxHistory>
<totalSizeCap>${LOG_FILE_ROTATION_TOTAL_SIZE_CAP:-3GB}</totalSizeCap>
<maxFileSize>${LOG_FILE_ROTATION_MAX_FILE_SIZE:-1GB}</maxFileSize>
</rollingPolicy>
</appender>
<root level="${LOG_LEVEL:-INFO}">
<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
</root>
</configuration>
Error:
java.lang.IllegalStateException: Logback configuration error detected:
ERROR in ch.qos.logback.core.joran.spi.Interpreter#19:29 - no applicable action for [requestHeaders], current ElementPath is [[configuration][appender][encoder][fieldNames][requestHeaders]]
The xml configuration file you provided appears to be for logback-classic (since it includes <root level=...).
Automatic logging of request headers by logstash-logback-encoder is only available for IAccessEvents logged via logback-access.
In other words, automatic logging of request headers is not available for ILoggingEvents logged via a Logger from logback-classic. However, you can manually include them when using logback-classic as described below.
Logging of request headers with logback-access
To log request headers for IAccessEvents logged via logback-access, follow the instructions for setting up logback-access for tomcat or jetty, and add the following to your logback-access.xml. (Note this is not the logback.xml file used by logback-classic)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="net.logstash.logback.encoder.LogstashAccessEncoder">
<fieldNames>
<requestHeaders>request_headers</requestHeaders>
</fieldNames>
</encoder>
</appender>
<appender-ref ref="console"/>
</configuration>
This configuration was tested using logstash-logback-encoder 5.3. Note that the xml element names are different in logstash-logback-encoder versions prior to 5.0, so ensure you are using 5.0+ with that configuration.
Logging of request headers with logback-classic
logstash-logback-encoder does not provide first-class support for logging request headers via logback-classic. However, you include them in a log event logged via a Logger by using event-specific custom fields.
For example, in a class that has access to the http request (such as a servlet filter), you could do something like this:
Map<String, String> httpHeadersMap = ...; // get http request headers as a map
LOGGER.info("request", StructuredArguments.entries(httpHeadersMap));
and configure a LogbackEncoder in your logback.xml like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="net.logstash.logback.encoder.LogstashEncoder"/>
</appender>
<root level="info">
<appender-ref ref="console" />
</root>
</configuration>
I am running NServiceBus 5.2.14 with NServiceBus.Host 6.0.0
I am using MSMQ as transport and RavenDBPersistence.
All queues appear in computer management except for the error queue.
Everything functions fine for messages and endpoints. Errors are retried 5 times as they should. However after retrying 5 times they do not appear in the error queue.
I have specified the error queue in as such:
<MessageForwardingInCaseOfFaultConfig ErrorQueue="error" />
and included in configSections:
<section name="MessageForwardingInCaseOfFaultConfig" type="NServiceBus.Config.MessageForwardingInCaseOfFaultConfig, NServiceBus.Core" />
Edit1: app.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" />
<section name="TransportConfig" type="NServiceBus.Config.TransportConfig, NServiceBus.Core" />
<section name="MessageForwardingInCaseOfFaultConfig" type="NServiceBus.Config.MessageForwardingInCaseOfFaultConfig, NServiceBus.Core" />
</configSections>
<TransportConfig MaximumConcurrencyLevel="5" MaxRetries="5" />
<MessageForwardingInCaseOfFaultConfig ErrorQueue="error" />
<UnicastBusConfig ForwardReceivedMessagesTo="audit">
<MessageEndpointMappings>
...
</MessageEndpointMappings>
</UnicastBusConfig>
...
Edit2 : endpointconfig:
public class EndpointConfig : IConfigureThisEndpoint, AsA_Server
{
...
public void Customize(BusConfiguration busConfiguration)
{
...
var containerFactory = new ContainerFactory();
Container.InitializeContainer(containerFactory);
AutoMapperInitializer.Configure();
busConfiguration.AssembliesToScan(AllAssemblies.Matching("NServiceBus").And("OurProjectName."));
busConfiguration.UseTransport<MsmqTransport>();
busConfiguration.EndpointName(ConfigurationManager.AppSettings["InputQueueName"]);
busConfiguration.UseContainer<WindsorBuilder>(customizations => customizations.ExistingContainer(Container.Instance));
busConfiguration.UsePersistence<RavenDBPersistence>();
busConfiguration.EnableCriticalTimePerformanceCounter();
busConfiguration.RegisterComponents(components => { components.ConfigureComponent<UsernameForwarder>(DependencyLifecycle.InstancePerCall); });
...
}
}
I run the endpoints in self-hosting console. In the list of FEATURES I see this:
Name: ForwarderFaultManager
Version: 5.2.14
Enabled by Default: Yes
Status: Disabled
Deactivation reason: Did not meet one of the dependencies:
Name: InMemoryFaultManager
Version: 5.2.14
Enabled by Default: No
Status: Enabled
Dependencies: None
Startup Tasks: None
I suspect my problem is with the ForwarderFaultManager, however there is nothing listed in the missing dependencies list. What may I be missing? Where could I start looking?
I am new to the wso2 esb server and I am trying to create a proxy service to connect to a rest service. I am having issue trying to test the proxy when in the "Deployed Services" page of the esb. The source view of the proxy service is:
> <?xml version="1.0" encoding="UTF-8"?>
> <proxy xmlns="http://ws.apache.org/ns/synapse"
> name="search"
> transports="https,http,local"
> statistics="disable"
> trace="disable"
> startOnLoad="true">
> <target>
> <outSequence>
> <send/>
> </outSequence>
> <faultSequence>
> <log level="full" category="DEBUG"/>
> </faultSequence>
> <endpoint>
> <http method="get" uri-template="http://52.24.50.197:8080/search"/>
> <property name="q" value="test"/>
> </endpoint> </target> <description/> </proxy>
I click on "Try this Service" link and I get this in the console:
[2015-05-19 09:06:43,573] DEBUG - SynapseMessageReceiver Synapse received a new message for message mediation...
[2015-05-19 09:06:43,574] DEBUG - SynapseMessageReceiver Received To: /services/mediate/mediate
[2015-05-19 09:06:43,575] DEBUG - SynapseMessageReceiver SOAPAction: null
[2015-05-19 09:06:43,575] DEBUG - SynapseMessageReceiver WSA-Action: null
[2015-05-19 09:06:43,575] DEBUG - Axis2SynapseEnvironment Injecting MessageContext
[2015-05-19 09:06:43,576] DEBUG - Axis2SynapseEnvironment Using Main Sequence for injected message
[2015-05-19 09:06:43,576] DEBUG - SequenceMediator Start : Sequence <main>
[2015-05-19 09:06:43,576] DEBUG - SequenceMediator Sequence <SequenceMediator> :: mediate()
[2015-05-19 09:06:43,577] DEBUG - SequenceMediator Mediation started from mediator position : 0
[2015-05-19 09:06:43,577] DEBUG - InMediator Start : In mediator
[2015-05-19 09:06:43,578] DEBUG - InMediator Current message is incoming - executing child mediators
[2015-05-19 09:06:43,578] DEBUG - InMediator Sequence <InMediator> :: mediate()
[2015-05-19 09:06:43,578] DEBUG - InMediator Mediation started from mediator position : 0
[2015-05-19 09:06:43,579] DEBUG - LogMediator Start : Log mediator
[2015-05-19 09:06:43,579] INFO - LogMediator To: /services/mediate/mediate, MessageID: urn:uuid:e2c5b5f7-3c2c-4969-9c0b-6aa4d8282f2d, Direction: requ
st, Envelope: <?xml version="1.0" encoding="utf-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body></soapen
:Body></soapenv:Envelope>
[2015-05-19 09:06:43,580] DEBUG - LogMediator End : Log mediator
[2015-05-19 09:06:43,581] DEBUG - FilterMediator Start : Filter mediator
[2015-05-19 09:06:43,581] DEBUG - FilterMediator Source : get-property('To') against : http://localhost:9000.* does not match - skipping child mediato
s
[2015-05-19 09:06:43,582] DEBUG - FilterMediator End : Filter mediator
[2015-05-19 09:06:43,582] DEBUG - InMediator End : In mediator
[2015-05-19 09:06:43,582] DEBUG - OutMediator Start : Out mediator
[2015-05-19 09:06:43,583] DEBUG - OutMediator Current message is a request - skipping child mediators
[2015-05-19 09:06:43,583] DEBUG - OutMediator End : Out mediator
[2015-05-19 09:06:43,584] DEBUG - SequenceMediator End : Sequence <main>
Can someone explain to me why the data is not coming back.We have open the ports to the server the service resides, which is port 8080.
Thanks
It seems that you´re pointing to the wrong URL in ESB. The log shows a message received for the folowing URI: /services/mediate/mediate. Since your proxy is named "search", it should be something link /services/search.
Also, I see that your http endpoint template is not taking any parameters, which probably is not what you want.
The send mediator should look something like that:
<inSequence>
<!-- Assigns URI-Template var to some value. You could use an expression here too -->
<property name="uri.var.search" value="test"/>
</inSequence>
<outSequence>
<send/>
</outSequence>
<endpoint>
<html uri-template="http://52.24.50.197:8080/search?q={uri.var.search}" method="GET"/>
</endpoint>
Rather define your endpoint outside the proxy , so in the ESB main console create your endpoint :
<endpoint xmlns="http://ws.apache.org/ns/synapse" name="HTTPEndpoint">
<http uri-template="http://{uri.var.ip}:8080/{uri.var.servicepath} method="GET">
</http>
</endpoint>
Then try out this proxy :
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse" name="search"
transports="https,http,local"
statistics="disable"
trace="disable"
startOnLoad="true">
<target>
<inSequence>
<property name="uri.var.ip" value="52.24.50.197"/>
<property name="uri.var.servicepath" value="search"/>
<send>
<endpoint key="MyHTTPEndpoint"/>
</send>
</inSequence>
<outSequence>
<respond/>
</outSequence>
<faultSequence>
<log level="full" category="DEBUG"/>
</faultSequence>
</target> <description/> </proxy>
So you will be sending the get request to the proxy endpoint , that will forward it to the service , and show response , hopefully.
I am able to use a Logback PropertyDefiner to access a single property from a logback.xml configuration file. If I have 3 properties to access, I am currently using 3 separate implementations of PropertyDefiner (one for each property).
Is there a way to access multiple properties from a single PropertyDefiner implementation? Or perhaps there is another interface that supports multiple properties?
I want to be be able to use properties to plugin different values, based on environment (dev, ist, uat, perf, prod) for various logging configurations (context name, log levels, appender file names, file sizes, etc.).
I found this question, which is similar, but did not answer the question of how to access multiple properties.
Create a PropertyDefiner implementation class. The PropertyDefinerBase implementation is already provided.
package foo.bar;
import java.util.HashMap;
import java.util.Map;
import ch.qos.logback.core.PropertyDefinerBase;
public class LoggingPropertiesDefiner extends PropertyDefinerBase {
private static Map<String, String> properties = new HashMap<>();
static {
properties.put("encoderPattern", "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %message%n");
properties.put("maxFileSize", "50MB");
properties.put("rootLogLevel", "INFO");
}
private String propertyLookupKey;
public void setPropertyLookupKey(String propertyLookupKey) {
this.propertyLookupKey = propertyLookupKey;
}
#Override
public String getPropertyValue() {
//TODO In the real world, get properties from a properties loader.
return properties.get(propertyLookupKey);
}
}
In the logback.xml, use the same PropertyDefiner class for each property. Provide a different lookup key for each:
<define name="encoderPattern" class="foo.bar.LoggingPropertiesDefiner">
<propertyLookupKey>encoderPattern</propertyLookupKey>
</define>
<define name="maxFileSize" class="foo.bar.LoggingPropertiesDefiner">
<propertyLookupKey>maxFileSize</propertyLookupKey>
</define>
<define name="rootLogLevel" class="foo.bar.LoggingPropertiesDefiner">
<propertyLookupKey>rootLogLevel</propertyLookupKey>
</define>
Reference the property names in the logback.xml:
<root level="${rootLogLevel}">
<appender-ref ref="FILE"/>
</root>
You could use the property resource support from logback
logback.properties
mode=prod
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true">
<property resource="logback.properties" />
<if condition='property("mode").equals("prod")'>
<then>
<include file="logback-prod.xml" />
</then>
</if>
<if condition='property("mode").equals("dev")'>
<then>
<include resource="logback-dev.xml" />
</then>
</if>
</configuration>
logback-prod.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--Daily rolling file appender -->
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${MYAPP_HOME}/myApp.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>myApp.%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>2</MaxHistory>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</Pattern>
</layout>
</appender>
<root level="ERROR">
<appender-ref ref="file" />
</root>
</configuration>
logback-dev.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--Daily rolling file appender -->
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${MYAPP_HOME}/myApp.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>myApp.%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>2</MaxHistory>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</Pattern>
</layout>
</appender>
<root level="TRACE">
<appender-ref ref="file" />
</root>
</configuration>
More detailed explaination here.
Does that help to resolve your problem?
I'm trying to set a property isEven on the Exchange.property and then use choice when to evaluate it in the route.
The property is being set but I am always getting the otherwise result (NACK) no matter what isEven is set to.
Here is where I set it:
// Below is used for development
// If the property.isEven == true then an ACK will be returned from the Mock HRM
// If false then NACK
int lastDigit = Integer.parseInt(exchange.getExchangeId().substring(exchange.getExchangeId().length() - 1));
// check if lastDigit is odd or even
if ((lastDigit & 1) == 0)
{
exchange.setProperty("isEven", Boolean.TRUE);
System.out.println("\n\n\n********** Exchange Id lastDigit " + lastDigit + " isEven: " + exchange.getProperty("isEven") + " ***********");
}
else
{
exchange.setProperty("isEven", Boolean.FALSE);
System.out.println("\n\n\n********** Exchange Id lastDigit " + lastDigit + " isEven: " + exchange.getProperty("isEven") + " ***********");
}
The println's show that I am setting isEven the way I expect.
Here is the route:
<!-- Used to ramdomly send Ack or Nack -->
<log message="isEven property is :: ${property[isEven]}" />
<camel:choice>
<camel:when>
<simple>"${property[isEven]}"</simple>
<transform>
<constant>ACK</constant>
</transform>
</camel:when>
<camel:otherwise>
<transform>
<constant>NACK</constant>
</transform>
</camel:otherwise>
</camel:choice>
The log message never evaluates the expression ${property[isEven]}
Here is the output
log[isEven property is :: ${property[isEven]}]
if I change the simple expression to explicitly check for true I alway get ACK no matter what the property is set to.
<simple>"${property[isEven]} == true"</simple>
I have searched the web but couldn't find a lot of examples using simple and Exchange property.
Can anyone see what I'm missing?
Thanks,
Andrew
After Peter showed he could do it easily I tried 2 of his examples that I hadn't tried already. Here is one. It didn't work for me. It generated Hello :: NACK whether isEven is true or false:
<camel:choice>
<camel:when>
<simple>${property[isEven]} == "true"</simple>
<log message="HELLO :: ACK" />
<!-- <transform>
<constant>ACK</constant>
</transform> -->
</camel:when>
<camel:otherwise>
<log message="HELLO :: NACK" />
<!-- <transform>
<constant>NACK</constant>
</transform> -->
</camel:otherwise>
</camel:choice>
Here is something interesting. It looks below like the log is saying its empty On the last like
********** Exchange Id lastDigit 2 isEven: true ***********
14/02/20 14:09:13 INFO interceptor.Tracer: >>> (toHRMRoute) bean://hl7handler?method=handleORM --> log[isEven property is :: ${property[isEven]}] <<< Pattern:InOut, Properties {CamelToEndpoint=bean://hl7handler?method=handleORM, CamelMessageHistory [DefaultMessageHistory[routeId=toHRMRoute, node=to3], DefaultMessage History[routeId=toHRMRoute, node=log1]], CamelCreatedTimestamp=Thu Feb 20 14:09:13 CST 2014}
14/02/20 14:09:13 INFO toHRMRoute: ** isEven property is :: **
I think Peter is correct in that it has to be the way I have my routes set up.
<endpoint id="hrmMockHL7Listener"
uri="netty:tcp://localhost:9200?sync=true" />
<!-- Sending data using postman to a rest server-->
<route id="pushRESTRoute">
<from uri="cxfrs://bean://pushRESTServer" />
<!-- this process is where we set isEven on the Exchange-->
<process ref="transformer"/>
<!-- Send it to a tcp listener at port 9200-->
<to ref="hrmMockHL7Listener" />
</route>
<!-- Changed routes does the Exchange keep properties? -->
<route id="toMRoute">
<from uri="hrmMockHL7Listener" />
<to uri="bean:hl7handler?method=handleORM" />
<!-- Used to ramdomly send Ack or Nack -->
<log message="isEven property is :: ${property[isEven]}">
// see the beginning of the question for choice code.
Looking at the output it seems the isEven property is being dropped between routes:
14/02/21 09:37:26 INFO interceptor.Tracer: >>> (pushRESTRoute) ref:transformer --> tcp://localhost:9200 <<< Pattern:InOut, Properties {CamelMessageHistory=[DefaultMessageHistory[routeId=pushRESTRoute, node=process1], DefaultMessageHistory[routeId=pushRESTRoute, node=to1]], CamelCreatedTimestamp=Fri Feb 21 09:37:26 CST 2014, isEven=true}
See isEven at the end? The next tracer that comes doesn't have it
/02/21 09:37:26 INFO interceptor.Tracer: >>> (toMRoute) from(tcp://localhost:9200) --> bean://hl7handler?method=handleORM <<< Pattern:InOut, Properties:{CamellMessageHistory=[DefaultMessageHistory[routeId=toMRoute, node=to3]], CamelCreatedTimestamp=Fri Feb 21 09:37:26 CST 2014}
From the Exchange javadoc
An Exchange is the message container holding the information during the entire routing of a Message received by a Consumer.
Does entire include across differents routes?
For testing I changed the route a little bit:
<route id="startRoute">
<from uri="direct:start" />
<multicast stopOnException="true">
<to uri="direct:trigger" />
<to uri="direct:trigger" />
<to uri="direct:trigger" />
</multicast>
</route>
<route>
<from uri="direct:trigger" />
<process ref="myProcessor" />
<log message="isEven property is :: ${property[isEven]}" />
<camel:choice>
<camel:when>
<simple>"${property.isEven}"</simple>
<log message="HELLO :: ACK" />
</camel:when>
<camel:otherwise>
<log message="HELLO :: NACK" />
</camel:otherwise>
</camel:choice>
</route>
<!-- scope singleton is default -->
<bean id="myProcessor" class="ch.keller.test.testcamelspring.util.Trigger" scope="singleton" />
The processor is defined as follows:
public class Trigger implements Processor {
#Override
public void process(final Exchange exchange) throws Exception {
// your code comes here
}
}
For me, following expressions worked as expected:
<simple>"${property[isEven]}"</simple>
or
<simple>${property[isEven]}</simple>
or
<simple>${property[isEven]} == "true"</simple>
or
<simple>"${property.isEven}"</simple>
or
<simple>${property.isEven} == "true"</simple>
or
<simple>${property.isEven}</simple>
I prefer the last version.
EDIT:
In order to debug if the property is correctly set, enable showProperties in your Spring configuration file:
<bean id="traceFormatter" class="org.apache.camel.processor.interceptor.DefaultTraceFormatter">
<property name="showBreadCrumb" value="false" />
<property name="showProperties" value="true" />
</bean>
Then you should see following output in your log (shorten for better readability):
[main] Tracer INFO >>> (route1) log[isEven property is :: ${property[isEven]}] --> choice <<< Pattern:InOnly, Properties:{CamelToEndpoint=direct://trigger, ..., isEven=true, ...
The important part is isEven=true.
EDIT:
The property is kept when forwarding to another route which can be proven as follows:
<route>
<from uri="direct:trigger" />
<process ref="myProcessor" />
<log message="isEven property is :: ${property[isEven]}" />
<to uri="direct:acktarget" />
</route>
<route>
<from uri="direct:acktarget" />
<log message="acktarget: isEven property is :: ${property[isEven]}" />
</route>
Output:
exchange.getExchangeId() = ID-pis-iMac-local-54434-1393006139076-0-3
********** Exchange Id lastDigit 3 isEven: false ***********
[ main] route1 INFO isEven property is :: false
[ main] route2 INFO acktarget: isEven property is :: false
exchange.getExchangeId() = ID-pis-iMac-local-54434-1393006139076-0-4
********** Exchange Id lastDigit 4 isEven: true ***********
[ main] route1 INFO isEven property is :: true
[ main] route2 INFO acktarget: isEven property is :: true
exchange.getExchangeId() = ID-pis-iMac-local-54434-1393006139076-0-5
********** Exchange Id lastDigit 5 isEven: false ***********
[ main] route1 INFO isEven property is :: false
[ main] route2 INFO acktarget: isEven property is :: false
Even if I invoke a bean before forwarding the message to the other route, the property is kept. So, I guess your problems is in <to uri="bean:hl7handler?method=handleORM" />. Try to log the property before invoking this bean and see if the property is still set. If not, have a look at the bean.
For newer version of apache camel use exchangeProperty instead of property
${exchangeProperty.isEven}
The simple language property function was deprecated in Camel 2.x and has been removed. Use exchangeProperty as function name.
You do not need to use quotes. Try just
<simple>${property.isEven} == true</simple>