JMeter failed to keep JSON order by using fastjson JSONObject.parseObject - json

Backgroud:
In Jmeter, I need to get the json post data, and then parse to the JSONObject
But the key order should the same
The json post data is: { "one": "1", "two": "2", "three": "3", "four": "4" }
After JSON Object parse, it also should be: { "one": "1", "two": "2", "three": "3", "four": "4" }
Solution:
In pure java, I could use the following code to keep the order
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
String requestBody = "{ \"one\": \"1\", \"two\": \"2\", \"three\": \"3\", \"four\": \"4\" }";
log.info("********************requestBody: " + requestBody);
// Expected: keep the JSONObject key oder same as the body data
// But following code not working in JMeter JSR223 Sampler, it works fine in pure JAVA
JSONObject maps = JSONObject.parseObject(requestBody, Feature.OrderedField);
log.info("********************maps expected: " + maps);
Issue:
But the above code is not working in JMETER JSR223 Sampler, I get the following error:
Static method parseObject( java.lang.String, com.alibaba.fastjson.parser.Feature ) not found in class'com.alibaba.fastjson.JSONObject'...
Reproduce:
Save the following code as .jmx file to reproduce in JMeter
You need to download the fastjson 1.2.83, and put to the jmeter lib folder: https://mvnrepository.com/artifact/com.alibaba/fastjson/1.2.83
<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.5">
<hashTree>
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Test Plan" enabled="true">
<stringProp name="TestPlan.comments"></stringProp>
<boolProp name="TestPlan.functional_mode">false</boolProp>
<boolProp name="TestPlan.tearDown_on_shutdown">true</boolProp>
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
<collectionProp name="Arguments.arguments"/>
</elementProp>
<stringProp name="TestPlan.user_define_classpath"></stringProp>
</TestPlan>
<hashTree>
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Thread Group" enabled="true">
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
<boolProp name="LoopController.continue_forever">false</boolProp>
<stringProp name="LoopController.loops">1</stringProp>
</elementProp>
<stringProp name="ThreadGroup.num_threads">1</stringProp>
<stringProp name="ThreadGroup.ramp_time">1</stringProp>
<boolProp name="ThreadGroup.scheduler">false</boolProp>
<stringProp name="ThreadGroup.duration"></stringProp>
<stringProp name="ThreadGroup.delay"></stringProp>
<boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
</ThreadGroup>
<hashTree>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="JSON Sort Issue" enabled="true">
<boolProp name="HTTPSampler.postBodyRaw">true</boolProp>
<elementProp name="HTTPsampler.Arguments" elementType="Arguments">
<collectionProp name="Arguments.arguments">
<elementProp name="" elementType="HTTPArgument">
<boolProp name="HTTPArgument.always_encode">false</boolProp>
<stringProp name="Argument.value">{
"one": "1",
"two": "2",
"three": "3",
"four": "4"
}</stringProp>
<stringProp name="Argument.metadata">=</stringProp>
</elementProp>
</collectionProp>
</elementProp>
<stringProp name="HTTPSampler.domain">httpbin.org</stringProp>
<stringProp name="HTTPSampler.port"></stringProp>
<stringProp name="HTTPSampler.protocol">https</stringProp>
<stringProp name="HTTPSampler.contentEncoding"></stringProp>
<stringProp name="HTTPSampler.path">/post</stringProp>
<stringProp name="HTTPSampler.method">POST</stringProp>
<boolProp name="HTTPSampler.follow_redirects">true</boolProp>
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp>
<stringProp name="HTTPSampler.connect_timeout"></stringProp>
<stringProp name="HTTPSampler.response_timeout"></stringProp>
</HTTPSamplerProxy>
<hashTree>
<JSR223PreProcessor guiclass="TestBeanGUI" testclass="JSR223PreProcessor" testname="JSR223 预处理程序" enabled="true">
<stringProp name="cacheKey">true</stringProp>
<stringProp name="filename"></stringProp>
<stringProp name="parameters"></stringProp>
<stringProp name="script">import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
String requestBody = sampler.getArguments().getArgument(0).getValue();
log.info("********************requestBody: " + requestBody);
// UnExpected: key order is not same as the body data
JSONObject maps = JSONObject.parseObject(requestBody);
log.info("********************maps unexpected: " + maps);
// Expected: keep the JSONObject key oder same as the body data
// But following code not working in JMeter JSR223 Sampler, it works fine in pure JAVA
JSONObject maps = JSONObject.parseObject(requestBody, Feature.OrderedField);
log.info("********************maps expected: " + maps);
</stringProp>
<stringProp name="scriptLanguage">beanshell</stringProp>
</JSR223PreProcessor>
<hashTree/>
</hashTree>
</hashTree>
</hashTree>
</hashTree>
</jmeterTestPlan>

