Client and Server UDP transport layer - udp

I need to send a message saying "Hi" from client to a server, the server will reply back to the client adding to the received message "Received", once the client receives this new message it will send this to another server and that server will add another message to the received message saying "Replied". So in the end the client will receive the message "Hi Received Replied".
Client code:
public class UDPClient{
public static void main(String args[]) {
// args[0] = message to be sent to the server;
// args[1] = IP address of the server
DatagramSocket aSocket=null;
try {
aSocket=new DatagramSocket();
byte [] m = args[0].getBytes();
InetAddress aHost = InetAddress.getByName(args[1]);
int serverPort = 6789;
DatagramPacket request = new DatagramPacket(m,args[0].length(), aHost, serverPort);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer,buffer.length);
aSocket.receive(reply);
System.out.println("Reply: " + new String(reply.getData(), 0, reply.getLength()));
}catch (SocketException e){System.out.println("Socket: " + e.getMessage());
}catch (IOException e){System.out.println("IO: " + e.getMessage());
}finally {
if(aSocket != null) aSocket.close();
}
}
}
Server Code:
public class UDPServer{
public static void main(String args[]) {
DatagramSocket aSocket = null;
try{
aSocket = new DatagramSocket(6789);
byte[] buffer = new byte[1000];
while(true){
DatagramPacket request = new DatagramPacket(buffer,buffer.length);
aSocket.receive(request);
System.out.println("Server is ready and waiting for requests ... ");
DatagramPacket reply = new DatagramPacket(request.getData(), request.getLength(),request.getAddress(), request.getPort());
}
}catch (SocketException e){System.out.println("Socket: " + e.getMessage());
}catch (IOException e) {System.out.println("IO: " + e.getMessage());
}finally {
if(aSocket != null) aSocket.close();
}
}
}

Related

UDP Port Hole Punching C#

