Wanted to remove property name while printing the log in WSO2 - wso2

Here I have one doubt
I am creating log mediator in WSO2 and setting one property msg and it gives me output as follows
[2017-08-04 18:13:10,041] [] INFO - LogMediator Msg = Msg Coming************************
Here I just want the output like Msg Coming************************ I dont want to print property name...
How I will able to do it..

Example
<property name="*******************" value="hello" />
or
<property name="*******************" expression="translate('some string to log', 'abcdefg.....z', '****************************')" />
In first case you will get unknown property, in second unkond property with unknown value. Why you need such logging

Related

Dynamic custom mediator parametres in wso2 ESB

I built custom mediator using articles http://wso2.com/library/2898/ and http://wso2.com/library/2936/ .
It looks like this:
<inSequence>
<property expression="local-name($body/*[1])" name="method" scope="default" type="STRING"/>
<MyMediator>
<header>SomeHeader<header/>
<topic>SomeTopic</topic>
</MyMediator>
</inSequence>
It works well, but one issue I didn't solve, how I can dynamically change value of header and/or topic mediators parameter?
When I tried to put something like get-property('method') instead of SomeHeader. It was delivered into mediator code like string, ebs didn't calculate it.
My question is how to change value of my custom mediators parameter to property value?
You can choose for exemple to use {} braces to say that your string is an XPath request. In your mediator, if you find {} in first and last position, use org.apache.synapse.util.xpath.SynapseXPath : create a new SynapseXPath with your xpath (the string between {}) and use stringValueOf(theMessageContext)
You can't pass any dynamic value to a custom mediator, but you can read any property within custom mediators.
public boolean mediate(MessageContext mc) {
String value = (String) mc.getProperty("SomeHeader");
}
Current implementation doesn't support for expressions as class mediator properties. Please refer Jira for more details.

PayloadFactory - Enrich with Response

I make a callout that response is like this:
<ns:return>
<ax2446:contract>
<ax2446:array>variable1</ax2446:array>
<ax2446:array>value1</ax2446:array>
</ax2446:contract>
<ax2446:contract>
<ax2446:array>variable2</ax2446:array>
<ax2446:array>value2</ax2446:array>
</ax2446:contract>
<ax2446:contract>
<ax2446:array>variable3</ax2446:array>
<ax2446:array>value3</ax2446:array>
</ax2446:contract>
<ax2446:documents>
<ax2446:array>attachement1</ax2446:array>
<ax2446:array>D:\AUTO\filename-1.txt</ax2446:array>
</ax2446:documents>
<ax2446:documents>
<ax2446:array>attachment2</ax2446:array>
<ax2446:array>D:\AUTO\filename-2.txt</ax2446:array>
</ax2446:documents>
<ax2446:process>TEST_PROCESS</ax2446:modulo>
</ns:return>
i want to create a new payload with contracts values (the number can change)
<p:instantiateProcess xmlns:p="http://carbon.sample">
<xs:process xmlns:xs="http://carbon.sample">TEST_PROCESS</xs:process>
<ns:contract xmlns:ns="http://carbon.sample">
<xs:array xmlns:xs="http://carbon.sample">variable1</xs:array>
<xs:array xmlns:xs="http://carbon.sample">value1</xs:array>
</ns:contract>
<ns:contract xmlns:ns="http://carbon.sample">
<xs:array xmlns:xs="http://carbon.sample">variable2</xs:array>
<xs:array xmlns:xs="http://carbon.sample">value2</xs:array>
</ns:contract>
<ns:contract xmlns:ns="http://carbon.sample">
<xs:array xmlns:xs="http://carbon.sample">variable3</xs:array>
<xs:array xmlns:xs="http://carbon.sample">value3</xs:array>
</ns:contract>
</p:instantiateProcess>ยด
i get all the contract by:
<property
expression="//ns:return/ax2431:contract"
name="contract" scope="default" type="STRING"
xmlns:ax2431="http://vo.carbon.sample/xsd" xmlns:ns="http://carbon.sample"/>
I try with payloadfactory, by i dont know how to enrinch (if it is correct to use this mediator) the message to make a call to a new web service. or if i have to make the payload with an iterator...
can anybody help me? thanks
You appear to have a few options:
Use a Payload factory
Use XSLT
Use Script meditator
I suspect all 3 could get the result you are after. It is a question of which you feel most comfortable with. Personally, I would head down the Script mediator route, mapping between two XML payloads, here is an example: http://nimbleapi.com/2016/05/javascript-mapping-between-xml-payloads/
Once you get the contract list you can use iterate mediator to iterate the list and inside the iterator you can add payloadFactory mediator to create payload, then, same time you can send the modified payload to a new web service.
Please find the following links which explain in detail how you use iterate mediator.
http://sparkletechthoughts.blogspot.com/2012/08/how-to-use-iterator-mediator-to-iterate.html
In addition to XSLT or Script meditators, ForEach mediator is also an option.
https://docs.wso2.com/display/ESB490/ForEach+Mediator

Mock a message from a 3rd party system in Mule using MUnit

