I am currently using map-api-2.1.0.jar and map-impl-2.1.0.jar for handling USSD string from mobile phone. This is working fine and user is receiving USSD response.
MapHandling Class
public class MapHandling implements MAPDialogListener,MAPServiceSmsListener,MAPServiceMobilityListener,MAPServiceCallHandlingListener,MAPSer viceSupplementaryListener{
#Override
public void onProcessUnstructuredSSRequest(ProcessUnstructuredSSRequest procUnstrReqInd)
{
try
{
logger.debug("dialogId: " +procUnstrReqInd.getMAPDialog().getLocalDialogId() + " USSD String:"+procUnstrReqInd.getUSSDString()+"MSISDN:"+procUnstrReqInd.getMAPDialog().getReceivedDestReference().getAddress());
} catch (Exception exp)
{
logger.error("USSD - error while loging ussd data ", exp);
}
ss7.request.UnstructuredSSRequest ussdRequest = new ss7.request.UnstructuredSSRequest(procUnstrReqInd);
Thread thr = new Thread(ussdRequest);
thr.start();
}
}
ss7.request.UnstructuredSSRequest Class
public class UnstructuredSSRequest extends SS7Operation implements Runnable {
ProcessUnstructuredSSRequest procUnstrReqInd;
public UnstructuredSSRequest(ProcessUnstructuredSSRequest procUnstrReqInd) {
this.procUnstrReqInd = procUnstrReqInd;
}
#Override
public void run() {
logger.debug("[" + refId + "] Sending USSD response");
sendUSSDResponse(validRequest);
}
private void sendUSSDResponse(boolean validRequest) {
MAPDialogSupplementary dialog = procUnstrReqInd.getMAPDialog();
USSDString ussdStrObj = MapProvider.getMAPParameterFactory().createUSSDString("Thank you for using CC service!");
dialog.addProcessUnstructuredSSResponse(procUnstrReqInd.getInvokeId(),procUnstrReqInd.getDataCodingScheme(), ussdStrObj);
dialog.close(false);
dialog.release();
}
}
Above code is running fine and I receive "Thank you for using CC service!" response when I dial USSD from my phone.
I want to change this into an interactive USSD handler, I want to take input from user when he dials USSD code instead of sending him response and closing the session.
Kindly help me how can I maintain a session for user and take his input.
I believe you are using Mobicents jSS7 project and above code is server side connected to HLR/MSC over SIGTRAN or E1.
If yes, you can see the sample code for server side at https://code.google.com/p/jss7/source/browse/map/load/src/main/java/org/mobicents/protocols/ss7/map/load/Server.java
Related
first post here. I've tried to look for a question I have but no luck so I figure I ask it myself.
I am working on 2 programs. An Android app in Java and a C# Windows Form App on windows. They are both simply scorekeeping calculators to keep track of the score of 2 players.
The goal of the 2 programs is to use a Bluetooth connection to send data back and forth between each other so that they are "synced". Android app is a client, c# app is a server (32feet library).
Using the Bluetooth Chat example on Android and some code i put together in VS, I managed to get the 2 programs to connect and send and receive data to each other, great!
But now my main goal is that I need to find out a way to take the incoming data coming from the Android app and change the appropriate labels/text on the windows app.
So for example:
on the Windows App, there are 2 Labels: one for Player1, one for Player2 that both say "10".
On the Android App, I have 2 buttons that separately subtract from either Player1 or Player2's score.
On the android app, if I touch the button that subtracts(-) 1 from Player1 it would be 9. I now want that change to apply to Player1's score label on the windows app, where it would also show 9.
I then want the same thing for Player2's score.
This is the best I can describe my goal, and I would like to know if it's possible, and if so, be pointed in the right direction.
Here is some provided code for what I have so far:
C# windows form app:
private void button1_Click(object sender, EventArgs e)
{
if (serverStarted == true)
{
updateUI("Server already started");
return;
}
if (radioButton1.Checked)
{
connectAsClient();
}
else
{
connectAsServer();
}
}
private void connectAsServer()
{
Thread bluetoothServerThread = new Thread(new ThreadStart(ServerConnectThread)); //creates new thread and runs "ServerConnectThread"
bluetoothServerThread.Start();
}
private void connectAsClient()
{
throw new NotImplementedException();
}
Guid mUUID = new Guid("fa87c0d0-afac-11de-8a39-0800200c9a66");
bool serverStarted = false;
public void ServerConnectThread()
{
serverStarted = true;
updateUI("Server started, waiting for client");
BluetoothListener blueListener = new BluetoothListener(mUUID);
blueListener.Start();
BluetoothClient conn = blueListener.AcceptBluetoothClient();
updateUI("Client has connected");
Stream mStream = conn.GetStream();
while (true)
{
try
{
//handle server connection
byte[] received = new byte[1024];
mStream.Read(received, 0, received.Length);
updateUI("Received: " + Encoding.ASCII.GetString(received));
byte[] sent = Encoding.ASCII.GetBytes("hello world");
mStream.Write(sent, 0, sent.Length);
}
catch (IOException exception)
{
updateUI("Client disconnected");
}
}
}
private void updateUI(string message)
{
Func<int> del = delegate ()
{
textBox1.AppendText(message + Environment.NewLine);
return 0;
};
Invoke(del);
}
}
Android App (snippet from the Bluetooth Chat example - i think this is the only relevant part):
/**
* Sends a message.
*
* #param message A string of text to send.
*/
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
You will want to have to add the clients to alist of streams for reference and also store the scores of each client on a list and then send the data coming from each client to the rest of the clients
so from the server youd have basically something like this
List<Stream> clients=new List<Stream>();
List<String> client_scores=new List<String>();
public void ServerConnectThread()
{
serverStarted = true;
updateUI("Server started, waiting for client");
BluetoothListener blueListener = new BluetoothListener(mUUID);
blueListener.Start();
BluetoothClient conn = blueListener.AcceptBluetoothClient();
updateUI("Client has connected");
Stream mStream = conn.GetStream();
clients.add(mStream);
client_scores.add(new Random().Next()+"");
int index_cnt = clients.IndexOf(mStream);
while (true)
{
try
{
//handle server connection
byte[] received = new byte[1024];
mStream.Read(received, 0, received.Length);
updateUI("Received: " + Encoding.ASCII.GetString(received));
client_scores[client_scores.FindIndex(ind=>ind.Equals(index_cnt))] = Encoding.ASCII.GetString(received);
byte[] sent = Encoding.ASCII.GetBytes("hello world");
mStream.Write(sent, 0, sent.Length);
foreach(Stream str in clients)
{
byte[] my_score = Encoding.ASCII.GetBytes(clients.ToArray()[index_cnt]+"");
str.Write(my_score, 0, my_score.Length);
}
}
catch (IOException exception)
{
updateUI("Client disconnected");
}
}
}
You can then serialize the data being sent in some sort of json so as to send multiple fields of data comfortably for example :
{
"data type": "score",
"source_id": "client_unique_id",
"data": "200"
}
On your displaying side,just get the values of (in our example case source_id and data) and display on a label
I have two Telegram bots, written in Java.
First bot send some message every 10 min. (It works).
Second bot must read this sended message, and store it to txt file...
But problem is that the second bot don't see this message... He see messages only from USERS.
M - bot
YR - user
Chat image
Console result
Here says if
BotFather=>Bot=>Settings=>Group Privacy => Privacy mode disabled and >BotFather=>Bot=>Settings=>Allow Groups? => Groups are currently enabled
bots must see messages sent from one to another.
I did it, also bots was invited to new group with Administrator rights. Here code example (second bot):
public class TelegramBot extends TelegramLongPollingBot {
public final String BOT_TOKEN = "****************************";
public final String BOT_NAME = "*****************";
#Override
public void onUpdateReceived(Update update) {
long inChatID = 0;
int inMessID = 0;
String inText = "";
try { // from chanel
inChatID = update.getChannelPost().getChatId();
inText = update.getChannelPost().getText();
inMessID = update.getChannelPost().getMessageId();
} catch (Throwable t1) {};
try { // from chat
inChatID = update.getMessage().getChatId();
inText = update.getMessage().getText();
inMessID = update.getMessage().getMessageId();
} catch (Throwable t2) {};
System.out.println(inChatID);
System.out.println(inMessID);
System.out.println(inText);
}
#Override
public String getBotUsername() {
return BOT_NAME;
}
#Override
public String getBotToken() {
return BOT_TOKEN;
}
}
If I send any message like user, i getting in console ChatID, MessID, Text...
But if first bot send some message, i got nothing. Help me with this issue. Any suggestion where my mistake ?
I solved this issue by adding this two bots to channel with administrator rights.
It's don't works with GROUP CHAT.
Now i can see message sended from another bots.
But there is another problem: all messages sended by any bot in channel throws like channel message, with out Bot ID, Bot Name, etc...
So, I just can read message text, and parse it.
I am trying to make an android chat application. I am thinking about making it with aws. But the problem is that I am unable to find any good tutorial for doing this and I have no idea how to do it.
So could anyone please suggest some tutorial for sending push notification or on how to make a chat application?
Firebase is well suited to this due to its "realtime database" feature. Here's a few tutorials I found by Googling
https://code.tutsplus.com/tutorials/how-to-create-an-android-chat-app-using-firebase--cms-27397
http://myapptemplates.com/simple-android-chat-app-tutorial-firebase-integration/
https://codelabs.developers.google.com/codelabs/firebase-android/#0
Check Socket.IO for android. ( https://github.com/socketio/socket.io-client-java )
Its really easy to write a chat application. But you need a server side.
Easy to write a simple server for this chat app.
Server reveice the all message from clients and broadcast the message, to all.
Gradle:
compile 'com.github.nkzawa:socket.io-client:0.5.1'
Android manifest:
<uses-permission android:name="android.permission.INTERNET" />
Java
public static Socket mSocket;
try {
mSocket = IO.socket("http://192.168.1.104:4444");
mSocket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
Send messsage to server:
MainActivity.mSocket.emit("message","Text here...");
Create a listener for another message:
MainActivity.mSocket.on("newMessage", onMessageArrive); // Oncreate
private Emitter.Listener onMessageArrive = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String)args[0];
// Here is all message. add it to list :) Or Push notif
}
});
}
};
// Server side:
var http = require('http');
var express = require('express'),
app = module.exports.app = express();
var io = require('socket.io').listen(app.listen(4444));
io.on('connection', function (socket) {
socket.on("message",function(msg){
io.sockets.emit('newMessage', msg);
});
});
Run:
npm install express
npm install socket.io
node filename.js
Just dont forget to check you IP! :)
Done! You have a Real Time Chat!!
I want to consume SOAP based web services when click on a login button.
My code is as follows
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Log.p(" CaterId : "+catererId.getText());
Log.p(" Username : "+loginId.getText());
Log.p(" Password : "+password.getText());
final String InputParameter = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:tem=\"http://tempuri.org/\">"
+" <soap:Header/>"
+" <soap:Body>"
+" <tem:AuthenticateSupervisor>"
+" <tem:username>TestAbhi</tem:username>"
+" <tem:password>TestAbhi</tem:password>"
+" <tem:caterer>calihanint</tem:caterer>"
+" </tem:AuthenticateSupervisor>"
+" </soap:Body>"
+"</soap:Envelope>";
ConnectionRequest r= new ConnectionRequest() {
#Override
protected void buildRequestBody(OutputStream os) throws IOException {
os.write(InputParameter.getBytes("UTF-8"));
}
#Override
protected void postResponse() {
//super.postResponse();
}
#Override
protected void readResponse(InputStream input) throws IOException {
//super.readResponse(input);
XMLParser parser = new XMLParser();
Element elem = parser.parse(new InputStreamReader(input));
Log.p(" Came heer"+elem);
}
};
r.setUrl("http://192.168.10.224:8888/CXPPostScheduleService/Service.asmx");
r.setPost(false);
/*r.addArgument("username", "TestAbhi");
r.addArgument("password", "TestAbhi");
r.addArgument("caterer", "calihanint");*/
r.setContentType("application/soap+xml;charset=UTF-8");
NetworkManager.getInstance().addToQueueAndWait(r);
r.getResponseData();
}
});
It displays an html file as response. Could you please assist me to check what I'm doing wrong in this code.
I assume you need a post request try:
r.setPost(true);
If you are calling this from the device make sure the device is in the same network as the server otherwise the NAT local address will be unreachable. Notice that this will also apply to the simulator if the server is hosted elsewhere and not on your machine.
I also suggest checking the server logs, the error response code and post the error HTML. You can use the network monitor tool in the simulator to further debug this.
I am new to android. I am developing the new app with email sending option. To send a mail I have used gmail configurations host "smtp.gmail.com", port 465 with SSL true. To send an email I have apache commons API. OnTouch event mail sending method will call. Whenever touch button it shows following errors,
Error : Could not find class 'javax.naming.InitialContext', referenced from method org.apache.commons.mail.Email.setMailSessionFromJNDI
Warning: VFY: unable to resolve new-instance 955 (Ljavax/naming/InitialContext;) in Lorg/apache/commons/mail/Email;
Warning : org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465
I have added uses-permission android:name="android.permission.INTERNET" in my manifest file.
Can i use all java files in android ?
My email code executed correctly as a stand alone java program.
Here is an example of what I am doing in an app. I have an app that has its own email account that sends an email to the user when they fill out a form and press the submit button.
Important make sure you have the libSMTP.jar file referenced in your app. I am using this library for the following code. Here is the following code being used, take from it what you'd like, hope this is useful:
Imports needed:
import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.commons.net.smtp.SimpleSMTPHeader;
Submit button to make the request to send email
submit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//-- Submit saves data to sqlite db, but removed that portion for this demo...
//-- Executes an new task to send an automated email to user when they fill out a form...
new sendEmailTask().execute();
}
}
});
Email task to be preformed on seperate thread:
private class sendEmailTask extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPostExecute(Void result)
{
}
#Override
protected void onPreExecute()
{
}
#SuppressLint("ParserError")
#Override
protected Void doInBackground(Void... params)
{
try {
//--Note the send format is as follows: send(from, to, subject line, body message)
send("myAppName#gmail.com", "emailToSendTo#gmail.com", "Form Submitted", "You submitted the form.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Send function being used:
public void send(String from, String to, String subject, String text) throws IOException
{
SMTPClient client = new SMTPClient("UTF-8");
client.setDefaultTimeout(60 * 1000);
client.setRequireStartTLS(true); // requires STARTTLS
//client.setUseStartTLS(true); // tries STARTTLS, but falls back if not supported
client.setUseAuth(true); // use SMTP AUTH
//client.setAuthMechanisms(authMechanisms); // sets AUTH mechanisms e.g. LOGIN
client.connect("smtp.gmail.com", 587);
checkReply(client);
//--Note the following format is as follows: client.login("localhost", (...your email account being used to send email from...), (...your email accounts password ...));
client.login("localhost", "myAppName#gmail.com", "...myAppName email account password...");
checkReply(client);
client.setSender(from);
checkReply(client);
client.addRecipient(to);
checkReply(client);
Writer writer = client.sendMessageData();
if (writer != null)
{
SimpleSMTPHeader header = new SimpleSMTPHeader(from, to, subject);
writer.write(header.toString());
writer.write(text);
writer.close();
client.completePendingCommand();
checkReply(client);
}
client.logout();
client.disconnect();
}
Check reply function being used:
private void checkReply(SMTPClient sc) throws IOException
{
if (SMTPReply.isNegativeTransient(sc.getReplyCode()))
{
sc.disconnect();
throw new IOException("Transient SMTP error " + sc.getReplyCode());
}
else if (SMTPReply.isNegativePermanent(sc.getReplyCode()))
{
sc.disconnect();
throw new IOException("Permanent SMTP error " + sc.getReplyCode());
}
}
From Apache Commons Net 3.3, you can just drop the jar in your classpath and start using the AuthenticationSMTPClient : http://blog.dahanne.net/2013/06/17/sending-a-mail-in-java-and-android-with-apache-commons-net/