First of all, you declare your maps variable twice in the same scope, this is not valid code at all.
Coming back to your question: just change language to groovy, it will resolve your issue.
Since JMeter 3.1 it's recommended to use Groovy language for scripting mainly because Groovy performance is much better comparing the other scripting options. Moreover Groovy supports Java better and Beanshell doesn't support any Java 5+ feature.

Related

Error when trying to create custom Json to XML transformer in Mule

I'm trying to create a custom Json to XML conversion in mule (custom transformer), its just a one to one direct mapping values, not a complex transformation.
here is my flow:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:metadata="http://www.mulesoft.org/schema/mule/metadata" xmlns:json="http://www.mulesoft.org/schema/mule/json" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd">
<http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" basePath="/test" doc:name="HTTP Listener Configuration"/>
<flow name="test_finalFlow">
<http:listener config-ref="HTTP_Listener_Configuration" path="/" doc:name="HTTP"/>
<json:json-to-xml-transformer metadata:id="57c0cd3d-ece4-48fe-9adf-79fc36a31b12" doc:name="JSON to XML"/>
<logger level="INFO" doc:name="Logger"/>
</flow>
</mule>
I'm using theses files to configure my Json to XML component
jsonFile.json:
{
"inData": "value"
}
xml file: outData.xml
<?xml version='1.0' encoding='UTF-8'?>
<root>
<outData>someValue</outData>
</root>
setting the metadata:
right now when I deploy the application I do not have any problem,
but when I use postman to send a POST data with payload I got these errors:
and this is the full output of the console:
*******************************************************************************************************
* - - + APPLICATION + - - * - - + DOMAIN + - - * - - + STATUS + - - *
*******************************************************************************************************
* test_final * default * DEPLOYED *
*******************************************************************************************************
ERROR 2017-01-17 21:23:29,014 [[test_final].HTTP_Listener_Configuration.worker.01] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message : java.io.IOException: Illegal character: <i> (javax.xml.stream.XMLStreamException)
Payload : org.glassfish.grizzly.utils.BufferInputStream#526ed3db
Transformer : JsonToXml{this=6993c8df, name='JsonToString', ignoreBadInput=false, returnClass=SimpleDataType{type=java.lang.String, mimeType='text/xml', encoding='null'}, sourceTypes=[SimpleDataType{type=java.lang.String, mimeType='*/*', encoding='null'}, SimpleDataType{type=java.io.InputStream, mimeType='*/*', encoding='null'}, SimpleDataType{type=[B, mimeType='*/*', encoding='null'}, SimpleDataType{type=java.io.Reader, mimeType='*/*', encoding='null'}, SimpleDataType{type=java.net.URL, mimeType='*/*', encoding='null'}, SimpleDataType{type=java.io.File, mimeType='*/*', encoding='null'}]}
Element : /test_finalFlow/processors/0 # test_final:test_final.xml:13 (JSON to XML)
Element XML : <json:json-to-xml-transformer metadata:id="57c0cd3d-ece4-48fe-9adf-79fc36a31b12" doc:name="JSON to XML"></json:json-to-xml-transformer>
--------------------------------------------------------------------------------
Root Exception stack trace:
java.io.IOException: Illegal character: <i>
at de.odysseus.staxon.json.stream.impl.Yylex.yylex(Yylex.java:641)
at de.odysseus.staxon.json.stream.impl.Yylex.nextSymbol(Yylex.java:271)
at de.odysseus.staxon.json.stream.impl.JsonStreamSourceImpl.next(JsonStreamSourceImpl.java:107)
at de.odysseus.staxon.json.stream.impl.JsonStreamSourceImpl.peek(JsonStreamSourceImpl.java:250)
at de.odysseus.staxon.json.JsonXMLStreamReader.consume(JsonXMLStreamReader.java:128)
at de.odysseus.staxon.json.JsonXMLStreamReader.consume(JsonXMLStreamReader.java:161)
at de.odysseus.staxon.base.AbstractXMLStreamReader.initialize(AbstractXMLStreamReader.java:216)
at de.odysseus.staxon.json.JsonXMLStreamReader.<init>(JsonXMLStreamReader.java:65)
at de.odysseus.staxon.json.JsonXMLInputFactory.createXMLStreamReader(JsonXMLInputFactory.java:139)
at de.odysseus.staxon.json.JsonXMLInputFactory.createXMLStreamReader(JsonXMLInputFactory.java:120)
at de.odysseus.staxon.json.JsonXMLInputFactory.createXMLStreamReader(JsonXMLInputFactory.java:44)
at org.mule.module.json.transformers.JsonToXml.doTransform(JsonToXml.java:55)
at org.mule.transformer.AbstractTransformer.transform(AbstractTransformer.java:415)
at org.mule.transformer.AbstractTransformer.transform(AbstractTransformer.java:366)
at org.mule.DefaultMuleMessage.transformMessage(DefaultMuleMessage.java:1589)
at org.mule.DefaultMuleMessage.applyAllTransformers(DefaultMuleMessage.java:1488)
at org.mule.DefaultMuleMessage.applyTransformers(DefaultMuleMessage.java:1462)
at org.mule.DefaultMuleMessage.applyTransformers(DefaultMuleMessage.java:1454)
at org.mule.transformer.AbstractTransformer.process(AbstractTransformer.java:114)
at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:27)
at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:108)
at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
at org.mule.processor.BlockingProcessorExecutor.executeNext(BlockingProcessorExecutor.java:98)
at org.mule.processor.BlockingProcessorExecutor.execute(BlockingProcessorExecutor.java:59)
at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:27)
at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
at org.mule.processor.BlockingProcessorExecutor.executeNext(BlockingProcessorExecutor.java:98)
at org.mule.processor.BlockingProcessorExecutor.execute(BlockingProcessorExecutor.java:59)
at org.mule.processor.AsyncInterceptingMessageProcessor.process(AsyncInterceptingMessageProcessor.java:102)
at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:27)
at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:108)
at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
at org.mule.processor.BlockingProcessorExecutor.executeNext(BlockingProcessorExecutor.java:98)
at org.mule.processor.BlockingProcessorExecutor.execute(BlockingProcessorExecutor.java:59)
at org.mule.construct.DynamicPipelineMessageProcessor.process(DynamicPipelineMessageProcessor.java:55)
at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:27)
at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:108)
at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
at org.mule.processor.BlockingProcessorExecutor.executeNext(BlockingProcessorExecutor.java:88)
Any idea about what causing the error ?
java.io.IOException: Illegal character: i ?
Note:
I'm trying to create this custom transformer because I'm using just Mule server 3.8.1 CE right now , I'll get access soon to an enterprise edition version that's why I'm trying to deploy in a community edition server at this time.
please refer the below link for creating a custom json to xml transformer
https://docs.mulesoft.com/mule-user-guide/v/3.6/creating-custom-transformers

