Sfoglia il codice sorgente

Annullamento conformità errate pratiche di tipo B e C

master
Salvatore La Manna 4 anni fa
parent
commit
21015fd1e0
  1. 247
      liferay-plugins-sdk-6.2/portlets/portos-bo-portlet/docroot/WEB-INF/src/it/mwg/sismica/bo/util/PuliziaDatabase.java
  2. 13
      liferay-plugins-sdk-6.2/portlets/portos-bo-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/bo/model/impl/AvvisoImpl.java
  3. 23
      liferay-plugins-sdk-6.2/portlets/portos-bo-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/bo/scheduler/SchedulerGeneraDocumento.java
  4. 79
      liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/hook/events/StartupAction.java
  5. 23
      liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/hook/listener/DLFileEntryListener.java
  6. 124
      liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/messaging/SendMailMessageListener.java
  7. 52
      liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/portlet/EmailPortlet.java
  8. 165
      liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/portlet/EmailTemplatesPortlet.java
  9. 149
      liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/service/impl/EmailAttachmentLocalServiceImpl.java
  10. 4
      liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/service/impl/EmailServiceImpl.java
  11. 63
      liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/service/impl/EmailTemplateServiceImpl.java
  12. 678
      liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/util/MailEngine.java
  13. 2
      liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/util/MailSenderUtil.java
  14. 64
      liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/util/VelocityUtil.java
  15. 4
      liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/service.properties

247
liferay-plugins-sdk-6.2/portlets/portos-bo-portlet/docroot/WEB-INF/src/it/mwg/sismica/bo/util/PuliziaDatabase.java

