How to send a broadcast message with SmackAPI? - java

We're developing special devices that uses XMPP to talk to each other. A new API i am developing now, should talk to these devices too. The problem i am facing - all these devices are building little groups - for each customer we have... so we will have a chat-room for each group of devices, or, for each of our customer with his bunch of devices ;)
But now.. the api should be able to talk to every device that is connected. I don't need a real broadcast-mechanism - in the end, i will send a message only to one specific device..
But i don't want to login to each chat-room either - running a product with over 40k customers and much more devices, will end in a funny api, that is opening over 40k chat-rooms at startup... even if don't tried this yet, i can't imagine that an app like this will run well... even though we can have millions of customers in a few years.. i don't like solutions that will grow linear with the amount of customers, if you know what i mean :/
Now, basically i'm thinking of a solution, where i just can use the basic XMPPConnection to do my stuff.
MyCustomMessage msg = new MyCustomMessage();
msg.setTo("*"); // don't know what to address, i want to send it to "all"
msg.setFrom("ThatAPI"); // just a string telling that is sent from my java api ;)
msg.setEvent(event); // stuff that is coming through the parameters of the method where this code is inside
msg.setCustomStanza(data); // same here
connection.sendPacket(msg); // my try to send it to all till now..
Somewhere in the Ignite Realtime Forums i have read of one guy who "solved" it, but everything he says is "it's working now, i push my message through the sendPacket of Connection"... ok nice, my attempt of this seems not to work :(
Any better ideas/real implementations how this will work fine?
Basically i start to think that XMPP will not be the best technology to achieve something like this at all - i wish i could have a real/basic socket-implementation where something like this would be piece of cake.. But i can't choose - the third-party-system has implemented XMPP already... not enough time to change all of this... Just if you're wondering why we try this on XMPP..

You seem to have some conflicting requirements in that you want to send to all devices now, but only 1 specific device later. Are both models required at the same time, or do you plan on switching? How either is done would be different solutions.
As for your current approach, I think pubsub would make more sense than your chatroom approach, as that is oriented to generic message passing to subscribers.
You could set up a pubsub node per customer to send messages to all
of their devices.
As for a broadcast to all, you can make all devices
subscribe to a single pubsub node.
Thus you control broadcast and group messages by sending to the appropriate pubsub node.
For sending to a specific device, that is just a sendPacket to the specific entity, nothing really special there.

Related

How could an "extra" json element appear in my payload after the http exchange

Imagine there is chatting software. A java microservice listens to agents chatting with customers. The microservice dumps some pertinent data items in an SQS queue. A java bot reads from the queue, formats some things into the appropriate json and fires this off to a RESTful endpoint outside the network. Alternatively, in simulation of that bot, I can post manually properly formatted json into postman. At the last line of appcode before it is sent off in an httpRequestEntity to get a synchronous response before asynchronous processing it can be seen that the json message is properly formed. This is seen in logging and traffic sniffing. The same is true if using the postman test harness method. Some seconds later the package that got sent out of the network arrives at where it was sent.
WITH AN EXTRA JSON ELEMENT!
That reads as if it is metadata from the chatting software!
But remember this happens if the message originates in the chatting software or if I am using the fake cut in line method of mocking the message starting at a later point in the sequence.
I am so stumped. Every step of the way in every way I know to monitor data along its way the package looks right. Then at some point it doesn't. I don't want to bring this up with the people at the other end, receiving the message. Because it sounds like something that couldn't possible happen.
Please any comments even long shots would be much appreciated. I will watch this thread and respond to any questions it generates. Thank you so much.

Since when is the phone charging/discharging

I wanted to learn more about the Android Services / Broadcasts, so I started a simple project, to create a battery monitoring app. It turned out pretty good, I'm using it for a few days now, but I want to add a new function: to show since when is the phone charging/discharging.
First I thought that I would create two static fields in my BoradcastReciever extension class, where I get and publish the data about the battery, one for the actual state (charging/discharging), and one for the time, when the change in state happened. This way, I could just subtract from the current time the last change, and know exactly since when is the phone charging/discharging.
But there is a problem with this solution: It won't show the correct data at first, when a user starts the app. I wouldn't make a big deal of it, but I saw that Android tracks this data somewhere, because inside my phone settings I found this information, so why take the hard way.
So my question is: is there an easy way to get from the Android system the date/time (no matter what format) of the last charging state change?
I looked at the BatteryManager reference but there are no constants named after what I seek, and which I could use, to get the information from the Intent of my receiver.
The Android OS tracks the connect/disconnect of a power source, but does not make this data accessible to apps. You have to record this all yourself, using intent filters.
The two intent filters to use are android.intent.action.ACTION_POWER_CONNECTED and android.intent.action.ACTION_POWER_DISCONNECTED; with these, you can monitor when the power source is connected and disconnected.
You can find information about this process explained incredibly clearly here. Another blog describing the process can be found here.

Network Communication TCP [Code Design]

I've been messing a lot with TCP/IP Communication the last few days (Using Java and C#). I understand how it works and am able to use it. My Question is more a code design question, how its done the best and easy way to make a real communication.
For Example ive Built my own Multiuser Chat Server. I want my Communication to be able to decide wather its an Auth request, or a new chat message the ability to get the current user list etc etc.
Ive implemented a few ways on my own, but im not quite happy About that since i think theres a more standard and beauty way to do this.
My first thought was a String with Delimiters wich gets splitted, here is the Example of my Implementation of my Communication in Java:
//The Object-types im Using
clientSocket = new Socket(host, port_number);
_toServer = new PrintStream(clientSocket.getOutputStream());
_fromServer = new DataInputStream(clientSocket.getInputStream());
//Example Commands my Client sends to the server
_toServer.println("STATUS|"); //Gets the Status if server is online or closed (closed can occur when server runs but chat is disabled)
_toServer.println("AUTH|user|pw"); //Sends an auth Request to Server with username and Password
_toServer.println("MESSAGE|Hello World|ALL"); //Sends hello World in the Normal Chat to all Users
_toServer.println("MESSAGE|Hello World|PRIVATE|foo"); //Sends hello World only to the user "foo"
_toServer.println("USERS|GET"); //Request a list of all Connected Users
//Example In the Recieved Message Method where all The Server Messages Get Analyzed
serverMessage = _fromServer.readLine(); //Reads the Server Messages
String action = serverMessage.split("|")[0];
if (action.equals("USERS")) { //Example "USERS|2|foo;bar"
String users[] = serverMessage.split("|")[2].split(";");
}
if (action.equals("MESSAGE")) { //Example "MESSAGE|Hello World|PRIVATE|foo"
if(serverMessage.split("|")[2].equals("ALL") {
//Code and else for private....
}
}
if (serverMessage.equals("STATUS|ONLINE")) {
// Code
// I leave out //Code and } for the next If statements
}
if (serverMessage.equals("STATUS|OFFLINE")) {
if (serverMessage.equals("AUTH|ACCEPTED")) {
if (serverMessage.equals("AUTH|REJECT")) {
Is this the way its normally Done? Ad You See I need to send Statuscodes and Objects Corresponding to the Code. Ive Thought about Writing the Data in Bytes aswell and Implementing a "Decoder for Each Object", Example:
int action = _fromServer.readInt();
//opcodes is just an Enum Holding the corresponding int
switch(action) {
case(opcodes.MESSAGE):
break;
case(opcodes.AUTH):
break;
}
Note that this is more over a general design Question not just for this Chat Server Example, I think im Implementing a little Network Based Console Game just for Practise.
Is there a better way to do this or even an API/Framework?
Thanks in advance!
Essentially you're designing a protocol. There are a number of communication protocols that can handle this, the main one that comes to mind is IRC. I'm sure you can do a web search for tips on how to implement the protocol.
As for extending something like this for a console game, well I would start with implementing IRC, and using that to learn how real communication protocols are written. Once you've done that you can build on it to add your own commands to your framework.
If you are designing a protocol for inter-language communication, I would suggest not to use formated Strings as a means of communication but statusbytes. If you consider for example the design of TCP/IP itself you will find, messages consist of a fixed-format header and a variable payload. That way you always know, that (e.g.) the third byte of the message contains the messagetype, the fifth denotes an errorstate and so on. This makes handling easier.
If you have designed your protocol, you could consider working with explicit MessageObjects on the java-side, in which case you would implement a factory with marshalling and unmarshalling methods for these objects, converting objects from and to messages in your protocol.
If you are all-java you can even spare that effort and use ObjectInputStreams and ObjectOutputStreams on client and Server. If you are not, you might want to take a look at the Google Protocol Buffers: http://code.google.com/intl/de-DE/apis/protocolbuffers/, which do essentially the same for inter-language communication.
If your project grows, you may want to have a look at Netty - it's a framework for dealing with communication code. If your code is simple, you will be better off doing things manually.
As for protocol design, it depends on what is most important for you: performance, extensibility, human-readability, ease of debugging etc. These criteria may oppose each other to some degree, for example high performance may mean preference for binary protocols, but these negatively impact ease of debugging and sometimes extensibility. It's usually a good idea to not reinvent the wheel. Get inspired by existing protocols. If you choose to go binary, don't start from scratch unless you really have to, start with Protocol Buffers. If your app is simple and not aimed at very high performance, use a human-readable protocol which will make your life easier (debugging and testing are possible with standard shell tools such as strace and nc).
I think Apache MINA will help you. http://mina.apache.org/
Building a Java C/S application is really complex, you need to deal TCP, UDP and multi threads programming; MINA can help you for these things.
I think the other part you need is your private chatting protocol, but how about the open sourced IM service like Jabber? :)

How can I send various information on one socket?

I want to write an application for my android phone to control it via wlan. That should contain its camera abilities.
Is there any elegant method to send live pictures and other information in one socket "at the same time"? My idea is to let the server accept more than one client: the first for life images, the second for information, third for audio streaming...
It should work like skype: you can call people and chat at the same time with one connection. How can I implement something like that?
I doubt multiple sockets would do you any good (unless Android makes it really hard to put data from multiple sources into the same stream). Just send everything sequentially in the same stream, with a tag in front to identify each type of data. The fancy name for this is "time-division multiplexing".
Multiple sockets might make sense if you get into fancy tweaking to, say, give more priority to realtime streams, but I have a feeling that shouldn't be necessary.

Suggested Approaches to programmatically make and record a VOIP call

I want to write a program that will be able to call into my company's bi-weekly conference calls, and record the call, so it can then be made into a podcast.
I am thinking of using Gizmo's SIP interface (and the fact that it allows you to make toll-free calls for free), but I am having trouble finding any example code (preferably in Java) that will be able to make an audio call, and get hold of the audio stream.
I have seen plenty of SIP programming tutorials that deal with establishing a session, and then they seem to just do some hand waving, and say "here is where you can establish the audio connection" without actually doing it.
I am experienced in Java, so I would prefer to use it, but other language suggestions are welcome as well.
I have never written a VOIP application, so I'm not really sure where to start. Can anyone suggest a good library or other resource that would help me get started?
Thanks!
Look for a VOIP softphone writtin in Java, then modify it to save the final audio stream instead of sending it to be played.
Side note: In many states you would be violating the law unless you do one of several things, varying by state: Notify the participants they're being recorded, insert BEEPs every N seconds, both, etc. Probably you only have to comply with the laws of the state you're calling from. Even worse, you may need to allow the users to decline recording (requires you to be there before recording starts). If you control the conference server, you may be able to get it to play a canned announcement that the call is being recorded.
You could do this with Twilio with almost no programming whatsoever. It will cost you 3ยข per minute, so if your company's weekly call is 45 minutes long, you're looking at $1.35 per week, about as close to free as possible. Here are the steps:
Sign up for Twilio and make note of your Account ID and token
Create a publicly accessible file on your web server that does nothing but output the following XML (see the documentation for explanation of the record parameters):
<Response>
<Record timeout="30" finishOnKey="#" />
</ Response>
When it's time to start the recording, perform a POST to this URL (documented here) with your browser or set up an automated process or script to do it for you:
POST http://api.twilio.com/2008-08-01/Accounts/ACCOUNT SID HERE/Calls
HTTP/1.1
Called=CONFERENCE NUMBER HERE
&Url=WEB PAGE HERE
&Method=GET
&SendDigits=PIN CODE HERE
If you want to get really creative, you can actually write code to handle the result of the recording verb and email the link to the MP3 or WAV file that Twilio hosts for you. But, if this is a one off, you can skip it because you can access all your recordings in the control panel for your account anyway.
try peers with mediaDebug option true in peers.xml. This option records all outgoing and incoming media streams in a media/ folder with a date pattern for file name. Nevertheless this file will probably not be usable as is. It contains raw uncompressed lienar PCM samples. You can use Audacity, sox or ffmpeg to convert it to whatever you want.
https://voip.dev.java.net/
They have some sample code there.

Categories

Resources