Blackberry Push notification using C# as server side - web-services

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.

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.

Authentication Error (Authentication Failed) Using Sabre Soap Message

I am using soap service to authenticate request by sabre as in the document https://developer.sabre.com/docs/read/soap_basics/Authentication.
I generate the proxy classes using wsdl. i put authentication credential in the code. This is my Code for test purpose:
using ConsoleApplication1.SessionReference1;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
[STAThread]
static void Main(string[] args)
{
try
{
// Set user information, including security credentials and the IPCC.
string username = "my-username";
string password = "my-password";
string ipcc = "not-understand";
string domain = "EXT";
string temp = Environment.GetEnvironmentVariable("tmp"); // Get temp directory
string PropsFileName = temp + "/session.properties"; // Define dir and file name
DateTime dt = DateTime.UtcNow;
string tstamp = dt.ToString("s") + "Z";
//Create the message header and provide the conversation ID.
MessageHeader msgHeader = new MessageHeader();
msgHeader.ConversationId = "TestSession"; // Set the ConversationId
From from = new From();
PartyId fromPartyId = new PartyId();
PartyId[] fromPartyIdArr = new PartyId[1];
fromPartyId.Value = "WebServiceClient";
fromPartyIdArr[0] = fromPartyId;
from.PartyId = fromPartyIdArr;
msgHeader.From = from;
To to = new To();
PartyId toPartyId = new PartyId();
PartyId[] toPartyIdArr = new PartyId[1];
toPartyId.Value = "WebServiceSupplier";
toPartyIdArr[0] = toPartyId;
to.PartyId = toPartyIdArr;
msgHeader.To = to;
//Add the value for eb:CPAId, which is the IPCC.
//Add the value for the action code of this Web service, SessionCreateRQ.
msgHeader.CPAId = ipcc;
msgHeader.Action = "SessionCreateRQ";
Service service = new Service();
service.Value = "SessionCreate";
msgHeader.Service = service;
MessageData msgData = new MessageData();
msgData.MessageId = "mid:20001209-133003-2333#clientofsabre.com1";
msgData.Timestamp = tstamp;
msgHeader.MessageData = msgData;
Security security = new Security();
SecurityUsernameToken securityUserToken = new SecurityUsernameToken();
securityUserToken.Username = username;
securityUserToken.Password = password;
securityUserToken.Organization = ipcc;
securityUserToken.Domain = domain;
security.UsernameToken = securityUserToken;
SessionCreateRQ req = new SessionCreateRQ();
SessionCreateRQPOS pos = new SessionCreateRQPOS();
SessionCreateRQPOSSource source = new SessionCreateRQPOSSource();
source.PseudoCityCode = ipcc;
pos.Source = source;
req.POS = pos;
SessionCreatePortTypeClient s = new SessionCreatePortTypeClient();
SessionCreateRS resp = s.SessionCreateRQ(ref msgHeader, ref security, req);
//SessionCreateRQService serviceObj = new SessionCreateRQService();
//serviceObj.MessageHeaderValue = msgHeader;
//serviceObj.SecurityValue = security;
//SessionCreateRS rs = new SessionCreateRS();
//SessionCreateRS = serviceObj.SessionCreateRQ(req); // Send the request
if (resp.Errors != null && resp.Errors.Error != null)
{
Console.WriteLine("Error : " + resp.Errors.Error.ErrorInfo.Message);
}
else
{
// msgHeader = serviceObj.MessageHeaderValue;
// security = serviceObj.SecurityValue;
Console.WriteLine("**********************************************");
Console.WriteLine("Response of SessionCreateRQ service");
Console.WriteLine("BinarySecurityToken returned : " + security.BinarySecurityToken);
Console.WriteLine("**********************************************");
string ConvIdLine = "convid=" + msgHeader.ConversationId; // ConversationId to a string
string TokenLine = "securitytoken=" + security.BinarySecurityToken; // BinarySecurityToken to a string
string ipccLine = "ipcc=" + ipcc; // IPCC to a string
// File.Delete(PropsFileName); // Clean up
// TextWriter tw = new StreamWriter(PropsFileName); // Create & open the file
// tw.WriteLine(DateTime.Now); // Write the date for reference
// tw.WriteLine(TokenLine); // Write the BinarySecurityToken
// tw.WriteLine(ConvIdLine); // Write the ConversationId
// tw.WriteLine(ipccLine); // Write the IPCC
// tw.Close();
//Console.Read();
}
}
catch (Exception e)
{
Console.WriteLine("Exception Message : " + e.Message);
Console.WriteLine("Exception Stack Trace : " + e.StackTrace);
Console.Read();
}
}
}
}
Please Help me
I didn't check the sequence of the code in detail, but checking the values you set for organization and domain:
string ipcc = "not-understand";
string domain = "EXT";
Unless you did it intentionally to mask the values, you should have received your ipcc value from Sabre after getting a SOAP webservices account.
The value for SOAP APIs domain is normally "DEFAULT".
Registering on dev studio only gives you REST test credentials (not SOAP), so you can use this form to request SOAP test credentials:
https://developer.sabre.com/contact
Finally, I don't quite see the environment/target url you're using to test the SessionCreate service...CERT one is: https://sws3-crt.cert.sabre.com/

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.

How to call .Net webservice in Blackberry?

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();

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.