* calls the sendNewsletter method for each one. After sending, the
* recipient sent property is updated to the current time
*
*/
if (InodeUtils.isSet(inode)) {
Campaign c = CampaignFactory.getCampaign(inode);
campaigns = new ArrayList<Campaign>();
if (c.isActive() &&
!(UtilMethods.isSet(c.getExpirationDate()) && c.getExpirationDate().before(new Date()))) {
// create new child campaign and added to campaign array
try {
Campaign childCampaign = new Campaign();
BeanUtils.copyProperties(childCampaign, c);
childCampaign.setParentCampaign(c.getInode());
childCampaign.setInode(null);
childCampaign.setIsRecurrent(false);
childCampaign.setLocked(true);
HibernateUtil.saveOrUpdate(childCampaign);
MailingList ml = (MailingList) InodeFactory.getChildOfClass(c, MailingList.class);
HTMLPage page = (HTMLPage) InodeFactory.getChildOfClass(c, HTMLPage.class);
Communication comm = (Communication) InodeFactory.getChildOfClass(c, Communication.class);
UserFilter userfilter = (UserFilter) InodeFactory.getChildOfClass(c, UserFilter.class);
if(InodeUtils.isSet(ml.getInode())){
relationshipAPI.addRelationship(childCampaign.getInode(), ml.getInode(), "child");
}
if(InodeUtils.isSet(page.getInode())){
relationshipAPI.addRelationship(childCampaign.getInode(), page.getInode(), "child");
}
if (InodeUtils.isSet(comm.getInode())) {
relationshipAPI.addRelationship(childCampaign.getInode(), comm.getInode(), "child");
}
if (InodeUtils.isSet(userfilter.getInode())) {
relationshipAPI.addRelationship(childCampaign.getInode(), userfilter.getInode(), "child");
}
HibernateUtil.saveOrUpdate(childCampaign);
campaigns.add(childCampaign);
c.setLocked(false);
}
catch (Exception ex) {
Logger.debug(this, ex.getMessage());
}
}
}
else {
//get a list of waiting queues
campaigns = CampaignFactory.getWaitingCampaigns();
}
StringBuffer message = null;
if (campaigns.size() == 0)
{
campaigns = null;
return;
}
try {
Logger.debug(DeliverCampaignThread.class, "GOING to deliver campaigns");
Iterator<Campaign> campIter = campaigns.iterator();
//### LOOP THE CAMPAIGNS ###
while (campIter.hasNext())
{
//Obtain the campaign
Campaign c = (Campaign) campIter.next();
Communication comm = (Communication) InodeFactory.getChildOfClass(c, Communication.class);
if ((comm == null) || (!InodeUtils.isSet(comm.getInode()))) {
Logger.info(DeliverCampaignThread.class, "I didn't find a communication for campaign inode=" + c.getInode());
c.setCompletedDate(new java.util.Date());
c.setLocked(false);
message = null;
HibernateUtil.saveOrUpdate(c);
continue;
}
Logger.debug(DeliverCampaignThread.class, "got campaign:" + c.getTitle());
//Mailing list
String campaingSendTo = c.getSendTo();
MailingList ml = null;
UserFilter uf = null;
List<UserProxy> subscribers = null;
if ((campaingSendTo != null) && campaingSendTo.equalsIgnoreCase("mailingList")) {
ml = (MailingList) InodeFactory.getChildOfClass(c,MailingList.class);
if (!InodeUtils.isSet(ml.getInode()))
{
Logger.info(DeliverCampaignThread.class, "I didn't find a mailing list for campaign inode=" + c.getInode());
c.setCompletedDate(new java.util.Date());
c.setLocked(false);
message = null;
HibernateUtil.saveOrUpdate(c);
continue;
}
else
{
Logger.debug(DeliverCampaignThread.class, "got mailingList:" + ml.getTitle());
//Get the subscribers
subscribers = MailingListFactory.getMailingListSubscribers(ml);
Logger.debug(DeliverCampaignThread.class, "Got subscribers:" + subscribers.size());
}
}
else if ((campaingSendTo != null) && campaingSendTo.equalsIgnoreCase("userFilter")) {
uf = (UserFilter) InodeFactory.getChildOfClass(c,UserFilter.class);
if (!InodeUtils.isSet(uf.getInode()))
{
Logger.info(DeliverCampaignThread.class, "I didn't find an user filter for campaign inode=" + c.getInode());
c.setCompletedDate(new java.util.Date());
c.setLocked(false);
message = null;
HibernateUtil.saveOrUpdate(c);
continue;
}
else
{
Logger.debug(DeliverCampaignThread.class, "got user filter:" + uf.getUserFilterTitle());
//Get the subscribers
try {
subscribers = UserFilterFactory.getUserProxiesFromFilter(uf);
}
catch (Exception e) {
Logger.info(DeliverCampaignThread.class, "Error getting subscriber from user filter for campaign inode=" + c.getInode());
c.setCompletedDate(new java.util.Date());
c.setLocked(false);
message = null;
HibernateUtil.saveOrUpdate(c);
continue;
}
Logger.debug(DeliverCampaignThread.class, "Got subscribers:" + subscribers.size());
}
}
//Unsubscriber mailing list
MailingList unSubscribers = MailingListFactory.getUnsubscribersMailingList();
//do we have an html page?
String alternateTextMessage = null;
HTMLPageAPI pageAPI = APILocator.getHTMLPageAPI();
HTMLPage htmlPage = (HTMLPage) pageAPI.loadWorkingPageById(comm.getHtmlPage(), APILocator.getUserAPI().getSystemUser(), false);
String serverName;
if (htmlPage != null && UtilMethods.isSet(htmlPage.getTitle())) {
html = true;
Logger.debug(DeliverCampaignThread.class, "Got htmlPage:"+ htmlPage.getTitle());
// get the newsletter and the attachments
Identifier id = APILocator.getIdentifierAPI().find(htmlPage);
serverName = APILocator.getHostAPI().find(id.getHostId(), APILocator.getUserAPI().getSystemUser(), false).getHostname();
//rewrite the urls
try {
Logger.debug(DeliverCampaignThread.class, "Retrieving page from url " + "http://"+ serverName + UtilMethods.encodeURIComponent(id.getURI()));
message = new StringBuffer(UtilMethods.escapeUnicodeCharsForHTML(UtilMethods.getURL("http://"+ serverName + UtilMethods.encodeURIComponent(id.getURI())).toString()));
Logger.debug(DeliverCampaignThread.class, "Page retrieved " + message);
message = EmailFactory.alterBodyHTML(message, serverName);
Logger.debug(DeliverCampaignThread.class, "Page altered " + message);
alternateTextMessage = "If you are having trouble reading this message, click here: "+ "http://"+ serverName + UtilMethods.encodeURIComponent(id.getURI());
}catch(Exception e){
/**
* This condition was included to avoid send
* campaigns without content
* */
Logger.info(DeliverCampaignThread.class, "Error generating message for campaign inode=" + c.getInode() + " and htmlPage inode=" + htmlPage.getInode());
c.setCompletedDate(new java.util.Date());
c.setLocked(false);
message = null;
HibernateUtil.saveOrUpdate(c);
continue;
}
} else {
serverName = APILocator.getHostAPI().findDefaultHost(APILocator.getUserAPI().getSystemUser(), false).getHostname();
html = false;
if (comm.getTextMessage() != null){
message = new StringBuffer(UtilMethods.escapeUnicodeCharsForHTML(comm.getTextMessage()));
message = EmailFactory.alterBodyHTML(message, serverName);
}
else
message = new StringBuffer("");
}
//add tracking shim
message.append("<img src='http://"+ serverName + "/imageShim?r=<rId>' width='1' height='1'>");
// big loop over recipients
Iterator<UserProxy> subscriberIterator = subscribers.iterator();
String send_per_hour = c.getSendsPerHour();
User user = new User();
try {
user = APILocator.getUserAPI().loadUserById(c.getUserId(),APILocator.getUserAPI().getSystemUser(),false);
} catch (Exception e) {
Logger.error(DeliverCampaignThread.class, "deliverCampaigns Failed - getting campaign owner: "+ c.getUserId()+ " " + e.getMessage());
}
//### LOOP THE SUBSCRIBERS OF EACH CAMPAIGN ###
while (subscriberIterator.hasNext())
{
UserProxy userProxy = (UserProxy) subscriberIterator.next();
try {
// validting permissions over subscriber
try {
_checkUserPermissions(userProxy, user, PERMISSION_READ);
}catch(Exception e){
continue;
}
User member = new User();
try {
member = APILocator.getUserAPI().loadUserById(userProxy.getUserId(), APILocator.getUserAPI().getSystemUser(), false);
} catch (Exception e) {
Logger.error(DeliverCampaignThread.class, "deliverCampaigns Failed - getting subscriber: " + userProxy.getUserId() + " " + e.getMessage());
}
Recipient recipient = RecipientFactory.getRecipientByCampaignAndSubscriber(c, member);
recipient.setUserId(member.getUserId());
if (EmailFactory.isSubscribed(unSubscribers,member))
{
recipient.setLastMessage("On "+MailingListFactory.getUnsubscribersMailingList().getTitle());
recipient.setLastResult(500);
userProxy.setLastMessage("On "+MailingListFactory.getUnsubscribersMailingList().getTitle());
userProxy.setLastResult(500);
c.addChild(recipient);
continue;
}
//if this recipient already got the email
List<UserComment> l = UserCommentsFactory.getUserCommentsByComm(userProxy.getInode(), comm.getInode());
if (InodeUtils.isSet(recipient.getInode()) || l.size() > 0)
{
Logger.debug(EmailFactory.class,"Already got this email:" + recipient.getEmail());
if (!c.isSendEmail()) {
continue;
}
}
recipient.setEmail(member.getEmailAddress());
recipient.setName(member.getFirstName());
recipient.setLastname(member.getLastName());
recipient.setSent(new java.util.Date());
HibernateUtil.saveOrUpdate(recipient);
setRecipient(recipient);
setCampaign(c);
setSubscriber(member);
setAlternateTextMessage(alternateTextMessage);
setMessage(message);
setHtml(true);
c.addChild(recipient);
if (!comm.getCommunicationType().equalsIgnoreCase("alert")) {
if(!sendEmail()) {
//If got errors sending the email then we mark it as a bounce
//from the mailing list
MailingListFactory.markAsBounceFromMailingList(ml, userProxy);
}
}
else {
//for alert communications only
recipient.setLastResult(200);
recipient.setLastMessage("Alert created");
}
HibernateUtil.saveOrUpdate(recipient);
long sleepTime = 10;
if(UtilMethods.isSet(send_per_hour) && !send_per_hour.equals("unlimited"))
{
sleepTime = 3600000 / Integer.parseInt(send_per_hour);
}
try
{
Thread.sleep(sleepTime);
}
catch(Exception t)
{
Logger.error(this,t.getMessage(),t);
}
} catch (Exception e) {
Logger.info(DeliverCampaignThread.class, "Failed to sent campaign inode=" + c.getInode() + " to userProxy inode=" + userProxy.getInode() + " e=" + e);
}
}
c.setWasSent(true);
c.setCompletedDate(new java.util.Date());
c.setLocked(false);
message = null;
HibernateUtil.saveOrUpdate(c);
Logger.debug(DeliverCampaignThread.class, "Campaign sent: " + c.getTitle());
}
} catch (Exception e) { }
finally {
try {
CampaignFactory.unlockAllCampaigns();