How to search user details from local Openfire server using aSmack library? - android

I'm developing chat application, In which I'm using openfire server and asmack library. I want to search users who was registered on that server.
Here is the code which I have written..
UserSearchManager search = new UserSearchManager(connection);
try {
Log.d("JWP", "cc:"+connection.getServiceName());
org.jivesoftware.smackx.Form searchForm = search.getSearchForm("search."+connection.getServiceName());
org.jivesoftware.smackx.Form answerForm = searchForm.createAnswerForm();
answerForm.setAnswer("Username", true);
answerForm.setAnswer("search", editTextSearch.getText().toString());
org.jivesoftware.smackx.ReportedData data;
data = search.getSearchResults(answerForm,"search."+connection.getServiceName());
if(data.getRows() != null){
Iterator<org.jivesoftware.smackx.ReportedData.Row> it = data.getRows();
while(it.hasNext()){
org.jivesoftware.smackx.ReportedData.Row row = it.next();
Iterator iterator = row.getValues("jid");
if(iterator.hasNext()){
String value = iterator.next().toString();
Log.i("Iteartor values......"," "+value);
}
}
Toast.makeText(Welcome.this,"Username Exists",Toast.LENGTH_SHORT).show();
}
}
catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But here getSerachFrom() method returns null value, have tried various things but don't understand why this is happening.
My openfire server having number of registered users.

Related

Is it possible to use Javamail to receive mails in Android

