How to call .Net webservice in Blackberry? - web-services

I would like to call .Net webservice from my Blackbrry application. How can I call webservice from my app and which protocol is user and which jar file i have to used to call webservice. and how to get responce from webservice in Blackberry?

you can use something like this (you probably need to setup correct request headers and cookies):
connection = (HttpConnection) Connector.open(url
+ ConnectionUtils.getConnectionString(), Connector.READ_WRITE);
connection.setRequestProperty("ajax","true");
connection.setRequestProperty("Cookie", "JSESSIONID=" + jsessionId);
inputStream = connection.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = inputStream.read(responseData))) {
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + responseCode);
}
responseString = rawResponse.toString();

Related

how do i process Flux<Object> returned by webflux at client side in plain java code

I have written a webservice using spring webflux and reactive mongodb connectors, but my client side could be non spring based client.
So, how do I write a plain java code to consume flex at client side?
ServerSide code:
#GetMapping(value = "/findAll")
public Flux<Security> findAll() {
Flux<Security> flux = service.findAll();
return flux;
}
Client side code:
public static void sendRequest() {
try {
long start = System.currentTimeMillis();
for (int i = 0; i <= 100; i++) {
long start1 = System.currentTimeMillis();
URL url = new URL("http://localhost:8080/findAll/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/stream+json");
if (conn.getResponseCode() == 200) {
// url = new URL("http://localhost:8182/status/");
String json = "";
try (BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())))) {
json = br.lines().collect(Collectors.joining());
}
conn.disconnect();
System.out.println("size of each Security: " + json.length());
ArrayList<Security> list = getListOfsecurities(json);
System.out.println(list.get(0).getIsin());
}
}
The above client side gives me an empty array.
I don't think it is possible. It's an asynchronous response.At least you have to use Java 5 Futures to invoke asynchronous response.

Receiving a Version Mismatch SOAP Fault even if Correct namespaces are used

