How to describe an ASP.NET Web Service ENUM for JSR-172 (Java ME) Consumption - asp.net

I have .NET Web Service and I am trying to use that web service from a Java Mobile phone. I am also using the NetBeans development environment with the web service tool kit. When I try to create the proxies, it falters on the enumerations stating that the simple types are not supported. Is there a way to describe the enumeration type in the WSDL so it is understandable to the toolkit?

// send a POST request to web server
public String sendPostRequest(String urlstring, String requeststring)
{
HttpConnection hc = null;
DataInputStream dis = null;
DataOutputStream dos = null;
String message = "";
// specifying the query string
String requeststring = "request=gettimestamp";
try
{
// openning up http connection with the web server
// for both read and write access
hc = (HttpConnection) Connector.open(urlstring, Connector.READ_WRITE);
// setting the request method to POST
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty("User-Agent","Profile/MIDP-2.0 Confirguration/CLDC-1.0");
hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// obtaining output stream for sending query string
dos = hc.openDataOutputStream();
byte[] request_body = requeststring.getBytes();
// sending query string to web server
for (int i = 0; i < request_body.length; i++)
{
dos.writeByte(request_body[i]);
}
// flush outdos.flush();
// obtaining input stream for receiving HTTP response
dis = new DataInputStream(hc.openInputStream());
// reading the response from web server character by character
int ch;
while ((ch = dis.read()) != -1)
{
message = message + (char) ch;
}
}
catch (IOException ioe){
message = "ERROR";
}
finally{
// freeing up i/o streams and http connection
try{
if (hc != null)
hc.close();
}
catch (IOException ignored){}
try{
if (dis != null)
dis.close();
}
catch (IOException ignored){}
try{
if (dos != null)
dos.close();
}
catch (IOException ignored){}
}
return message;
}

Related

Using RestSharp to aend files between to API's on Kubernetes