I'm writing a test suite (using Munit) for a Mule application that is processing new data coming from an instance of Magento. One of my flows is polling Magento for new customers and the message it receives is of type: com.magento.api.CustomerCustomerEntity
I'm wondering how I'd mock this so that in my test case, when the Magento message processor is called I can return a payload of the same type and make the appropriate assertations?
Currently my Munit test looks as follows:
<mock:config name="mock_MagentoToSalesforce" doc:name="Mock configuration"/>
<spring:beans>
<spring:import resource="classpath:MagentoToSalesforce.xml"/>
<spring:bean id="myBean" name="myBean" class="com.magento.api.CustomerCustomerEntity">
<spring:property name="email" value="test#test.com"/>
</spring:bean>
</spring:beans>
<munit:test name="MagentoToSalesforce-test-getCustomersFlowTest" description="Test">
<mock:when config-ref="mock_MagentoToSalesforce" messageProcessor=".*:.*" doc:name="Mock">
<mock:with-attributes>
<mock:with-attribute whereValue-ref="#[string:Get New Customers]" name="doc:name"/>
</mock:with-attributes>
<mock:then-return payload-ref="#[app.registry.myBean]"/>
</mock:when>
<flow-ref name="getCustomers" doc:name="Flow-ref to getCustomers"/>
</munit:test>
And the flow I'm trying to test is:
<flow name="getCustomers" processingStrategy="synchronous">
<poll doc:name="Poll">
<fixed-frequency-scheduler frequency="30" timeUnit="SECONDS"/>
<watermark variable="watermark" default-expression="#[new org.mule.el.datetime.DateTime().plusYears(-30)]" update-expression="#[new org.mule.el.datetime.DateTime().plusYears(-0)]" selector-expression="#[new org.mule.el.datetime.DateTime(payload.created_at, 'yyyy-MM-dd HH:mm:ss')]"/>
<magento:list-customers config-ref="Magento" filter="dsql:SELECT confirmation,created_at,created_in,customer_id,dob,email,firstname,group_id,increment_id,lastname,middlename,password_hash,prefix,store_id,suffix,taxvat,updated_at,website_id FROM CustomerCustomerEntity WHERE updated_at > '#[flowVars.watermark]'" doc:name="Get New Customers"/>
</poll>
<foreach doc:name="For Each">
<data-mapper:transform config-ref="MagentoCustomer_To_SalesforceContact" doc:name="Map Customer to SFDC Contact">
<data-mapper:input-arguments>
<data-mapper:input-argument key="ContactSource">Magento</data-mapper:input-argument>
</data-mapper:input-arguments>
</data-mapper:transform>
<flow-ref name="upsertSalesforceContactFlow" doc:name="upsertSalesforceContactFlow"/>
</foreach>
</flow>
Update following Ryan's answer:
Changed the expression to return a payload of #[ent = new com.magento.api.CustomerCustomerEntity(); ent.setEmail('test#test.com'); return [ent];] - note, changed the method to setEmail to match the documentation here. The error I get with this is:
ERROR 2015-06-22 09:58:34,719 [main] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message : Object "org.mule.transport.NullPayload" not of correct type. It must be of type "{interface java.lang.Iterable,interface java.util.Iterator,interface org.mule.routing.MessageSequence,interface java.util.Collection}" (java.lang.IllegalArgumentException). Message payload is of type: NullPayload
Code : MULE_ERROR--2
--------------------------------------------------------------------------------
Exception stack is:
1. Object "org.mule.transport.NullPayload" not of correct type. It must be of type "{interface java.lang.Iterable,interface java.util.Iterator,interface org.mule.routing.MessageSequence,interface java.util.Collection}" (java.lang.IllegalArgumentException)
org.mule.util.collection.EventToMessageSequenceSplittingStrategy:64 (null)
2. Object "org.mule.transport.NullPayload" not of correct type. It must be of type "{interface java.lang.Iterable,interface java.util.Iterator,interface org.mule.routing.MessageSequence,interface java.util.Collection}" (java.lang.IllegalArgumentException). Message payload is of type: NullPayload (org.mule.api.MessagingException)
org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor:32 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/MessagingException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
java.lang.IllegalArgumentException: Object "org.mule.transport.NullPayload" not of correct type. It must be of type "{interface java.lang.Iterable,interface java.util.Iterator,interface org.mule.routing.MessageSequence,interface java.util.Collection}"
at org.mule.util.collection.EventToMessageSequenceSplittingStrategy.split(EventToMessageSequenceSplittingStrategy.java:64)
at org.mule.util.collection.EventToMessageSequenceSplittingStrategy.split(EventToMessageSequenceSplittingStrategy.java:25)
at org.mule.routing.CollectionSplitter.splitMessageIntoSequence(CollectionSplitter.java:29)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************
One way is to build up the object yourself using the constructor or properties/setters.
From the docs:
http://mulesoft.github.io/magento-connector/2.1.2/java/com/magento/api/CustomerCustomerEntity.html
<mock:then-return payload-ref="#[ent = new com.magento.api.CustomerCustomerEntity(); ent.email('test#test.com'); return ent;]"/>
You can also create these objects aS reusable spring beans and reference them from MEL.
<bean class="com.magento.api.CustomerCustomerEntity" id="myEntityWithEmail">
<property name="email" value="test#test.com" />
</bean>
<mock:then-return payload-ref="#[app.registry.myEntityWithEmail]"/>
After your update I can see that you sre using a foreach which expects a collection or iterable. YOu can return a collection of you custom object simply in MEL using: [] for example:
#[ent = new com.magento.api.CustomerCustomerEntity(); ent.email('test#test.com'); return [ent];]
More on MEL here: https://developer.mulesoft.com/docs/display/current/Mule+Expression+Language+MEL
Or again you can use Spring to return a list:
<util:list id="entities">
<ref bean="myEntityWithEmail" />
</util:list>