Apache camel Body is not convertible to type DBObject nor List<DBObject>

I am trying out a sample for MongoDB using Apache Camel.
What I did is something like this:
I have my main method as :
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("camel-context-mongo.xml");
}
My camel-context-mongo.xml as :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camel="http://camel.apache.org/schema/spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camel:camelContext id="camel-client">
<camel:routeBuilder ref="vinodroute" />
</camel:camelContext>
<bean id="myDb" class="com.mongodb.Mongo">
<constructor-arg index="0" value="localhost" />
</bean>
<bean id="vinodroute" class="com.camel.test.CamelMongoRoute" />
</beans>
And my camel route is
public void configure() throws Exception {
from("jetty:http://localhost:8181/data")
.to("mongodb:myDb?database=DataDB&collection=data&operation=findAll");
from("jetty:http://localhost:8181/dataInsert")
.to("mongodb:myDb?database=DataDB&collection=data&operation=insert");
}
Now I am trying the insert operation i.e. I am trying to invoke http://localhost:8181/dataInsert rest service through soapUI and my json payload is :
[{
"DataID": "19dd8a2e-45cb-40cc-ba2c-15d5a81733f8",
"DataDescription": "Data High",
"DataPriority": "High"
},
{
"DataID": "cfc6f177-fe18-419e-84cd-db11617f12af",
"DataDescription": "Data Low Low",
"DataPriority": "Low"
},
{
"DataID": "822accd4-061f-491b-a417-1c683d0c268f",
"DataDescription": "Data High",
"DataPriority": "High"
},
{
"DataID": "1c7dcf89-629c-4523-96c4-a2cc740d1769",
"DataDescription": "Data High",
"DataPriority": "High"
},
{
"DataID": "1c0b5e66-3ca4-4a0a-a9a5-8d1397589ee9",
"DataDescription": "Data Low",
"DataPriority": "Low"
},
{
"DataID": "05677b88-d43b-4224-be7e-66360a2f35a8",
"DataDescription": "Data High",
"DataPriority": "High"
}]
Now the above json is a valid json. But still I am getting this exception as :
<data contentType="text/plain;charset=ISO-8859-1" contentLength="3128"><![CDATA[org.apache.camel.component.mongodb.CamelMongoDbException: MongoDB operation = insert, Body is not conversible to type DBObject nor List<DBObject>
at org.apache.camel.component.mongodb.MongoDbProducer.doInsert(MongoDbProducer.java:261)
at org.apache.camel.component.mongodb.MongoDbProducer.invokeOperation(MongoDbProducer.java:106)
at org.apache.camel.component.mongodb.MongoDbProducer.process(MongoDbProducer.java:72)
at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:110)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:72)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:398)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.component.jetty.CamelContinuationServlet.service(CamelContinuationServlet.java:151)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:652)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1320)
at org.eclipse.jetty.servlets.MultiPartFilter.doFilter(MultiPartFilter.java:119)
at org.apache.camel.component.jetty.CamelFilterWrapper.doFilter(CamelFilterWrapper.java:44)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1291)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:443)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1044)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:372)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:978)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:367)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:486)
at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:937)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:998)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:861)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:240)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:628)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
at java.lang.Thread.run(Thread.java:722)
]]></data>
What am I doing wrong? Looking forward to your solutions.
Thanks in advance.
Try to unmarshall your message with jackon, to a List. The MongoDB component know how to create a DBObject, but not a List of DBObject, you have to provide something convertible to a List first.
from("jetty:http://localhost:8181/data")
.unmarshall(new ListJacksonDataFormat())
.to("mongodb:myDb?database=DataDB&collection=data&operation=findAll");
from("")
.marshal().json(JsonLibrary.Jackson)
.unmarshal(new ListJacksonDataFormat())
.to("mongodb:mongoClient?database=mytest&collection=testc&operation=insert")
This worked for me