i am trying to make two clients behind NAT communicates each other using a server with port forward working, my scenario:
Server start listering on port 45000 for Client_A connection;
Server Start listering on port 45001 for Client_B connection;
Client_A connect to server on port 45000 and send hello message;
Client_B connect to server on port 45001 and send hello message;
Server Receive hello message from Client_B and send message with Client_B external port (ex 56000) to Client_B;
Client_B receive external port and start listering on port 56000;
Server Receive hello message from Client_A and send message with Client_B IP and port to Client_A;
Client_A receive IP and Port of Client_B;
Client_A connect to Client_B and send hello message
The problem:
Client_B does not receive message from Client_A;
Here is the code:
Server:
static int server_A_Port = 45000;
static int server_B_Port = 45001;
static UdpClient server_A;
static UdpClient server_B;
static bool client_B_Connected = false;
static string client_A_Ip = "";
static string client_B_Ip = "";
static int client_A_Port = 0;
static int client_B_Port = 0;
static Thread Server_A_Thread = new Thread(Start_Server_A);
static Thread Server_B_Thread = new Thread(Start_Server_B);
static void Main(string[] args)
{
Server_A_Thread.Start();
Server_B_Thread.Start();
}
static void Start_Server_A()
{
Console.WriteLine("Starting Server_A on port: " + server_A_Port);
server_A = new UdpClient();
IPEndPoint client_A_IpEp = new IPEndPoint(IPAddress.Any, server_A_Port);
server_A.Client.Bind(client_A_IpEp);
Console.WriteLine("Server Started. Waiting Client_A Message");
string c_a = "";
while (string.IsNullOrEmpty(c_a))
{
try
{
c_a = ReceiveMessageFromClient(server_A, ref client_A_IpEp);
Console.WriteLine("Message received from Client_A: " + c_a);
client_A_Ip = ((IPEndPoint)client_A_IpEp).Address.ToString();
client_A_Port = ((IPEndPoint)client_A_IpEp).Port;
server_A.Connect(client_A_IpEp);
}
catch(Exception err)
{
Thread.Sleep(1000);
}
}
Console.WriteLine("Waiting Client_B connection");
bool sended = false;
while (!sended)
{
if(client_B_Connected)
{
Console.WriteLine("Client_B connected, sending Client_B IP and Port to Client_A");
SendMessageToClient(server_A, client_B_Ip + ":" + client_B_Port);
sended = true;
Console.WriteLine("Message Sended to Client_A");
break;
}
Thread.Sleep(1000);
}
Console.ReadLine();
}
static void Start_Server_B()
{
Console.WriteLine("Starting Server_B on port: " + server_B_Port);
server_B = new UdpClient();
IPEndPoint client_B_IpEp = new IPEndPoint(IPAddress.Any, server_B_Port);
server_B.Client.Bind(client_B_IpEp);
Console.WriteLine("Server Started. Waiting Client_B Message");
string c_b = "";
while (string.IsNullOrEmpty(c_b))
{
try
{
c_b = ReceiveMessageFromClient(server_B, ref client_B_IpEp);
Console.WriteLine("Message received from Client_B: " + c_b);
client_B_Ip = ((IPEndPoint)client_B_IpEp).Address.ToString();
client_B_Port = ((IPEndPoint)client_B_IpEp).Port;
server_B.Connect(client_B_IpEp);
client_B_Connected = true;
}
catch (Exception err)
{
Thread.Sleep(1000);
}
}
Console.WriteLine("Sending external Port to Client_B start listering");
SendMessageToClient(server_B,client_B_Port + "");
}
static void SendMessageToClient(UdpClient client, string message)
{
byte[] data = Encoding.GetEncoding(28591).GetBytes(message);
client.Send(data, data.Length);
}
static string ReceiveMessageFromClient(UdpClient client, ref IPEndPoint ep)
{
byte[] data = client.Receive(ref ep);
string receivedString = Encoding.GetEncoding(28591).GetString(data);
return receivedString;
}
Client_A
static string serverIp = "X.X.X.X";
static int serverPort = 45000;
static string otherClientIp = "0.0.0.0";
static int otherClientPort = 0;
static UdpClient client = new UdpClient();
static void Main(string[] args)
{
Console.WriteLine("Connecting to server...");
client.Connect(serverIp, serverPort);
Console.WriteLine("Connected. Sending request message...");
SendMessageToServer();
Console.WriteLine("Sended. Waiting response...");
string s = "";
while (string.IsNullOrEmpty(s))
{
try
{
s = ReceiveMessageFromServer();
Console.WriteLine("Response received from server.");
}
catch (Exception err)
{
Thread.Sleep(1000);
}
}
string[] otherClientInfo = s.Split(':');
otherClientIp = otherClientInfo[0];
otherClientPort = int.Parse(otherClientInfo[1]);
Console.WriteLine("Other Client info: " + otherClientIp + ":" + otherClientPort);
Thread.Sleep(2000);
Console.WriteLine("Connecting to Client_B...");
client.Connect(otherClientIp, otherClientPort);
Console.WriteLine("Connected. Sending hello hessage...");
SendMessageToClient();
Console.WriteLine("Sended. Waiting response...");
string c = "";
while (string.IsNullOrEmpty(c))
{
try
{
IPEndPoint ep = (IPEndPoint)client.Client.RemoteEndPoint;
c = ReceiveMessageFromClient(client,ref ep);
Console.WriteLine("Response received from Client_B.");
Console.WriteLine("Response: " + c);
Console.ReadLine();
}
catch (Exception err)
{
Thread.Sleep(1000);
}
}
}
static void SendMessageToServer()
{
byte[] data = Encoding.GetEncoding(28591).GetBytes("FROM CLIENT TO SERVER");
client.Send(data, data.Length);
}
static void SendMessageToClient()
{
byte[] data = Encoding.GetEncoding(28591).GetBytes("FROM CLIENT_A TO CLIENT_B");
client.Send(data, data.Length);
}
static string ReceiveMessageFromServer()
{
IPEndPoint serverIpEp = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);
byte[] data = client.Receive(ref serverIpEp);
string receivedString = Encoding.GetEncoding(28591).GetString(data);
return receivedString;
}
static string ReceiveMessageFromClient(UdpClient server, ref IPEndPoint ep)
{
byte[] data = server.Receive(ref ep);
string receivedString = Encoding.GetEncoding(28591).GetString(data);
return receivedString;
}
Client_B
static string serverIp = "X.X.X.X";
static int serverPort = 45001;
static UdpClient client = new UdpClient();
static void Main(string[] args)
{
Console.WriteLine("Connecting to server...");
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
client.Connect(serverIp, serverPort);
Console.WriteLine("Connected. Sending request message...");
SendMessageToServer();
Console.WriteLine("Sended. Waiting response...");
string s = "";
while (string.IsNullOrEmpty(s))
{
try
{
s = ReceiveMessageFromServer();
Console.WriteLine("Response received from server.");
}
catch (Exception err)
{
Thread.Sleep(1000);
}
}
Console.WriteLine("My External Port: " + s);
//IPEndPoint ep = new IPEndPoint(IPAddress.Any, ((IPEndPoint)client.Client.LocalEndPoint).Port);
IPEndPoint ep = new IPEndPoint(IPAddress.Any, int.Parse(s));
Console.WriteLine("Start Binding on Extenal Port: " + ep.Port);
UdpClient server = new UdpClient();
server.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
server.Client.Bind(ep);
Console.WriteLine("Started. Waiting hello message...");
string c = "";
while (string.IsNullOrEmpty(c))
{
try
{
c = ReceiveMessageFromClient(server, ref ep);
Console.WriteLine("Response received from Client_A.");
Console.WriteLine("Response: " + c);
client.Connect(ep);
Console.ReadLine();
}
catch (Exception err)
{
}
}
Console.WriteLine("Sending message to Client_A...");
SendMessageToClient();
Console.WriteLine("Sended.");
Console.ReadLine();
var myRule = FirewallManager.Instance.Rules.SingleOrDefault(r => r.Name == "TEST_RULE");
FirewallManager.Instance.Rules.Remove(myRule);
}
static void SendMessageToServer()
{
byte[] data = Encoding.GetEncoding(28591).GetBytes("FROM CLIENT TO SERVER");
client.Send(data, data.Length);
}
static void SendMessageToClient()
{
byte[] data = Encoding.GetEncoding(28591).GetBytes("FROM CLIENT_B TO CLIENT_A");
client.Send(data, data.Length);
}
static string ReceiveMessageFromServer()
{
IPEndPoint serverIpEp = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);
byte[] data = client.Receive(ref serverIpEp);
string receivedString = Encoding.GetEncoding(28591).GetString(data);
return receivedString;
}
static string ReceiveMessageFromClient(UdpClient server, ref IPEndPoint ep)
{
byte[] data = server.Receive(ref ep);
string receivedString = Encoding.GetEncoding(28591).GetString(data);
return receivedString;
}
I have no idea what's wrong and how to make it work, I've researched a lot and haven't found the solution.
Sorry for bad english