@ -5,94 +5,231 @@
*/
package it.mwg.sismica.bo.util;
import flexjson.JSONSerializer;
import it.tref.liferay.portos.bo.model.Avviso;
import it.tref.liferay.portos.bo.model.Collaudo;
import it.tref.liferay.portos.bo.model.ControlloPratica;
import it.tref.liferay.portos.bo.model.Delega;
import it.tref.liferay.portos.bo.model.DettPratica;
import it.tref.liferay.portos.bo.model.DocAggiuntiva;
import it.tref.liferay.portos.bo.model.DocPratica;
import it.tref.liferay.portos.bo.model.FineLavori;
import it.tref.liferay.portos.bo.model.IntPratica;
import it.tref.liferay.portos.bo.model.Soggetto;
import it.tref.liferay.portos.bo.model.Sorteggio;
import it.tref.liferay.portos.bo.service.AvvisoLocalServiceUtil;
import it.tref.liferay.portos.bo.service.CollaudoLocalServiceUtil;
import it.tref.liferay.portos.bo.service.DelegaLocalServiceUtil;
import it.tref.liferay.portos.bo.service.ConfigurazioneLocalServiceUtil;
import it.tref.liferay.portos.bo.service.ControlloPraticaLocalServiceUtil;
import it.tref.liferay.portos.bo.service.DettPraticaLocalServiceUtil;
import it.tref.liferay.portos.bo.service.DocAggiuntivaLocalServiceUtil;
import it.tref.liferay.portos.bo.service.DocPraticaLocalServiceUtil;
import it.tref.liferay.portos.bo.service.FineLavoriLocalServiceUtil;
import it.tref.liferay.portos.bo.service.IntPraticaLocalServiceUtil;
import it.tref.liferay.portos.bo.service.SoggettoLocalServiceUtil;
import it.tref.liferay.portos.bo.service.SorteggioLocalServiceUtil;
import it.tref.liferay.portos.bo.shared.util.ConfigurazioneConstants;
import it.tref.liferay.portos.bo.shared.util.StatoPraticaConstants;
import it.tref.liferay.portos.bo.util.AvvisoUtil;
import it.tref.liferay.portos.bo.util.WorkflowConstants;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.liferay.portal.kernel.cache.CacheRegistryUtil;
import com.liferay.portal.kernel.cache.MultiVMPoolUtil;
import com.liferay.portal.kernel.cache.SingleVMPoolUtil;
import com.liferay.portal.kernel.dao.jdbc.DataAccess;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.repository.model.FileEntry;
import com.liferay.portal.kernel.repository.model.Folder;
import com.liferay.portal.kernel.servlet.DirectServletRegistryUtil;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.UniqueList;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.Organization;
import com.liferay.portal.model.User;
import com.liferay.portal.service.ClassNameLocalServiceUtil;
import com.liferay.portal.security.permission.ActionKeys;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portlet.documentlibrary.model.DLFileEntry;
import com.liferay.portlet.documentlibrary.model.DLFileEntryMetadata;
import com.liferay.portlet.documentlibrary.model.DLFolder;
import com.liferay.portlet.documentlibrary.model.DLSyncConstants;
import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil;
import com.liferay.portlet.documentlibrary.service.DLFolderLocalServiceUtil;
import com.liferay.portlet.dynamicdatamapping.model.DDMContent;
import com.liferay.portlet.dynamicdatamapping.model.DDMStorageLink;
import com.liferay.portlet.messageboards.model.MBDiscussion;
public class PuliziaDatabase {
private static final Log _log = LogFactoryUtil.getLog(PuliziaDatabase.class);
private static final int SLICE = 1000;
public static List<String> pulisci(ServiceContext serviceContext) {
public static List<String> pulisci(ServiceContext serviceContext) throws SystemException {
List<String> esito = new ArrayList<>();
int numeroPratiche = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date min = null;
Date max = null;
try {
List<IntPratica> pratiche = null;
int start = 0;
do {
pratiche = IntPraticaLocalServiceUtil.getIntPraticas(start, start + SLICE);
for (IntPratica pratica : pratiche) {
List<Avviso> avvisi = AvvisoLocalServiceUtil.findByIntPratica(pratica.getIntPraticaId(),
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
int noFile = 0;
for (Avviso avviso : avvisi) {
if (0 == avviso.getFileEntryIdBase()) {
AvvisoLocalServiceUtil.deleteAvviso(avviso);
noFile++;
}
min = sdf.parse("2020-09-25 18:43:49");
max = sdf.parse("2020-09-25 18:44:15");
} catch (ParseException e) {
esitoLog(esito, "Errore date: " + e.getMessage());
return esito;
}
long companyId = serviceContext.getCompanyId();
long folderId = ConfigurazioneLocalServiceUtil.findByC_ChiaveLong(companyId,
ConfigurazioneConstants.TEMPLATE_FOLDER_ID);
long templateAnnullamentoId = 0;
try {
Folder folder = DLAppLocalServiceUtil.getFolder(folderId);
FileEntry template = DLAppLocalServiceUtil.getFileEntry(folder.getGroupId(), folderId, "ATAP");
templateAnnullamentoId = template.getFileEntryId();
} catch (PortalException e1) {
}
if (Validator.isNull(templateAnnullamentoId)) {
esitoLog(esito, "Template ATAP non trovato");
return esito;
}
String descLongAnnullamento = "Annullamento d'ufficio";
long templateConformitaId = ConfigurazioneLocalServiceUtil.findByC_ChiaveLong(companyId,
"conf.geniocivile.avviso.template.id.deposito.B2");
String descLongConformita = "Avviso di conformità";
List<Avviso> sbagliati = new ArrayList<>();
List<Long> inviate = new UniqueList<>();
List<Long> conformi = new UniqueList<>();
int start = 0;
List<Avviso> avvisi = new ArrayList<>();
do {
avvisi = AvvisoLocalServiceUtil.getAvvisos(start, start + SLICE);
for (Avviso avviso : avvisi) {
if (avviso.getDtAvviso().after(min) && avviso.getDtAvviso().before(max)
&& avviso.getTipoDocumento().equalsIgnoreCase(StatoPraticaConstants.CONFORME)) {
sbagliati.add(avviso);
} else if (avviso.getFileEntryIdTemplate() == templateAnnullamentoId) {
inviate.add(avviso.getIntPraticaId());
} else if (avviso.getFileEntryIdTemplate() == templateConformitaId) {
conformi.add(avviso.getIntPraticaId());
}
}
start += SLICE;
} while (avvisi.size() > 0);
SimpleDateFormat dfmt = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
JSONSerializer jsonSerializer = new JSONSerializer();
int noIntPratica = 0;
int annullatiA = 0;
int annullatiB = 0;
int annullatiC = 0;
for (Avviso avviso : sbagliati) {
long intPraticaId = avviso.getIntPraticaId();
if (!inviate.contains(intPraticaId)) {
IntPratica intPratica = null;
try {
intPratica = IntPraticaLocalServiceUtil.getIntPratica(intPraticaId);
} catch (PortalException e) {
}
if (Validator.isNull(intPratica)) {
noIntPratica++;
} else {
Map<String, String> parameters = new HashMap<>();
parameters.put("dataProtocolloAnnullato", dfmt.format(avviso.getDtProtocollo()));
parameters.put("numeroProtocolloAnnullato", avviso.getProtocollo());
DettPratica dettPratica = DettPraticaLocalServiceUtil
.getLastCompletedByIntPratica(intPraticaId);
List<ControlloPratica> controlli = ControlloPraticaLocalServiceUtil
.findByIntPraticaId_Status(intPraticaId, WorkflowConstants.STATUS_PENDING);
long controlloPraticaId = 0;
if (controlli.size() > 0) {
controlloPraticaId = controlli.get(controlli.size() - 1).getPrimaryKey();
}
if (noFile > 0) {
esitoLog(esito,
"Pratica " + pratica.getNumeroProgetto() + "(" + pratica.getIntPraticaId()
+ ") - " + avvisi.size() + " avvisi, eliminati: " + noFile);
ServiceContext ctx = new ServiceContext();
ctx.setCompanyId(intPratica.getCompanyId());
ctx.setScopeGroupId(intPratica.getGroupId());
ctx.setUserId(intPratica.getUserId());
ctx.setGroupPermissions(new String[] { ActionKeys.VIEW });
String jsonParameters = StringPool.BLANK;
switch (intPratica.getTipoProcedura().toUpperCase()) {
case "A":
annullatiA++;
break;
case "B":
case "B1":
Sorteggio sorteggio = SorteggioLocalServiceUtil.findByIntPratica(intPratica
.getIntPraticaId());
if (Validator.isNull(sorteggio)) {
jsonParameters = jsonSerializer.serialize(parameters);
try {
AvvisoLocalServiceUtil.addAvviso(intPraticaId, descLongAnnullamento,
new Date(), AvvisoUtil.TIPO_AVVISO_DIRETTO, "MA",
templateAnnullamentoId, dettPratica.getPrimaryKey(),
DettPratica.class.getName(), StringPool.BLANK, jsonParameters,
controlloPraticaId, serviceContext);
if (!conformi.contains(intPraticaId)) {
AvvisoLocalServiceUtil.addAvviso(intPratica.getIntPraticaId(),
descLongConformita, new Date(), AvvisoUtil.TIPO_AVVISO_DIRETTO,
StatoPraticaConstants.CONFORME, templateConformitaId,
dettPratica.getDettPraticaId(), DettPratica.class.getName(),
controlloPraticaId, serviceContext);
}
} catch (PortalException e) {
esitoLog(esito,
"Errore nell'invio per pratica " + intPratica.getNumeroProgetto()
+ ", " + e.getMessage());
}
esitoLog(esito, "Pratica "
+ intPratica.getNumeroProgetto()
+ " ("
+ intPraticaId
+ "), procedura "
+ intPratica.getTipoProcedura()
+ ", invio annullamento"
+ (conformi.contains(intPraticaId) ? ", conformità già inviata"
: " e conformità"));
annullatiB++;
} else {
esitoLog(esito, "Pratica " + intPratica.getNumeroProgetto() + " (" + intPraticaId
+ "), procedura " + intPratica.getTipoProcedura()
+ ", non invio perché sorteggiata");
}
break;
case "C":
Avviso valido = null;
avvisi = AvvisoLocalServiceUtil.findByIntPraticaId_tipoDocumento(intPraticaId,
StatoPraticaConstants.VIDIMATA);
for (Avviso presente : avvisi) {
if (presente.getPrimaryKey() != avviso.getPrimaryKey()) {
if ((presente.getPrimaryKey() <= avviso.getPrimaryKey())
&& (Validator.isNull(valido) || (valido.getPrimaryKey() > presente
.getPrimaryKey()))) {
valido = presente;
}
}
}
if (Validator.isNotNull(valido)) {
parameters.put("dataProtocolloValido", dfmt.format(valido.getDtProtocollo()));
parameters.put("numeroProtocolloValido", valido.getProtocollo());
jsonParameters = jsonSerializer.serialize(parameters);
try {
AvvisoLocalServiceUtil.addAvviso(intPraticaId, descLongAnnullamento,
new Date(), AvvisoUtil.TIPO_AVVISO_DIRETTO, "MA",
templateAnnullamentoId, dettPratica.getPrimaryKey(),
DettPratica.class.getName(), StringPool.BLANK, jsonParameters,
controlloPraticaId, serviceContext);
} catch (PortalException e) {
esitoLog(esito,
"Errore nell'invio per pratica " + intPratica.getNumeroProgetto()
+ ", " + e.getMessage());
}
}
esitoLog(esito, "Pratica " + intPratica.getNumeroProgetto() + " (" + intPraticaId
+ "), procedura " + intPratica.getTipoProcedura() + ", " + jsonParameters);
annullatiC++;
break;
}
}
start += SLICE;
numeroPratiche += pratiche.size();
} while (pratiche.size() > 0);
esitoLog(esito, numeroPratiche + " pratiche");
} catch (Exception e) {
esitoLog(esito, "Interrotto per errore: " + e.getMessage());
}
}
_log.info(sbagliati.size() + " avvisi");
_log.info("Procedura A = " + annullatiA);
_log.info("Procedura B = " + annullatiB);
_log.info("Procedura C = " + annullatiC);
_log.info("IntPratica non esistente = " + noIntPratica);
return esito;
}

13
liferay-plugins-sdk-6.2/portlets/portos-bo-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/bo/model/impl/AvvisoImpl.java

@ -124,11 +124,14 @@ public class AvvisoImpl extends AvvisoBaseImpl {
public String getDescriptionOggettoProtocollo() throws PortalException, SystemException {
String tipoDocumento = AvvisoUtil.getAllTipoDocumento().containsKey(this.getTipoDocumento()) ? AvvisoUtil
.getAllTipoDocumento().get(this.getTipoDocumento())
: "label.admingeniocivile.avviso.tipoDocumento.avvisomanuale";
String fullDescription = LanguageUtil.get(LocaleUtil.ITALIAN, tipoDocumento);
String fullDescription = LanguageUtil.get(LocaleUtil.ITALIAN,
"label.admingeniocivile.avviso.tipoDocumento.avvisomanuale");
if (AvvisoUtil.getAllTipoDocumento().containsKey(this.getTipoDocumento())) {
fullDescription = LanguageUtil.get(LocaleUtil.ITALIAN,
AvvisoUtil.getAllTipoDocumento().get(this.getTipoDocumento()));
} else if (Validator.isNotNull(this.getDescLong())) {
fullDescription = this.getDescLong();
}
if (this.getTipoDocumento().equalsIgnoreCase(StatoPraticaConstants.VIDIMATA)) {

23
liferay-plugins-sdk-6.2/portlets/portos-bo-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/bo/scheduler/SchedulerGeneraDocumento.java

@ -132,29 +132,6 @@ public class SchedulerGeneraDocumento implements MessageListener {
if (Validator.isNotNull(avviso.getJsonParameters())) {
JSONDeserializer<Map<String, String>> deserializer = JSONFactoryUtil.createJSONDeserializer();
parameters.putAll(deserializer.deserialize(avviso.getJsonParameters()));
// TODO vedere se vann oaggiunti dati presi in altro modo
// if
// (parameters.containsKey(WorkflowConstants.WORKFLOW_PARAM_NAME_DELEGATO_OUT))
// {
// User user = null;
// String delegato =
// GetterUtil.getString(parameters.get(WorkflowConstants.WORKFLOW_PARAM_NAME_DELEGATO_OUT));
// List<ExpandoValue> expandoValues =
// ExpandoValueLocalServiceUtil.getColumnValues(companyId,
// User.class.getName(),
// Constants.CUSTOM_FIELD_TABLE_NAME,
// Constants.CUSTOM_FIELD_GC_USERID, delegato,
// QueryUtil.ALL_POS,
// QueryUtil.ALL_POS);
// if (expandoValues != null && !expandoValues.isEmpty()) {
// ExpandoValue expandoValue = expandoValues.get(0);
// user =
// UserLocalServiceUtil.fetchUserById(expandoValue.getClassPK());
// }
// parameters.put(WorkflowConstants.WORKFLOW_PARAM_NAME_DELEGATO,
// user.getFullName());
// }
}
Object bean;

79
liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/hook/events/StartupAction.java

@ -22,63 +22,62 @@ import com.liferay.portlet.documentlibrary.service.DLFolderLocalServiceUtil;
public class StartupAction extends SimpleAction {
private final static Log _log = LogFactoryUtil.getLog(StartupAction.class);
private final static Log _log = LogFactoryUtil.getLog(StartupAction.class);
@Override
public void run(String[] ids) throws ActionException {
@Override
public void run(String[] ids) throws ActionException {
for (String id : ids) {
for (String id : ids) {
long companyId = GetterUtil.getLong(id);
long companyId = GetterUtil.getLong(id);
try {
try {
Company company = CompanyLocalServiceUtil.getCompany(companyId);
Company company = CompanyLocalServiceUtil.getCompany(companyId);
Group companyGroup = company.getGroup();
User userDefault = company.getDefaultUser();
Group companyGroup = company.getGroup();
User userDefault = company.getDefaultUser();
// Folders
// Folders
String[] groupActions = {ActionKeys.VIEW};
String[] guestActions = {ActionKeys.VIEW};
String[] groupActions = { ActionKeys.VIEW };
String[] guestActions = { ActionKeys.VIEW };
addDLFolderIfNotExists(userDefault.getUserId(), companyGroup.getGroupId(), companyGroup.getGroupId(),
DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, EmailConstants.DEFAULT_ATTACHMENTS_FOLDER_NAME, true,
groupActions, guestActions);
addDLFolderIfNotExists(userDefault.getUserId(), companyGroup.getGroupId(),
companyGroup.getGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
EmailConstants.DEFAULT_ATTACHMENTS_FOLDER_NAME, true, groupActions, guestActions);
} catch (Exception e) {
_log.error(e, e);
}
}
}
} catch (Exception e) {
_log.error(e, e);
}
}
}
private DLFolder addDLFolderIfNotExists(long userId, long groupId, long repositoryId, long parentFolderId,
String name, boolean hidden, String[] groupActions, String[] guestActions) throws PortalException,
SystemException {
private DLFolder addDLFolderIfNotExists(long userId, long groupId, long repositoryId,
long parentFolderId, String name, boolean hidden, String[] groupActions, String[] guestActions)
throws PortalException, SystemException {
DLFolder dlFolder = null;
DLFolder dlFolder = null;
try {
dlFolder = DLFolderLocalServiceUtil.getFolder(groupId, parentFolderId, name);
} catch (PortalException e) {
try {
dlFolder = DLFolderLocalServiceUtil.getFolder(groupId, parentFolderId, name);
} catch (PortalException e) {
ServiceContext serviceContext = new ServiceContext();
ServiceContext serviceContext = new ServiceContext();
if (groupActions != null) {
serviceContext.setGroupPermissions(groupActions);
}
if (groupActions != null) {
serviceContext.setGroupPermissions(groupActions);
}
if (guestActions != null) {
serviceContext.setGuestPermissions(guestActions);
}
if (guestActions != null) {
serviceContext.setGuestPermissions(guestActions);
}
dlFolder =
DLFolderLocalServiceUtil.addFolder(userId, groupId, repositoryId, false, parentFolderId, name,
StringPool.BLANK, hidden, serviceContext);
}
dlFolder = DLFolderLocalServiceUtil.addFolder(userId, groupId, repositoryId, false,
parentFolderId, name, StringPool.BLANK, hidden, serviceContext);
}
return dlFolder;
}
return dlFolder;
}
}

23
liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/hook/listener/DLFileEntryListener.java

@ -10,17 +10,18 @@ import com.liferay.portlet.documentlibrary.model.DLFileEntry;
public class DLFileEntryListener extends BaseModelListener<DLFileEntry> {
@Override
public void onBeforeRemove(DLFileEntry model) throws ModelListenerException {
@Override
public void onBeforeRemove(DLFileEntry model) throws ModelListenerException {
try {
EmailAttachment emailAttachment = EmailAttachmentLocalServiceUtil.fetchByFileEntryId(model.getFileEntryId());
if (emailAttachment != null) {
throw new ModelListenerException();
}
} catch (SystemException e) {
throw new ModelListenerException(e);
}
}
try {
EmailAttachment emailAttachment = EmailAttachmentLocalServiceUtil.fetchByFileEntryId(model
.getFileEntryId());
if (emailAttachment != null) {
throw new ModelListenerException();
}
} catch (SystemException e) {
throw new ModelListenerException(e);
}
}
}

124
liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/messaging/SendMailMessageListener.java

@ -25,93 +25,93 @@ import java.util.Date;
public class SendMailMessageListener implements MessageListener {
private static final String _LOCK_CLASS_NAME = SendMailMessageListener.class.getName();
private static final String _LOCK_CLASS_NAME = SendMailMessageListener.class.getName();
private static final Log _log = LogFactoryUtil.getLog(SendMailMessageListener.class);
private static final Log _log = LogFactoryUtil.getLog(SendMailMessageListener.class);
@Override
public void receive(Message message) throws MessageListenerException {
@Override
public void receive(Message message) throws MessageListenerException {
try {
try {
ActionableDynamicQuery actionableDynamicQuery = new EmailActionableDynamicQuery() {
ActionableDynamicQuery actionableDynamicQuery = new EmailActionableDynamicQuery() {
@Override
protected void addCriteria(DynamicQuery dynamicQuery) {
dynamicQuery.add(PropertyFactoryUtil.forName("sent").eq(false));
dynamicQuery.add(PropertyFactoryUtil.forName("cancel").eq(false));
}
@Override
protected void addCriteria(DynamicQuery dynamicQuery) {
dynamicQuery.add(PropertyFactoryUtil.forName("sent").eq(false));
dynamicQuery.add(PropertyFactoryUtil.forName("cancel").eq(false));
}
@Override
protected void performAction(Object obj) throws PortalException, SystemException {
@Override
protected void performAction(Object obj) throws PortalException, SystemException {
Email email = (Email) obj;
Email email = (Email) obj;
try {
try {
MailSenderUtil.sendMail(email);
MailSenderUtil.sendMail(email);
EmailLocalServiceUtil.markAsSent(email.getEmailId(), new Date(), StringPool.BLANK);
} catch (Exception e) {
EmailLocalServiceUtil.updateStatusMessage(email.getEmailId(), e.getMessage());
}
}
};
EmailLocalServiceUtil.markAsSent(email.getEmailId(), new Date(), StringPool.BLANK);
} catch (Exception e) {
EmailLocalServiceUtil.updateStatusMessage(email.getEmailId(), e.getMessage());
}
}
};
long count = actionableDynamicQuery.performCount();
long count = actionableDynamicQuery.performCount();
if (count > 0) {
if (count > 0) {
String owner = PortalUUIDUtil.generate();
String owner = PortalUUIDUtil.generate();
if (tryLock(owner)) {
if (tryLock(owner)) {
try {
actionableDynamicQuery.performActions();
} finally {
unlock(owner);
}
}
}
try {
actionableDynamicQuery.performActions();
} finally {
unlock(owner);
}
}
}
} catch (Exception e) {
_log.error(e, e);
}
}
} catch (Exception e) {
_log.error(e, e);
}
}
private boolean tryLock(String owner) {
private boolean tryLock(String owner) {
try {
try {
Lock lock = null;
Lock lock = null;
while (true) {
try {
lock = LockLocalServiceUtil.lock(_LOCK_CLASS_NAME, _LOCK_CLASS_NAME, owner);
while (true) {
try {
lock = LockLocalServiceUtil.lock(_LOCK_CLASS_NAME, _LOCK_CLASS_NAME, owner);
break;
} catch (SystemException se) {
break;
} catch (SystemException se) {
try {
Thread.sleep(50);
} catch (InterruptedException ie) {
}
}
}
try {
Thread.sleep(50);
} catch (InterruptedException ie) {
}
}
}
if (!lock.isNew()) {
throw new DuplicateLockException(lock);
}
if (!lock.isNew()) {
throw new DuplicateLockException(lock);
}
} catch (DuplicateLockException e) {
return false;
}
} catch (DuplicateLockException e) {
return false;
}
return true;
}
return true;
}
private void unlock(String owner) throws SystemException {
private void unlock(String owner) throws SystemException {
LockLocalServiceUtil.unlock(_LOCK_CLASS_NAME, _LOCK_CLASS_NAME, owner);
}
LockLocalServiceUtil.unlock(_LOCK_CLASS_NAME, _LOCK_CLASS_NAME, owner);
}
}

52
liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/portlet/EmailPortlet.java

@ -20,45 +20,45 @@ import javax.portlet.ActionResponse;
*/
public class EmailPortlet extends MVCPortlet {
private static Log _log = LogFactoryUtil.getLog(EmailPortlet.class);
private static Log _log = LogFactoryUtil.getLog(EmailPortlet.class);
public void editEmail(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {
public void editEmail(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {
_log.debug("editEmail - Inizio metodo");
_log.debug("editEmail - Inizio metodo");
ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
long emailId = ParamUtil.getLong(actionRequest, "emailId");
long emailId = ParamUtil.getLong(actionRequest, "emailId");
String from = ParamUtil.getString(actionRequest, "from");
String[] to = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "to"));
String[] cc = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "cc"));
String[] ccn = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "ccn"));
String from = ParamUtil.getString(actionRequest, "from");
String[] to = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "to"));
String[] cc = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "cc"));
String[] ccn = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "ccn"));
String subject = ParamUtil.getString(actionRequest, "subject");
String body = ParamUtil.getString(actionRequest, "body");
String subject = ParamUtil.getString(actionRequest, "subject");
String body = ParamUtil.getString(actionRequest, "body");
EmailServiceUtil.updateEmail(emailId, from, to, cc, ccn, subject, body, serviceContext);
EmailServiceUtil.updateEmail(emailId, from, to, cc, ccn, subject, body, serviceContext);
}
}
public void annullaEmail(ActionRequest actionRequest, ActionResponse actionResponse) throws PortalException,
SystemException {
public void annullaEmail(ActionRequest actionRequest, ActionResponse actionResponse)
throws PortalException, SystemException {
_log.debug("annullaEmail - inizio metodo");
_log.debug("annullaEmail - inizio metodo");
ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
long emailId = ParamUtil.getLong(actionRequest, "emailId");
EmailServiceUtil.cancelEmail(emailId, serviceContext);
}
ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
long emailId = ParamUtil.getLong(actionRequest, "emailId");
EmailServiceUtil.cancelEmail(emailId, serviceContext);
}
public void resendEmail(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {
public void resendEmail(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {
_log.debug("reinviaEmail - Inizio metodo");
_log.debug("reinviaEmail - Inizio metodo");
ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
long emailId = ParamUtil.getLong(actionRequest, "emailId");
EmailServiceUtil.resendEmail(emailId, serviceContext);
}
ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
long emailId = ParamUtil.getLong(actionRequest, "emailId");
EmailServiceUtil.resendEmail(emailId, serviceContext);
}
}

165
liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/portlet/EmailTemplatesPortlet.java

@ -36,117 +36,114 @@ import javax.portlet.ActionResponse;
*/
public class EmailTemplatesPortlet extends MVCPortlet {
private static Log _log = LogFactoryUtil.getLog(EmailTemplatesPortlet.class);
private static Log _log = LogFactoryUtil.getLog(EmailTemplatesPortlet.class);
public void editTemplateEmail(ActionRequest actionRequest, ActionResponse actionResponse) throws PortalException,
SystemException {
public void editTemplateEmail(ActionRequest actionRequest, ActionResponse actionResponse)
throws PortalException, SystemException {
String cmd = ParamUtil.getString(actionRequest, Constants.CMD);
String cmd = ParamUtil.getString(actionRequest, Constants.CMD);
ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
long emailTemplateId = ParamUtil.getLong(actionRequest, "emailTemplateId");
long emailTemplateId = ParamUtil.getLong(actionRequest, "emailTemplateId");
String templateName = ParamUtil.getString(actionRequest, "templateName");
String templateName = ParamUtil.getString(actionRequest, "templateName");
String from = ParamUtil.getString(actionRequest, "from");
String[] to = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "to"));
String[] cc = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "cc"));
String[] ccn = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "ccn"));
String from = ParamUtil.getString(actionRequest, "from");
String[] to = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "to"));
String[] cc = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "cc"));
String[] ccn = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "ccn"));
String subject = ParamUtil.getString(actionRequest, "subject");
String body = ParamUtil.getString(actionRequest, "body");
String subject = ParamUtil.getString(actionRequest, "subject");
String body = ParamUtil.getString(actionRequest, "body");
Boolean attachmentPermitted = ParamUtil.getBoolean(actionRequest, "attachmentPermitted");
Boolean attachmentPermitted = ParamUtil.getBoolean(actionRequest, "attachmentPermitted");
try {
EmailTemplate emailTemplate = null;
if (cmd.equals(Constants.ADD)) {
emailTemplate =
EmailTemplateServiceUtil.addEmailTemplate(templateName, from, to, cc, ccn, subject, body,
attachmentPermitted, serviceContext);
emailTemplateId = emailTemplate.getEmailTemplateId();
} else if (cmd.equals(Constants.UPDATE)) {
emailTemplate =
EmailTemplateServiceUtil.updateEmailTemplate(emailTemplateId, templateName, from, to, cc, ccn, subject,
body, attachmentPermitted, serviceContext);
}
emailTemplateId = emailTemplate.getEmailTemplateId();
try {
EmailTemplate emailTemplate = null;
if (cmd.equals(Constants.ADD)) {
emailTemplate = EmailTemplateServiceUtil.addEmailTemplate(templateName, from, to, cc, ccn,
subject, body, attachmentPermitted, serviceContext);
emailTemplateId = emailTemplate.getEmailTemplateId();
} else if (cmd.equals(Constants.UPDATE)) {
emailTemplate = EmailTemplateServiceUtil.updateEmailTemplate(emailTemplateId, templateName,
from, to, cc, ccn, subject, body, attachmentPermitted, serviceContext);
}
emailTemplateId = emailTemplate.getEmailTemplateId();
} catch (PortalException e) {
SessionErrors.add(actionRequest, e.getClass());
}
} catch (PortalException e) {
SessionErrors.add(actionRequest, e.getClass());
}
if (SessionErrors.isEmpty(actionRequest)) {
actionResponse.setRenderParameter("emailTemplateId", String.valueOf(emailTemplateId));
actionResponse.setRenderParameter("mvcPath", "/html/email_templates/edit.jsp");
} else {
actionResponse.setRenderParameter("mvcPath", "/html/email_templates/edit.jsp");
PortalUtil.copyRequestParameters(actionRequest, actionResponse);
}
if (SessionErrors.isEmpty(actionRequest)) {
actionResponse.setRenderParameter("emailTemplateId", String.valueOf(emailTemplateId));
actionResponse.setRenderParameter("mvcPath", "/html/email_templates/edit.jsp");
} else {
actionResponse.setRenderParameter("mvcPath", "/html/email_templates/edit.jsp");
PortalUtil.copyRequestParameters(actionRequest, actionResponse);
}
}
}
public void deleteEmailTemplate(ActionRequest actionRequest, ActionResponse actionResponse) throws PortalException,
SystemException {
public void deleteEmailTemplate(ActionRequest actionRequest, ActionResponse actionResponse)
throws PortalException, SystemException {
long emailTemplateId = ParamUtil.getLong(actionRequest, "emailTemplateId");
EmailTemplateServiceUtil.deleteEmailTemplate(emailTemplateId);
long emailTemplateId = ParamUtil.getLong(actionRequest, "emailTemplateId");
EmailTemplateServiceUtil.deleteEmailTemplate(emailTemplateId);
}
}
public void addEmailByTemplate(ActionRequest actionRequest, ActionResponse actionResponse) throws PortalException,
SystemException {
public void addEmailByTemplate(ActionRequest actionRequest, ActionResponse actionResponse)
throws PortalException, SystemException {
UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);
ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);
ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
long emailTemplateId = ParamUtil.getLong(actionRequest, "emailTemplateId");
EmailTemplate emailTemplate = EmailTemplateLocalServiceUtil.getEmailTemplate(emailTemplateId);
long emailTemplateId = ParamUtil.getLong(actionRequest, "emailTemplateId");
EmailTemplate emailTemplate = EmailTemplateLocalServiceUtil.getEmailTemplate(emailTemplateId);
String sendModeStr = ParamUtil.getString(actionRequest, "sendMode");
SendTemplateMode sendMode = SendTemplateMode.parse(sendModeStr);
String sendModeStr = ParamUtil.getString(actionRequest, "sendMode");
SendTemplateMode sendMode = SendTemplateMode.parse(sendModeStr);
String className = ParamUtil.getString(actionRequest, "className");
long classPK = ParamUtil.getLong(actionRequest, "classPK");
String className = ParamUtil.getString(actionRequest, "className");
long classPK = ParamUtil.getLong(actionRequest, "classPK");
try {
try {
// eventuali allegati email
List<com.liferay.mail.model.FileAttachment> fileAttachments = null;
if (emailTemplate.getAttachmentPermitted()) {
fileAttachments = MailUtil.getEmailFileAttachments(uploadPortletRequest);
}
// eventuali allegati email
List<com.liferay.mail.model.FileAttachment> fileAttachments = null;
if (emailTemplate.getAttachmentPermitted()) {
fileAttachments = MailUtil.getEmailFileAttachments(uploadPortletRequest);
}
if (sendMode == SendTemplateMode.REVIEW) {
if (sendMode == SendTemplateMode.REVIEW) {
String templateParamJSON = ParamUtil.getString(actionRequest, "templateParamJSON");
JSONObject templateParamJSONObj = JSONFactoryUtil.createJSONObject(templateParamJSON);
MailManagerUtil.addEmailByTemplate(className, classPK, emailTemplateId, templateParamJSONObj, fileAttachments,
serviceContext);
String templateParamJSON = ParamUtil.getString(actionRequest, "templateParamJSON");
JSONObject templateParamJSONObj = JSONFactoryUtil.createJSONObject(templateParamJSON);
MailManagerUtil.addEmailByTemplate(className, classPK, emailTemplateId, templateParamJSONObj,
fileAttachments, serviceContext);
} else if (sendMode == SendTemplateMode.EDIT) {
} else if (sendMode == SendTemplateMode.EDIT) {
String from = ParamUtil.getString(actionRequest, "from");
String to = ParamUtil.getString(actionRequest, "to");
String cc = ParamUtil.getString(actionRequest, "cc");
String ccn = ParamUtil.getString(actionRequest, "ccn");
String subject = ParamUtil.getString(actionRequest, "subject");
String body = ParamUtil.getString(actionRequest, "body");
String from = ParamUtil.getString(actionRequest, "from");
String to = ParamUtil.getString(actionRequest, "to");
String cc = ParamUtil.getString(actionRequest, "cc");
String ccn = ParamUtil.getString(actionRequest, "ccn");
String subject = ParamUtil.getString(actionRequest, "subject");
String body = ParamUtil.getString(actionRequest, "body");
EmailLocalServiceUtil.addEmail(className, classPK, from, StringUtil.split(to, StringPool.COMMA),
StringUtil.split(cc, StringPool.COMMA), StringUtil.split(ccn, StringPool.COMMA), subject, body, true,
fileAttachments, serviceContext);
}
UploadPortletRequestUtil.copyRequestParameters(uploadPortletRequest, actionResponse);
actionResponse.setRenderParameter("mvcPath", "/html/email_templates/send_popup/close_popup.jsp");
} catch (Exception ex) {
UploadPortletRequestUtil.copyRequestParameters(uploadPortletRequest, actionResponse);
throw new SystemException("Error add email by template.", ex);
}
EmailLocalServiceUtil.addEmail(className, classPK, from,
StringUtil.split(to, StringPool.COMMA), StringUtil.split(cc, StringPool.COMMA),
StringUtil.split(ccn, StringPool.COMMA), subject, body, true, fileAttachments,
serviceContext);
}
UploadPortletRequestUtil.copyRequestParameters(uploadPortletRequest, actionResponse);
actionResponse.setRenderParameter("mvcPath", "/html/email_templates/send_popup/close_popup.jsp");
} catch (Exception ex) {
UploadPortletRequestUtil.copyRequestParameters(uploadPortletRequest, actionResponse);
throw new SystemException("Error add email by template.", ex);
}
}
}
}