I'm learning Javamail these days following this website:
http://www.tutorialspoint.com/javamail_api/
I test the sending & added some extra stuff because it was on Android & it worked!
But things have changed completely when I tried to follow receiving email Tutorial which makes me wonder..
Is it possible to make this code :
https://www.tutorialspoint.com/javamail_api/javamail_api_fetching_emails.htm
works on android but using XML interface?!
You can use the following code:
public static void receiveEmail(String pop3Host, String storeType, user, String password) {
try {
//1) get the session object
Properties properties = new Properties();
properties.put("mail.pop3.host", pop3Host);
Session emailSession = Session.getDefaultInstance(properties);
//2) create the POP3 store object and connect with the pop server
POP3Store emailStore = (POP3Store) emailSession.getStore(storeType);
emailStore.connect(user, password);
//3) create the folder object and open it
Folder emailFolder = emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
//4) retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
//5) close the store and folder objects
emailFolder.close(false);
emailStore.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
call your method passing some parameters:
String host = "pop.gmail.com";//change accordingly
String mailStoreType = "pop3";
String username= "example#gmail.com";
String password= "xxxxx";//change accordingly
receiveEmail(host, mailStoreType, username, password);
Source: Steps for receiving the email using JavaMail API

Getting all users from an openfire server using smack android

i have a openfire server running on my localhost and i am successfully able to send and receive messages to registered users. however i am not been able to get all users from server. i am logged in with user that doesn't have a administration access. so do i need to give any permission on server side?
The code i am using for getting all users is..
if ( xmpp.getConnection()== null || !xmpp.getConnection().isConnected())
return;
try {
UserSearchManager usm = new UserSearchManager(xmpp.getConnection());
Form searchForm = usm.getSearchForm("search." + xmpp.getConnection().getServiceName());
Form answerForm = searchForm.createAnswerForm();
UserSearch userSearch = new UserSearch();
answerForm.setAnswer("Username", true);
answerForm.setAnswer("search", userName);
ReportedData data = userSearch.sendSearchForm(xmpp.getConnection(), answerForm, "search." + xmpp.getConnection().getServiceName());
for (ReportedData.Row row : data.getRows())
{
arrayList.add(row.getValues("Username").toString());
}
} catch (Exception e) {
e.printStackTrace();
}
i tried some solutions that shows to use Roster class, however that is also not helping me. Can anyone show what i am doing wrong or if i need to give any permission as i am not logged in as admin?
The error i am getting is..
org.jivesoftware.smack.XMPPException$XMPPErrorException: XMPPError: remote-server-not-found
Thanks :)
This is how I am getting all users from openfire
You actually have to pass wildcard(*) for the username
Here's the working code
Utils.getConnection() - my xmpp connection
public static void getAllXmppUsers()
{
try {
UserSearchManager manager = new UserSearchManager(Utils.getConnection());
String searchFormString = "search." + Utils.getConnection().getServiceName();
Log.d("***", "SearchForm: " + searchFormString);
Form searchForm = null;
searchForm = manager.getSearchForm(searchFormString);
Form answerForm = searchForm.createAnswerForm();
UserSearch userSearch = new UserSearch();
answerForm.setAnswer("Username", true);
answerForm.setAnswer("search", "*");
ReportedData results = userSearch.sendSearchForm(Utils.getConnection(), answerForm, searchFormString);
if (results != null) {
List<ReportedData.Row> rows = results.getRows();
for (ReportedData.Row row : rows) {
Log.d("***", "row: " + row.getValues("Username").toString());
}
} else {
Log.d("***", "No result found");
}
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
Try this code. I tweak this code from this answer
UserSearchManager usm= new UserSearchManager(xmpp.getConnection());
Form searchForm = usm.getSearchForm("search." +xmpp.getConnection().getServiceName());
Form answerForm = searchForm.createAnswerForm();
answerForm.setAnswer("Username", true);
answerForm.setAnswer("search", userName);
ReportedData data = usm
.getSearchResults(answerForm, "search." + xmpp.getConnection().getServiceName());
if (data.getRows() != null) {
for (ReportedData.Row row: data.getRows()) {
for (String jid:row.getValues("jid")) {
System.out.println(jid);
}
}
}
Smack is used to create a client. A client is used by one user. A user typically does not have access to all users of the server. Users do have contact lists, or rosters though, where you an add other users.

XMPP IIllegalArgumentException at Form#setAnswer("Username",true) while using UserSearchManager

I am working on android chat application using ejabberd 2.1.11. For searching whether a particular user exists or not i'm using UserSearchManager
public boolean isUserExists(IrishContact ic) {
try {
UserSearchManager search = new UserSearchManager(connection);
Collection<String> services = search.getSearchServices();
if (services.isEmpty()) {
Log.v("IrishuserSearch ", "no service found");
}
Log.v("service name: ", connection.getServiceName());
Form searchForm = search.getSearchForm("vjud."
+ connection.getServiceName());
Form answerForm = searchForm.createAnswerForm();
answerForm.setAnswer("Username", true);
answerForm.setAnswer("search", ic.getPhoneNumber());
org.jivesoftware.smackx.ReportedData data = search
.getSearchResults(answerForm,
"search." + connection.getServiceName());
if (data.getRows() != null) {
Iterator<Row> it = data.getRows();
if (it.hasNext()) {
return true;
} else
return false;
} else
return false;
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
On the basis on this answer
i'm using
Form searchForm = search.getSearchForm("vjud."
+ connection.getServiceName());
instead of
Form searchForm =
search.getSearchForm("search."+connection.getServiceName());
the later part was giving 503 service not found exception so i changed my code and it got solved, but now the problem is I am getting IllegalArgumentException at
answerForm.setAnswer("Username", true);
I am using asmack-android-8-0.8.10.
STACK_TRACE=java.lang.IllegalArgumentException: Field not found for the specified variable name.
at org.jivesoftware.smackx.Form.setAnswer(Form.java:258)
at com.irishtalk.utilities.IrishUserSearch.isUserExists(IrishUserSearch.java:42)
at com.irishtalk.utilities.IrishContactsHelper.addContactToDefaultRoster(IrishContactsHelper.java:51)
at com.irishtalk.utilities.IrishContactsHelper.getRoster(IrishContactsHelper.java:32)
at com.irishtalk.service.IXmppAidlStub$1.run(IXmppAidlStub.java:221)
can anyone help me out why this is happening? Thanks
Ejabberd does not support the field value "Username". It is used in openfire. Please use the field vale "user" and pass arguments as string in ejabberd. Thanks. Please Vote up if your error is solved.

How to insert and get .NET web-service data Object to My Android App

I have a web-service in .NET it's inserting and retrieving data's from database as object's..
I'll copy some part of web-service here..
[WebMethod(Description = "This is used to insert details into sql server")]
public string InsertDetails(DataTable myDetails, string STR1)
{
try
{
foreach (DataRow row in myDetails.Rows)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dbo.InsertQry";
cmd.Parameters.Add(new SqlParameter("#P_no", row["POD_Number"].ToString()));
cmd.Parameters.Add(new SqlParameter("#P_id", STR1));
cmd.Parameters.Add(new SqlParameter("#P_author", Convert.ToInt64(row["P_author"])));
//opening the connection
cmd.Connection = sqlCon;
sqlCon.Open();
int retValue = cmd.ExecuteNonQuery();
sqlCon.Close();
if (retValue == 0)
return "false";
}
return "true";
}
catch (Exception ex)
{
ErrorLogger(ex);
return "false";
}
}
//-----------------------------------------------------------------------------------
[WebMethod(Description = "This is used to get details from sql server")]
public DataSet GetDetails(string STR1)
{
DataSet ds = new DataSet();
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dbo.SelectQryFromDB";
//opening the connection
cmd.Connection = sqlCon;
sqlCon.Open();
ds.DataSetName = "myTbl";
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds,"myTbl");
sqlCon.Close();
return ds;
}
catch (Exception ex)
{
ErrorLogger(ex);
ds.DataSetName = "Error";
return ds;
}
}
//----------------------------
Any-one Help me by providing me the details how can i send those data's and retrieve data's in Android..This is my first application so i don't know much??
Please Provide me details so that i can insert and get data's using web-service??
I heard of kSOAP2 and i'm trying to accomplish this by using kSOAP2..
Working in Ksoap can be challenging sometimes. You first need to make sure your webservice is working fine and is giving you the proper result.
If that's done then you can consume the same from Android using ksoap library.
Here are few links that will help solve your problem:
1) How to call a local web service from Android mobile application will help you understand how you need to make a Ksoap call.
2) Inserting data into remote database from Android via ksoap
3) Returning data from server to Android

