Spring MVC bulk message using MimeMessagePreparator - email

I'm trying to send bulk emails using Spring MVC. Here is my code:
if(customerClients != null){
int count = 0;
boolean sent = false;
List<MimeMessagePreparator> preparators = new ArrayList<MimeMessagePreparator>();
for (BulkEmail client : customerClients) {
if(customerID==-1)
customerID = client.getCustomerID();
CustomerAccount customerAccount = service.getCustomerAccount(client.getCustomerID());
if (instantMessage.isEmailChecked() && customerAccount.getBalance()>0) {
try{
final String receiverID = client.getEmail();
instantMessage.setIpersonOrGroupValue(receiverID);
preparators.add(new MimeMessagePreparator()
{
public void prepare(MimeMessage mimeMessage) throws Exception
{
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.setSubject(instantMessage.getSubject());
message.setTo(receiverID);
message.setFrom(from);
message.setText(instantMessage.getMessage(), true);
}
});
sent = false;
}
catch(Exception ex){
ex.printStackTrace();
}
}
++count;
if(count%100==0){
springMail.send(preparators);
preparators = new ArrayList<MimeMessagePreparator>();
sent = true;
}
}
if(!sent)
springMail.send(preparators);
Here is the code that uses JavaMailSender for sending the preparators:
public void send(List<MimeMessagePreparator> preparatorsList) {
MimeMessagePreparator[] preparators = preparatorsList.toArray(new MimeMessagePreparator[preparatorsList.size()]);
mailSender.send(preparators);
}
The problem with this code is it takes around 1 second per email address. This means 300 emails in 5 minutes.
I want to know if this is normal or there is something I can do to improve.
Thanks

Related

Curator ServiceCacheListener is triggered three times when a service is added

I am learning zookeeper and trying out the Curator framework for service discoveries. However, I am facing a weird issue that I have difficulties to figure out. The problem is when I tried to register an instance via serviceDiscovery, the cacheChanged event of the serviceCache gets triggered three times. When I removed an instance, it is only triggered once, which is the expected behavior. Please see the code below:
public class DiscoveryExample {
private static String PATH = "/base";
static ServiceDiscovery<InstanceDetails> serviceDiscovery = null;
public static void main(String[] args) throws Exception {
CuratorFramework client = null;
try {
// this is the ip address of my VM
client = CuratorFrameworkFactory.newClient("192.168.149.129:2181", new ExponentialBackoffRetry(1000, 3));
client.start();
JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>(
InstanceDetails.class);
serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class)
.client(client)
.basePath(PATH)
.serializer(serializer)
.build();
serviceDiscovery.start();
ServiceCache<InstanceDetails> serviceCache = serviceDiscovery.serviceCacheBuilder()
.name("product")
.build();
serviceCache.addListener(new ServiceCacheListener() {
#Override
public void stateChanged(CuratorFramework curator, ConnectionState state) {
// TODO Auto-generated method stub
System.out.println("State Changed to " + state.name());
}
// THIS IS THE PART GETS TRIGGERED MULTIPLE TIMES
#Override
public void cacheChanged() {
System.out.println("Cached Changed ");
List<ServiceInstance<InstanceDetails>> list = serviceCache.getInstances();
Iterator<ServiceInstance<InstanceDetails>> it = list.iterator();
while(it.hasNext()) {
System.out.println(it.next().getAddress());
}
}
});
serviceCache.start();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("> ");
String line = in.readLine();
} finally {
CloseableUtils.closeQuietly(serviceDiscovery);
CloseableUtils.closeQuietly(client);
}
}
}
AND
public class RegisterApplicationServer {
final static String PATH = "/base";
static ServiceDiscovery<InstanceDetails> serviceDiscovery = null;
public static void main(String[] args) throws Exception {
CuratorFramework client = null;
try {
client = CuratorFrameworkFactory.newClient("192.168.149.129:2181", new ExponentialBackoffRetry(1000, 3));
client.start();
JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>(
InstanceDetails.class);
serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class).client(client).basePath(PATH)
.serializer(serializer).build();
serviceDiscovery.start();
// SOME OTHER CODE THAT TAKES CARES OF USER INPUT...
} finally {
CloseableUtils.closeQuietly(serviceDiscovery);
CloseableUtils.closeQuietly(client);
}
}
private static void addInstance(String[] args, CuratorFramework client, String command,
ServiceDiscovery<InstanceDetails> serviceDiscovery) throws Exception {
// simulate a new instance coming up
// in a real application, this would be a separate process
if (args.length < 2) {
System.err.println("syntax error (expected add <name> <description>): " + command);
return;
}
StringBuilder description = new StringBuilder();
for (int i = 1; i < args.length; ++i) {
if (i > 1) {
description.append(' ');
}
description.append(args[i]);
}
String serviceName = args[0];
ApplicationServer server = new ApplicationServer(client, PATH, serviceName, description.toString());
server.start();
serviceDiscovery.registerService(server.getThisInstance());
System.out.println(serviceName + " added");
}
private static void deleteInstance(String[] args, String command, ServiceDiscovery<InstanceDetails> serviceDiscovery) throws Exception {
// in a real application, this would occur due to normal operation, a
// crash, maintenance, etc.
if (args.length != 2) {
System.err.println("syntax error (expected delete <name>): " + command);
return;
}
final String serviceName = args[0];
Collection<ServiceInstance<InstanceDetails>> set = serviceDiscovery.queryForInstances(serviceName);
Iterator<ServiceInstance<InstanceDetails>> it = set.iterator();
while (it.hasNext()) {
ServiceInstance<InstanceDetails> si = it.next();
if (si.getPayload().getDescription().indexOf(args[1]) != -1) {
serviceDiscovery.unregisterService(si);
}
}
System.out.println("Removed an instance of: " + serviceName);
}
}
I appriciate if anyone can please point out where I am doing wrong and maybe can share some good materials/examples so I can refer to. The official website and the examples on github does not help a lot.