149
liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/service/impl/EmailAttachmentLocalServiceImpl.java

@ -13,7 +13,6 @@
package it.tref.liferay.portos.mailmanager.service.impl;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.repository.model.FileEntry;
@ -41,13 +40,15 @@ import java.util.List;
* The implementation of the email attachment local service.
*
* <p>
* All custom service methods should be put in this class. Whenever methods are added, rerun
* ServiceBuilder to copy their definitions into the
* {@link it.noovle.azimut.icf.mailmanager.service.EmailAttachmentLocalService} interface.
* All custom service methods should be put in this class. Whenever methods are
* added, rerun ServiceBuilder to copy their definitions into the
* {@link it.noovle.azimut.icf.mailmanager.service.EmailAttachmentLocalService}
* interface.
*
* <p>
* This is a local service. Methods of this service will not have security checks based on the
* propagated JAAS credentials because this service can only be accessed from within the same VM.
* This is a local service. Methods of this service will not have security
* checks based on the propagated JAAS credentials because this service can only
* be accessed from within the same VM.
* </p>
*
* @author
@ -55,96 +56,96 @@ import java.util.List;
* @see it.noovle.azimut.icf.mailmanager.service.EmailAttachmentLocalServiceUtil
*/
public class EmailAttachmentLocalServiceImpl extends EmailAttachmentLocalServiceBaseImpl {
/*
* NOTE FOR DEVELOPERS:
*
* Never reference this interface directly. Always use {@link
* it.noovle.azimut.icf.mailmanager.service.EmailAttachmentLocalServiceUtil} to access the
* email attachment local service.
*/
public EmailAttachment addEmailAttachment(long companyId, long emailId, long folderId, String fileName, File file)
throws PortalException, SystemException {
/*
* NOTE FOR DEVELOPERS:
*
* Never reference this interface directly. Always use {@link
* it.noovle.azimut.icf.mailmanager.service.EmailAttachmentLocalServiceUtil}
* to access the email attachment local service.
*/
public EmailAttachment addEmailAttachment(long companyId, long emailId, long folderId, String fileName,
File file) throws PortalException, SystemException {
Company company = companyLocalService.getCompany(companyId);
Company company = companyLocalService.getCompany(companyId);
User defaultUser = company.getDefaultUser();
User defaultUser = company.getDefaultUser();
validate(emailId, fileName, file);
validate(emailId, fileName, file);
Folder folder = dlAppLocalService.getFolder(folderId);
Folder folder = dlAppLocalService.getFolder(folderId);
String sourceFileName = file.getName();
String mimeType = MimeTypesUtil.getContentType(sourceFileName);
String sourceFileName = file.getName();
String mimeType = MimeTypesUtil.getContentType(sourceFileName);
String title = fileName;
if (Validator.isNull(title)) {
title = file.getName();
}
String title = fileName;
if (Validator.isNull(title)) {
title = file.getName();
}
ServiceContext serviceContext = new ServiceContext();
serviceContext.setGroupPermissions(new String[] {ActionKeys.VIEW});
serviceContext.setGuestPermissions(new String[] {ActionKeys.VIEW});
ServiceContext serviceContext = new ServiceContext();
serviceContext.setGroupPermissions(new String[] { ActionKeys.VIEW });
serviceContext.setGuestPermissions(new String[] { ActionKeys.VIEW });
FileEntry fileEntry =
dlAppLocalService.addFileEntry(defaultUser.getUserId(), folder.getRepositoryId(), folder.getFolderId(),
sourceFileName, mimeType, title, StringPool.BLANK, StringPool.BLANK, file, serviceContext);
FileEntry fileEntry = dlAppLocalService.addFileEntry(defaultUser.getUserId(),
folder.getRepositoryId(), folder.getFolderId(), sourceFileName, mimeType, title,
StringPool.BLANK, StringPool.BLANK, file, serviceContext);
EmailAttachment emailAttachment =
emailAttachmentLocalService.createEmailAttachment(new EmailAttachmentPK(emailId, fileEntry.getFileEntryId()));
EmailAttachment emailAttachment = emailAttachmentLocalService
.createEmailAttachment(new EmailAttachmentPK(emailId, fileEntry.getFileEntryId()));
return emailAttachmentLocalService.addEmailAttachment(emailAttachment);
}
return emailAttachmentLocalService.addEmailAttachment(emailAttachment);
}
@Override
public EmailAttachment deleteEmailAttachment(EmailAttachmentPK emailAttachmentPK) throws PortalException,
SystemException {
EmailAttachment emailAttachment = emailAttachmentLocalService.getEmailAttachment(emailAttachmentPK);
return deleteEmailAttachment(emailAttachment);
}
@Override
public EmailAttachment deleteEmailAttachment(EmailAttachmentPK emailAttachmentPK) throws PortalException,
SystemException {
EmailAttachment emailAttachment = emailAttachmentLocalService.getEmailAttachment(emailAttachmentPK);
return deleteEmailAttachment(emailAttachment);
}
@Override
public EmailAttachment deleteEmailAttachment(EmailAttachment emailAttachment) throws SystemException {
@Override
public EmailAttachment deleteEmailAttachment(EmailAttachment emailAttachment) throws SystemException {
super.deleteEmailAttachment(emailAttachment);
super.deleteEmailAttachment(emailAttachment);
// File Entry
// File Entry
try {
dlAppLocalService.deleteFileEntry(emailAttachment.getFileEntryId());
} catch (PortalException e) {
}
try {
dlAppLocalService.deleteFileEntry(emailAttachment.getFileEntryId());
} catch (PortalException e) {
}
return emailAttachment;
}
return emailAttachment;
}
public List<EmailAttachment> findByEmailId(long emailId) throws SystemException {
return emailAttachmentPersistence.findByEmailId(emailId);
}
public List<EmailAttachment> findByEmailId(long emailId) throws SystemException {
return emailAttachmentPersistence.findByEmailId(emailId);
}
public List<EmailAttachment> findByEmailId(long emailId, int start, int end) throws SystemException {
return emailAttachmentPersistence.findByEmailId(emailId);
}
public List<EmailAttachment> findByEmailId(long emailId, int start, int end) throws SystemException {
return emailAttachmentPersistence.findByEmailId(emailId);
}
public int countByEmailId(long emailId) throws SystemException {
return emailAttachmentPersistence.countByEmailId(emailId);
}
public int countByEmailId(long emailId) throws SystemException {
return emailAttachmentPersistence.countByEmailId(emailId);
}
public EmailAttachment fetchByFileEntryId(long fileEntryId) throws SystemException {
return emailAttachmentPersistence.fetchByFileEntryId(fileEntryId);
}
public EmailAttachment fetchByFileEntryId(long fileEntryId) throws SystemException {
return emailAttachmentPersistence.fetchByFileEntryId(fileEntryId);
}
private void validate(long emailId, String fileName, File file) throws PortalException, SystemException {
private void validate(long emailId, String fileName, File file) throws PortalException, SystemException {
if (Validator.isNull(emailId)) {
throw new NoSuchEmailException();
}
if (Validator.isNull(emailId)) {
throw new NoSuchEmailException();
}
if (Validator.isNull(fileName) && Validator.isNull(file)) {
throw new EmailAttachmentTitleException();
}
if (Validator.isNull(fileName) && Validator.isNull(file)) {
throw new EmailAttachmentTitleException();
}
if (Validator.isNull(file) || (Validator.isNotNull(file) && !FileUtil.exists(file))) {
throw new EmailAttachmentFileException();
}
}
if (Validator.isNull(file) || (Validator.isNotNull(file) && !FileUtil.exists(file))) {
throw new EmailAttachmentFileException();
}
}
}

