Google Talk receiving messages with different jid resource - google-app-engine

I think I'm doing something wrong.
I want to send a XMPP message to my GTalk id but I don't want that the GTalk app receives the message so I'm changing the resource of the recipient JID.
My problem is that GTalk is receiving all the messages although thay have different resource.
My code:
public void doPost(HttpServletRequest req,
HttpServletResponse resp) throws IOException {
// Parse incoming message
XMPPService xmpp = XMPPServiceFactory.getXMPPService();
Message msg = xmpp.parseMessage(req);
JID jid = msg.getFromJid();
String body = msg.getBody();
String jidID = jid.getId().split("/")[0];
JID jid2 = new JID(jidID+"/myownresource453242352");
String response = jid2.getId() + " " + body;
// Send out response
msg = new MessageBuilder().withRecipientJids(jid2).withBody(response).build();
xmpp.sendMessage(msg);
}
The output:
Rafa Espillaque, 18:33 -
You shouldn't respond!
prueba-gae-gdx#appspot.com, 18:33 -
rafaespillaque#gmail.com/myownresource453242352 You shouldn't respond!
What's wrong?
UPDATE:
Now I'm sending messages to myapp#appspot.com/bot from an aSmack client and it is resending the message to me at my client.
The problem is GTalk for Gmail and GTalk for Android is registering all sent messages but they don't receive the app responses. Other clients don't show the messages I don't sent with them.
Will I be able to hide my messages to Gmail and Android?
My code:
SERVER
public void doPost(HttpServletRequest req,
HttpServletResponse resp) throws IOException {
LOG.setLevel(Level.INFO);
// Parse incoming message
XMPPService xmpp = XMPPServiceFactory.getXMPPService();
Message msg = xmpp.parseMessage(req);
LOG.info(msg.getStanza());
JID jid = msg.getFromJid();
String body = msg.getBody();
String response = "FullID: "+jid.getId()+" El mensaje recibido es: "+body;
// Send out response
msg = new MessageBuilder().
withRecipientJids(jid)
.withMessageType(MessageType.NORMAL)
.withBody(response)
.build();
xmpp.sendMessage(msg);
}
CLIENT:
ConnectionConfiguration connectionConfiguration = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
XMPPConnection connection = new XMPPConnection(connectionConfiguration);
try {
Log.i("TAG","Trying to connect");
connection.connect();
Log.i("TAG","Connected");
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
Log.i("TAG","Trying to Log In");
connection.login("rafaespillaque#gmail.com",mypass, mires");
Log.i("TAG","Logged In");
} catch (XMPPException e) {
e.printStackTrace();
Log.i("TAG","Problem connecting or logging in");
}
//Creating chat object for processing friend chat
Chat chat = connection.getChatManager().createChat(Server, new MessageListener() {
//Overriding process message function of MessageListener Interface which will be
//called whenever a message is received
#Override
public void processMessage(Chat c, Message m) {
//Displaying message sent by friend
//System.out.println(friendId+ " : " + m.getBody());
Log.i("TAG", m.getBody());
message = m.getBody();
}
});
try {
Message out = new Message();
out.setBody("Definitivo22222222");
out.setType(Type.normal);
chat.sendMessage(out);
Log.i("TAG", "Mensaje enviado");
} catch (XMPPException e) {
Log.i("TAG", "No se envió el mensaje");
e.printStackTrace();
}
Last thing: I've seen in AppEngine Logs that the Stanza received from aSmack isn't of normal type but chat type.
Thanks for helping!!
Last-last thing: You can test what Gmail is doing by connecting from any client and Gmail at same time and talking from the client. Gmail is receiving your messages.
Thanks again.
Another thing:
My goalis use XMPP to communicate 2 clients of a game with their gmail account. Do you know an alternative?

See RFC 6120, section 10.5.4:
If the JID contained in the 'to' attribute is of the form
localpart#domainpart/resourcepart and the user exists but there is
no connected resource that exactly matches the full JID, the stanza
SHOULD be processed as if the JID were of the form
localpart#domainpart as described under Section 10.5.3.2.
If you send to an invalid resource, the server treats it as if you had sent it to the bare JID. On GoogleTalk, this goes to all non-negative priority resources.

I think that this is by design. IIRC GTalk routes all messages for a given JID to all connected resources of the JID. This is even true if the message has a full JID as to.

If you send the message with JID and resource (user#yoursever/reourcex) then the receiving server will route your request to the intended receiver. The receiving server will decide how to route the JID/resource.
A standard server will look for an exact match of the sent JID/resource. If found then it will behave as expected and the message will be delivered. If that fails on the other hand, it will send the message to the highest priority online resource. If that fails, it will store the message offline.
In the case of Google Talk this will happen: it will try to match the exact resource, and if that fails, broadcast it to all of the online resources. The same is also applied if no resource included.

Related

Twilio voice application error occurred

I am trying to integrate Twilio to my AngularJS and spring MVC application. After following Twilio documentation I set up at front end device setup and calling etc. In Java class I am generating a token, and passing that token while making the call. In java the code is:
#RequestMapping(value = "/phoneCalling", method {
RequestMethod.GET, RequestMethod.POST
})
public #ResponseBody Phone phoneCalling(HttpServletRequest request, HttpServletResponse response, #RequestParam String leadPhone) {
try {
Number number = new Number.Builder(leadPhone).build();
Dial dial = new Dial.Builder().number(number).build();
VoiceResponse responseVR = new VoiceResponse.Builder().dial(dial).build();
System.out.println(responseVR.toXml());
} catch (TwiMLException e) {
e.printStackTrace();
}
return null;
}
At twilio TwiML, I set request URL as:
https://865c048b.ngrok.io/ZingyCRM/phoneCalling/
As I am testing locally, so used ngrok. But after clicking on make a call, it gives me voice message as application error occurred. I believe the TwiML request URL I might be setting wrong, can some one help here?