Not able to add user to ejabbered using c# and agsXMPP

I am developing a chat application in iOS and the APIs are on Windows server. Have got ejabbered installed on the server and am able to connect successfully from C# using agsXMPP.
The issue is that I am not able to register user every time, it sometimes executes successfully and sometimes not. Below is the code:
static ManualResetEvent done = new ManualResetEvent(false);
public void Login()
{
XmppClientConnection xmpp = (XmppClientConnection)Application["xmpp"];
try
{
if (xmpp == null)
{
xmpp = new XmppClientConnection();
Application["xmpp"] = xmpp;
}
xmpp.OnLogin += new ObjectHandler(xmpp_OnLogin);
xmpp.OnError += new ErrorHandler(xmpp_OnError);
xmpp.AutoPresence = true;
xmpp.AutoResolveConnectServer = false;
xmpp.Port = 5222;
xmpp.UseSSL = false;
xmpp.ConnectServer = "127.0.0.1";
xmpp.Server = "plutus-pc1";
xmpp.Username = "admin";
xmpp.Password = "p#ssword";
xmpp.KeepAlive = true;
xmpp.Open();
done.WaitOne();
Register();
}
catch (Exception ex)
{
xmpp.Close();
}
}
void xmpp_OnError(object sender, Exception ex)
{
XmppClientConnection xmpp = (XmppClientConnection)Application["xmpp"];
xmpp.Close();
}
void xmpp_OnLogin(object sender)
{
done.Set();
}
protected void cmdLogout_Click(object sender, EventArgs e)
{
XmppClientConnection xmpp = (XmppClientConnection)Application["xmpp"];
xmpp.Close();
}
public void Register()
{
try
{
XmppClientConnection xmpp;
xmpp = (XmppClientConnection)Application["xmpp"];
if (xmpp == null)
{
xmpp = new XmppClientConnection();
Application["xmpp"] = xmpp;
}
xmpp.AutoPresence = true;
xmpp.AutoResolveConnectServer = false;
xmpp.Port = 5222;
xmpp.UseSSL = false;
xmpp.ConnectServer = "127.0.0.1";
xmpp.Server = "plutus-pc1";
xmpp.Username = "user1";
xmpp.Password = "p#ssword1";
xmpp.RegisterAccount = true;
xmpp.OnRegisterError += xmpp_OnRegisterError;
xmpp.OnRegistered += xmpp_OnRegistered;
xmpp.Open();
//done.WaitOne();
}
catch (Exception ex)
{
}
}
void xmpp_OnRegistered(object sender)
{
}
void xmpp_OnRegisterError(object sender, agsXMPP.Xml.Dom.Element e)
{
//throw new NotImplementedException();
}
I get different errors when registration is not successful:
agsXMPP.Xml.Xpnet.InvalidTokenException
Unable to cast object of type
'agsXMPP.protocol.stream.feature.Register' to type
'agsXMPP.protocol.Stream'
Unable to read data from the transport
connection: Cannot access a disposed object.\r\nObject name:
'System.Net.Sockets.Socket'
Despite not change in code, get different errors

