WSO2 websocket + SockJS - Cross origin requests blocked - websocket

Since WSO2 5.0 supports WebSockets, I have written a simple app following by tutorials:
WebSocket Transport
Sending a Message from a WebSocket Client to an HTTP Endpoint
Here's my source view output from WSO2:
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://ws.apache.org/ns/synapse">
<registry provider="org.wso2.carbon.mediation.registry.WSO2Registry">
<parameter name="cachableDuration">15000</parameter>
</registry>
<taskManager provider="org.wso2.carbon.mediation.ntask.NTaskTaskManager"/>
<sequence name="fault">
<!-- Log the message at the full log level with the ERROR_MESSAGE and the ERROR_CODE-->
<log level="full">
<property name="MESSAGE" value="Executing default 'fault' sequence"/>
<property expression="get-property('ERROR_CODE')" name="ERROR_CODE"/>
<property expression="get-property('ERROR_MESSAGE')" name="ERROR_MESSAGE"/>
</log>
<!-- Drops the messages by default if there is a fault -->
<drop/>
</sequence>
<sequence name="main">
<in>
<!-- Log all messages passing through -->
<log level="full"/>
<!-- ensure that the default configuration only sends if it is one of samples -->
<!-- Otherwise Synapse would be an open proxy by default (BAD!) -->
<filter regex="http://localhost:9000.*" source="get-property('To')">
<!-- Send the messages where they have been sent (i.e. implicit "To" EPR) -->
<send/>
</filter>
</in>
<out>
<send/>
</out>
<description>The main sequence for the message mediation</description>
</sequence>
<sequence name="outDispatchSeq">
<log level="full"/>
<respond/>
</sequence>
<sequence name="dispatchSeq">
<switch
source="get-property('websocket.source.handshake.present')" xmlns:ns="http://org.apache.synapse/xsd">
<case regex="true">
<drop/>
</case>
<default>
<call/>
<respond/>
</default>
</switch>
</sequence>
<!-- You can add any flat sequences, endpoints, etc.. to this synapse.xml file if you do
*not* want to keep the artifacts in several files -->
<inboundEndpoint name="test" onError="fault" protocol="ws"
sequence="dispatchSeq" suspend="false">
<parameters>
<parameter name="inbound.ws.port">9091</parameter>
<parameter name="ws.client.side.broadcast.level">0</parameter>
<parameter name="ws.outflow.dispatch.sequence">outDispatchSeq</parameter>
<parameter name="ws.outflow.dispatch.fault.sequence">fault</parameter>
</parameters>
</inboundEndpoint>
</definitions>
I was able to successfully test it with Nett client:
C:\work\servers\netty>java -Durl=ws://localhost:9091/websocket -DsubProtocol="synapse(contentType='application/xml')" -cp netty-example-4.1.4.Final.jar;lib/*;. io.netty.example.http.websocketx.client.WebSocketClient
WebSocket Client connected!
However if I try to test it from JavaScript code I am getting error like:
Do you know what is wrong in my code?