4
liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/service/impl/EmailServiceImpl.java

@ -61,6 +61,6 @@ public class EmailServiceImpl extends EmailServiceBaseImpl {
public Email cancelEmail(long emailId, ServiceContext serviceContext) throws PortalException, SystemException {
EmailPermission.check(getPermissionChecker(), serviceContext.getScopeGroupId(), ActionKeys.ADMIN_EMAIL);
return emailLocalService.cancelEmail(emailId);
}
return emailLocalService.cancelEmail(emailId);
}
}

63
liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/service/impl/EmailTemplateServiceImpl.java

@ -26,13 +26,15 @@ import it.tref.liferay.portos.mailmanager.service.base.EmailTemplateServiceBaseI
* The implementation of the email template remote service.
*
* <p>
* All custom service methods should be put in this class. Whenever methods are added, rerun
* ServiceBuilder to copy their definitions into the
* {@link it.noovle.azimut.icf.mailmanager.service.EmailTemplateService} interface.
* All custom service methods should be put in this class. Whenever methods are
* added, rerun ServiceBuilder to copy their definitions into the
* {@link it.noovle.azimut.icf.mailmanager.service.EmailTemplateService}
* interface.
*
* <p>
* This is a remote service. Methods of this service are expected to have security checks based on
* the propagated JAAS credentials because this service can be accessed remotely.
* This is a remote service. Methods of this service are expected to have
* security checks based on the propagated JAAS credentials because this service
* can be accessed remotely.
* </p>
*
* @author
@ -40,39 +42,40 @@ import it.tref.liferay.portos.mailmanager.service.base.EmailTemplateServiceBaseI
* @see it.noovle.azimut.icf.mailmanager.service.EmailTemplateServiceUtil
*/
public class EmailTemplateServiceImpl extends EmailTemplateServiceBaseImpl {
/*
* NOTE FOR DEVELOPERS:
*
* Never reference this interface directly. Always use {@link
* it.noovle.azimut.icf.mailmanager.service.EmailTemplateServiceUtil} to access the email
* template remote service.
*/
/*
* NOTE FOR DEVELOPERS:
*
* Never reference this interface directly. Always use {@link
* it.noovle.azimut.icf.mailmanager.service.EmailTemplateServiceUtil} to
* access the email template remote service.
*/
public EmailTemplate addEmailTemplate(String templateName, String from, String[] to, String[] cc, String[] ccn,
String subject, String body, boolean attachmentPermitted, ServiceContext serviceContext) throws SystemException,
PortalException {
public EmailTemplate addEmailTemplate(String templateName, String from, String[] to, String[] cc,
String[] ccn, String subject, String body, boolean attachmentPermitted,
ServiceContext serviceContext) throws SystemException, PortalException {
EmailTemplatePermission.check(getPermissionChecker(), serviceContext.getScopeGroupId(), ActionKeys.ADD_ENTRY);
EmailTemplatePermission.check(getPermissionChecker(), serviceContext.getScopeGroupId(),
ActionKeys.ADD_ENTRY);
return emailTemplateLocalService.addEmailTemplate(templateName, from, to, cc, ccn, subject, body,
attachmentPermitted, serviceContext);
}
return emailTemplateLocalService.addEmailTemplate(templateName, from, to, cc, ccn, subject, body,
attachmentPermitted, serviceContext);
}
public EmailTemplate updateEmailTemplate(long emailTemplateId, String templateName, String from, String[] to,
String[] cc, String[] ccn, String subject, String body, boolean attachmentPermitted, ServiceContext serviceContext)
throws SystemException, PortalException {
public EmailTemplate updateEmailTemplate(long emailTemplateId, String templateName, String from,
String[] to, String[] cc, String[] ccn, String subject, String body, boolean attachmentPermitted,
ServiceContext serviceContext) throws SystemException, PortalException {
EmailTemplateEntryPermission.check(getPermissionChecker(), emailTemplateId, ActionKeys.UPDATE);
EmailTemplateEntryPermission.check(getPermissionChecker(), emailTemplateId, ActionKeys.UPDATE);
return emailTemplateLocalService.updateEmailTemplate(emailTemplateId, templateName, from, to, cc, ccn, subject,
body, attachmentPermitted, serviceContext);
}
return emailTemplateLocalService.updateEmailTemplate(emailTemplateId, templateName, from, to, cc,
ccn, subject, body, attachmentPermitted, serviceContext);
}
public EmailTemplate deleteEmailTemplate(long emailTemplateId) throws PortalException, SystemException {
public EmailTemplate deleteEmailTemplate(long emailTemplateId) throws PortalException, SystemException {
EmailTemplateEntryPermission.check(getPermissionChecker(), emailTemplateId, ActionKeys.DELETE);
EmailTemplateEntryPermission.check(getPermissionChecker(), emailTemplateId, ActionKeys.DELETE);
return emailTemplateLocalService.deleteEmailTemplate(emailTemplateId);
}
return emailTemplateLocalService.deleteEmailTemplate(emailTemplateId);
}
}

