I want to send the following IQ stanza to Ejabberd XMPP Server using Smack Android Library. How can I send?
<iq from='hag66#shakespeare.example'
to='coven#muc.shakespeare.example'
type='set'
id='E6E10350-76CF-40C6-B91B-1EA08C332FC7'>
<subscribe xmlns='urn:xmpp:mucsub:0'
nick='mynick'
password='roompassword'>
<event node='urn:xmpp:mucsub:nodes:messages' />
<event node='urn:xmpp:mucsub:nodes:affiliations' />
<event node='urn:xmpp:mucsub:nodes:subject' />
<event node='urn:xmpp:mucsub:nodes:config' />
</subscribe>
</iq>
I want to Subscribe to MUC/Sub events as described in https://docs.ejabberd.im/developer/xmpp-clients-bots/proposed-extensions/muc-sub/
I have done using following code please check might be helpful you.
try {
IQ iq=new IQ("mynick","urn:xmpp:mucsub:0") {
#Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.setEmptyElement();
return xml;
}
};
iq.setType(IQ.Type.get);
//add your urn:xmpp:muclight:0#affiliations extension element
iq.addExtension();
iq.setTo(AppConstants.CHAT_HOSTNAME);
iq.setFrom(connection.getUser());
debugLog("ping send stanza:"+iq.toXML());
connection.sendStanza(iq);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Related
I have an Azure bot service which runs perfectly when tested on webchat.
Now I tried to open a websocket and test the bot.
I first send a POST request (with all required headers) to https://directline.botframework.com/v3/directline/conversations
I get a response with
{
"conversationId": "7FY18sO6FCT9OVi0pW7WBY",
"token": "my_token_here",
"expires_in": 1800,
"streamUrl":
"wss://directline.botframework.com/v3/directline/conversations/7FY18sO6FCT9OVi0pW7WBY/stream?watermark=-&t=token_value_here",
"referenceGrammarId": "c1c290dd-f896-5857-b328-cdc10298e440"
}
Now I try to use the streamUrl to send/receive data using web socket.
I got an error: Undefined
I tried to test the streamUrl on different online websocket testing tool. I still got the undefined error.
How can I test whether there is a problem in the streamUrl?
How can I test the web socket?
Firstly, as Eric Dahlvang mentioned, it enables us to receive activities via WebSocket stream, but not send activities.
Besides, I do a test with the following steps and sample, the activities can be received as expected via WebSocket stream, you can refer to it.
Step1: make a request to start a conversation
Step2: start client app (a console application) to wait for receiving acitivities
class Program
{
private static string botId = "fehanbasicbot";
static void Main(string[] args)
{
var url = Console.ReadLine();
StartReceivingActivities(url).Wait();
Console.ReadLine();
}
private static async Task StartReceivingActivities(string url)
{
var webSocketClient = new WebSocket(url);
webSocketClient.OnMessage += WebSocketClient_OnMessage;
webSocketClient.Connect();
}
private static void WebSocketClient_OnMessage(object sender, MessageEventArgs e)
{
// Occasionally, the Direct Line service sends an empty message as a liveness ping. Ignore these messages.
if (string.IsNullOrWhiteSpace(e.Data))
{
return;
}
var activitySet = JsonConvert.DeserializeObject<ActivitySet>(e.Data);
var activities = from x in activitySet.Activities
where x.From.Id == botId
select x;
foreach (Activity activity in activities)
{
Console.WriteLine(activity.Text);
}
}
}
packages.config
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Bot.Connector.DirectLine" version="3.0.2" targetFramework="net461" />
<package id="Microsoft.Rest.ClientRuntime" version="2.3.2" targetFramework="net461" />
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net461" />
<package id="WebSocketSharp" version="1.0.3-rc11" targetFramework="net461" />
</packages>
Step3: make a request to send an activity to the bot
Step4: check the console app output, I can find the activities are received
I have a requirement where I need to expose a SOAP webservice .. So I have the following Mule flow :-
<jms:activemq-connector name="Active_MQ" brokerURL="tcp://localhost:61616" validateConnections="true" doc:name="Active MQ"/>
<flow name="Flow1" doc:name="Flow1" >
<http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8082" path="mainData" doc:name="HTTP"/>
<cxf:jaxws-service serviceClass="com.test.services.schema.maindata.v1.MainData" doc:name="SOAP"/>
<mulexml:object-to-xml-transformer doc:name="Object to XML"/>
<jms:outbound-endpoint queue="NewQueue" connector-ref="Active_MQ" doc:name="JMS" exchange-pattern="request-response"/>
<logger message="Response2 :- #[message.payload]" level="INFO" doc:name="Logger"/>
<mulexml:xml-to-object-transformer doc:name="XML to Object"/>
</flow>
<flow name="flow2" doc:name="flow2" >
<jms:inbound-endpoint connector-ref="Active_MQ" address="jms://tcp:NewQueue" doc:name="JMS" exchange-pattern="request-response" disableTemporaryReplyToDestinations="true" responseTimeout="90000"/>
<set-variable variableName="SOAPRequest" value="#[message.payload]" doc:name="Variable"/>
<mulexml:xml-to-object-transformer doc:name="XML to Object"/>
<component class="com.test.services.schema.maindata.v1.Impl.MainDataImpl" doc:name="JavaMain_ServiceImpl">
<method-entry-point-resolver>
<include-entry-point method="retrieveDataOperation"/>
<include-entry-point method="insertDataOperation"/>
<include-entry-point method="updateDataOperation"/>
<include-entry-point method="deleteDataOperation"/>
</method-entry-point-resolver>
</component>
<mulexml:object-to-xml-transformer doc:name="Object to XML"/>
</flow>
Here you can see the request is getting into JMS queue from the first flow and the second flow use JMS inbound takes it from the JMS queue and the webservice implemented class proccess it .. Now the service works fine without any issue .. the only issue is it get Mule Header in the SOAP in the response like the following :-
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<mule:header xmlns:mule="http://www.muleumo.org/providers/soap/1.0">
<mule:MULE_CORRELATION_ID>ID:ANIRBAN-PC-49483-1408719168461-1:1:10:1:1</mule:MULE_CORRELATION_ID>
<mule:MULE_CORRELATION_GROUP_SIZE>-1</mule:MULE_CORRELATION_GROUP_SIZE>
<mule:MULE_CORRELATION_SEQUENCE>-1</mule:MULE_CORRELATION_SEQUENCE>
</mule:header>
</soap:Header>
<soap:Body>
<deleteDataResponse xmlns="http://services.test.com/schema/MainData/V1">
<Response>Data not exists !!! Please provide correct ID</Response>
<Id>0</Id>
<Age>0</Age>
</deleteDataResponse>
</soap:Body>
</soap:Envelope>
Now please help me to remove the Mule headers from the SOAP response .. I tried with the following :- <cxf:jaxws-service serviceClass="com.test.services.schema.maindata.v1.MainData" enableMuleSoapHeaders="false" doc:name="SOAP"/> but no use .. it's still showing the Mule headers .. Please help ..
You can potentially get away with a temporary workaround until the enableMuleSoapHeaders="false" issue gets solved, by either:
Adding a between the HTTP inbound endpoint and the CXF service ; in order to remove the undue SOAP headers but XSL-Transformation
Using delete-message-property to remove the MULE_* props at the end of Flow1, right after the mulexml:xml-to-object-transformer
I also found an alternate solution off adding it to cxf:outInterceptors
<cxf:jaxws-service serviceClass="com.test.services.schema.maindata.v1.MainData" doc:name="SOAP">
<cxf:outInterceptors >
<spring:bean id="outfault" class="com.test.services.schema.SOAPOptionalData.SOAPInterceptorOutboundHeaderRemover"/>
</cxf:outInterceptors>
</cxf:jaxws-service>
And in the Java class :-
public class SOAPInterceptorOutboundHeaderRemover extends AbstractSoapInterceptor {
public SOAPInterceptorOutboundHeaderRemover() {
super(Phase.PRE_PROTOCOL);
}
#Override
public void handleMessage(SoapMessage arg0) throws Fault {
List<Header> headerList = arg0.getHeaders();
Header muleHeader = null;
boolean isMuleHeader = false;
for (Header header : headerList) {
ElementNSImpl element = (ElementNSImpl) header.getObject();
if ("mule:header".equals(element.getNodeName())) {
isMuleHeader = true;
muleHeader = header;
}
}
if (isMuleHeader) {
arg0.getHeaders().remove(muleHeader);
}
}
}
And this is also working fine
I am trying to implement Supersockets - https://supersocket.codeplex.com/ for a project i am working on. I have the a server that uses configuration to run.
In my project
I have referenced:
SuperSocket.Common,
SuperSocket.SocketBase,
SuperSocket.SocketEngine
I added the following config section:
<configSections>
<section name="superSocket" type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="ServiceName" value="SomeService" />
</appSettings>
<superSocket logFactory="ConsoleLogFactory"
disablePerformanceDataCollector="true"
maxWorkingThreads="500"
maxCompletionPortThreads="500"
minWorkingThreads="5"
minCompletionPortThreads="5">
<servers>
<server name="SomeService"
serverType="SomeService.Server.SomeService, SomeService"
ip="192.168.1.107"
port="4096"
disableSessionSnapshot="true"
clearIdleSession="false"
maxConnectionNumber="10"
sendWelcome="false">
</server>
</servers>
<logFactories>
<add name="ConsoleLogFactory"
type="SuperSocket.SocketBase.Logging.ConsoleLogFactory, SuperSocket.SocketBase" />
</logFactories>
</superSocket>
I also created the server and session class as follows:
namespace SomeService.Server
{
class SomeService: AppServer<SomeServiceSession>
{
protected override bool Setup(IRootConfig rootConfig, IServerConfig config)
{
return base.Setup(rootConfig, config);
}
protected override void OnStartup()
{
base.OnStarted();
}
protected override void OnStopped()
{
base.OnStopped();
}
}
}
namespace SomeService.Server
{
class SomeServiceSession : AppSession<SomeServiceSession>
{
protected override void OnSessionStarted()
{
// this.Send("Welcome to SuperSocket Telnet Server");
}
protected override void HandleUnknownRequest(StringRequestInfo requestInfo)
{
this.Send("Unknow request");
}
protected override void HandleException(Exception e)
{
this.Send("Application error: {0}", e.Message);
}
protected override void OnSessionClosed(CloseReason reason)
{
//add you logics which will be executed after the session is closed
base.OnSessionClosed(reason);
}
}
}
At this point the Server runs and it listens on a port as intended. Here is a wireshark representation of what i would want to do With SuperSocket http://imgur.com/rxKJbOD.
If you see on the request reply one chuck of the data :
.MSH|^~\&|MRI|ABC|||201403251406||QRY|173883426|P|2.1
QRD|201403251406|R|I|xxxxx|||25^RD|AB851656^|MPI
QRF|UPI||||
.
is from the client and
.MSH|^~\&|MRI|ABC|||201403251406||QRY|173883426|P|2.1
QRD|201403251406|R|I|xxxx|||25^RD|AB851656^|MPI
QRF|UPI||||
MSA|AA|173883426
.
is from the server. the response returned varies depending on the request and what is created after the business logic executes (but it is always going to be the same format- HL7 en(dot)wikipedia(dot)org/wiki/Health_Level_7 ). HL7 follows MLLP messaging format where each message begins with a Start Block code (0x0B) and each segment within the message is terminated with a Carriage Return code (0x0D) and each message is terminated by an End Block code (0x1C) followed by a Carriage Return code (0x0D). Once i get the request i have a business logic class that parses out the values, calls a web service gets the data and constructs a the tcp reply. What i would like to know is where in SuperSocket can i have a method or event listener to read the buffer and do my business logic and return the response for the same session. I know that there are concepts like filters and commands in SuperSocket but i haven't been able to figure them out. Any help is greatly appreciated. Let me know if you need additional detail.
I would like to ask how to add file as attachment in Mule (3.4.0)?
I tried many solutions and googled a lot but haven't found anything good.
This is what I have now (last try before posting here):
<sub-flow name="sendBackMail" doc:name="sendBackMail">
<set-attachment attachmentName="changed.xml" value="#[payload]" contentType="text/xml" doc:name="Attachment"/>
<logger message="Attachment ok" level="INFO" doc:name="Logger"/>
<file:file-to-byte-array-transformer doc:name="File to Byte Array"/>
<logger message="Attachment ok. Message: #[message]" level="INFO" doc:name="Logger"/>
<smtps:outbound-endpoint host="${mailSMTP}" port="${mailSendPort}"
user="${mailUser}" password="${mailPass}" to="${receiver}"
from="${mailUser}" responseTimeout="60000" doc:name="SMTP"
connector-ref="SMTP" mimeType="text/xml" subject="msp2bass" >
</smtps:outbound-endpoint>
</sub-flow>
It sends mail but I get content of xml file as body of mail.
What should I do/change so that mail would be sent as attachment. I get file from another sevice, do XSLT on it and then I should send it to some mail.
Any more info I should provide?
Thank you!
EDIT
How I call bean:
<spring:bean id="SetAttachment" name="SetAttachment" class="si.irose.msp.cust.bass.SetAttachment">
</spring:bean>
<component doc:name="Java">
<spring-object bean="SetAttachment"/>
</component>
Java class:
package si.irose.msp.cust.bass;
import org.mule.api.MuleEventContext;
import org.mule.api.MuleMessage;
import org.mule.api.lifecycle.Callable;
public class SetAttachment implements Callable{
private MuleMessage mule;
private String name;
#Override
public Object onCall(MuleEventContext eventContext) throws Exception {
mule = eventContext.getMessage();
String tryit="routeid";
for (int i=0;i<mule.getInvocationPropertyNames().toArray().length;i++) {
if (mule.getInvocationPropertyNames().toArray()[i].equals(tryit)) {
name=mule.getInvocationProperty(mule.getInvocationPropertyNames().toArray()[i].toString()).toString();
break;
}
}
mule.addOutboundAttachment(name, mule.getInvocationProperty(name), "text/xml");
return null;
}
}
Ok issue solved.
When you read from file inbound or generate with quartz (string or file) you can add "Attachment" directly BUT if you do an XSLT transformation and then try to send that payload via smtp, then you need to add "Object to String" transformer before attachment.
Final working solution:
<sub-flow name="sendBackMail" doc:name="sendBackMail">
<object-to-string-transformer doc:name="Object to String"/>
<set-attachment attachmentName="changed.xml" value="#[payload]" contentType="text/xml" doc:name="Attachment"/>
<logger message="Attachment ok" level="INFO" doc:name="Logger"/>
<file:file-to-byte-array-transformer doc:name="File to Byte Array"/>
<logger message="Attachment ok. Message: #[message]" level="INFO" doc:name="Logger"/>
<smtps:outbound-endpoint host="${mailSMTP}" port="${mailSendPort}"
user="${mailUser}" password="${mailPass}" to="${receiver}"
from="${mailUser}" responseTimeout="60000" doc:name="SMTP"
connector-ref="SMTP" mimeType="text/xml" subject="msp2bass" >
</smtps:outbound-endpoint>
</sub-flow>
I haven't checked yet what transformer you need to apply if you do any other job instead of XSLT so if anyone wish to add some knowledge to this then please do so and add comment.
You need to use set-payload before the smtps:outbound-endpoint to set the body of the email to whatever you want, otherwise it will contain the same value attached with set-attachment.
Also remove the file:file-to-byte-array-transformer: it's unclear what it's there for.
My Silverlight Client and REST Web Server(Implented using ASP.NET Handlers) both are on same domain.
Both HTTP and HTTPS protocol bindings are configured in IIS 7.0
When Request a URI using HTTPS , i Get Error " Message: "Security error."
But Same URI works just fine on HTTP request without any error
private void btnLoginWebRequest_Click(object sender, RoutedEventArgs e)
{
bool httpResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
bool httpsResult = WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);
this.Dispatcher.BeginInvoke(()=>
{
WebClient webClient = new WebClient();
webClient.Headers["CustomHeader"] = String.Format("myHeaders={0}", "Value");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(new Uri(#"https://xxx.xx.xxx.xxx/MyRESTApi/UserGroups"));
});
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
}
}
I Get a Error and e.Error contains the following Error information
{System.Security.SecurityException: Security error.
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.OpenReadAsyncCallback(IAsyncResult result)}
[System.Security.SecurityException]: {System.Security.SecurityException: Security error.
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.OpenReadAsyncCallback(IAsyncResult result)}
Data: {System.Collections.ListDictionaryInternal}
InnerException: null
Message: "Security error."
StackTrace: " at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)\r\n at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)\r\n at System.Net.WebClient.OpenReadAsyncCallback(IAsyncResult result)"
crossdomain.xml is as follows :-
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="*" secure="true"/>
<allow-http-request-headers-from domain="*" headers="*" secure="true"/>
</cross-domain-policy>
clientaccesspolicy.xml is as follows :-
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="https://"/>
<domain uri="http://"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
I Have seen many threads related to similar error on stack overflow but not able to resolve this issue by any of the solutions provided in those threads. Am i missing something?