How to get Messages by the consumer according to priority of the messages set by the publishers RabbitMQ

I have publish messages with some priority set for a single consumer(i.e single consumer that may receive messages according to message priority).
What i want is to get that messages and print them according to the message priority on the consumer side. Hey guys Help me out in this !
public class Send extends Thread {
int priority;
String name = "";
String app_type = "";
private static final String EXCHANGE_NAME = "topic_exchange";
public void run()
{
ConnectionFactory connFac = new ConnectionFactory();
connFac.setHost("localhost");
try {
Connection conn = connFac.newConnection();
Channel channel = conn.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME,
BuiltinExchangeType.TOPIC);
for(int j=1; j<=200; j++)
{
randomWait();
int random = (int)(Math.random() * 10 + 1);
String routingKey = j+"."+"update"+"."+app_type;
String msg = name;
channel.basicPublish(EXCHANGE_NAME, routingKey, new
AMQP.BasicProperties.Builder()
.contentType("text/plain")
.deliveryMode(2)
.priority(priority)
.build(),
msg.getBytes("UTF-8"));
System.out.println("Sent " + routingKey + " : " + msg +
" "+" Priority : "+priority);
}
channel.close();
conn.close();
} catch (IOException ex) {
Logger.getLogger(Send.class.getName()).log(Level.SEVERE, null,
ex);
System.out.println("Exception1 :--"+ex);
} catch (TimeoutException ex) {
Logger.getLogger(Send.class.getName()).log(Level.SEVERE, null,
ex);
System.out.println("Exception 2:--"+ex);
}
}
void randomWait()
{
try {
Thread.currentThread().sleep((long)(200*Math.random()));
} catch (InterruptedException x) {
System.out.println("Interrupted!");
}
}
public static void main(String[] args) {
// TODO code application logic here
Send test1 = new Send();
test1.name = "Hello ANDROID";
test1.app_type = "ANDROID";
test1.priority = 10;
Send test2 = new Send();
test2.name = "Hello ANDROID";
test2.app_type = "ANDROID";
test2.priority = 5;
test1.start();
test2.start();
}
}
In the above code I have use thread to pass the priority and message value and started the both the thread at the same time to publish messages with different priorities. I have set the priority value in the AMQ Builder.
The queue has to be configured to support priority.

Setting socket buffer size in Apache HttpClient