678
liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/util/MailEngine.java

@ -65,470 +65,476 @@ import javax.mail.internet.MimeMultipart;
*/
public class MailEngine {
public static Session getSession() {
return getSession(false);
}
public static Session getSession() {
return getSession(false);
}
public static Session getSession(Account account) {
Properties properties = _getProperties(account);
public static Session getSession(Account account) {
Properties properties = _getProperties(account);
Session session = Session.getInstance(properties);
Session session = Session.getInstance(properties);
if (_log.isDebugEnabled()) {
session.setDebug(true);
if (_log.isDebugEnabled()) {
session.setDebug(true);
session.getProperties().list(System.out);
}
session.getProperties().list(System.out);
}
return session;
}
return session;
}
public static Session getSession(boolean cache) {
Session session = null;
public static Session getSession(boolean cache) {
Session session = null;
try {
session = MailServiceUtil.getSession();
} catch (SystemException se) {
if (_log.isWarnEnabled()) {
_log.warn(se, se);
}
try {
session = MailServiceUtil.getSession();
} catch (SystemException se) {
if (_log.isWarnEnabled()) {
_log.warn(se, se);
}
session = InfrastructureUtil.getMailSession();
}
session = InfrastructureUtil.getMailSession();
}
if (_log.isDebugEnabled()) {
session.setDebug(true);
if (_log.isDebugEnabled()) {
session.setDebug(true);
session.getProperties().list(System.out);
}
session.getProperties().list(System.out);
}
return session;
}
return session;
}
public static void send(byte[] bytes) throws MailEngineException {
try {
Session session = getSession();
public static void send(byte[] bytes) throws MailEngineException {
try {
Session session = getSession();
Message message = new MimeMessage(session, new UnsyncByteArrayInputStream(bytes));
Message message = new MimeMessage(session, new UnsyncByteArrayInputStream(bytes));
_send(session, message, null, _BATCH_SIZE);
} catch (Exception e) {
throw new MailEngineException(e);
}
}
_send(session, message, null, _BATCH_SIZE);
} catch (Exception e) {
throw new MailEngineException(e);
}
}
public static void send(InternetAddress from, InternetAddress to, String subject, String body)
throws MailEngineException {
public static void send(InternetAddress from, InternetAddress to, String subject, String body)
throws MailEngineException {
send(from, new InternetAddress[] {to}, null, null, subject, body, false, null, null, null);
}
send(from, new InternetAddress[] { to }, null, null, subject, body, false, null, null, null);
}
public static void send(InternetAddress from, InternetAddress to, String subject, String body, boolean htmlFormat)
throws MailEngineException {
public static void send(InternetAddress from, InternetAddress to, String subject, String body,
boolean htmlFormat) throws MailEngineException {
send(from, new InternetAddress[] {to}, null, null, subject, body, htmlFormat, null, null, null);
}
send(from, new InternetAddress[] { to }, null, null, subject, body, htmlFormat, null, null, null);
}
public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc, InternetAddress[] bcc,
InternetAddress[] bulkAddresses, String subject, String body, boolean htmlFormat, InternetAddress[] replyTo,
String messageId, String inReplyTo) throws MailEngineException {
public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc,
InternetAddress[] bcc, InternetAddress[] bulkAddresses, String subject, String body,
boolean htmlFormat, InternetAddress[] replyTo, String messageId, String inReplyTo)
throws MailEngineException {
send(from, to, cc, bcc, bulkAddresses, subject, body, htmlFormat, replyTo, messageId, inReplyTo, null);
}
send(from, to, cc, bcc, bulkAddresses, subject, body, htmlFormat, replyTo, messageId, inReplyTo, null);
}
public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc, InternetAddress[] bcc,
InternetAddress[] bulkAddresses, String subject, String body, boolean htmlFormat, InternetAddress[] replyTo,
String messageId, String inReplyTo, List<FileAttachment> fileAttachments) throws MailEngineException {
public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc,
InternetAddress[] bcc, InternetAddress[] bulkAddresses, String subject, String body,
boolean htmlFormat, InternetAddress[] replyTo, String messageId, String inReplyTo,
List<FileAttachment> fileAttachments) throws MailEngineException {
send(from, to, cc, bcc, bulkAddresses, subject, body, htmlFormat, replyTo, messageId, inReplyTo, fileAttachments,
null);
}
send(from, to, cc, bcc, bulkAddresses, subject, body, htmlFormat, replyTo, messageId, inReplyTo,
fileAttachments, null);
}
public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc, InternetAddress[] bcc,
InternetAddress[] bulkAddresses, String subject, String body, boolean htmlFormat, InternetAddress[] replyTo,
String messageId, String inReplyTo, List<FileAttachment> fileAttachments, SMTPAccount smtpAccount)
throws MailEngineException {
public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc,
InternetAddress[] bcc, InternetAddress[] bulkAddresses, String subject, String body,
boolean htmlFormat, InternetAddress[] replyTo, String messageId, String inReplyTo,
List<FileAttachment> fileAttachments, SMTPAccount smtpAccount) throws MailEngineException {
long startTime = System.currentTimeMillis();
long startTime = System.currentTimeMillis();
if (_log.isDebugEnabled()) {
_log.debug("From: " + from);
_log.debug("To: " + Arrays.toString(to));
_log.debug("CC: " + Arrays.toString(cc));
_log.debug("BCC: " + Arrays.toString(bcc));
_log.debug("List Addresses: " + Arrays.toString(bulkAddresses));
_log.debug("Subject: " + subject);
_log.debug("Body: " + body);
_log.debug("HTML Format: " + htmlFormat);
_log.debug("Reply to: " + Arrays.toString(replyTo));
_log.debug("Message ID: " + messageId);
_log.debug("In Reply To: " + inReplyTo);
if (_log.isDebugEnabled()) {
_log.debug("From: " + from);
_log.debug("To: " + Arrays.toString(to));
_log.debug("CC: " + Arrays.toString(cc));
_log.debug("BCC: " + Arrays.toString(bcc));
_log.debug("List Addresses: " + Arrays.toString(bulkAddresses));
_log.debug("Subject: " + subject);
_log.debug("Body: " + body);
_log.debug("HTML Format: " + htmlFormat);
_log.debug("Reply to: " + Arrays.toString(replyTo));
_log.debug("Message ID: " + messageId);
_log.debug("In Reply To: " + inReplyTo);
if ((fileAttachments != null) && _log.isDebugEnabled()) {
for (int i = 0; i < fileAttachments.size(); i++) {
if ((fileAttachments != null) && _log.isDebugEnabled()) {
for (int i = 0; i < fileAttachments.size(); i++) {
FileAttachment fileAttachment = fileAttachments.get(i);
if (fileAttachment instanceof it.tref.liferay.portos.mailmanager.shared.model.FileAttachment) {
((it.tref.liferay.portos.mailmanager.shared.model.FileAttachment) fileAttachment).generateFile();
}
File file = fileAttachment.getFile();
FileAttachment fileAttachment = fileAttachments.get(i);
if (fileAttachment instanceof it.tref.liferay.portos.mailmanager.shared.model.FileAttachment) {
((it.tref.liferay.portos.mailmanager.shared.model.FileAttachment) fileAttachment)
.generateFile();
}
File file = fileAttachment.getFile();
if (file == null) {
continue;
}
if (file == null) {
continue;
}
_log.debug("Attachment " + i + " file " + file.getAbsolutePath() + " and file name "
+ fileAttachment.getFileName());
}
}
}
_log.debug("Attachment " + i + " file " + file.getAbsolutePath() + " and file name "
+ fileAttachment.getFileName());
}
}
}
try {
InternetAddressUtil.validateAddress(from);
try {
InternetAddressUtil.validateAddress(from);
if (ArrayUtil.isNotEmpty(to)) {
InternetAddressUtil.validateAddresses(to);
}
if (ArrayUtil.isNotEmpty(to)) {
InternetAddressUtil.validateAddresses(to);
}
if (ArrayUtil.isNotEmpty(cc)) {
InternetAddressUtil.validateAddresses(cc);
}
if (ArrayUtil.isNotEmpty(cc)) {
InternetAddressUtil.validateAddresses(cc);
}
if (ArrayUtil.isNotEmpty(bcc)) {
InternetAddressUtil.validateAddresses(bcc);
}
if (ArrayUtil.isNotEmpty(bcc)) {
InternetAddressUtil.validateAddresses(bcc);
}
if (ArrayUtil.isNotEmpty(replyTo)) {
InternetAddressUtil.validateAddresses(replyTo);
}
if (ArrayUtil.isNotEmpty(replyTo)) {
InternetAddressUtil.validateAddresses(replyTo);
}
if (ArrayUtil.isNotEmpty(bulkAddresses)) {
InternetAddressUtil.validateAddresses(bulkAddresses);
}
if (ArrayUtil.isNotEmpty(bulkAddresses)) {
InternetAddressUtil.validateAddresses(bulkAddresses);
}
Session session = null;
Session session = null;
if (smtpAccount == null) {
session = getSession();
} else {
session = getSession(smtpAccount);
}
if (smtpAccount == null) {
session = getSession();
} else {
session = getSession(smtpAccount);
}
Message message = new LiferayMimeMessage(session);
Message message = new LiferayMimeMessage(session);
message.addHeader("X-Auto-Response-Suppress", "AutoReply, DR, NDR, NRN, OOF, RN");
message.addHeader("X-Auto-Response-Suppress", "AutoReply, DR, NDR, NRN, OOF, RN");
message.setFrom(from);
message.setFrom(from);
if (ArrayUtil.isNotEmpty(to)) {
message.setRecipients(Message.RecipientType.TO, to);
}
if (ArrayUtil.isNotEmpty(to)) {
message.setRecipients(Message.RecipientType.TO, to);
}
if (ArrayUtil.isNotEmpty(cc)) {
message.setRecipients(Message.RecipientType.CC, cc);
}
if (ArrayUtil.isNotEmpty(cc)) {
message.setRecipients(Message.RecipientType.CC, cc);
}
if (ArrayUtil.isNotEmpty(bcc)) {
message.setRecipients(Message.RecipientType.BCC, bcc);
}
if (ArrayUtil.isNotEmpty(bcc)) {
message.setRecipients(Message.RecipientType.BCC, bcc);
}
subject = GetterUtil.getString(subject);
subject = GetterUtil.getString(subject);
message.setSubject(subject);
message.setSubject(subject);
if ((fileAttachments != null) && (fileAttachments.size() > 0)) {
MimeMultipart rootMultipart = new MimeMultipart(_MULTIPART_TYPE_MIXED);
if ((fileAttachments != null) && (fileAttachments.size() > 0)) {
MimeMultipart rootMultipart = new MimeMultipart(_MULTIPART_TYPE_MIXED);
MimeMultipart messageMultipart = new MimeMultipart(_MULTIPART_TYPE_ALTERNATIVE);
MimeMultipart messageMultipart = new MimeMultipart(_MULTIPART_TYPE_ALTERNATIVE);
MimeBodyPart messageBodyPart = new MimeBodyPart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(messageMultipart);
messageBodyPart.setContent(messageMultipart);
rootMultipart.addBodyPart(messageBodyPart);
rootMultipart.addBodyPart(messageBodyPart);
if (htmlFormat) {
MimeBodyPart bodyPart = new MimeBodyPart();
if (htmlFormat) {
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(body, _TEXT_HTML);
bodyPart.setContent(body, _TEXT_HTML);
messageMultipart.addBodyPart(bodyPart);
} else {
MimeBodyPart bodyPart = new MimeBodyPart();
messageMultipart.addBodyPart(bodyPart);
} else {
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setText(body);
bodyPart.setText(body);
messageMultipart.addBodyPart(bodyPart);
}
messageMultipart.addBodyPart(bodyPart);
}
for (int i = 0; i < fileAttachments.size(); i++) {
FileAttachment fileAttachment = fileAttachments.get(i);
for (int i = 0; i < fileAttachments.size(); i++) {
FileAttachment fileAttachment = fileAttachments.get(i);
File file = fileAttachment.getFile();
File file = fileAttachment.getFile();
if (file == null) {
continue;
}
if (file == null) {
continue;
}
MimeBodyPart mimeBodyPart = new MimeBodyPart();
MimeBodyPart mimeBodyPart = new MimeBodyPart();
DataSource dataSource = new FileDataSource(file);
DataSource dataSource = new FileDataSource(file);
mimeBodyPart.setDataHandler(new DataHandler(dataSource));
mimeBodyPart.setDisposition(Part.ATTACHMENT);
mimeBodyPart.setDataHandler(new DataHandler(dataSource));
mimeBodyPart.setDisposition(Part.ATTACHMENT);
if (fileAttachment.getFileName() != null) {
mimeBodyPart.setFileName(fileAttachment.getFileName());
} else {
mimeBodyPart.setFileName(file.getName());
}
if (fileAttachment.getFileName() != null) {
mimeBodyPart.setFileName(fileAttachment.getFileName());
} else {
mimeBodyPart.setFileName(file.getName());
}
rootMultipart.addBodyPart(mimeBodyPart);
}
rootMultipart.addBodyPart(mimeBodyPart);
}
message.setContent(rootMultipart);
message.setContent(rootMultipart);
message.saveChanges();
} else {
if (htmlFormat) {
message.setContent(body, _TEXT_HTML);
} else {
message.setContent(body, _TEXT_PLAIN);
}
}
message.saveChanges();
} else {
if (htmlFormat) {
message.setContent(body, _TEXT_HTML);
} else {
message.setContent(body, _TEXT_PLAIN);
}
}
message.setSentDate(new Date());
message.setSentDate(new Date());
if (ArrayUtil.isNotEmpty(replyTo)) {
message.setReplyTo(replyTo);
}
if (ArrayUtil.isNotEmpty(replyTo)) {
message.setReplyTo(replyTo);
}
if (messageId != null) {
message.setHeader("Message-ID", messageId);
}
if (messageId != null) {
message.setHeader("Message-ID", messageId);
}
if (inReplyTo != null) {
message.setHeader("In-Reply-To", inReplyTo);
message.setHeader("References", inReplyTo);
}
if (inReplyTo != null) {
message.setHeader("In-Reply-To", inReplyTo);
message.setHeader("References", inReplyTo);
}
int batchSize = GetterUtil.getInteger(PropsUtil.get(PropsKeys.MAIL_BATCH_SIZE), _BATCH_SIZE);
int batchSize = GetterUtil.getInteger(PropsUtil.get(PropsKeys.MAIL_BATCH_SIZE), _BATCH_SIZE);
_send(session, message, bulkAddresses, batchSize);
} catch (SendFailedException sfe) {
_log.error(sfe);
_send(session, message, bulkAddresses, batchSize);
} catch (SendFailedException sfe) {
_log.error(sfe);
// if (_isThrowsExceptionOnFailure()) {
// throw new MailEngineException(sfe);
// }
throw new MailEngineException(sfe);
} catch (Exception e) {
throw new MailEngineException(e);
}
// if (_isThrowsExceptionOnFailure()) {
// throw new MailEngineException(sfe);
// }
throw new MailEngineException(sfe);
} catch (Exception e) {
throw new MailEngineException(e);
}
if (_log.isDebugEnabled()) {
_log.debug("Sending mail takes " + (System.currentTimeMillis() - startTime) + " ms");
}
}
if (_log.isDebugEnabled()) {
_log.debug("Sending mail takes " + (System.currentTimeMillis() - startTime) + " ms");
}
}
public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc, InternetAddress[] bcc,
String subject, String body) throws MailEngineException {
public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc,
InternetAddress[] bcc, String subject, String body) throws MailEngineException {
send(from, to, cc, bcc, subject, body, false, null, null, null);
}
send(from, to, cc, bcc, subject, body, false, null, null, null);
}
public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc, InternetAddress[] bcc,
String subject, String body, boolean htmlFormat, InternetAddress[] replyTo, String messageId, String inReplyTo)
throws MailEngineException {
public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc,
InternetAddress[] bcc, String subject, String body, boolean htmlFormat,
InternetAddress[] replyTo, String messageId, String inReplyTo) throws MailEngineException {
send(from, to, cc, bcc, null, subject, body, htmlFormat, replyTo, messageId, inReplyTo, null);
}
send(from, to, cc, bcc, null, subject, body, htmlFormat, replyTo, messageId, inReplyTo, null);
}
public static void
send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc, String subject, String body)
throws MailEngineException {
public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc, String subject,
String body) throws MailEngineException {
send(from, to, cc, null, subject, body, false, null, null, null);
}
send(from, to, cc, null, subject, body, false, null, null, null);
}
public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc, String subject,
String body, boolean htmlFormat) throws MailEngineException {
public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc, String subject,
String body, boolean htmlFormat) throws MailEngineException {
send(from, to, cc, null, subject, body, htmlFormat, null, null, null);
}
send(from, to, cc, null, subject, body, htmlFormat, null, null, null);
}
public static void send(InternetAddress from, InternetAddress[] to, String subject, String body)
throws MailEngineException {
public static void send(InternetAddress from, InternetAddress[] to, String subject, String body)
throws MailEngineException {
send(from, to, null, null, subject, body, false, null, null, null);
}
send(from, to, null, null, subject, body, false, null, null, null);
}
public static void send(InternetAddress from, InternetAddress[] to, String subject, String body, boolean htmlFormat)
throws MailEngineException {
public static void send(InternetAddress from, InternetAddress[] to, String subject, String body,
boolean htmlFormat) throws MailEngineException {
send(from, to, null, null, subject, body, htmlFormat, null, null, null);
}
send(from, to, null, null, subject, body, htmlFormat, null, null, null);
}
public static void send(MailMessage mailMessage) throws MailEngineException {
public static void send(MailMessage mailMessage) throws MailEngineException {
send(mailMessage.getFrom(), mailMessage.getTo(), mailMessage.getCC(), mailMessage.getBCC(), mailMessage
.getBulkAddresses(), mailMessage.getSubject(), mailMessage.getBody(), mailMessage.isHTMLFormat(), mailMessage
.getReplyTo(), mailMessage.getMessageId(), mailMessage.getInReplyTo(), mailMessage.getFileAttachments(),
mailMessage.getSMTPAccount());
}
send(mailMessage.getFrom(), mailMessage.getTo(), mailMessage.getCC(), mailMessage.getBCC(),
mailMessage.getBulkAddresses(), mailMessage.getSubject(), mailMessage.getBody(),
mailMessage.isHTMLFormat(), mailMessage.getReplyTo(), mailMessage.getMessageId(),
mailMessage.getInReplyTo(), mailMessage.getFileAttachments(), mailMessage.getSMTPAccount());
}
public static void send(String from, String to, String subject, String body) throws MailEngineException {
public static void send(String from, String to, String subject, String body) throws MailEngineException {
try {
send(new InternetAddress(from), new InternetAddress(to), subject, body);
} catch (AddressException ae) {
throw new MailEngineException(ae);
}
}
try {
send(new InternetAddress(from), new InternetAddress(to), subject, body);
} catch (AddressException ae) {
throw new MailEngineException(ae);
}
}
private static Address[] _getBatchAddresses(Address[] addresses, int index, int batchSize) {
private static Address[] _getBatchAddresses(Address[] addresses, int index, int batchSize) {
if ((batchSize == _BATCH_SIZE) && (index == 0)) {
return addresses;
} else if (batchSize == _BATCH_SIZE) {
return null;
}
if ((batchSize == _BATCH_SIZE) && (index == 0)) {
return addresses;
} else if (batchSize == _BATCH_SIZE) {
return null;
}
int start = index * batchSize;
int start = index * batchSize;
if (start > addresses.length) {
return null;
}
if (start > addresses.length) {
return null;
}
int end = ((index + 1) * batchSize);
int end = ((index + 1) * batchSize);
if (end > addresses.length) {
end = addresses.length;
}
if (end > addresses.length) {
end = addresses.length;
}
return ArrayUtil.subset(addresses, start, end);
}
return ArrayUtil.subset(addresses, start, end);
}
private static Properties _getProperties(Account account) {
Properties properties = new Properties();
private static Properties _getProperties(Account account) {
Properties properties = new Properties();
String protocol = account.getProtocol();
String protocol = account.getProtocol();
properties.setProperty("mail.transport.protocol", protocol);
properties.setProperty("mail." + protocol + ".host", account.getHost());
properties.setProperty("mail." + protocol + ".port", String.valueOf(account.getPort()));
properties.setProperty("mail.transport.protocol", protocol);
properties.setProperty("mail." + protocol + ".host", account.getHost());
properties.setProperty("mail." + protocol + ".port", String.valueOf(account.getPort()));
if (account.isRequiresAuthentication()) {
properties.setProperty("mail." + protocol + ".auth", "true");
properties.setProperty("mail." + protocol + ".user", account.getUser());
properties.setProperty("mail." + protocol + ".password", account.getPassword());
}
if (account.isRequiresAuthentication()) {
properties.setProperty("mail." + protocol + ".auth", "true");
properties.setProperty("mail." + protocol + ".user", account.getUser());
properties.setProperty("mail." + protocol + ".password", account.getPassword());
}
if (account.isSecure()) {
properties.setProperty("mail." + protocol + ".socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail." + protocol + ".socketFactory.fallback", "false");
properties.setProperty("mail." + protocol + ".socketFactory.port", String.valueOf(account.getPort()));
}
if (account.isSecure()) {
properties.setProperty("mail." + protocol + ".socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail." + protocol + ".socketFactory.fallback", "false");
properties.setProperty("mail." + protocol + ".socketFactory.port",
String.valueOf(account.getPort()));
}
return properties;
}
return properties;
}
private static String _getSMTPProperty(Session session, String suffix) {
String protocol = GetterUtil.getString(session.getProperty("mail.transport.protocol"));
private static String _getSMTPProperty(Session session, String suffix) {
String protocol = GetterUtil.getString(session.getProperty("mail.transport.protocol"));
if (protocol.equals(Account.PROTOCOL_SMTPS)) {
return session.getProperty("mail.smtps." + suffix);
} else {
return session.getProperty("mail.smtp." + suffix);
}
}
if (protocol.equals(Account.PROTOCOL_SMTPS)) {
return session.getProperty("mail.smtps." + suffix);
} else {
return session.getProperty("mail.smtp." + suffix);
}
}
// private static boolean _isThrowsExceptionOnFailure() {
// return GetterUtil.getBoolean(PropsUtil.get(PropsKeys.MAIL_THROWS_EXCEPTION_ON_FAILURE));
// }
// private static boolean _isThrowsExceptionOnFailure() {
// return
// GetterUtil.getBoolean(PropsUtil.get(PropsKeys.MAIL_THROWS_EXCEPTION_ON_FAILURE));
// }
private static void _send(Session session, Message message, InternetAddress[] bulkAddresses, int batchSize)
throws MailEngineException {
private static void _send(Session session, Message message, InternetAddress[] bulkAddresses, int batchSize)
throws MailEngineException {
try {
boolean smtpAuth = GetterUtil.getBoolean(_getSMTPProperty(session, "auth"), false);
String smtpHost = _getSMTPProperty(session, "host");
int smtpPort = GetterUtil.getInteger(_getSMTPProperty(session, "port"), Account.PORT_SMTP);
String user = _getSMTPProperty(session, "user");
String password = _getSMTPProperty(session, "password");
try {
boolean smtpAuth = GetterUtil.getBoolean(_getSMTPProperty(session, "auth"), false);
String smtpHost = _getSMTPProperty(session, "host");
int smtpPort = GetterUtil.getInteger(_getSMTPProperty(session, "port"), Account.PORT_SMTP);
String user = _getSMTPProperty(session, "user");
String password = _getSMTPProperty(session, "password");
if (smtpAuth && Validator.isNotNull(user) && Validator.isNotNull(password)) {
if (smtpAuth && Validator.isNotNull(user) && Validator.isNotNull(password)) {
String protocol = GetterUtil.getString(session.getProperty("mail.transport.protocol"), Account.PROTOCOL_SMTP);
String protocol = GetterUtil.getString(session.getProperty("mail.transport.protocol"),
Account.PROTOCOL_SMTP);
Transport transport = session.getTransport(protocol);
Transport transport = session.getTransport(protocol);
transport.connect(smtpHost, smtpPort, user, password);
transport.connect(smtpHost, smtpPort, user, password);
Address[] addresses = null;
Address[] addresses = null;
if (ArrayUtil.isNotEmpty(bulkAddresses)) {
addresses = bulkAddresses;
} else {
addresses = message.getAllRecipients();
}
if (ArrayUtil.isNotEmpty(bulkAddresses)) {
addresses = bulkAddresses;
} else {
addresses = message.getAllRecipients();
}
for (int i = 0;; i++) {
Address[] batchAddresses = _getBatchAddresses(addresses, i, batchSize);
for (int i = 0;; i++) {
Address[] batchAddresses = _getBatchAddresses(addresses, i, batchSize);
if (ArrayUtil.isEmpty(batchAddresses)) {
break;
}
if (ArrayUtil.isEmpty(batchAddresses)) {
break;
}
transport.sendMessage(message, batchAddresses);
}
transport.sendMessage(message, batchAddresses);
}
transport.close();
} else {
if (ArrayUtil.isNotEmpty(bulkAddresses)) {
int curBatch = 0;
transport.close();
} else {
if (ArrayUtil.isNotEmpty(bulkAddresses)) {
int curBatch = 0;
Address[] portion = _getBatchAddresses(bulkAddresses, curBatch, batchSize);
Address[] portion = _getBatchAddresses(bulkAddresses, curBatch, batchSize);
while (ArrayUtil.isNotEmpty(portion)) {
Transport.send(message, portion);
while (ArrayUtil.isNotEmpty(portion)) {
Transport.send(message, portion);
curBatch++;
curBatch++;
portion = _getBatchAddresses(bulkAddresses, curBatch, batchSize);
}
} else {
Transport.send(message);
}
}
} catch (MessagingException me) {
if (me.getNextException() instanceof SocketException) {
if (_log.isWarnEnabled()) {
_log.warn("Failed to connect to a valid mail server. Please " + "make sure one is properly configured. "
+ me.getMessage());
}
} else {
LogUtil.log(_log, me);
}
portion = _getBatchAddresses(bulkAddresses, curBatch, batchSize);
}
} else {
Transport.send(message);
}
}
} catch (MessagingException me) {
if (me.getNextException() instanceof SocketException) {
if (_log.isWarnEnabled()) {
_log.warn("Failed to connect to a valid mail server. Please "
+ "make sure one is properly configured. " + me.getMessage());
}
} else {
LogUtil.log(_log, me);
}
// if (_isThrowsExceptionOnFailure()) {
// throw new MailEngineException(me);
// }
// if (_isThrowsExceptionOnFailure()) {
// throw new MailEngineException(me);
// }
throw new MailEngineException(me);
}
}
throw new MailEngineException(me);
}
}
private static final int _BATCH_SIZE = 0;
private static final int _BATCH_SIZE = 0;
private static final String _MULTIPART_TYPE_ALTERNATIVE = "alternative";
private static final String _MULTIPART_TYPE_ALTERNATIVE = "alternative";
private static final String _MULTIPART_TYPE_MIXED = "mixed";
private static final String _MULTIPART_TYPE_MIXED = "mixed";
private static final String _TEXT_HTML = "text/html;charset=\"UTF-8\"";
private static final String _TEXT_HTML = "text/html;charset=\"UTF-8\"";
private static final String _TEXT_PLAIN = "text/plain;charset=\"UTF-8\"";
private static final String _TEXT_PLAIN = "text/plain;charset=\"UTF-8\"";
private static Log _log = LogFactoryUtil.getLog(MailEngine.class);
private static Log _log = LogFactoryUtil.getLog(MailEngine.class);
}