How to send GCM Topic Message from Java Appengine

To send a normal GCM, I can do
Sender sender = new Sender(apiKey);
Message message = new Message.Builder()
.addData("message", "this is the message")
.addData("other-parameter", "some value")
.build();
Result result = sender.send(message, registrationId, numOfRetries);
Will someone please show how I might send a topic message from Appengine (Java)
You can use this version of the Java GCM library. It will soon be merged into the master branch. It supports topic messaging. To send a topic message simply set the topic as the "to" field. Eg: /topics/mytopic
Sender sender = new Sender(apiKey);
sender.send(message, topic);

email address on GAE

I have an application on google app engine like abc.appspot.com can I have an email address to send/receive emails like admin#abc.appspot.com kindly help me.
Edit
here is my SendMail class
public class SendMail {
private static String fromAddress = "abc#gmail.com";
private static Logger log = Logger.getLogger(SendMail.class.getCanonicalName());
// Send the Mail
public void send(String toAddress, String subject, String msgBody)
throws IOException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(fromAddress));
InternetAddress to = new InternetAddress(toAddress);
msg.addRecipient(Message.RecipientType.TO, to);
msg.setSubject(subject);
msg.setText(msgBody);
Transport.send(msg, new InternetAddress[] { to });
} catch (AddressException addressException) {
log.log(Level.SEVERE, "Address Exception , mail could not be sent", addressException);
} catch (MessagingException messageException) {
log.log(Level.SEVERE, "Messaging Exception , mail could not be sent", messageException);
}
}
}
So it sends an email regarding abc#gmail.com but I want that it should send from email#abc.appspot.com.
You can only receive emails in the form of #abc.appspotmail.com. AFAIK there is no way to have #abc.appspot.com as receiving address.
If you wan to receive emails from your custom domain, e.g. #abc.com, than the only way is to have external email service forward emails to your #abc.appspotmail.com. Most domain registrars offer free limited email service with forwarding (we use GoDaddy and get limited forwarding free).
Yes you can: https://developers.google.com/appengine/docs/java/mail/usingjavamail#Senders_and_Recipients

GAE Channel Sending First Message Repetatively