CXF : How to remove <stackTrace> from the Fault in outFaultInterceptors?

After setting up
<cxf:properties>
<entry key="faultStackTraceEnabled" value="true" />
</cxf:properties>
I was able to get the stack trace. But I am struggling to remove it from the outgoing message.
I tried with following code:
Fault fault = (Fault) message.getContent(Exception.class);
StackTraceElement[] stackTrace = fault.getCause().getStackTrace();
List<StackTraceElement> tempList = new ArrayList<StackTraceElement>(Arrays.asList(stackTrace));
tempList.removeAll(tempList);
stackTrace = tempList.toArray(new StackTraceElement[0]);
fault.getCause().setStackTrace(stackTrace);
message.setContent(Exception.class, fault);
Even though the last line is setting the content back with empty stackTrace but the outgoing message still has the full stack trace.
Can you provide some code snippet how to remove the <stackTrace>?
#soilworker I was able to achieve what I was looking for. I was looking for stackTrace for logging.
I removed the following lines
<cxf:properties>
<entry key="faultStackTraceEnabled" value="true" />
</cxf:properties>`
Code:
Fault fault = (Fault) message.getContent(Exception.class);
String exceptionMsg = null;
for (StackTraceElement element : fault.getCause().getStackTrace()) {
exceptionMsg = // concatenate
}
So no <stackTrace> present in outgoing message.
But it will interesting to know how to modify the outgoing fault (like add additional tags) in the outgoing interceptor.
Thanks.

WSO2 Script mediator unable to parse self closing XML tags

I'm using a script mediator to convert the XML response to a JSON. The mediator works properly if the XML is well formatted but if the XML has self closing tags , it fails..
Any ideas to fix this issue is greatly appreciated..
<!-- XML data-->
<getMyClsScheduleResponse >
<RegisteredClass>
<ClassNumber>10757</ClassNumber>
<SubjectCode>AAS</SubjectCode>
<CatalogNumber>510</CatalogNumber>
<SectionNumber>001</SectionNumber>
<SectionType>IND</SectionType>
<SectionTypeDescr>Independent Study</SectionTypeDescr>
<SessionDescr>Regular</SessionDescr>
<CourseDescr>Supervised Research</CourseDescr>
<ClassTopic />
<CreditHours>1 - 6</CreditHours>
<LMSURL /> <!-- Self Closing tag -->
<Meeting>
<MeetingNumber>1</MeetingNumber>
<Days />
<Times />
<StartDate>09/02/2014</StartDate>
<EndDate>12/10/2014</EndDate>
<Location>TBA</Location>
<TopicDescr />
</Meeting>
/** Script Mediator */
function transformPayload(output) {
payload = output.getPayloadJSON();
results = payload.getMyClsScheduleResponse.RegisteredClasses;
var response = new Array();
var registeredClass = new Array();
for (i=0;i<results.length; i++ ) {
class_schedule = results[i];
newcls = new Object();
newcls.Link = class_schedule.LMSURL; // Error at this line..
}
}
Error Log :
TID: [0] [ESB] [2014-10-24 14:19:45,541] ERROR - The script engine returned an error executing the external js script : Value {name ='null', keyValue ='conf:/repository/esb/js/functions.js'} function transformPayload {org.apache.synapse.mediators.bsf.ScriptMediator}
com.sun.phobos.script.util.ExtendedScriptException: org.mozilla.javascript.WrappedException: Wrapped com.sun.phobos.script.util.ExtendedScriptException: org.mozilla.javascript.EvaluatorException: syntax error (<Unknown source>#1) in <Unknown source> at line number 1 (<Unknown source>#53) in <Unknown source> at line number 53
at com.sun.phobos.script.javascript.RhinoScriptEngine.invokeMethod(RhinoScriptEngine.java:259)
Thanks
Kranthi
According to the given scenario that issue will be occur with self closing tags(As you described).In the case of self closing tags it returns the value as null.Workaround for this to check the value in the js mediator and handle the null value in the case of the self closing tags.
You can use the following js function to set the value in such a scenario within the js mediator.
function assignValuesWithNull(value){
var returnValue;
if(!value){
returnValue='';
}
else{
returnValue=value;
}
return returnValue;
}
Why do you use script mediator to change XML to JSON? what you have to do is , set content-type properly to get required format response.