How do you set the socket buffer size in Apache HttpClient version 4.3.3?
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 128 * 1024);
HttpPost post = new HttpPost(url);
String res = null;
try
{
post.addHeader("Connection", "Keep-Alive");
post.addHeader("Content-Name", selectedFile.getName());
post.setEntity(new ByteArrayEntity(fileBytes));
HttpResponse response = client.execute(post);
res = EntityUtils.toString(response.getEntity());
}
catch (Exception e)
{
e.printStackTrace();
}
You create a custom ConnectionConfig object with your desired buffer size and pass it as a parameter when creating your HttpClient object. For example:
ConnectionConfig connConfig = ConnectionConfig.custom()
.setBufferSize(DESIRED_BUFFER_SIZE)
.build();
try (CloseableHttpClient client = HttpClients.custom()
.setDefaultConnectionConfig(connConfig)
.build()) {
HttpGet get = new HttpGet("http://google.com");
try (CloseableHttpResponse response = client.execute(get)) {
// Do something with the response
} catch (IOException e) {
System.err.println("Error transferring file: " + e.getLocalizedMessage());
}
} catch (IOException e) {
System.err.println("Error connecting to server: " + e.getLocalizedMessage());
}
There are lots of other configurable options available, checkout the API for the full list.

Client giving error when invoking a secured web service