I am using apache commons httpclient version 4.2 to execute a simple web service based on SOAP 1.2. I am able to fire the web service properly through SOAP UI but I am unable to do the same using Java.
Following is the method I'm using to invoke the service.
private static byte[] callSOAPServer(String body, String SOAP_ACTION,
String SERVER_URL) {
byte[] result = null;
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 15000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 35000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
/*
* httpclient.getCredentialsProvider().setCredentials( new
* AuthScope("os.icloud.com", 80, null, "Digest"), new
* UsernamePasswordCredentials(username, password));
*/
HttpPost httppost = new HttpPost(SERVER_URL);
httppost.setHeader("soapaction", SOAP_ACTION);
httppost.setHeader("Content-Type", "text/xml; charset=utf-8");
System.out.println("executing request" + httppost.getRequestLine());
// now create a soap request message as follows:
final StringBuffer soap = new StringBuffer();
soap.append("\n");
soap.append("");
// this is a sample data..you have create your own required data BEGIN
soap.append(" \n");
soap.append(" \n");
soap.append("" + body);
soap.append(" \n");
soap.append(" \n");
/* soap.append(body); */
// END of MEssage Body
soap.append("");
System.out.println("SOAP Request : " + soap.toString());
// END of full SOAP request message
try {
HttpEntity entity = new StringEntity(soap.toString(), HTTP.UTF_8);
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);// calling
// server
HttpEntity r_entity = response.getEntity(); // get response
System.out.println("Reponse Header:Begin..."); // response headers
System.out.println("Reponse Header StatusLine:"
+ response.getStatusLine());
Header[] headers = response.getAllHeaders();
for (Header h : headers) {
System.out.println("Reponse Header " + h.getName() + ": "
+ h.getValue());
}
System.out.println("Reponse Header END...");
if (r_entity != null) {
result = new byte[(int) r_entity.getContentLength()];
if (r_entity.isStreaming()) {
DataInputStream is = new DataInputStream(
r_entity.getContent());
is.readFully(result);
}
}
} catch (Exception E) {
System.out.println("Exception While Connecting " + E.getMessage());
E.printStackTrace();
}
httpclient.getConnectionManager().shutdown(); // shut down the
// connection
return result;
}
Following is my SOAP Request as well as the end point.
String soapRequest = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:typ=\"http://skash.service.sahaj.com/types/\">"
+ "<soap:Header/>"
+ "<soap:Body>"
+ "<typ:remoteSKASHDeductionElement>"
+ "<typ:vleId>?</typ:vleId>"
+ "<typ:paidAmt>?</typ:paidAmt>"
+ "<typ:refTxnId>?</typ:refTxnId>"
+ "</typ:remoteSKASHDeductionElement>"
+ "</soap:Body>"
+ "</soap:Envelope>";
String soapEndPoint = "http://xxx.xxx.xxx.xxx:xxxx/skashws/remoteSKASHDeductionSoap12HttpPort";
String soapAction = "http://xxx.xxx.xxx.xxx:xxxx//remoteSKASHDeduction";
// executeSOAPRequest(soapRequest, soapEndPoint, soapAction);
byte[] resp = callSOAPServer(soapRequest, soapAction, soapEndPoint);
System.out.println(IOUtils.toString(resp));
I can see that the namespace set to Envelope tag is for SOAP 1.2 and is well set. I am not sure where I'm going wrong. I am receiving the following version mismatch error.
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Header>
<env:Upgrade>
<env:SupportedEnvelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope" qname="soap12:Envelope"/>
</env:Upgrade>
</env:Header>
<env:Body>
<env:Fault xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<faultcode>env:VersionMismatch</faultcode>
<faultstring>Version Mismatch</faultstring>
<faultactor>http://schemas.xmlsoap.org/soap/actor/next</faultactor>
</env:Fault>
</env:Body>
you may use this code block
public class GenericSoapMessageFactory extends SaajSoapMessageFactory implements InitializingBean {
#Override
public SaajSoapMessage createWebServiceMessage(InputStream inputStream) throws IOException {
setMessageFactoryForRequestContext(soap11);
if (inputStream instanceof TransportInputStream) {
TransportInputStream transportInputStream = (TransportInputStream) inputStream;
if (soapProtocolChooser.useSoap12(transportInputStream)) {
setMessageFactoryForRequestContext(soap12);
}
}
SaajSoapMessageFactory mf = getMessageFactoryForRequestContext();
return mf.createWebServiceMessage(inputStream);
}
}
And web.xml params
<servlet>
<servlet-name>spring-ws2</servlet-name>
<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
<init-param>
<param-name>messageFactoryBeanName</param-name>
<param-value>genericSoapMessageFactory</param-value>
</init-param>
</servlet>
I saw this error once and I changed the following line;
httppost.setHeader("Content-Type", "text/xml; charset=utf-8");
to
httppost.setHeader("Content-Type", "application/soap+xml;charset=UTF-8;");
and it fixed the issue. Try it.

Blackberry Push notification using C# as server side

I am trying to send push notification in blackberry by using C# Web
service but i am facing problem is it return exception "The remote
server returned an error: (404) Not Found.". all info is correct as
per RIM Standard so please Help me ASAP.
[WebMethod]
public bool push(string notification)
{
bool success = true;
byte[] bytes = Encoding.ASCII.GetBytes("Hello");
Stream requestStream = null;
HttpWebResponse HttpWRes = null;
HttpWebRequest HttpWReq = null;
String BESName = "cp****.pushapi.eval.blackberry.com";
try
{
//http://<BESName>:<BESPort>/push?DESTINATTION=<PIN/EMAIL>&PORT=<PushPort>&REQUESTURI=/
// Build the URL to define our connection to the BES.
string httpURL = "https://" + BESName + "/push?DESTINATION=2B838E45&PORT=32721&REQUESTURI=/";
//make the connection
HttpWReq = (HttpWebRequest)WebRequest.Create(httpURL);
HttpWReq.Method = ("POST");
//add the headers nessecary for the push
HttpWReq.ContentType = "text/plain";
HttpWReq.ContentLength = bytes.Length;
// ******* Test this *******
HttpWReq.Headers.Add("X-Rim-Push-Id", "2B838E45" + "~" + DateTime.Now); //"~" +pushedMessage +
HttpWReq.Headers.Add("X-Rim-Push-Reliability", "application-preferred");
HttpWReq.Headers.Add("X-Rim-Push-NotifyURL", ("http://" + BESName + "2B838E45~Hello~" + DateTime.Now).Replace(" ", ""));
// *************************
HttpWReq.Credentials = new NetworkCredential("Username", "Password");
requestStream = HttpWReq.GetRequestStream();
//Write the data from the source
requestStream.Write(bytes, 0, bytes.Length);
//get the response
HttpWRes = (HttpWebResponse)HttpWReq.GetResponse();
var pushStatus = HttpWRes.Headers["X-RIM-Push-Status"];
//if the MDS received the push parameters correctly it will either respond with okay or accepted
if (HttpWRes.StatusCode == HttpStatusCode.OK || HttpWRes.StatusCode == HttpStatusCode.Accepted)
{
success = true;
}
else
{
success = false;
}
//Close the streams
HttpWRes.Close();
requestStream.Close();
}
catch (System.Exception)
{
success = false;
}
return success;
}
I got the same error when I tried your code above. Replace
String BESName = "cp****.pushapi.eval.blackberry.com";
With
String BESName = "cpxxx.pushapi.eval.blackberry.com/mss/PD_pushRequest";
and make sure you provide the right username and password here:
HttpWReq.Credentials = new NetworkCredential("username", "password");
I got success = true;
However, even though the above code executed successfully, I still do not see the push message on the BlackBerry device.