2
liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/util/MailSenderUtil.java

@ -30,7 +30,7 @@ import org.apache.commons.lang.StringUtils;
public class MailSenderUtil {
private static final Log _log = LogFactoryUtil.getLog(MailSenderUtil.class.getName());
private static final Log _log = LogFactoryUtil.getLog(MailSenderUtil.class);
public static void sendMail(Email email) throws Exception {

64
liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/util/VelocityUtil.java

@ -13,57 +13,57 @@ import org.apache.velocity.runtime.RuntimeConstants;
public class VelocityUtil {
public static VelocityContext fromJSONObjectOneLevelDepth(JSONObject jsonObject) {
public static VelocityContext fromJSONObjectOneLevelDepth(JSONObject jsonObject) {
VelocityContext velocityContext = new VelocityContext();
VelocityContext velocityContext = new VelocityContext();
while (jsonObject.keys().hasNext()) {
while (jsonObject.keys().hasNext()) {
String key = jsonObject.keys().next();
String key = jsonObject.keys().next();
velocityContext.put(key, jsonObject.getString(key));
velocityContext.put(key, jsonObject.getString(key));
}
}
return velocityContext;
return velocityContext;
}
}
public static String evaluate(String input) throws Exception {
return evaluate(input, null);
}
public static String evaluate(String input) throws Exception {
return evaluate(input, null);
}
public static String evaluate(String input, JSONObject variables) throws Exception {
public static String evaluate(String input, JSONObject variables) throws Exception {
VelocityEngine velocityEngine = new VelocityEngine();
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
com.liferay.portal.kernel.util.PropsUtil.get(PropsKeys.VELOCITY_ENGINE_LOGGER));
velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
com.liferay.portal.kernel.util.PropsUtil.get(PropsKeys.VELOCITY_ENGINE_LOGGER));
velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM + ".log4j.category",
com.liferay.portal.kernel.util.PropsUtil.get(PropsKeys.VELOCITY_ENGINE_LOGGER_CATEGORY));
velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM + ".log4j.category",
com.liferay.portal.kernel.util.PropsUtil.get(PropsKeys.VELOCITY_ENGINE_LOGGER_CATEGORY));
velocityEngine.init();
velocityEngine.init();
VelocityContext velocityContext = new VelocityContext();
VelocityContext velocityContext = new VelocityContext();
if (variables != null) {
if (variables != null) {
Iterator<String> iteratiorKeys = variables.keys();
Iterator<String> iteratiorKeys = variables.keys();
while (iteratiorKeys.hasNext()) {
String key = iteratiorKeys.next();
if (Validator.isNotNull(key)) {
velocityContext.put(key, variables.getString(key));
}
}
}
while (iteratiorKeys.hasNext()) {
String key = iteratiorKeys.next();
if (Validator.isNotNull(key)) {
velocityContext.put(key, variables.getString(key));
}
}
}
UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();
UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();
velocityEngine.evaluate(velocityContext, unsyncStringWriter, VelocityUtil.class.getName(), input);
velocityEngine.evaluate(velocityContext, unsyncStringWriter, VelocityUtil.class.getName(), input);
return unsyncStringWriter.toString();
}
return unsyncStringWriter.toString();
}
}

4
liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/service.properties

@ -13,8 +13,8 @@
##
build.namespace=portos_Mail
build.number=75
build.date=1592823810355
build.number=76
build.date=1603286289030
build.auto.upgrade=true
##

Caricamento…
Annulla
Salva