I am trying to develop XMPP chat in Android and while creating new user using AccountManager I am having the following exception :
jid-malformed(400)
My user-connection code goes like this:
AccountManager manager = connection.getAccountManager();
try {
manager.createAccount(username, password);
}
catch(XMPPException e){
e..printStackTrace();
}
here my
username = abc#xyz.com
password = 12345678
I learned that we need not require to send service name with the username from post
But in my username the format says that my user is "abc" and my service is "xyz.com"
what should I do to keep '#' in my username?
Thank You. :)
JID escaping is done as per XEP-0106. Specifically, the "#" character should be replaced by "\40" to keep the "#" as part of the JID.
Related
I have an android app that have a login form for student, and I want to check the student credential at web api depending on the stored data in sql server
I have searched the web and watch many videos that talking about many scenarios and nothing helped me.
All I want is a custom validation for my rest service (so I should send the credential for each request)
What should I do at asp.net web api service
how I can implement that at android application
Seems you didn't search for "Web API Token Based Authentication" ;) Anyhow what you need to implement is very simple.
You need to use OAuth 2.0 Resource Owner Credentials Flow which means that you want to provide the username/password only once for a specific endpoint i.e(/token) and then you if the username/password valid you obtain something called Bearer Access Token.
This token is valid for specified period and you can configure this in your Web API.
Once you obtain the access token, you need to store it securely in your android app, then you keep sending it with each request to your web api protected end points using the Authorization header (Bearer scheme(.
I've written very detailed post which covers your scenario 100%. Please check the post Token Based Authentication and let me know if you need further help.
I have used basic authentication for security,so I should provide the base64 encoding of
username:password
in header for each request as the following
authorization: Basic 'encoded username:password
httpGet.setHeader("Authorization", "Basic "+encodeUsernameAndPassword());
At the server side I have implemented message handler
public class BasicAuthenticationHandler : DelegatingHandler
{
public readonly IAuthenticationService authService;
public BasicAuthenticationHandler(IAuthenticationService service)
{
this.authService = service;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
AuthenticationHeaderValue authHeader = request.Headers.Authorization;
if (authHeader == null || authHeader.Scheme != "Basic")
{
return Unauthorized(request);
}
string encodedCredentials = authHeader.Parameter;
var credentialsBytes = Convert.FromBase64String(encodedCredentials);
var credentials = Encoding.ASCII.GetString(credentialsBytes).Split(':');
if (!authService.Authenticate(credentials[0], credentials[1]))
{
return Unauthorized(request);
}
string[] roles = null;//todo
IIdentity identity = new GenericIdentity(credentials[0], "Basic");
IPrincipal user = new GenericPrincipal(identity, roles);
HttpContext.Current.User = user;
return base.SendAsync(request, cancellationToken);
}
I work to develop a chat app with android on node.js server.I made a simple chat app.But everyone gets involved in the same room.I want to make a chat between only two people.How can I do that? What information should I send to the server?such as sender_name,receiver_name,message as a json format.
-How can I to do list online-users?
-And How can I start a chat between only two people?
What are the requirements for it?
This might help:
I'd recommend setting up namespaces for each room you have your chat in. I did something similar in my own code. Note: Rooms and namespaces are a little different from each other in socket.io itself (socket.io has both: http://socket.io/docs/rooms-and-namespaces/).
In the Server code:
I have a method under socket.on('connection') that is similar to
socket.on('groupConnect', function(group){
var groupNsp = io.of('/' + group);
}
This essentially makes sure that a namespace is exists under the name of the desired one. It doesn't mess it up or reset the namespace when it is called again.
Then for receiving the messages:
socket.on('message', function(data){
var msg = data.msg;
var nsp = data.nsp;
io.of(nsp).emit('message', msg);
}
You could also add the nsp to the data you have already and then just send the data again to the clients.
Then, in the client code:
var socketOut = io.connect('http://yourdomain:1337/');
var someGroupOrMethodToGetGroup;
socketOut.emit('groupConnect', someGroupOrMethodToGetGroup);
var nsp;
setTimeout(function(){
socket = io.connect('http://yourdomain:1377/' + someGroupOrMethodToGetGroup);
socket.on('message', function(msg){
displayMessage(msg);
}
nsp = '/' + someGroupOrMethodToGetGroup;
}, 1500);
Then in my displayMessage code I have:
socketOut.emit('message', { msg: desiredMessage, nsp: nsp });
From another answer of mine (https://stackoverflow.com/a/24805494/3842050).
I'm developing an IM app use tigase as server, and use asmack library in android side. Now I can do register/login/chat p2p, but when I create chat room, I met a problem, android side code as below:
XMPPConnection connection = XmppConnectionManager.getInstance().getConnection();
try {
MultiUserChat muc = new MultiUserChat(connection, "testroom" + "#" +
connection.getServiceName());
muc.create("nickname");
------
} catch (Exception e) {
e.printStackTrace();
}
After execute muc.create("nickname"), It's always throw exception, and exception info is: No response from server. In tigase server side, I'm enabled the MUC component in etc/init.properties as below:
--comp-name-1 = muc
--comp-class-1 = tigase.muc.MUCComponent
I have modify the project as the question
create a group chat functionality in android and getting No response from server.. on muc.create()
But still do not work,I do not know why, need your kindly help.
I have fixed this problem. It's my fault in client side, I must specify the MUC service name as configured in server side, It's different with tigase service name, configured as below:
--virt-hosts = localhost #tigase server name
--external= muc.localhost:muc-pass #muc.localhost is muc service name
So the client side code is as below:
MultiUserChat muc = new MultiUserChat(connection, roomName
+ "#muc." + connection.getServiceName());
Thanks to #Haider.
I have an Android application with GAE server. I tried to authenticate the user as described on developers.google.com, I added the user parameter to the endpoint methods etc. I get a User which is not null, but this method getUserId() returns null. It is similar to this, rather old problem:
Function User.getUserId() in Cloud endpoint api returns null for a user object that is not null
But I still don't know how to work around it. How do you handle this error? Have you ever encountered it?
In android client here's what I did (its simplified) :
credentials = GoogleAccountCredential.usingAudience(getApplicationContext(), "server:client_id:" + WEB_CLIENT_ID);
credentials.setSelectedAccountName(accountName);
WarriorEntityEndpoint.Builder endpointBuilder = new WarriorEntityEndpoint.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credentials);
warriorEntityEndpoint = endpointBuilder.build();
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
warriorEntityEndpoint.getWarrior().execute();
} catch (Exception e) {
}
return null;
}
}.execute();
And on GAE:
#Api(name = "warriorEntityEndpoint", namespace = #ApiNamespace(ownerDomain = "szpyt.com", ownerName = "szpyt.com", packagePath = "mmorpg.monsters"),
version = "version1",
scopes = {"https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"},
clientIds = {Constants.ANDROID_CLIENT_ID, Constants.WEB_CLIENT_ID},
audiences = {Constants.ANDROID_AUDIENCE})
public class WarriorEntityEndpoint {
private static final Logger log = Logger.getLogger(WarriorEntityEndpoint.class.getName());
#ApiMethod(name = "getWarrior")
public WarriorEntity getWarrior(User user) throws OAuthRequestException, IOException {
log.log(Level.SEVERE, "this gives correct email: " + user.getEmail());
log.log(Level.SEVERE, "this is null: " + user.getUserId());
I have also another very important question: is this user authenticated, if getMail() gives me correct account, but getUserId() gives null? I read that user object should be null if it was not authenticated but I am not sure any more...
I'm using App engine SDK 1.8.7. I'm testing on a real device and backend deployed to GAE.
I asked the same question a while ago and got an answer. See link:
Function User.getUserId() in Cloud endpoint api returns null for a user object that is not null
The cause is a bug on appengine.
I guess there is no good solution for it right now. I store e-mail as a normal property and remove it from default fetch group, I use long as a primary key (generated by AppEngine) and I query the entity by the e-mail property. I don't like my solution, I'll accept ( and implement :) ) a better one if anyone can provide.
This is a known issue which has been filed with google, I've attached the issue link below.
There are two workarounds (1) save the user and read back from the store, if it refers to a valid account the user id will be populated (this sucks because you pay the saving / loading / deletion cost for each API access that is authenticated even if it is tiny, and obviously some performance cost) and (2) you could use the google+ ID but that is NOT the same as the user id.
This is extremely frustrating and there is currently no ETA as they are working on some fundamental issues with the auth design as far as I understand.
Please, vote for that issue by starring it. You can find all the information here
https://code.google.com/p/googleappengine/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Type%20Component%20Status%20Stars%20Summary%20Language%20Priority%20Owner%20Log&groupby=&sort=&id=8848
And here is the current formally approved workaround [(1) above], which you can also find in the link above, but for ease it's here: How can I determine a user_id based on an email address in App Engine?
For workaround (2) mentioned above, you can look at the first link, and go to post #39.
I am developing an android application..in that application there is a registration module.for that i have to implement email verification functionality.
by using the following code I am able to send email for particular email..
public void onClick(View v) {
// TODO Auto-generated method stub
try {
GMailSender sender = new GMailSender("username#gmail.com", "*******");
sender.sendMail("This is Subject",
"This is Body",
"rose.jasmine87#gmail.com",
"naresh_bammidi#yahoo.co.in"
);
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
but how to know the status, whether it has been sent or not?
I'm assuming that you're using GMailSender as defined in this post.
Internally GMailSender calls Transport.send(message) which will throw an exception if the send to the GMail server is unsuccessful, but this is being caught and suppressed, so your calling code has no way of knowing whether sending was successful. Firstly you'll need to change the GMailSender code to do something a bit more meaningful in the case of a send error.
What you must remember is that email is not delivered directly to the final recipient by your app or even the GMail server. Just because you managed to send correctly to the GMail server, does not mean that it will actually reach its intended recipient, as it could fail at any mail relay on its route. To properly detect and report on whether mail actually reaches its destination you'll need something a little more sophisticated than this.
RFC 1891 is an extension to the SMTP protocol which supports delivery status notifications, but you may need to re-architect your app to be able to use this. Essentially it works by setting flags in your outgoing message to instruct mail relays to inform you of the message status. In order for you to receive this notification, you must essentially have your own mail server which is capable of receiving emails. You will receive an email containing, for example, a delivery report once a mail relay has successfully delivered it to the recipient's mailbox.
So, to properly implement this, you'll need a mail account for your app which will receive delivery status notifications. You'll need to create an SMTPMessage object, and add a header including a "Return-Receipt-To" header, whose value is set to this mail account. You'll also need to setNotifyOptions() on your message, and then send it to the GMail server. Your app will need to check its account periodically for delivery notifications.
This is a purely email-centric approach. Without knowing your precise requirements, there are alternate mechanisms that you can use. For example, if your requirement is purely to verify that an email address exists, then you can send an email which contains a URI to a server that you control. The URI contains parameters which uniquely identify both the user, and the installation of your app. The user must click on the link, and your server component verifies the mail account. It can then use something like C2DM to inform your app that the mail account is real and valid.
Sorry if this answer is a little long, and does not offer you a simple solution, but if you want to be able to properly determine whether mail is reaching its recipient, then there is no simple answer, I'm afraid.
check below method, which will validate email from client side, simply pass mail string it will return a boolean, whether entered email is correct or not.
public boolean isEmail(String email)
{
boolean matchFound1;
boolean returnResult=true;
email=email.trim();
if(email.equalsIgnoreCase(""))
returnResult=false;
else if(!Character.isLetter(email.charAt(0)))
returnResult=false;
else
{
Pattern p1 = Pattern.compile("^\\.|^\\# |^_");
Matcher m1 = p1.matcher(email.toString());
matchFound1=m1.matches();
Pattern p = Pattern.compile("^[a-zA-z0-9._-]+[#]{1}+[a-zA-Z0-9]+[.]{1}+[a-zA-Z]{2,4}$");
// Match the given string with the pattern
Matcher m = p.matcher(email.toString());
// check whether match is found
boolean matchFound = m.matches();
StringTokenizer st = new StringTokenizer(email, ".");
String lastToken = null;
while (st.hasMoreTokens())
{
lastToken = st.nextToken();
}
if (matchFound && lastToken.length() >= 2
&& email.length() - 1 != lastToken.length() && matchFound1==false)
{
returnResult= true;
}
else returnResult= false;
}
return returnResult;
}