saaj exception - Unable to parse content type: null

I'm fairly new to webservices and working through a SAAJ example of sending and recieving attachments (binary files). I can get it to work when the client sends the file but not when it requests it. I get an exception on the client side:
ERROR: 'Content is not allowed in prolog.'
24-Oct-2012 13:59:28 com.sun.xml.internal.messaging.saaj.soap.EnvelopeFactory createEnvelope
SEVERE: SAAJ0511: Unable to create envelope from given source
com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Unable to create envelope from given source
Anybody have any ideas???my client code is as follows:
SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
SOAPConnection con = scf.createConnection();
SOAPFactory soapFactory = SOAPFactory.newInstance();
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage msg = mf.createMessage();
SOAPHeader header = msg.getSOAPHeader();
header.detachNode();
SOAPBody body = msg.getSOAPBody();
Name bodyName = soapFactory.createName(
"remoteOpen", "remoteOpen",
"http://schemas.remoteOpen.com/remoteOpen");
SOAPBodyElement bodyElement = body.addBodyElement(bodyName);
SOAPElement projectName = bodyElement.addChildElement("projectName");
projectName.addTextNode("filename");
msg.saveChanges();
// create the endpoint and send the message
URL endpoint = new URL("http://localhost:8080/RemoteSaveProject/OpenServlet");
SOAPMessage response = con.call(msg, endpoint);
con.close();
SOAPBody responseBody = response.getSOAPBody();
SOAPElement ackElem = (SOAPElement)responseBody.getFirstChild();
String acknowledgement = ackElem.getValue();
the server code looks like this:
MimeHeaders mimeHeaders = new MimeHeaders();
Enumeration en = request.getHeaderNames();
while (en.hasMoreElements())
{
String headerName = (String)en.nextElement();
String headerVal = request.getHeader(headerName);
StringTokenizer tk = new StringTokenizer(headerVal, ",");
while (tk.hasMoreTokens()){
mimeHeaders.addHeader(headerName, tk.nextToken().trim());
}
}
SOAPMessage message = mf.createMessage(mimeHeaders, request.getInputStream());
SOAPBody body = message.getSOAPBody();
Name bodyName = soapFactory.createName(
"remoteOpen", "remoteOpen",
"http://schemas.remoteOpen.com/remoteOpen");
Iterator projects = body.getChildElements(bodyName);
SOAPElement project = (SOAPElement)projects.next();
Iterator projectNameIter = project.getChildElements(soapFactory.createName("projectName"));
SOAPElement projectNameEle = (SOAPElement)projectNameIter.next();
String projectName = projectNameEle.getValue();
File file = new File(projectName);
SOAPMessage reply = mf.createMessage();
SOAPHeader header = reply.getSOAPHeader();
header.detachNode();
SOAPBody replyBody = reply.getSOAPBody();
SOAPBodyElement bodyElement = replyBody.addBodyElement(soapFactory.createName("ack"));
bodyElement.addTextNode("OK");
DataHandler dh = new DataHandler(new FileDataSource(file));
AttachmentPart attachment = reply.createAttachmentPart(dh);
attachment.setContentId("123");
reply.addAttachmentPart(attachment);
reply.saveChanges();
response.setStatus(HttpServletResponse.SC_OK);
putHeaders(reply.getMimeHeaders(), response);
response.setContentType("text/xml");
ServletOutputStream replyOS = response.getOutputStream();
reply.writeTo(replyOS);
replyOS.flush();
replyOS.close();
putHeaders looks like:
Iterator it = headers.getAllHeaders();
while (it.hasNext())
{
MimeHeader header = (MimeHeader) it.next();
String[] values = headers.getHeader(header.getName());
if (values.length == 1)
{
res.setHeader( header.getName(), header.getValue());
}
else
{
StringBuffer concat = new StringBuffer();
int i = 0;
while (i < values.length)
{
if (i != 0)
{
concat.append(',');
}
concat.append(values[i++]);
}
res.setHeader(header.getName(), concat.toString());
}
}
If you are using Google app engine, like me, the problem is that GAE doesn't support com.sun.xml.internal.messaging.saaj.packaging.mime.internet.ParameterList which is used internally somewhere in the call chain of javax.xml.soap.SOAPConnection.call(). So you must use a workaround.
I personally did it by using java.net.HttpURLConnection instead of javax.xml.soap.SOAPConnection and manually sending and parsing SOAP messages.