Retrieve email according to date time using javamail in android

I am doing on task to retrieve gmails. I manage to retrieve with below codes. However, it retrieved received email from the earliest to latest emails in the gmail inbox. Is there a way to make it retrieved the latest mails? I intend to implement a way to retrieved the latest 20 mails only instead of retrieved all the mails in the inbox. Thanks in advance for the guidance.
public ArrayList<HashMap<String, String>> getMail(int inboxList){
Folder inbox;
/* Set the mail properties */
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try
{
/* Create the session and get the store for read the mail. */
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com",username, password);
/* Mention the folder name which you want to read. */
inbox = store.getFolder("Inbox");
System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());
/*Open the inbox using store.*/
inbox.open(Folder.READ_WRITE);
/* Get the messages which is unread in the Inbox*/
Message messages[];
if(recent){
messages = inbox.search(new FlagTerm(new Flags(Flag.RECENT), false));
}else{
messages = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
}
/* Use a suitable FetchProfile */
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.CONTENT_INFO);
inbox.fetch(messages, fp);
try
{
printAllMessages(messages);
inbox.close(true);
store.close();
}
catch (Exception ex)
{
System.out.println("Exception arise at the time of read mail");
ex.printStackTrace();
}
}
catch (NoSuchProviderException e)
{
//e.printStackTrace();
System.exit(1);
}
catch (MessagingException e)
{
//e.printStackTrace();
System.exit(2);
}
Instead of using inbox.search() use
inbox.getMessages(int start,int end);
it will retrieve the range of messages.
To get the latest 20 mails use:
int n=inbox.getMessageCount();
messages= inbox.getMessages(n-20,n);
If you just want the last 20 messages, just ask for the last 20 message numbers,
or access the last 20 entries in the array returned by folder.getMessages().
Not that the order of messages in the mailbox is the order in which they arrived,
not the order in which they were sent.
Used the android.os.Message
static class DateCompare implements Comparator<Message> {
public int compare(Message one, Message two){
return one.getWhen().compareTo(two.getWhen());
}
}
............
DateCompare compare = new DateCompare();
Message messages[];
if(recent){
messages = inbox.search(new FlagTerm(new Flags(Flag.RECENT), false));
}else{
messages = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
}
List<Message> list = Arrays.asList(messages );
Collections.sort(list,compare);
List<Messsage> newList = list.subList(0,19);
hope this helps.

Categories

Resources