I have written a client that invokes webservice. My client is:
String publisherEPR = "https://abc:8280/services/ProviderPublication";
protected void publicationOpenSession(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Inside publicationOpenSession");
date = new Date();
namespace = "http://www.openoandm.org/xml/ISBM/";
fac = OMAbstractFactory.getOMFactory();
OMNamespace ns = fac.createOMNamespace(namespace, "ns1");
OMElement result = null;
channelURI = request.getParameter("TxtPublisher1ChannelURI");
textfield = request.getParameter("TxtAreaServicePublisherLog");
String finalChannelURI = "";
int count = 0;
try {
if (channelURI != null && (channelURI.indexOf(".") > -1)) {
System.out.println("Inside If Checking Channel URI");
String[] tempChannelURI = channelURI.split("\\.");
for (count = 0; count < tempChannelURI.length - 1; count++) {
finalChannelURI = finalChannelURI + tempChannelURI[count];
if (count < tempChannelURI.length - 2) {
finalChannelURI = finalChannelURI + ".";
}
}
System.out.println("Inside If Checking Channel URI : " + finalChannelURI);
}
System.out.println("OpenPublicationSession" + finalChannelURI);
System.out.println(publisherEPR);
OMElement OpenPublicationSessionElement = fac.createOMElement("OpenPublicationSession", ns);
OMElement ChannelURIElement = fac.createOMElement("ChannelURI", ns);
ChannelURIElement.setText(finalChannelURI);
OpenPublicationSessionElement.addChild(ChannelURIElement);
String webinfFolder = request.getSession().getServletContext().getRealPath("/WEB-INF");
ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
webinfFolder, webinfFolder + "/conf/axis2.xml");
Options options = new Options();
ServiceClient client = new ServiceClient(ctx, null);
EndpointReference targetEPR = new EndpointReference(publisherEPR);
options.setTo(targetEPR);
options.setAction("urn:OpenPublicationSession");
options.setManageSession(true);
options.setUserName(user_name);
java.util.Map<String, Object> m = new java.util.HashMap<String, Object>();
/*m.put("javax.net.ssl.trustStorePassword", "wso2carbon");
m.put("javax.net.ssl.trustStore", "wso2carbon.jks");
*/
System.out.println(new Date() + " Checkpoint1");
// We are accessing STS over HTTPS - so need to set trustStore parameters.
System.setProperty("javax.net.ssl.trustStore", "client.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "apache");
/*m.put("javax.net.ssl.trustStore", "client.jks");
m.put("javax.net.ssl.trustStorePassword", "apache");*/
/*m.put("org.apache.ws.security.crypto.provider","org.apache.ws.security.components.crypto.Merlin");
m.put("org.apache.ws.security.crypto.merlin.keystore.type", "jks");
m.put("org.apache.ws.security.crypto.merlin.keystore.password","apache");
m.put("org.apache.ws.security.crypto.merlin.file", "client.jks");*/
//options.setProperties(m);
System.out.println(new Date() + " Checkpoint2");
client.setOptions(options);
MessageContext messageContext = new MessageContext();
messageContext.setOptions(options);
messageContext.setMessageID("MyMessageID");
System.out.println("provider:user_name: " + user_name);
messageContext.setProperty("username", user_name);
messageContext.setProperty("password", user_password);
MessageContext.setCurrentMessageContext(messageContext);
messageContext.setProperty("myproperty", "mypropertyvalue");
String falconNS = "http://cts.falcon.isbm";
falcon = fac.createOMNamespace(falconNS, "falcon");
OMElement falconUserElement = fac.createOMElement("FalconUser", falcon);
falconUserElement.setText(user_name);
client.addHeader(falconUserElement);
// invoke web-service
try {
errorText = "Client Didnt Respond.";
result = client.sendReceive(OpenPublicationSessionElement);
System.out.println(result.toString());
OMElement SessionIDElement = null;
SessionIDElement = result.getFirstChildWithName(new QName(namespace, "SessionID"));
SessionID = SessionIDElement.getText();
request.setAttribute("PublisherSession", SessionID);
StringBuffer text = new StringBuffer();
text.append((request.getParameter("TxtAreaServicePublisherLog")).trim());
text.trimToSize();
SessionID = SessionIDElement.getText();
StringBuffer publisherLog = new StringBuffer();
publisherLog.append((request.getParameter("TxtAreaServicePublisherLog")).trim());
publisherLog.trimToSize();
System.out.println("Checkpoint1");
publisherLog.append("\n" + new Date().toString() + " " + PUBLISHER_SESSION_SUCCESS_MSG + SessionID);
request.setAttribute("textMessageService2", publisherLog);
request.setAttribute("PublisherSession", SessionID);
System.out.println("Checkpoint3");
RequestDispatcher rd = request.getRequestDispatcher("/Provider.jsp");// hard-coded
try {
rd.forward(request, response);
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ServletException se) {
se.printStackTrace();
}
} catch (Exception e) {
errorText = "Client not responding";
buildErrorLog(request, response, e);
e.printStackTrace();
}
//buildCallLog(request, response, result);
} catch (Exception e) {
e.printStackTrace();
buildErrorLog(request, response, e);
}
}
And i have a proxy service upon which i have implemented security and its url is:
https://abc:8280/services/ProviderPublication.
My handle method inside callback handler is:
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
System.out.println("\n \n " + new Date() + " ISBMClient.PWCBHandler.handle");
if(MessageContext.getCurrentMessageContext() == null){
System.out.println("CurrentMessageContext is null");
}else{
//get the credentials from the jsp
System.out.println("MessageID: " + MessageContext.getCurrentMessageContext().getMessageID());
dynamicUser = MessageContext.getCurrentMessageContext().getProperty("username").toString();
dynamicPassword = MessageContext.getCurrentMessageContext().getProperty("password").toString();
System.out.println("MessageContext user_name: " + dynamicUser);
System.out.println("MessageContext user_password: " + dynamicPassword);
}
for (int i = 0; i < callbacks.length; i++) {
WSPasswordCallback pwcb = (WSPasswordCallback)callbacks[i];
pwcb.setIdentifier(dynamicUser);
String id = pwcb.getIdentifier();
System.out.println("Invoking service with user: " + id);
if(dynamicUser.equals(id)){
pwcb.setPassword(dynamicPassword);
}
}
}
Now the problem is when i invoke this proxy service through my client code i am getting exception as
[INFO] Unable to sendViaPost to url[https://abc:8280/services/ProviderPublication]
org.apache.axis2.AxisFault: Trying to write END_DOCUMENT when document has no root (ie. trying to output empty document).
at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)
at org.apache.axis2.transport.http.SOAPMessageFormatter.writeTo(SOAPMessageFormatter.java:78)
at org.apache.axis2.transport.http.AxisRequestEntity.writeRequest(AxisRequestEntity.java:84)
at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:499)
at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:621)
at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:193)
at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:404)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:231)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:443)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:406)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:555)
at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:531)
at cts.falcon.isbm.client.Provider.publicationOpenSession(Provider.java:557)
at cts.falcon.isbm.client.Provider.doPost(Provider.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.xml.stream.XMLStreamException: Trying to write END_DOCUMENT when document has no root (ie. trying to output empty document).
at com.ctc.wstx.sw.BaseStreamWriter.throwOutputError(BaseStreamWriter.java:1473)
at com.ctc.wstx.sw.BaseStreamWriter.reportNwfStructure(BaseStreamWriter.java:1502)
at com.ctc.wstx.sw.BaseStreamWriter.finishDocument(BaseStreamWriter.java:1663)
at com.ctc.wstx.sw.BaseStreamWriter.close(BaseStreamWriter.java:288)
at org.apache.axiom.util.stax.wrapper.XMLStreamWriterWrapper.close(XMLStreamWriterWrapper.java:46)
at org.apache.axiom.om.impl.MTOMXMLStreamWriter.close(MTOMXMLStreamWriter.java:222)
at org.apache.axiom.om.impl.llom.OMSerializableImpl.serializeAndConsume(OMSerializableImpl.java:192)
at org.apache.axis2.transport.http.SOAPMessageFormatter.writeTo(SOAPMessageFormatter.java:74)
... 38 more
But the same code is working for another web service written in eclipse. What am i doing wrong? Looking forward to your answers. Thanks in advance
You need to set SOAP envelope along with SOAP body which carries your payload from Service Client. I think that cause this problem. Please refer this blog post and refactor your code to add that.
http://amilachinthaka.blogspot.com/2009/09/sending-arbitrary-soap-message-with.html
A little late on the response here, but I ran into the same error message and after further digging it was due to some SSL certificate failures.
There were 2 ways to fix this:
Adding trusted certificate to Java using the keytool command.
OR
Using your own custom code to accept all certs (ex. below with a acceptallCerts() method)
public class SslUtil {
private static class SmacsTrustManager implements X509TrustManager {
#Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
#Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
public static void acceptAllCerts(){
try{
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] {new SmacsTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
}catch (Exception e){
}
}
}

JMS message consumption isn't happening outside of a bean

I'm running through a Glassfish web process and I need a non-container managed class (EJBUserManager) to be able to receive messages from a MessageDrivenBean. The class has the javax.jms.Queues and connection factories and I can write to the Queues. The queue sends to a MessageDrivenBean (AccountValidatorBean) that receives the code correctly, and then writes back a message. But the EJBUserManager attempts to read from the queue and never receives the message.
#Override
public boolean doesExist(String username) throws FtpException {
LOGGER.finer(String.format("Query if username %s exists", username));
QueueConnection queueConnection = null;
boolean doesExist = false;
try {
queueConnection = connectionFactory.createQueueConnection();
final UserManagerMessage userManagerMessage =
new UserManagerMessage(UserManagerQueryCommands.VALIDATE_USER, username);
final Session session = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
final ObjectMessage objectMessage = session.createObjectMessage(userManagerMessage);
session.createProducer(accountValidatorQueue).send(objectMessage);
session.close();
queueConnection.close();
queueConnection = connectionFactory.createQueueConnection();
final QueueSession queueSession =
queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
LOGGER.finest(String.format("Right before doesExist receive for username %s", username));
final Message firstAttemptMessage = queueSession.createConsumer(userManagerQueue).receive(3000);
final Message message = firstAttemptMessage != null ?
firstAttemptMessage : queueSession.createConsumer(userManagerQueue).receiveNoWait();
LOGGER.finest(String.format("Right after doesExist receive for username %s", username));
LOGGER.finest(String.format("Is the message null: %b", message != null));
if (message != null && message instanceof StreamMessage) {
final StreamMessage streamMessage = (StreamMessage) message;
doesExist = streamMessage.readBoolean();
}
} catch (JMSException e) {
e.printStackTrace();
} finally {
if (queueConnection != null) {
try {
queueConnection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
return doesExist;
}
The above is the code from the EJBUserManager. Now, it can send to the accountValidatorQueue. It just never receives from the userManagerQueue
Here's the code for the AccountValidatorBean
private void validateUser(final String username) {
QueueConnection queueConnection = null;
final String doctype = doctypeLookupDAO.getDocumentTypeForUsername(username);
LOGGER.finest(String.format("Doctype %s for username %s", doctype, username));
try {
queueConnection = queueConnectionFactory.createQueueConnection();
final Session session = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//final StreamMessage message = session.createStreamMessage();
//message.clearBody();
//message.writeBoolean(doctype != null);
//message.reset();
final ObjectMessage message = session.createObjectMessage(Boolean.valueOf(doctype != null));
final MessageProducer messageProducer =
session.createProducer(userManagerQueue);
LOGGER.finest(String.format("Queue name %s of producing queue", userManagerQueue.getQueueName()));
messageProducer.send(message);
LOGGER.finest(String.format("Sending user validate message for user %s", username));
messageProducer.close();
session.close();
} catch (JMSException e) {
e.printStackTrace();
} finally {
if (queueConnection != null) {
try {
queueConnection.close();
} catch (JMSException e1) {
e1.printStackTrace();
}
}
}
}
Fixed. I needed to call QueueConnection.start() to consume messages from the queue.