This issue occurs because SockJS internally trying to load the URL using XMLHttpRequest, but Chrome does not allow accessing cross origin content unless the protocol is one of the aforementioned protocols (In this case it is ws://). I have tried a similar scenario with Firefox and it works fine since it doesn't have this Chrome specific limitation.
In this scenario since WSO2 ESB exposes a WebSocket interface to invoke the HTTP Endpoint, you can use native HTML5 WebSocket implementation as follows.
var url = 'ws://localhost:9091/websocket';
var ws = new WebSocket(url);
ws.onopen = function() {
// todo
}
ws.onmessage = function(e) {
// todo
}

Related

Sending a PDF file in a REST Message

I am trying figure this out any help appreciated. Thanks in advance
The service is a file passthrough that picks up a PDF and then uses the BPL code below to create the rest wrapper and sends the stream data. I am not grabbing the stream from the inbound correctly, "request.Stream" or "request.StreamFC" always produces the following error.
Here is what is sent and returned in the message..
request:
*
<Stream>
15#%Library.FileCharacterStream
</Stream>
response:
<Stream>
Unable to load xml from message: Data at the root level is invalid. Line 1, position 1.
</Stream>
-I think my issue is I am not using the right class by using "%GlobalStreamCharacter", Or the raw PDF CDATA inbound I am not handling correctly
set context.RESTMessage.Stream=##class(%GlobalCharacterStream).%New()
I have tried using different Stream types...File, Binary....but no luck
-The general BPL below
/// BPL Definition
X
Data BPL [ XMLNamespace = "http://www.intersystems.com/bpl" ]
{
<process language='objectscript' request='Ens.StreamContainer' response='Ens.Response'
height='2000' width='2000' >
<context>
.....
.....
....
<code name='Create REST Message' xpos='200' ypos='250' >
<![CDATA[
set context.RESTMessage=##class(EnsLib.HTTP.GenericMessage).%New()
set context.RESTMessage.Stream=##class(%GlobalCharacterStream).%New()
set tSC=context.RESTMessage.Stream.Write(request.StreamFC)
set tSC=context.RESTMessage.HTTPHeaders.SetAt("application/xml","Content-Type")
set tSC=context.RESTMessage.HTTPHeaders.SetAt(context.RESTMessage.Stream.Size,"Content-
Length")
set tSC=context.RESTMessage.HTTPHeaders.SetAt("POST","HttpRequest")
]]>
</code>
You can try this code snippet. I got the answer in the community.
<call name='To application Rest' target='To application REST' async='0'>
<request type='EnsLib.REST.GenericMessage' >
<assign property="callrequest.Stream" value='##class(%Stream.GlobalCharacter).%New()'/>
<assign property="status" value='callrequest.Stream.CopyFrom(request.StreamFC)' action="set" />
<assign property="status" value='callrequest.HTTPHeaders.SetAt("application/xml", "Content-Type")' action="set" />
<assign property="status" value='callrequest.HTTPHeaders.SetAt(callrequest.Stream.Size, "Content-Length")' action="set" />
<assign property="status" value='callrequest.HTTPHeaders.SetAt("POST", "HttpRequest")' action="set" />
</request>
</call>

Azure Load test does not report data driven urls

I have a simple load test that basically executes a single webtest on a constant load. That webtest is hooked to an xml file data source that contains urls to my entire site.
When I execute the load test from my local environment, the test summary page reports the individual urls in the "Top 5 slowest pages" i.e. "https://mysite.or/page" . But when I execute the same test from Azure (i.e. changed Test run location to VSTS in .testsettings), the links are reported as "https://{{Enviroment}}{{Sitemap.url.loc}}". This seems to be just a reporting issue and I can validate that azure is correctly invoking the urls from the data source. Why would the tests from Azure not report the url constructed from the datasource?
Load Test Summary: Executed from Local
Same test executed on Azure
Webtest:
<?xml version="1.0" encoding="utf-8"?>
<WebTest Name="GenericSitemap" Id="02954e81-f3a7-4c9c-94f5-3a4304f88361" Owner="" Priority="2147483647" Enabled="True" CssProjectStructure="" CssIteration="" Timeout="0" WorkItemIds="" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010" Description="" CredentialUserName="" CredentialPassword="" PreAuthenticate="True" Proxy="default" StopOnError="False" RecordedResultFile="" ResultsLocale="">
<Items>
<Request Method="GET" Guid="01c37ffa-92db-42e8-9d25-a042dcd0123d" Version="1.1" Url="https://{{Enviroment}}{{Sitemap.url.loc}}" ThinkTime="0" Timeout="300" ParseDependentRequests="True" FollowRedirects="True" RecordResult="True" Cache="False" ResponseTimeGoal="0" Encoding="utf-8" ExpectedHttpStatusCode="0" ExpectedResponseUrl="https://{{Enviroment}}{{Sitemap.url.loc}}" ReportingName="" IgnoreHttpStatusCode="False" />
</Items>
<DataSources>
<DataSource Name="Sitemap" Provider="Microsoft.VisualStudio.TestTools.DataSource.XML" Connection="|DataDirectory|\..\Data\sitemap.xml">
<Tables>
<DataSourceTable Name="url" SelectColumns="SelectOnlyBoundColumns" AccessMethod="Random" />
</Tables>
</DataSource>
</DataSources>
<ContextParameters>
<ContextParameter Name="Enviroment" Value="mysite.net" />
</ContextParameters>
</WebTest>
Thanks to #AdrianHHH. I got it working by creating a requestPlugin and setting it on the data driven requests.
Here's my plugin:
[DisplayName("Set Request Params")]
[Description("Fix request urls when run from Azure")]
public class SetRequestParams : WebTestRequestPlugin
{
public override void PreRequest(object sender, PreRequestEventArgs e)
{
e.Request.ReportingName = e.Request.Url;
}
}

How can I get a pathname from a groupId? [duplicate]

Is there a simple way of taking the value of a property and then copy it to another property with certain characters replaced?
Say propA=This is a value. I want to replace all the spaces in it into underscores, resulting in propB=This_is_a_value.
Here is the solution without scripting and no external jars like ant-conrib:
The trick is to use ANT's resources:
There is one resource type called "propertyresource" which is like a source file, but provides an stream from the string value of this resource. So you can load it and use it in any task like "copy" that accepts files
There is also the task "loadresource" that can load any resource to a property (e.g., a file), but this one could also load our propertyresource. This task allows for filtering the input by applying some token transformations. Finally the following will do what you want:
<loadresource property="propB">
<propertyresource name="propA"/>
<filterchain>
<tokenfilter>
<filetokenizer/>
<replacestring from=" " to="_"/>
</tokenfilter>
</filterchain>
</loadresource>
This one will replace all " " in propA by "_" and place the result in propB. "filetokenizer" treats the whole input stream (our property) as one token and appies the string replacement on it.
You can do other fancy transformations using other tokenfilters: http://ant.apache.org/manual/Types/filterchain.html
Use the propertyregex task from Ant Contrib.
I think you want:
<propertyregex property="propB"
input="${propA}"
regexp=" "
replace="_"
global="true" />
Unfortunately the examples given aren't terribly clear, but it's worth trying that. You should also check what happens if there aren't any underscores - you may need to use the defaultValue option as well.
If ant-contrib isn't an option, here's a portable solution for Java 1.6 and later:
<property name="before" value="This is a value"/>
<script language="javascript">
var before = project.getProperty("before");
project.setProperty("after", before.replaceAll(" ", "_"));
</script>
<echo>after=${after}</echo>
In case you want a solution that does use Ant built-ins only, consider this:
<target name="replace-spaces">
<property name="propA" value="This is a value" />
<echo message="${propA}" file="some.tmp.file" />
<loadfile property="propB" srcFile="some.tmp.file">
<filterchain>
<tokenfilter>
<replaceregex pattern=" " replace="_" flags="g"/>
</tokenfilter>
</filterchain>
</loadfile>
<echo message="$${propB} = "${propB}"" />
</target>
Output is ${propB} = "This_is_a_value"
Use some external app like sed:
<exec executable="sed" inputstring="${wersja}" outputproperty="wersjaDot">
<arg value="s/_/./g"/>
</exec>
<echo>${wersjaDot}</echo>
If you run Windows get it googling for "gnuwin32 sed".
The command s/_/./g replaces every _ with .
This script goes well under windows. Under linux arg may need quoting.
Two possibilities :
via script task and builtin javascript engine (if using jdk >= 1.6)
<project>
<property name="propA" value="This is a value"/>
<script language="javascript">
project.setProperty('propB', project.getProperty('propA').
replace(" ", "_"));
</script>
<echo>$${propB} => ${propB}</echo>
</project>
or using Ant addon Flaka
<project xmlns:fl="antlib:it.haefelinger.flaka">
<property name="propA" value="This is a value"/>
<fl:let> propB := replace('${propA}', '_', ' ')</fl:let>
<echo>$${propB} => ${propB}</echo>
</project>
to overwrite exisiting property propA simply replace propB with propA
Here's a more generalized version of Uwe Schindler's answer:
You can use a macrodef to create a custom task.
<macrodef name="replaceproperty" taskname="#{taskname}">
<attribute name="src" />
<attribute name="dest" default="" />
<attribute name="replace" default="" />
<attribute name="with" default="" />
<sequential>
<loadresource property="#{dest}">
<propertyresource name="#{src}" />
<filterchain>
<tokenfilter>
<filetokenizer/>
<replacestring from="#{replace}" to="#{with}"/>
</tokenfilter>
</filterchain>
</loadresource>
</sequential>
</macrodef>
you can use this as follows:
<replaceproperty src="property1" dest="property2" replace=" " with="_"/>
this will be pretty useful if you are doing this multiple times
Adding an answer more complete example over a previous answer
<property name="propB_" value="${propA}"/>
<loadresource property="propB">
<propertyresource name="propB_" />
<filterchain>
<tokenfilter>
<replaceregex pattern="\." replace="/" flags="g"/>
</tokenfilter>
</filterchain>
</loadresource>
Just an FYI for answer Replacing characters in Ant property - if you are trying to use this inside of a maven execution, you can't reference maven variables directly. You will need something like this:
...
<target>
<property name="propATemp" value="${propA}"/>
<loadresource property="propB">
<propertyresource name="propATemp" />
...
Properties can't be changed but antContrib vars (http://ant-contrib.sourceforge.net/tasks/tasks/variable_task.html ) can.
Here is a macro to do a find/replace on a var:
<macrodef name="replaceVarText">
<attribute name="varName" />
<attribute name="from" />
<attribute name="to" />
<sequential>
<local name="replacedText"/>
<local name="textToReplace"/>
<local name="fromProp"/>
<local name="toProp"/>
<property name="textToReplace" value = "${#{varName}}"/>
<property name="fromProp" value = "#{from}"/>
<property name="toProp" value = "#{to}"/>
<script language="javascript">
project.setProperty("replacedText",project.getProperty("textToReplace").split(project.getProperty("fromProp")).join(project.getProperty("toProp")));
</script>
<ac:var name="#{varName}" value = "${replacedText}"/>
</sequential>
</macrodef>
Then call the macro like:
<ac:var name="updatedText" value="${oldText}"/>
<current:replaceVarText varName="updatedText" from="." to="_" />
<echo message="Updated Text will be ${updatedText}"/>
Code above uses javascript split then join, which is faster than regex. "local" properties are passed to JavaScript so no property leakage.
Or... You can also to try Your Own Task
JAVA CODE:
class CustomString extends Task{
private String type, string, before, after, returnValue;
public void execute() {
if (getType().equals("replace")) {
replace(getString(), getBefore(), getAfter());
}
}
private void replace(String str, String a, String b){
String results = str.replace(a, b);
Project project = getProject();
project.setProperty(getReturnValue(), results);
}
..all getter and setter..
ANT SCRIPT
...
<project name="ant-test" default="build">
<target name="build" depends="compile, run"/>
<target name="clean">
<delete dir="build" />
</target>
<target name="compile" depends="clean">
<mkdir dir="build/classes"/>
<javac srcdir="src" destdir="build/classes" includeantruntime="true"/>
</target>
<target name="declare" depends="compile">
<taskdef name="string" classname="CustomString" classpath="build/classes" />
</target>
<!-- Replacing characters in Ant property -->
<target name="run" depends="declare">
<property name="propA" value="This is a value"/>
<echo message="propA=${propA}" />
<string type="replace" string="${propA}" before=" " after="_" returnvalue="propB"/>
<echo message="propB=${propB}" />
</target>
CONSOLE:
run:
[echo] propA=This is a value
[echo] propB=This_is_a_value

Conflict 409 error when creating a Google Shared Contact using API

I'm continually getting a HTTP 409 "Conflict" error when attempting to add a new Google Shared Contact using the API.
I've followed the documentation as closely as possible and have defined the new entry as so:
<atom:entry xmlns:atom='http://www.w3.org/2005/Atom' xmlns:gd='http://schemas.google.com/g/2005'>
<atom:category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/contact/2008#contact' />
<gd:name>
<gd:givenName>Test</gd:givenName>
<gd:familyName>Testerson</gd:familyName>
<gd:fullName>Test Testerson</gd:fullName>
</gd:name>
<atom:content type='text'></atom:content>
<gd:email rel='http://schemas.google.com/g/2005#work' primary='true' address='test.testerson#sample.com.au' displayName='' />
<gd:email rel='http://schemas.google.com/g/2005#home' address='' />
<gd:phoneNumber rel='http://schemas.google.com/g/2005#work' primary='true'>(07) 33331111</gd:phoneNumber>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#mobile'>0411223344</gd:phoneNumber>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#fax'>(07) 33331122</gd:phoneNumber>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#home'></gd:phoneNumber>
<gd:im address='' protocol='http://schemas.google.com/g/2005#GOOGLE_TALK' primary='true' rel='http://schemas.google.com/g/2005#home' />
<gd:structuredPostalAddress rel='http://schemas.google.com/g/2005#work' primary='true'>
<gd:city>Abbey</gd:city>
<gd:street>PO Box 4561</gd:street>
<gd:region>WA</gd:region>
<gd:postcode>6280</gd:postcode>
<gd:country>Australia</gd:country>
<gd:formattedAddress>PO Box 4561, Abbey, WA, 6280, Australia</gd:formattedAddress>
</gd:structuredPostalAddress>
<gd:structuredPostalAddress rel='http://schemas.google.com/g/2005#other'>
<gd:city>Abbey</gd:city>
<gd:street>47 Example Avenue</gd:street>
<gd:region>WA</gd:region>
<gd:postcode>6280</gd:postcode>
<gd:country>Australia</gd:country>
<gd:formattedAddress>47 Example Avenue, Abbey, WA, 6280, Australia</gd:formattedAddress>
</gd:structuredPostalAddress>
<gd:organization rel='http://schemas.google.com/g/2005#other'>
<gd:orgTitle>Guinea Pig</gd:orgTitle>
<gd:orgName>Test Org</gd:orgName>
</gd:organization>
</atom:entry>
I've set up my HTTP request as follows:
lsToken = GetAuthToken()
Set lobjHttp = CreateObject("MSXML2.XMLHTTP")
Call lobjHttp.Open("POST", CS_FEED_DEFAULT, False, "", "")
Call lobjHttp.setRequestHeader("Authorization", "GoogleLogin auth=" + lsToken)
Call lobjHttp.setRequestHeader("Content-type", "application/atom+xml")
Call lobjHttp.Send(lsOut)
In this example CS_FEED_DEFAULT is the shared contact URL and lsOut is my entry as defined above.
After sending this request I get the 409 response and the following response text:
<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gContact='http://schemas.google.com/contact/2008' xmlns:batch='http://schemas.google.com/gdata/batch' xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://www.google.com/m8/feeds/contacts/test.com.au/base/47e904e10dd27dd2</id>
<updated>2014-09-17T02:08:39.761Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/contact/2008#contact'/>
<title type='text'></title>
<content type='text'></content>
<link rel='http://schemas.google.com/contacts/2008/rel#edit-photo' type='image/*' href='https://www.google.com/m8/feeds/photos/media/test.com.au/47e904e10dd27dd2/1B2M2Y8AsgTpgAmY7PhCfg'/>
<link rel='self' type='application/atom+xml' href='https://www.google.com/m8/feeds/contacts/test.com.au/full/47e904e10dd27dd2'/>
<link rel='edit' type='application/atom+xml' href='https://www.google.com/m8/feeds/contacts/test.com.au/full/47e904e10dd27dd2/1410919719761001'/>
<gd:email rel='http://schemas.google.com/g/2005#work' address='test.testerson#sample.com.au' primary='true'/>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#work' primary='true'>(07) 33331111</gd:phoneNumber>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#mobile'>0411223344</gd:phoneNumber>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#work_fax'>(07) 33331122</gd:phoneNumber>
</entry>
Can anyone offer me any advice on this issue?
Thanks.
According to the contacts API documentation, "409 error can be returned when there is a different contact with the same email address. As for now, google contacts API does not allow two different contacts to share an email address".
Have you been trying to add the same email address twice?
I had the same error because I forgot to Start my previously stopped SQL instance on GCP.

WSO2 ESB xpath problems

I want to use the following xpath
/Users/User/UserID
This does not work because the ESB adds a soap envelope and body around my xml, what is the correct xpath to use or how can I remove the soap envelope and body?
The xml is:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<Users xmlns="http://ws.wso2.org/dataservice">
<User>
<UserID>a</UserID>
<Username>a</Username>
<Email>a</Email>
<Password>a</Password>
</User>
<User>
<UserID>a</UserID>
<Username>a</Username>
<Email>a</Email>
<Password>a</Password>
</User>
<User>
<UserID>a</UserID>
<Username>a</Username>
<Email>a</Email>
<Password>a</Password>
</User>
</Users>
</soapenv:Body>
</soapenv:Envelope>
EDIT:
This works when I try to log it outside of my iterate mediator
//*[local-name() = 'Users']/*[local-name() = 'User']/*[local-name() = 'UserID']
but when I try to log it inside the iterate mediator it returns nothing?
Got this working by using the following
<property xmlns:int="http://ws.wso2.org/dataservice" name="uri.var.ID" expression="$body/int:User/int:UserID/text()" scope="default" type="STRING"/>
To access your elements you should go through envelope and body.
Here is an example with switch mediator:
<switch xmlns:ns="http://org.apache.synapse/xsd"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:int="http://ws.wso2.org/dataservice"
source="boolean(/soap:Envelope/soap:Body/int:Users/int:User/int:UserID/text() = 'string_to_compare'">
<case regex="true">
....
</case>
<default/>
</switch>
UPD
corrected XPath expression
Try this:
<property name="yourParamName" expression="$body/Users/User/UserID" scope="default" type="STRING"/>
You can read more on the predefined Synapse XPath variables here.

Resources