xml to json conversion in wso2

When I am trying to convert XML to Json using XSLT mediator in wso2 I am getting "Payload could not be written as JSON." error. Can anyone help to me resolve this.
Thanks in advance
Why you do not use payload factory? this is a best way for converting xml to Json.
for example:
<payloadFactory media-type="json">
<format>{ "error": "0", "message": "$1", "data": $2 }</format>
<args>
<arg evaluator="json" expression="$.USER.description"/>
<arg evaluator="json" expression="$.USER"/>
</args>
</payloadFactory>
<property name="ContentType" value="application/json" scope="axis2"/>
Or use this property for send message:
<property name="messageType" value="application/json" scope="axis2"/>
The media-type attribute specifies whether to format the message in XML or JSON.
In this example i use JSON to convert this xml:
<USER>
<description>some Notes</description>
<others></others>
</USER>
and the ESB result:
{
"error" : "0",
"message" : "Some notes",
"data" : {
"description" : "Some notes",
"others" : ""
}
}
for more information about payload factory please see this link:
https://docs.wso2.com/display/ESB490/PayloadFactory+Mediator
Update:
you must use switch case or filter mediator.
for example this is a switch case sample. you must complete regex:
<switch source="//body">
<case regex="">
<payloadFactory media-type="json">
</payloadFactory>
</case>
</switch>
or you can use filter. In this example, the Filter match your given regular expression or XPath. If this evaluation returns true, it will send the true json. If the evaluation returns false, it will return empty json.
<filter (source="[XPath|json-eval(JSONPath)]" regex="string") | xpath="[XPath|json-eval(JSONPath)]">
<then>
<payloadFactory media-type="json">
<format>{josn:"body"}</format>
<args>your args<args/>
</payloadFactory>
</then>
<else>
<payloadFactory media-type="json">
<format>{}</format>
<args/>
</payloadFactory>
</else>
</filter>
This link should help you:
https://docs.wso2.com/display/ESB490/Filter+Mediator
If you are trying to convert a soap service to rest, you can do it by specifying message type as (in a rest api):
<property name="messageType" value="application/json" scope="axis2"/>

Mule ESB: How to use a flow execution conditional on a JSON object