So I have to API's running on Kubernetes. One has a controller function as such:
string filePath = "/blobs/data/runsession/" + folderName;
if (!Directory.Exists(filePath))
return null;
var tempFile = Path.Combine(Path.GetTempPath(), guid.ToString());
logger.Info("GetTempPath()" + Path.GetTempPath());
logger.Info("Temp path is: " + tempFile);
ZipFile.CreateFromDirectory(filePath, (tempFile + ".zip"));
byte[] fileBytes = File.ReadAllBytes(tempFile + ".zip");
HelpMethods.GetNetworkTimeStamp("Stop", 2);
return fileBytes;
This controller method works fine and when I call it from postman it returns a file.
Now in the other API I want to call this function from one of my service classes as such:
public async Task<byte[]> DownloadRunSession(string foldername)
{
try
{
var request = new RestRequest($"blob/{foldername}")
{
Timeout = -1,
};
var response = await client.ExecuteGetAsync(request);
if (!response.IsSuccessful)
{
Console.WriteLine("File download failed");
Console.WriteLine(response.Content.ToString());
return null;
}
return response.RawBytes;
}catch(Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return null;
}
Now the server logs on the API that sends the file Give me a status 200 but says "the application aborted the connection", and the API that is supposed to receive the file gets no response and the response variable is always "null".
Any one that has had a similar dilemma and knows how to solve it?

Postman throwing 400 Bad request for multipart/form-data image upload with jersey 2.0

REQUEST :
URL: http://localhost:8080/RESTfulExample/rest/file/upload
METHOD : POST
HEADER: Content-Type : multipart/form-data
RESPONSE :
HTTP Status 400 - Bad Request
The same code is working with html forms but in postman it's throwing 400 BAD REQUEST, I looked up on google for solution and found that boundary is missing, How to resolve it ? As I have to recieve files from multiple clients like mobile application and web clients via Jquery and rest client.
#Path("/file")
public class UploadFileService {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
try {
String uploadedFileLocation = "/home/nash/" + fileDetail.getFileName();
// save it
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
System.out.println("File uploaded..........");
return Response.status(200).entity(output).build();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception " + e);
return null;
}
}
// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please follow these steps:
Add jersey-multipart dependency.
In Your Application Class (or in web.xml) enable MultipartFeature.class.
DO NOT Add Content-Type header in your postman request.
For me the above steps worked. Do let me know if that helped you or not.

Send push notifications from server with FCM

Recently I asked a question on sending push notifications using GCM: Send push notifications to Android. Now that there is FCM, I am wondering how different it would be from the server side development. Coding wise, are they the same? Where can I find example FCM codes showing sending push notifications from server to Android device?
Do I need to download any JAR library for sending notifications to FCM using Java codes? The example codes in Send push notifications to Android shows sending push notifications using GCM and a server side GCM JAR file is required.
However, another example in https://www.quora.com/How-do-I-make-a-post-request-to-a-GCM-server-in-Java-to-push-a-notification-to-the-client-app shows sending push notifications using GCM and no server side GCM JAR file is required since it is just sending via an HTTP connection. Can the same codes be used for FCM? The URL used is "https://android.googleapis.com/gcm/send". What would be the equivalent URL for FCM?
How different is server-side coding?
Since there is not much difference, you can just check out most of the example server-side codes for GCM as well. Main difference with regards to GCM and FCM is that when using FCM, you can use the new features with it (as mentioned in this answer). FCM also has a Console where you can send the Message/Notification from, without having your own app server.
NOTE: Creating your own app server is up to you. Just stating that you can send a message/notification via the console.
The URL used is "https://android.googleapis.com/gcm/send". What would be the equivalent URL for FCM?
The equivalent URL for FCM is https://fcm.googleapis.com/fcm/send. You can check out the this doc for more details.
Cheers! :D
Use below code to send push notification from FCM server :
public class PushNotifictionHelper {
public final static String AUTH_KEY_FCM = "Your api key";
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";
public static String sendPushNotification(String deviceToken)
throws IOException {
String result = "";
URL url = new URL(API_URL_FCM);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "key=" + AUTH_KEY_FCM);
conn.setRequestProperty("Content-Type", "application/json");
JSONObject json = new JSONObject();
json.put("to", deviceToken.trim());
JSONObject info = new JSONObject();
info.put("title", "notification title"); // Notification title
info.put("body", "message body"); // Notification
// body
json.put("notification", info);
try {
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(json.toString());
wr.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
result = CommonConstants.SUCCESS;
} catch (Exception e) {
e.printStackTrace();
result = CommonConstants.FAILURE;
}
System.out.println("GCM Notification is sent successfully");
return result;
}
This is coming straight from Google
You won’t need to make any server-side protocol changes for the upgrade. The service protocol has not changed. However, note that all new server enhancements will be documented in FCM server documentation.
And from receiving messages it seams there is only some places where its only slightly different. Mainly deleting somethings.
And the FCM server documentation can be found here
https://firebase.google.com/docs/cloud-messaging/server
FULL SOLUTION FOR TOPIC, SINGLE DEVICE AND MULTIPLE DEVICES
Create a class FireMessage. This is an example for data messages. You can change data to notification.
public class FireMessage {
private final String SERVER_KEY = "YOUR SERVER KEY";
private final String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";
private JSONObject root;
public FireMessage(String title, String message) throws JSONException {
root = new JSONObject();
JSONObject data = new JSONObject();
data.put("title", title);
data.put("message", message);
root.put("data", data);
}
public String sendToTopic(String topic) throws Exception { //SEND TO TOPIC
System.out.println("Send to Topic");
root.put("condition", "'"+topic+"' in topics");
return sendPushNotification(true);
}
public String sendToGroup(JSONArray mobileTokens) throws Exception { // SEND TO GROUP OF PHONES - ARRAY OF TOKENS
root.put("registration_ids", mobileTokens);
return sendPushNotification(false);
}
public String sendToToken(String token) throws Exception {//SEND MESSAGE TO SINGLE MOBILE - TO TOKEN
root.put("to", token);
return sendPushNotification(false);
}
private String sendPushNotification(boolean toTopic) throws Exception {
URL url = new URL(API_URL_FCM);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);
System.out.println(root.toString());
try {
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(root.toString());
wr.flush();
BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream())));
String output;
StringBuilder builder = new StringBuilder();
while ((output = br.readLine()) != null) {
builder.append(output);
}
System.out.println(builder);
String result = builder.toString();
JSONObject obj = new JSONObject(result);
if(toTopic){
if(obj.has("message_id")){
return "SUCCESS";
}
} else {
int success = Integer.parseInt(obj.getString("success"));
if (success > 0) {
return "SUCCESS";
}
}
return builder.toString();
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
And call anywhere like this. Both server and android we can use this.
FireMessage f = new FireMessage("MY TITLE", "TEST MESSAGE");
//TO SINGLE DEVICE
/* String fireBaseToken="c2N_8u1leLY:APA91bFBNFYDARLWC74QmCwziX-YQ68dKLNRyVjE6_sg3zs-dPQRdl1QU9X6p8SkYNN4Zl7y-yxBX5uU0KEKJlam7t7MiKkPErH39iyiHcgBvazffnm6BsKjRCsKf70DE5tS9rIp_HCk";
f.sendToToken(fireBaseToken); */
// TO MULTIPLE DEVICE
/* JSONArray tokens = new JSONArray();
tokens.put("c2N_8u1leLY:APA91bFBNFYDARLWC74QmCwziX-YQ68dKLNRyVjE6_sg3zs-dPQRdl1QU9X6p8SkYNN4Zl7y-yxBX5uU0KEKJlam7t7MiKkPErH39iyiHcgBvazffnm6BsKjRCsKf70DE5tS9rIp_HCk");
tokens.put("c2R_8u1leLY:APA91bFBNFYDARLWC74QmCwziX-YQ68dKLNRyVjE6_sg3zs-dPQRdl1QU9X6p8SkYNN4Zl7y-yxBX5uU0KEKJlam7t7MiKkPErH39iyiHcgBvazffnm6BsKjRCsKf70DE5tS9rIp_HCk");
f.sendToGroup(tokens); */
//TO TOPIC
String topic="yourTopicName";
f.sendToTopic(topic);
I have created a lib for FCM notification Server. Just use it like GCM lib.
For FCM Server use this code :
GCM Server URL-"android.googleapis.com/gcm/send"
FCM Server URL - "fcm.googleapis.com/fcm/send"
Append https with URL
Sender objSender = new Sender(gAPIKey);
or
Sender objSender = new Sender(gAPIKey,"SERVER_URL");
by DEFAULT FCM SERVER URL IS ASSIGNED
Message objMessage = new Message.Builder().collapseKey("From FCMServer").timeToLive(3).delayWhileIdle(false)
.notification(notification)
.addData("ShortMessage", "Sh").addData("LongMessage", "Long ")
.build();
objMulticastResult = objSender.send(objMessage,clientId, 4);
Dependency need for this lib is same like GCM lib required (jsonsimple.jar).
Download lib from FCM_Server.jar
public class SendPushNotification extends AsyncTask<Void, Void, Void> {
private final String FIREBASE_URL = "https://fcm.googleapis.com/fcm/send";
private final String SERVER_KEY = "REPLACE_YOUR_SERVER_KEY";
private Context context;
private String token;
public SendPushNotification(Context context, String token) {
this.context = context;
this.token = token;
}
#Override
protected Void doInBackground(Void... voids) {
/*{
"to": "DEVICE_TOKEN",
"data": {
"type": "type",
"title": "Android",
"message": "Push Notification",
"data": {
"key": "Extra data"
}
}
}*/
try {
URL url = new URL(FIREBASE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", "key=" + SERVER_KEY);
JSONObject root = new JSONObject();
root.put("to", token);
JSONObject data = new JSONObject();
data.put("type", "type");
data.put("title", "Android");
data.put("message", "Push Notification");
JSONObject innerData = new JSONObject();
innerData.put("key", "Extra data");
data.put("data", innerData);
root.put("data", data);
Log.e("PushNotification", "Data Format: " + root.toString());
try {
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(root.toString());
writer.flush();
writer.close();
int responseCode = connection.getResponseCode();
Log.e("PushNotification", "Request Code: " + responseCode);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((connection.getInputStream())));
String output;
StringBuilder builder = new StringBuilder();
while ((output = bufferedReader.readLine()) != null) {
builder.append(output);
}
bufferedReader.close();
String result = builder.toString();
Log.e("PushNotification", "Result JSON: " + result);
} catch (Exception e) {
e.printStackTrace();
Log.e("PushNotification", "Error: " + e.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
Log.e("PushNotification", "Error: " + e.getMessage());
}
return null;
}
}
Use
SendPushNotification sendPushNotification = new SendPushNotification(context, "token");
sendPushNotification.execute();

Live broadcast of the video site with Asp.Net WebForms + WebApi + HTML5

The problem is this:
on the server have a video file;
The administrator runs it on the play (video broadcast begins);
user is connected to the server - must be given to the video stream that is currently playing. A live webcast in real time.
To implement this task, I took as a basis for the article:
http://www.strathweb.com/2013/01/asynchronously-streaming-video-with-asp-net-web-api/
It worked. To give the stream a video file independently and in parallel.
I was looking on.
Next it was necessary to solve the problem of broadcasting to multiple customers (paragraph 3 in the job). I took this article:
http://gigi.nullneuron.net/gigilabs/streaming-data-with-asp-net-web-api-and-pushcontentstream/
Since I have to give evidence in the video byte - I replaced the StreamWriter class to Stream.
It works for one of the first client.
I made a website Asp.Net WebForms + WebApi + HTML5.
Web page - to run a video manager and viewed by users.
WebApi gives the player for <video> (HTML5) video stream.
HTML5:
<video>
<source src="http://localhost:8080/SiteVideoStreaming/api/live/?filename=nameFile" />
</video>
WebApi controllers:
//Controllers
public class LiveController : ApiController
{
private static ConcurrentBag<Stream> clients; // List of clients who need to simultaneously deliver video data
static string fileName = "";
static LiveController()
{
clients = new ConcurrentBag<Stream>();
WriteToStream(); // The first call - start to play a video file
}
[HttpGet]
public HttpResponseMessage Subscribe(string filename)
{
fileName = HostingEnvironment.MapPath("~/Videos/") + filename;
var response = Request.CreateResponse();
response.Content = new PushStreamContent((a, b, c) => { OnStreamAvailable(a, b, c); }, "video/mp4");
return response;
}
private void OnStreamAvailable(Stream stream, HttpContent content, TransportContext context)
{
clients.Add(stream); // Add new client
}
//Class record a video file into a streams
public async static void WriteToStream()
{
var buffer = new byte[65536];
using (var video = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var length = (int)video.Length;
var bytesRead = 1;
while (length > 0 && bytesRead > 0)
{
bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
foreach (var client in clients)// Each client in turn we return video data
{
try
{
await client.WriteAsync(buffer, 0, bytesRead); // ERROR - here !!! when you connect a second client
await client.FlushAsync();
}
catch (Exception ex)
{
Stream ignore;
clients.TryTake(out ignore);
}
}
length -= bytesRead;
}
}
}
}
If the request first came from one client - is given to video. Working.
If the request from the second client - when you try to start to give him a stream error occurs.
In this connection drops and the first client.
The error is as follows:
[System.Web.HttpException] = {"The remote host closed the connection.
The error code is 0x800704CD."}
As I understood after a search on the Internet is:
0x800704CD "An operation was attempted on a nonexistent network
connection."
Tell me that I'm not doing right?
Thank you.
I do so.
I use this controller:
public class VideoController : ApiController
{
// GET api/<controller>
public HttpResponseMessage Get(string filename)
{
if (filename == null)
return new HttpResponseMessage(HttpStatusCode.BadRequest);
string filePath = HostingEnvironment.MapPath("~/Videos/") + filename;
if (Request.Headers.Range != null)
{
//Range Specifc request: Stream video on wanted range.
try
{
//NOTE: ETag calculation only with file name is one approach (Not the best one though - GUIDs or DateTime is may required in live applications.).
Encoder stringEncoder = Encoding.UTF8.GetEncoder();
byte[] stringBytes = new byte[stringEncoder.GetByteCount(filePath.ToCharArray(), 0, filePath.Length, true)];
stringEncoder.GetBytes(filePath.ToCharArray(), 0, filePath.Length, stringBytes, 0, true);
MD5CryptoServiceProvider MD5Enc = new MD5CryptoServiceProvider();
string hash = BitConverter.ToString(MD5Enc.ComputeHash(stringBytes)).Replace("-", string.Empty);
HttpResponseMessage partialResponse = Request.CreateResponse(HttpStatusCode.PartialContent);
partialResponse.Headers.AcceptRanges.Add("bytes");
partialResponse.Headers.ETag = new EntityTagHeaderValue("\"" + hash + "\"");
var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
partialResponse.Content = new ByteRangeStreamContent(stream, Request.Headers.Range, new MediaTypeHeaderValue("video/mp4"));
return partialResponse;
}
catch (Exception ex)
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
else
{
return new HttpResponseMessage(HttpStatusCode.RequestedRangeNotSatisfiable);
}
}
}
On the client side - I run it <video> video player through technology SignalR.

How to call HTTP URL using wifi in J2ME code for BlackBerry 5.0 and above?

I am calling a web service from BlackBerry using J2ME code. When I try to open a connection using HttpConnection, it is checking only the GPRS connection. Now, I want to check the Wi-Fi connection and call a webservice through Wi-Fi.
The following code is my connection section. How to change the code for a Wi-Fi connection?
public boolean HttpUrl()
{
HttpConnection conn = null;
OutputStream out = null;
String url = "http://www.google.com";
try
{
conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection();
if (conn != null)
{
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Length", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
}
}
catch (Exception e)
{
return false;
}
finally
{
try
{
out.close();
}
catch (Exception e2)
{
}
}
//Only if exception occurs, we close the connection.
//Otherwise the caller should close the connection himself.
try
{
conn.close();
}
catch (Exception e1)
{
}
return true;
}
Check this way:
HttpConnection conn = null;
String URL = "http://www.myServer.com/myContent;deviceside=true;interface=wifi";
conn = (HttpConnection)Connector.open(URL);
source
Making Connections
Rafael's answer will certainly work if you know you'll only be using Wi-Fi.
However, if you only need to support BlackBerry OS 5.0 - 7.1, I would recommend that you do use the ConnectionFactory. Normally, you will not limit your code to only using one transport. You'll normally support (almost) any transport the device has, but you may want to code your app to choose certain transports first.
For example,
class ConnectionThread extends Thread
{
public void run()
{
ConnectionFactory connFact = new ConnectionFactory();
connFact.setPreferredTransportTypes(new int[] {
TransportInfo.TRANSPORT_TCP_WIFI,
TransportInfo.TRANSPORT_BIS_B,
TransportInfo.TRANSPORT_MDS,
TransportInfo.TRANSPORT_TCP_CELLULAR
});
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection("http://www.google.com");
if (connDesc != null)
{
HttpConnection httpConn;
httpConn = (HttpConnection)connDesc.getConnection();
try
{
// TODO: set httpConn request method and properties here!
final int iResponseCode = httpConn.getResponseCode();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Response code: " +
Integer.toString(iResponseCode));
}
});
}
catch (IOException e)
{
System.err.println("Caught IOException: "
+ e.getMessage());
}
}
}
}
will choose the Wi-Fi transport if Wi-Fi is available, but use the GPRS connection if it isn't. I think this is generally considered best practice for the 5.0+ devices.
Request Properties
This code
conn.setRequestProperty("Content-Length", "application/x-www-form-urlencoded");
is not right. Content-Length should be the size, in bytes, of your HTTP POST parameters. See an example here.
Threading
Remember that making network connections is slow. Do not block the user interface by running this code on the main/UI thread. Put your code into a background thread to keep the UI responsive while you request remote content.

Resources