Why does SQL Server CLR procedure hang in GetResponse() call to web service

Environment: C#, .Net 3.5, Sql Server 2005
I have a method that works in a stand-alone C# console application project. It creates an XMLElement from data in the database and uses a private method to send it to a web service on our local network. When run from VS in this test project, it runs in < 5 seconds.
I copied the class into a CLR project, built it, and installed it in SQL Server (WITH PERMISSION_SET = EXTERNAL_ACCESS). The only difference is the SqlContext.Pipe.Send() calls that I added for debugging.
I am testing it by using an EXECUTE command one stored procedure (in the CLR) from an SSMS query window. It never returns. When I stop execution of the call after a minute, the last thing displayed is "Calling GetResponse() using http://servername:53694/odata.svc/Customers/". Any ideas as to why the GetResponse() call doesn't return when executing within SQL Server?
private static string SendPost(XElement entry, SqlString url, SqlString entityName)
{
// Send the HTTP request
string serviceURL = url.ToString() + entityName.ToString() + "/";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceURL);
request.Method = "POST";
request.Accept = "application/atom+xml,application/xml";
request.ContentType = "application/atom+xml";
request.Timeout = 20000;
request.Proxy = null;
using (var writer = XmlWriter.Create(request.GetRequestStream()))
{
entry.WriteTo(writer);
}
try
{
SqlContext.Pipe.Send("Calling GetResponse() using " + request.RequestUri);
WebResponse response = request.GetResponse();
SqlContext.Pipe.Send("Back from GetResponse()");
/*
string feedData = string.Empty;
Stream stream = response.GetResponseStream();
using (StreamReader streamReader = new StreamReader(stream))
{
feedData = streamReader.ReadToEnd();
}
*/
HttpStatusCode StatusCode = ((HttpWebResponse)response).StatusCode;
response.Close();
if (StatusCode == HttpStatusCode.Created /* 201 */ )
{
return "Created # Location= " + response.Headers["Location"];
}
return "Creation failed; StatusCode=" + StatusCode.ToString();
}
catch (WebException ex)
{
return ex.Message.ToString();
}
finally
{
if (request != null)
request.Abort();
}
}
The problem turned out to be the creation of the request content from the XML. The original:
using (var writer = XmlWriter.Create(request.GetRequestStream()))
{
entry.WriteTo(writer);
}
The working replacement:
using (Stream requestStream = request.GetRequestStream())
{
using (var writer = XmlWriter.Create(requestStream))
{
entry.WriteTo(writer);
}
}
You need to dispose the WebResponse. Otherwise, after a few calls it goes to timeout.
You are asking for trouble doing this in the CLR. And you say you are calling this from a trigger? This belongs in the application tier.
Stuff like this is why when the CLR functionality came out, DBAs were very concerned about how it would be misused.