Mule ESB
I am trying to convert a Hello World program into a program that will accept a JSON object, examine the data, and route the execution accordingly.
Below is a copy of my flow:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:json="http://www.mulesoft.org/schema/mule/json" version="EE-3.5.0" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:core="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd">
<json:object-to-json-transformer name="Object_to_JSON" doc:name="Object to JSON"/>
<flow doc:name="HelloWorldFlow1" name="HelloWorldFlow1">
<http:inbound-endpoint doc:description="This endpoint receives an HTTP message." doc:name="HTTP" exchange-pattern="request-response" host="localhost" port="8081" contentType="application/json"/>
<echo-component doc:name="Echo"/>
</flow>
</mule>
I see the object-to-json in the code, which I believe is configured from the
HTTP Node->HTTP Settings->content type, which is set to
application/json
So I assume that the incoming object is in JSON format once within the flow, with no fursther Object to JSON nodes required.
I am sending the following string to the flow:
{ "uid" : "ABCxxx" }
What I am trying to achieve to get a node that will examine and verify that the first three letters of the uid is "ABC", and if so send it down one path, but if the first three characters of the uid does not equal "ABC", to go down another path., sort of like a IF statement with a true and a false configtion,
The following is a Pseudo code example
IF uid[3] == "ABC"
GOTO Database Connector
else
GOTO JSON-TO-OBJECT Transformer
My question is: Whhich node should I use to perform this, should I use an Expression filter or other
... and how do I write that in JSAONPath (or other)
(Does Mule ESB perform this sort of thing?)
Th json evaluator that executes JsonPath in mule is deprecated in favor of MEL. The preferred approach now is to convert json to an object and query the object instead. One of the simplest approaches is to convert the json to the map and use MEL to query the map. Like so:
<json:json-to-object-transformer returnClass="java.util.HashMap" />
<choice>
<when expression="#[payload.uid == 'ABC']">
</when>
</choice>
More info here: http://www.mulesoft.org/documentation/display/current/Mule+Expression+Language+Tips
You can also <json:json-to-object-transformer returnClass="java.lang.Object" /> alternatively
and then
<choice>
<when expression="#[message.payload.uid == 'ABC']">

Using Mule Studio to read CSV

i try this example : Using Mule Studio to read CSV step by step but but content of csv donot copy to database . i have not any errors i left my console and myflow :
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:file="http://www.mulesoft.org/schema/mule/file" xmlns:jdbc="http://www.mulesoft.org/schema/mule/jdbc" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:spring="http://www.springframework.org/schema/beans" version="CE-3.3.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
http://www.mulesoft.org/schema/mule/jdbc http://www.mulesoft.org/schema/mule/jdbc/current/mule-jdbc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd ">
<configuration doc:name="Configuration">
<expression-language autoResolveVariables="true">
<import class="org.mule.util.StringUtils" />
</expression-language>
</configuration>
<jdbc:mysql-data-source name="MySQL_Data_Source" user="roor" url="jdbc:mysql://localhost:3306/csv" transactionIsolation="UNSPECIFIED" doc:name="MySQL Data Source" password="1234"/>
<jdbc:connector name="Database" dataSource-ref="MySQL_Data_Source" validateConnections="true" queryTimeout="-1" pollingFrequency="0" doc:name="Database">
<jdbc:query key="InsertRecord" value="INSERT INTO "tblFamily"("Title", "FirstName", "LastName") VALUES (#[message.payload[0]],#[message.payload[1]],#[message.payload[2]])"/>
</jdbc:connector>
<flow name="csvFlow1" doc:name="csvFlow1">
<!-- Step 1: CSV file source -->
<file:inbound-endpoint path="C:\Users\masoudy\Downloads\Compressed\Resoes" pollingFrequency="5000" doc:name="Source"/>
<!-- Step 2: Convert between object arrays and strings -->
<object-to-string-transformer doc:name="Object to String"/>
<splitter expression="#[StringUtils.split(message.payload, '\n\r')]" doc:name="Splitter"/>
<expression-transformer expression="#[StringUtils.split(message.payload, ',')]" doc:name="Expression"/>
<jdbc:outbound-endpoint exchange-pattern="one-way" queryTimeout="-1" doc:name="Destination" connector-ref="Database" queryKey="InsertRecord"/>
</flow>
</mule>
my console:
.....
**********************************************************************
* Application: csv *
* OS encoding: Cp1256, Mule encoding: UTF-8 *
* *
* Agents Running: *
* JMX Agent *
**********************************************************************
INFO 2013-04-22 14:55:54,437 [main] org.mule.module.launcher.DeploymentService:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Started app 'csv' +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
console
csv
I could take good result and csv file converted to database.
I had 2 mistakes:
after run program, .csv file cleaned from path and I did not and run the program again without .csv file
name of fields in queries xml was difference to name of columns in database