IPP Add Account - The Account Isn't Valid

I am trying to add a bank account to QuickBooks Online using IPP. My code fails and says the account isn't valid. Here is my code:
Account account = new Account();
account.Desc = "Desc";
account.Name = "Checking2";
account.Type = AccountTypeEnum.Revenue;
account.TypeSpecified = true;
account.Subtype = AccountSubtypeEnum.Bank.ToString();
dataServices.Add(account);
Do I need to add fields? I also receive errors that an account with the same name exists, however, I do not see it.
I don't see any XML in my log:
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, ConfigurationManager.AppSettings["consumerKey"].ToString(), ConfigurationManager.AppSettings["consumerSecret"].ToString());
ServiceContext context = new ServiceContext(oauthValidator, accessToken, companyID, IntuitServicesType.QBO);
context.EnableServiceRequestsLogging = true;
context.IdsLogger = new MyCustomLogger();
dataServices = new DataServices(context);
return "OK";
public class MyCustomLogger : ILogger
{
public MyCustomLogger()
{
}
public string ClearLog()
{
try
{
string path = HttpContext.Current.Server.MapPath("/qblog.txt");
if (File.Exists(path))
{
File.Delete(path);
}
return "OK";
}
catch (Exception ex)
{
return ex.ToString();
}
}
public void Log(TraceLevel idsTraceLevel, string messageToWrite)
{
string level = idsTraceLevel.ToString();
WriteToLog(new ErrorMessage(MessageSeverity.Error, "QBFS", messageToWrite));
}
public string WriteToLog(ErrorMessage message)
{
if (!String.IsNullOrEmpty(message.Message))
{
string path = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath + "/qblog.txt");
FileStream fileStream = null;
//If the file exists, then append it
if (File.Exists(path))
{
fileStream = new FileStream(path, FileMode.Append);
}
else
{
fileStream = new FileStream(path, FileMode.OpenOrCreate);
}
StreamWriter sw = new StreamWriter(fileStream);
try
{
sw.WriteLine(String.Format("{0} : {1} {2} {3}", message.ApplicationName, message.Severity, DateTime.Now, message.Message));
return "OK";
}
//If there is an error, just do nothing. Don't stop.
catch (Exception ex)
{
return ex.ToString();
}
finally
{
sw.Close();
fileStream.Close();
}
}
return "Message is null or empty";
}
}
Here is my xml request:
<?xml version="1.0" encoding="utf-8"?><q1:Account xmlns="http://www.intuit.com/sb/cdm/qbo" xmlns:q1="http://www.intuit.com/sb/cdm/v2"><q1:Name>Checking</q1:Name><q1:Desc>Desc</q1:Desc><q1:Subtype>Bank</q1:Subtype></q1:Account>
Here is my response:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><FaultInfo xmlns="http://www.intuit.com/sb/cdm/baseexceptionmodel/xsd"><Message>Another account is already using this name. Please use a different name.</Message><ErrorCode>BAD_REQUEST</ErrorCode><Cause>-11202</Cause></FaultInfo>
I needed to specify the opening and current balance with the true variables:
ac = new Account();
ac.Desc = "Desc";
ac.Name = "Testy";
ac.Subtype = QboAccountDetailTypeEnum.Checking.ToString();
ac.OpeningBalanceDate = DateTime.Now;
ac.OpeningBalanceDateSpecified = true;
ac.CurrentBalance = 0;
ac.CurrentBalanceSpecified = true;
dataServices.Add(ac);
My Subtype was also incorrect. I needed to use the QboAccountDetailTypeEnum.