So this was working on this project a few months ago. I'm using Google App Engine's Channel API to push messages to my GWT app. I'm using http://code.google.com/p/gwt-gae-channel/ to interact through GWT.
Lets say I send 1 message to the client: "First Message"
The client will receive the message, "First Message" just fine.
Then let's say I send another message, "Second Message" to the client.
The client will again receive the message, "First Message".
This will continue happening. There have been some instances where I'll receive the second message, and it will be the message that gets stuck repeating.
When I finally close the page, and thus close the channel, I again receive the repeated message without sending something from the server.
Does anyone have any idea what is going on? I don't think this was happening when I was working on this a few months ago, and I can see no changes to the GAE Channel API.
Here is some code:
String json = AutoBeanHelper.toJson(proxy);
log.fine("Item's JSON Received: " + json);
List<ChannelEntity> channels = channelDAO.getByUserId();
if (channels.size() > 1) {
log.warning("Multiple channels for single user detected.");
}
ChannelService channelService = ChannelServiceFactory.getChannelService();
for (ChannelEntity channel : channels) {
channelService.sendMessage(new ChannelMessage(channel.getClientId(), json));
}
So whenever I store a new item of a specific type (this is in that entities update function):
1. I turn it into JSON.
2. I then log that JSON.
3. I get that users channel.
4. I send it to that users channel.
When I look at my logs, I see that the variable above that I'm logging is showing correctly, meaning I'm logging the correct JSON message but when I display the JSON in an alert on the client-side as soon as it gets to the client, it's the previous message that seems to be stuck repeating. I really don't see what I could be doing wrong here.
Let me know if you would like to see another part of the code. For good measure, here is the code on the client:
eventBus.addHandler(ReceivedChannelTokenEvent.TYPE, new ReceivedChannelTokenEventHandler() {
#Override
public void onEvent(ReceivedChannelTokenEvent event) {
ChannelFactory.createChannel(event.getChannelToken(), new ChannelCreatedCallback() {
#Override
public void onChannelCreated(Channel channel) {
final Socket channelSocket = channel.open(new SocketListener() {
#Override
public void onOpen() {
Window.alert("Channel Opened");
}
#Override
public void onMessage(String json) {
Window.alert(json);
eventBus.fireEvent(new MessageReceivedEvent(json));
}
#Override
public void onError(SocketError error) {
Window.alert("Channel Error: " + error.getDescription());
if ( error.getDescription().equals(CHANNEL_ERROR_TOKEN_TIME_OUT) ) {
eventBus.fireEvent(new ChannelTimeOutEvent());
}
}
#Override
public void onClose() {
Window.alert("Channel Closed.");
}
});
Window.addWindowClosingHandler(new Window.ClosingHandler() {
#Override
public void onWindowClosing(ClosingEvent event) {
channelSocket.close();
}
});
}
});
}
});
I see a lot of questions on SO where someone has a bug in their code but think it's part of the framework. Without seeing any code, I suspect there's some bug where you think you're sending "Second Message", but you're really sending a cached version of "First Message".
So I was finally able to figure it out. It seems that in the onMessage function within the app when I call
eventBus.fireEvent(new MessageReceivedEvent(json));
it seems that it never returns from this, thus never exiting the onMessage function in the code, causing me to receive the same message repetitively.

Strange problem with Google App Engine Java Mail

I'm using the MailService feature of Google App Engine in my
application. It works fine in one application without any issues.
But the same code doesn't work in another app. I'm not able to figure
it out. Please help. Following is the piece of code that I use to
send mail.
public static void sendHTMLEmail(String from, String fromName, String
to, String toName, String subject, String body) {
_logger.info("entering ...");
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
_logger.info("got mail session ...");
String htmlBody = body;
try {
Message msg = new MimeMessage(session);
_logger.info("created mimemessage ...");
msg.setFrom(new InternetAddress(from,
fromName));
_logger.info("from is set ...");
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
to, toName));
_logger.info("recipient is set ...");
msg.setSubject(subject);
_logger.info("subject is set ...");
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlBody, "text/html");
mp.addBodyPart(htmlPart);
_logger.info("body part added ...");
msg.setContent(mp);
_logger.info("content is set ...");
Transport.send(msg);
_logger.info("email sent successfully.");
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getMessage());
}
}
When I look at the log (on the server admin console), it prints the
statement "content is set ..." and after that there is nothing in the
log. The mail is not sent. At times I get the following error after
the above statement is printed (and the mail is not sent).
com.google.appengine.repackaged.com.google.common.base.internal.Finalizer
getInheritableThreadLocalsField: Couldn't access
Thread.inheritableThreadLocals. Reference finalizer threads will
inherit thread local values.
But the mail quota usage keeps increasing.
Remember, this works fine in one application, but not in other. I'm
using the same set of email addresses in both the apps (for from and
to).
I'm really stuck with this. Appreciate any help.
Thank you.
Velu
Have you tried logging the exceptions? I bet one of them is being thrown - your printStackTrace will go nowhere.

Resources