Prevent sending email and show message via plug-in

I am writing crm2011 plugin in "Email" entity with "Send" Message of Pre_operation. What i want to do is when i click "Send" button in email entity, I do the necessary checking before send. If the checking is not correct, I want to prevent and stop the sending email and show "the alert message" and stop the second plugin(this plugin send email and create the associated entity to convert "Case"). Please give me some suggestion for that plugin?
Should i use pre-Validation stage or Pre_operation state? And how can I return false to stop plugin.
public void Execute(IServiceProvider serviceProvider)
{
try
{
string message = null;
_serviceProvider = serviceProvider;
_context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
_serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
_currentUser = _context.UserId;
message = _context.MessageName.ToLower();
if (message == "send")
{
if (_context.InputParameters != null && _context.InputParameters.Contains("EmailId"))
{
object objEmailId = _context.InputParameters["EmailId"];
if (objEmailId != null)
{
_emailId = new Guid(objEmailId.ToString());
FindEmailInfo();
if (_email != null)
{
if (_email.Attributes.Contains("description") && _email.Attributes["description"] != null)//Email descritpion is not null
{
string emaildescription = StripHTML();
//Find KB Article prefix no in system config entity
serviceguideprefix = "ServiceGuidesPrefix";
QueryByAttribute query = new QueryByAttribute("ppp_systemconfig");
query.ColumnSet = new ColumnSet(true);
query.AddAttributeValue(sysconfig_name, serviceguideprefix);
EntityCollection sysconfig = _service.RetrieveMultiple(query);
if (sysconfig.Entities.Count > 0)
{
Entity e = sysconfig.Entities[0];
if (e.Attributes.Contains("ppp_value"))
{
ppp_value = e.Attributes["ppp_value"].ToString();
}
}
if (ppp_value != null && ppp_value != string.Empty)
{
//var matches = Regex.Matches(emaildescription, #"KBA-\d*-\w*").Cast<Match>().ToArray();
var matches = Regex.Matches(emaildescription, ppp_value + #"-\d*-\w*").Cast<Match>().ToArray();
//ReadKBNo(emaildescription);
foreach (Match kbnumber in matches)
{
EntityCollection kbarticlecol = FindKBArticleIds(kbnumber.ToString());
if (kbarticlecol.Entities.Count > 0)
{
Entity kbariticle = kbarticlecol.Entities[0];
if (kbariticle.Attributes.Contains("mom_internalkm"))
{
bool internalserviceguide = (bool)kbariticle.Attributes["mom_internalkm"];
if (internalserviceguide) found = true;
else found = false;
}
else found = false;
}
}
}
if (found)
{
//-----
}
}
}
}
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message, ex);
}
}
Well stopping the plugin is dead easy you just throw InvalidPluginException, the message you give it will be shown to the user in a alert window. You will have to do this on the pre of the send. In this case I don't think it will matter if its pre-validation or pre-operation.
Edit:
Yes, you should throw an InvalidPluginException even if no exception has happened in code. I accept this isnt what we would normally do, but its the way its meant to work. Msdn has more details: http://msdn.microsoft.com/en-us/library/gg334685.aspx
So for example the code would look like:
public void Execute(IServiceProvider serviceProvider)
{
try
{
//This is where we validate the email send
if(emailIsOkay)
{
//Do something
}
else if(emailIsNotOkay)
{
//Throw and exception that will stop the plugin and the message will be shown to the user (if its synchronous)
throw new InvalidPluginExecutionException("Hello user, your email is not correct!!");
}
}
catch (InvalidPluginExecutionException invalid)
{
//We dont to catch exception for InvalidPluginExecution, so just throw them on
throw;
}
catch (Exception ex)
{
//This exception catches if something goes wrong in the code, or some other process.
throw new InvalidPluginExecutionException(ex.Message, ex);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm;
using Microsoft.Xrm.Sdk;
using System.ServiceModel;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace SendEmail
{
public class Email : IPlugin
{
public void Execute(IServiceProvider serviceprovider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceprovider.GetService(typeof(IPluginExecutionContext));
if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity))
return;
//entity
Entity ent = (Entity)context.InputParameters["Target"];
if (ent.LogicalName != "entityName")//EntityName
throw new InvalidPluginExecutionException("Not a Service Request record! ");
//service
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceprovider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService _service = serviceFactory.CreateOrganizationService(context.UserId);
string Email="";
if (ent.Contains("emailidfiled"))
Email = (string)ent["emailidfiled"];
#region email template
QueryExpression query = new QueryExpression()
{
EntityName = "template",
Criteria = new FilterExpression(LogicalOperator.And),
ColumnSet = new ColumnSet(true)
};
query.Criteria.AddCondition("title", ConditionOperator.Equal, "templateName");
EntityCollection _coll = _service.RetrieveMultiple(query);
if (_coll.Entities.Count == 0)
throw new InvalidPluginExecutionException("Unable to find the template!");
if (_coll.Entities.Count > 1)
throw new InvalidPluginExecutionException("More than one template found!");
var subjectTemplate = "";
if (_coll[0].Contains("subject"))
{
subjectTemplate = GetDataFromXml(_coll[0]["subject"].ToString(), "match");
}
var bodyTemplate = "";
if (_coll[0].Contains("body"))
{
bodyTemplate = GetDataFromXml(_coll[0]["body"].ToString(), "match");
}
#endregion
#region email prep
Entity email = new Entity("email");
Entity entTo = new Entity("activityparty");
entTo["addressused"] =Email;
Entity entFrom = new Entity("activityparty");
entFrom["partyid"] = "admin#admin.com";
email["to"] = new Entity[] { entTo };
email["from"] = new Entity[] { entFrom };
email["regardingobjectid"] = new EntityReference(ent.LogicalName, ent.Id);
email["subject"] = subjectTemplate;
email["description"] = bodyTemplate;
#endregion
#region email creation & sending
try
{
var emailid = _service.Create(email);
SendEmailRequest req = new SendEmailRequest();
req.EmailId = emailid;
req.IssueSend = true;
GetTrackingTokenEmailRequest wod_GetTrackingTokenEmailRequest = new GetTrackingTokenEmailRequest();
GetTrackingTokenEmailResponse wod_GetTrackingTokenEmailResponse = (GetTrackingTokenEmailResponse)
_service.Execute(wod_GetTrackingTokenEmailRequest);
req.TrackingToken = wod_GetTrackingTokenEmailResponse.TrackingToken;
_service.Execute(req);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("Email can't be saved / sent." + Environment.NewLine + "Details: " + ex.Message);
}
#endregion
}
private static string GetDataFromXml(string value, string attributeName)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
XDocument document = XDocument.Parse(value);
// get the Element with the attribute name specified
XElement element = document.Descendants().Where(ele => ele.Attributes().Any(attr => attr.Name == attributeName)).FirstOrDefault();
return element == null ? string.Empty : element.Value;
}
}
}

XMPP: Smack client not receiving chat message

I've been struggling with XMPP chatting a lot through Smack and Openfire server.
My problem is as follows:
Whenever a user sends a message to another user, the message is received correctly at the other user. But any reply doesn't show up at the sender of the first message.
So User 1 sends to User 2 successfully. User 2 is then unable to send to User 1 any reply.
On the other hand, if I restart and let the users login again, User 2 can send to User 1 but not vice versa.
What I'm trying to say is that only the initiator of the chat can send a message, the receiver cannot reply back.
My code looks like this
package xmpp;
public class XMPPClient{
private static final int packetReplyTimeout = 500; // millis
private XMPPConnection connection;
private ChatManager chatManager;
private MessageListener messageListener;
private ConnectionConfiguration config;
private MyTimer t = MyTimer.getInstance();
private ArrayList<String> threadPool = new ArrayList<String>();
public XMPPClient()
{
SmackConfiguration.setPacketReplyTimeout(packetReplyTimeout);
//define openfire server information
config = new ConnectionConfiguration("localhost",5222);
config.setSASLAuthenticationEnabled(false);
config.setSecurityMode(SecurityMode.disabled);
connection = new XMPPConnection(config);
//connect to server
t.start("Connecting to server...");
try {
connection.connect();
} catch (XMPPException e) {
System.err.println("Failed to connect to server! Connect to VPN!\t"+e.getMessage());
System.exit(0);
}
t.end("Connection took ");
//setup chat mechanism
chatManager = connection.getChatManager();
chatManager.addChatListener(
new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally)
{
if (!createdLocally)
chat.addMessageListener(new MyMessageListener());
}
});
}
public boolean login(String userName, String password, String resource) {
t.start("Logging in...");
try {
if (connection!=null && connection.isConnected())
connection.login(userName, password, resource);
//set available presence
setStatus(true);
}
catch (XMPPException e) {
if(e.getMessage().contains("auth")){
System.err.println("Invalid Login Information!\t"+e.getMessage());
}
else{
e.printStackTrace();
}
return false;
}
t.end("Logging in took ");
return true;
}
public void setStatus(boolean available) {
if(available)
connection.sendPacket(new Presence(Presence.Type.available));
else
connection.sendPacket(new Presence(Presence.Type.unavailable));
}
public void sendMessage(String message, String buddyJID) throws XMPPException {
System.out.println(String.format("Sending mesage '%1$s' to user %2$s", message, buddyJID));
boolean chatExists = false;
Chat c = null;
for(String tid : threadPool)
{
if((c = chatManager.getThreadChat(tid)) != null)
{
if(c.getParticipant().equals(buddyJID))
{
if(checkAvailability(buddyJID))
{
chatExists = true;
break;
}
else
{
threadPool.remove(tid);
break;
}
}
}
}
if (chatExists)
{
Chat chat = c;
chat.sendMessage(message);
}
else
{
Chat chat = chatManager.createChat(buddyJID, messageListener);
threadPool.add(chat.getThreadID()); System.out.println(chat.getThreadID());
chat.sendMessage(message);
}
}
public void createEntry(String user, String name) throws Exception {
System.out.println(String.format("Creating entry for buddy '%1$s' with name %2$s", user, name));
Roster roster = connection.getRoster();
roster.createEntry(user, name, null);
}
public boolean checkAvailability(String jid)
{
System.out.print("Checking availability for: "+jid+"=");
System.out.println(connection.getRoster().getPresence(jid).isAvailable());
return connection.getRoster().getPresence(jid).isAvailable();
}
public void disconnect() {
if (connection!=null && connection.isConnected()) {
setStatus(false);
connection.disconnect();
}
}
}
import org.jivesoftware.smack.packet.Message;
public class MyMessageListener implements MessageListener {
#Override
public void processMessage(Chat chat, Message message) {
String from = message.getFrom();
String body = message.getBody();
System.out.println(String.format("Received message '%1$s' from %2$s", body, from));
}
}
I'm not sure what the problem is. Any suggestions? Sample code?
Thanks <3
I am not sure if this will help you but I can get reply with this code:
public void chat(String AddressedUser) throws NotConnectedException {
//Create username whom we want to send a message
String userToSend = AddressedUser + "#" + serverDomain;
ChatManager chatmanager = ChatManager.getInstanceFor(connection);
Chat newChat = chatmanager.createChat(userToSend , new MessageListener() {
#Override
public void processMessage(Chat chat, Message message ) {
// TODO Auto-generated method stub
System.out.println("Received message: " + message);
}
});
try {
newChat.sendMessage("Hey");
}
catch (XMPPException e) {
System.out.println("Error Delivering block");
}
}
I am sending "Hey" then what ever other user writes I will see in my logcat.
You haven't specified what the receiver is, for instance, if it is an existing client (like Spark for instance), or more custom code. This would be helpful, as would knowing what version of Smack you are using.
That particular code has several issues with it.
It keeps creating new Chat objects for every message sent, instead of
simply reusing the same chat.
There is no ChatManagerListener registered to handle new Chat messages that are not tied to an existing chat.
the is code is very complicated and it seems is meant only to send msgs.
Here is a sample code that works perfectly, both sending and receiving:
http://www.javaprogrammingforums.com/java-networking-tutorials/551-how-write-simple-xmpp-jabber-client-using-smack-api.html