Sfoglia il codice sorgente

Annullamento conformità errate pratiche di tipo B e C

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; package it.mwg.sismica.bo.util;
import flexjson.JSONSerializer;
import it.tref.liferay.portos.bo.model.Avviso; 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.ControlloPratica;
import it.tref.liferay.portos.bo.model.Delega;
import it.tref.liferay.portos.bo.model.DettPratica; 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.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.AvvisoLocalServiceUtil;
import it.tref.liferay.portos.bo.service.CollaudoLocalServiceUtil; import it.tref.liferay.portos.bo.service.ConfigurazioneLocalServiceUtil;
import it.tref.liferay.portos.bo.service.DelegaLocalServiceUtil; import it.tref.liferay.portos.bo.service.ControlloPraticaLocalServiceUtil;
import it.tref.liferay.portos.bo.service.DettPraticaLocalServiceUtil; 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.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.text.ParseException;
import java.sql.SQLException; import java.text.SimpleDateFormat;
import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import com.liferay.portal.kernel.cache.CacheRegistryUtil; import com.liferay.portal.kernel.cache.CacheRegistryUtil;
import com.liferay.portal.kernel.cache.MultiVMPoolUtil; import com.liferay.portal.kernel.cache.MultiVMPoolUtil;
import com.liferay.portal.kernel.cache.SingleVMPoolUtil; 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.PortalException;
import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil; 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.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.kernel.util.Validator;
import com.liferay.portal.model.Group; import com.liferay.portal.security.permission.ActionKeys;
import com.liferay.portal.model.Organization;
import com.liferay.portal.model.User;
import com.liferay.portal.service.ClassNameLocalServiceUtil;
import com.liferay.portal.service.ServiceContext; 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.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 { public class PuliziaDatabase {
private static final Log _log = LogFactoryUtil.getLog(PuliziaDatabase.class); private static final Log _log = LogFactoryUtil.getLog(PuliziaDatabase.class);
private static final int SLICE = 1000; 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<>(); 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 { try {
List<IntPratica> pratiche = null; min = sdf.parse("2020-09-25 18:43:49");
int start = 0; max = sdf.parse("2020-09-25 18:44:15");
do { } catch (ParseException e) {
pratiche = IntPraticaLocalServiceUtil.getIntPraticas(start, start + SLICE); esitoLog(esito, "Errore date: " + e.getMessage());
for (IntPratica pratica : pratiche) { return esito;
List<Avviso> avvisi = AvvisoLocalServiceUtil.findByIntPratica(pratica.getIntPraticaId(), }
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
int noFile = 0; long companyId = serviceContext.getCompanyId();
for (Avviso avviso : avvisi) { long folderId = ConfigurazioneLocalServiceUtil.findByC_ChiaveLong(companyId,
if (0 == avviso.getFileEntryIdBase()) { ConfigurazioneConstants.TEMPLATE_FOLDER_ID);
AvvisoLocalServiceUtil.deleteAvviso(avviso);
noFile++; 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) { ServiceContext ctx = new ServiceContext();
esitoLog(esito, ctx.setCompanyId(intPratica.getCompanyId());
"Pratica " + pratica.getNumeroProgetto() + "(" + pratica.getIntPraticaId() ctx.setScopeGroupId(intPratica.getGroupId());
+ ") - " + avvisi.size() + " avvisi, eliminati: " + noFile); 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; 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 { public String getDescriptionOggettoProtocollo() throws PortalException, SystemException {
String tipoDocumento = AvvisoUtil.getAllTipoDocumento().containsKey(this.getTipoDocumento()) ? AvvisoUtil String fullDescription = LanguageUtil.get(LocaleUtil.ITALIAN,
.getAllTipoDocumento().get(this.getTipoDocumento()) "label.admingeniocivile.avviso.tipoDocumento.avvisomanuale");
: "label.admingeniocivile.avviso.tipoDocumento.avvisomanuale"; if (AvvisoUtil.getAllTipoDocumento().containsKey(this.getTipoDocumento())) {
fullDescription = LanguageUtil.get(LocaleUtil.ITALIAN,
String fullDescription = LanguageUtil.get(LocaleUtil.ITALIAN, tipoDocumento); AvvisoUtil.getAllTipoDocumento().get(this.getTipoDocumento()));
} else if (Validator.isNotNull(this.getDescLong())) {
fullDescription = this.getDescLong();
}
if (this.getTipoDocumento().equalsIgnoreCase(StatoPraticaConstants.VIDIMATA)) { 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())) { if (Validator.isNotNull(avviso.getJsonParameters())) {
JSONDeserializer<Map<String, String>> deserializer = JSONFactoryUtil.createJSONDeserializer(); JSONDeserializer<Map<String, String>> deserializer = JSONFactoryUtil.createJSONDeserializer();
parameters.putAll(deserializer.deserialize(avviso.getJsonParameters())); 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; 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 { public class StartupAction extends SimpleAction {
private final static Log _log = LogFactoryUtil.getLog(StartupAction.class); private final static Log _log = LogFactoryUtil.getLog(StartupAction.class);
@Override @Override
public void run(String[] ids) throws ActionException { 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(); Group companyGroup = company.getGroup();
User userDefault = company.getDefaultUser(); User userDefault = company.getDefaultUser();
// Folders // Folders
String[] groupActions = {ActionKeys.VIEW}; String[] groupActions = { ActionKeys.VIEW };
String[] guestActions = {ActionKeys.VIEW}; String[] guestActions = { ActionKeys.VIEW };
addDLFolderIfNotExists(userDefault.getUserId(), companyGroup.getGroupId(), companyGroup.getGroupId(), addDLFolderIfNotExists(userDefault.getUserId(), companyGroup.getGroupId(),
DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, EmailConstants.DEFAULT_ATTACHMENTS_FOLDER_NAME, true, companyGroup.getGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
groupActions, guestActions); EmailConstants.DEFAULT_ATTACHMENTS_FOLDER_NAME, true, groupActions, guestActions);
} catch (Exception e) { } catch (Exception e) {
_log.error(e, e); _log.error(e, e);
} }
} }
} }
private DLFolder addDLFolderIfNotExists(long userId, long groupId, long repositoryId, long parentFolderId, private DLFolder addDLFolderIfNotExists(long userId, long groupId, long repositoryId,
String name, boolean hidden, String[] groupActions, String[] guestActions) throws PortalException, long parentFolderId, String name, boolean hidden, String[] groupActions, String[] guestActions)
SystemException { throws PortalException, SystemException {
DLFolder dlFolder = null; DLFolder dlFolder = null;
try { try {
dlFolder = DLFolderLocalServiceUtil.getFolder(groupId, parentFolderId, name); dlFolder = DLFolderLocalServiceUtil.getFolder(groupId, parentFolderId, name);
} catch (PortalException e) { } catch (PortalException e) {
ServiceContext serviceContext = new ServiceContext(); ServiceContext serviceContext = new ServiceContext();
if (groupActions != null) { if (groupActions != null) {
serviceContext.setGroupPermissions(groupActions); serviceContext.setGroupPermissions(groupActions);
} }
if (guestActions != null) { if (guestActions != null) {
serviceContext.setGuestPermissions(guestActions); serviceContext.setGuestPermissions(guestActions);
} }
dlFolder = dlFolder = DLFolderLocalServiceUtil.addFolder(userId, groupId, repositoryId, false,
DLFolderLocalServiceUtil.addFolder(userId, groupId, repositoryId, false, parentFolderId, name, parentFolderId, name, StringPool.BLANK, hidden, serviceContext);
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> { public class DLFileEntryListener extends BaseModelListener<DLFileEntry> {
@Override @Override
public void onBeforeRemove(DLFileEntry model) throws ModelListenerException { public void onBeforeRemove(DLFileEntry model) throws ModelListenerException {
try { try {
EmailAttachment emailAttachment = EmailAttachmentLocalServiceUtil.fetchByFileEntryId(model.getFileEntryId()); EmailAttachment emailAttachment = EmailAttachmentLocalServiceUtil.fetchByFileEntryId(model
if (emailAttachment != null) { .getFileEntryId());
throw new ModelListenerException(); if (emailAttachment != null) {
} throw new ModelListenerException();
} catch (SystemException e) { }
throw new ModelListenerException(e); } 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 { 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 @Override
public void receive(Message message) throws MessageListenerException { public void receive(Message message) throws MessageListenerException {
try { try {
ActionableDynamicQuery actionableDynamicQuery = new EmailActionableDynamicQuery() { ActionableDynamicQuery actionableDynamicQuery = new EmailActionableDynamicQuery() {
@Override @Override
protected void addCriteria(DynamicQuery dynamicQuery) { protected void addCriteria(DynamicQuery dynamicQuery) {
dynamicQuery.add(PropertyFactoryUtil.forName("sent").eq(false)); dynamicQuery.add(PropertyFactoryUtil.forName("sent").eq(false));
dynamicQuery.add(PropertyFactoryUtil.forName("cancel").eq(false)); dynamicQuery.add(PropertyFactoryUtil.forName("cancel").eq(false));
} }
@Override @Override
protected void performAction(Object obj) throws PortalException, SystemException { 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); EmailLocalServiceUtil.markAsSent(email.getEmailId(), new Date(), StringPool.BLANK);
} catch (Exception e) { } catch (Exception e) {
EmailLocalServiceUtil.updateStatusMessage(email.getEmailId(), e.getMessage()); 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 { try {
actionableDynamicQuery.performActions(); actionableDynamicQuery.performActions();
} finally { } finally {
unlock(owner); unlock(owner);
} }
} }
} }
} catch (Exception e) { } catch (Exception e) {
_log.error(e, 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) { while (true) {
try { try {
lock = LockLocalServiceUtil.lock(_LOCK_CLASS_NAME, _LOCK_CLASS_NAME, owner); lock = LockLocalServiceUtil.lock(_LOCK_CLASS_NAME, _LOCK_CLASS_NAME, owner);
break; break;
} catch (SystemException se) { } catch (SystemException se) {
try { try {
Thread.sleep(50); Thread.sleep(50);
} catch (InterruptedException ie) { } catch (InterruptedException ie) {
} }
} }
} }
if (!lock.isNew()) { if (!lock.isNew()) {
throw new DuplicateLockException(lock); throw new DuplicateLockException(lock);
} }
} catch (DuplicateLockException e) { } catch (DuplicateLockException e) {
return false; 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 { 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 from = ParamUtil.getString(actionRequest, "from");
String[] to = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "to")); String[] to = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "to"));
String[] cc = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "cc")); String[] cc = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "cc"));
String[] ccn = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "ccn")); String[] ccn = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "ccn"));
String subject = ParamUtil.getString(actionRequest, "subject"); String subject = ParamUtil.getString(actionRequest, "subject");
String body = ParamUtil.getString(actionRequest, "body"); 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, public void annullaEmail(ActionRequest actionRequest, ActionResponse actionResponse)
SystemException { throws PortalException, SystemException {
_log.debug("annullaEmail - inizio metodo"); _log.debug("annullaEmail - inizio metodo");
ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
long emailId = ParamUtil.getLong(actionRequest, "emailId"); long emailId = ParamUtil.getLong(actionRequest, "emailId");
EmailServiceUtil.cancelEmail(emailId, serviceContext); 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); ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
long emailId = ParamUtil.getLong(actionRequest, "emailId"); long emailId = ParamUtil.getLong(actionRequest, "emailId");
EmailServiceUtil.resendEmail(emailId, serviceContext); 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 { 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, public void editTemplateEmail(ActionRequest actionRequest, ActionResponse actionResponse)
SystemException { 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 from = ParamUtil.getString(actionRequest, "from");
String[] to = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "to")); String[] to = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "to"));
String[] cc = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "cc")); String[] cc = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "cc"));
String[] ccn = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "ccn")); String[] ccn = StringUtil.splitAndTrim(ParamUtil.getString(actionRequest, "ccn"));
String subject = ParamUtil.getString(actionRequest, "subject"); String subject = ParamUtil.getString(actionRequest, "subject");
String body = ParamUtil.getString(actionRequest, "body"); String body = ParamUtil.getString(actionRequest, "body");
Boolean attachmentPermitted = ParamUtil.getBoolean(actionRequest, "attachmentPermitted"); Boolean attachmentPermitted = ParamUtil.getBoolean(actionRequest, "attachmentPermitted");
try { try {
EmailTemplate emailTemplate = null; EmailTemplate emailTemplate = null;
if (cmd.equals(Constants.ADD)) { if (cmd.equals(Constants.ADD)) {
emailTemplate = emailTemplate = EmailTemplateServiceUtil.addEmailTemplate(templateName, from, to, cc, ccn,
EmailTemplateServiceUtil.addEmailTemplate(templateName, from, to, cc, ccn, subject, body, subject, body, attachmentPermitted, serviceContext);
attachmentPermitted, serviceContext); emailTemplateId = emailTemplate.getEmailTemplateId();
emailTemplateId = emailTemplate.getEmailTemplateId(); } else if (cmd.equals(Constants.UPDATE)) {
} else if (cmd.equals(Constants.UPDATE)) { emailTemplate = EmailTemplateServiceUtil.updateEmailTemplate(emailTemplateId, templateName,
emailTemplate = from, to, cc, ccn, subject, body, attachmentPermitted, serviceContext);
EmailTemplateServiceUtil.updateEmailTemplate(emailTemplateId, templateName, from, to, cc, ccn, subject, }
body, attachmentPermitted, serviceContext); emailTemplateId = emailTemplate.getEmailTemplateId();
}
emailTemplateId = emailTemplate.getEmailTemplateId();
} catch (PortalException e) { } catch (PortalException e) {
SessionErrors.add(actionRequest, e.getClass()); SessionErrors.add(actionRequest, e.getClass());
} }
if (SessionErrors.isEmpty(actionRequest)) { if (SessionErrors.isEmpty(actionRequest)) {
actionResponse.setRenderParameter("emailTemplateId", String.valueOf(emailTemplateId)); actionResponse.setRenderParameter("emailTemplateId", String.valueOf(emailTemplateId));
actionResponse.setRenderParameter("mvcPath", "/html/email_templates/edit.jsp"); actionResponse.setRenderParameter("mvcPath", "/html/email_templates/edit.jsp");
} else { } else {
actionResponse.setRenderParameter("mvcPath", "/html/email_templates/edit.jsp"); actionResponse.setRenderParameter("mvcPath", "/html/email_templates/edit.jsp");
PortalUtil.copyRequestParameters(actionRequest, actionResponse); PortalUtil.copyRequestParameters(actionRequest, actionResponse);
} }
} }
public void deleteEmailTemplate(ActionRequest actionRequest, ActionResponse actionResponse) throws PortalException, public void deleteEmailTemplate(ActionRequest actionRequest, ActionResponse actionResponse)
SystemException { throws PortalException, SystemException {
long emailTemplateId = ParamUtil.getLong(actionRequest, "emailTemplateId"); long emailTemplateId = ParamUtil.getLong(actionRequest, "emailTemplateId");
EmailTemplateServiceUtil.deleteEmailTemplate(emailTemplateId); EmailTemplateServiceUtil.deleteEmailTemplate(emailTemplateId);
} }
public void addEmailByTemplate(ActionRequest actionRequest, ActionResponse actionResponse) throws PortalException, public void addEmailByTemplate(ActionRequest actionRequest, ActionResponse actionResponse)
SystemException { throws PortalException, SystemException {
UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest); UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);
ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
long emailTemplateId = ParamUtil.getLong(actionRequest, "emailTemplateId"); long emailTemplateId = ParamUtil.getLong(actionRequest, "emailTemplateId");
EmailTemplate emailTemplate = EmailTemplateLocalServiceUtil.getEmailTemplate(emailTemplateId); EmailTemplate emailTemplate = EmailTemplateLocalServiceUtil.getEmailTemplate(emailTemplateId);
String sendModeStr = ParamUtil.getString(actionRequest, "sendMode"); String sendModeStr = ParamUtil.getString(actionRequest, "sendMode");
SendTemplateMode sendMode = SendTemplateMode.parse(sendModeStr); SendTemplateMode sendMode = SendTemplateMode.parse(sendModeStr);
String className = ParamUtil.getString(actionRequest, "className"); String className = ParamUtil.getString(actionRequest, "className");
long classPK = ParamUtil.getLong(actionRequest, "classPK"); long classPK = ParamUtil.getLong(actionRequest, "classPK");
try { try {
// eventuali allegati email // eventuali allegati email
List<com.liferay.mail.model.FileAttachment> fileAttachments = null; List<com.liferay.mail.model.FileAttachment> fileAttachments = null;
if (emailTemplate.getAttachmentPermitted()) { if (emailTemplate.getAttachmentPermitted()) {
fileAttachments = MailUtil.getEmailFileAttachments(uploadPortletRequest); fileAttachments = MailUtil.getEmailFileAttachments(uploadPortletRequest);
} }
if (sendMode == SendTemplateMode.REVIEW) { if (sendMode == SendTemplateMode.REVIEW) {
String templateParamJSON = ParamUtil.getString(actionRequest, "templateParamJSON"); String templateParamJSON = ParamUtil.getString(actionRequest, "templateParamJSON");
JSONObject templateParamJSONObj = JSONFactoryUtil.createJSONObject(templateParamJSON); JSONObject templateParamJSONObj = JSONFactoryUtil.createJSONObject(templateParamJSON);
MailManagerUtil.addEmailByTemplate(className, classPK, emailTemplateId, templateParamJSONObj, fileAttachments, MailManagerUtil.addEmailByTemplate(className, classPK, emailTemplateId, templateParamJSONObj,
serviceContext); fileAttachments, serviceContext);
} else if (sendMode == SendTemplateMode.EDIT) { } else if (sendMode == SendTemplateMode.EDIT) {
String from = ParamUtil.getString(actionRequest, "from"); String from = ParamUtil.getString(actionRequest, "from");
String to = ParamUtil.getString(actionRequest, "to"); String to = ParamUtil.getString(actionRequest, "to");
String cc = ParamUtil.getString(actionRequest, "cc"); String cc = ParamUtil.getString(actionRequest, "cc");
String ccn = ParamUtil.getString(actionRequest, "ccn"); String ccn = ParamUtil.getString(actionRequest, "ccn");
String subject = ParamUtil.getString(actionRequest, "subject"); String subject = ParamUtil.getString(actionRequest, "subject");
String body = ParamUtil.getString(actionRequest, "body"); String body = ParamUtil.getString(actionRequest, "body");
EmailLocalServiceUtil.addEmail(className, classPK, from, StringUtil.split(to, StringPool.COMMA), EmailLocalServiceUtil.addEmail(className, classPK, from,
StringUtil.split(cc, StringPool.COMMA), StringUtil.split(ccn, StringPool.COMMA), subject, body, true, StringUtil.split(to, StringPool.COMMA), StringUtil.split(cc, StringPool.COMMA),
fileAttachments, serviceContext); 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"); UploadPortletRequestUtil.copyRequestParameters(uploadPortletRequest, actionResponse);
} catch (Exception ex) { actionResponse.setRenderParameter("mvcPath", "/html/email_templates/send_popup/close_popup.jsp");
UploadPortletRequestUtil.copyRequestParameters(uploadPortletRequest, actionResponse); } catch (Exception ex) {
throw new SystemException("Error add email by template.", 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; package it.tref.liferay.portos.mailmanager.service.impl;
import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.repository.model.FileEntry; import com.liferay.portal.kernel.repository.model.FileEntry;
@ -41,13 +40,15 @@ import java.util.List;
* The implementation of the email attachment local service. * The implementation of the email attachment local service.
* *
* <p> * <p>
* All custom service methods should be put in this class. Whenever methods are added, rerun * All custom service methods should be put in this class. Whenever methods are
* ServiceBuilder to copy their definitions into the * added, rerun ServiceBuilder to copy their definitions into the
* {@link it.noovle.azimut.icf.mailmanager.service.EmailAttachmentLocalService} interface. * {@link it.noovle.azimut.icf.mailmanager.service.EmailAttachmentLocalService}
* interface.
* *
* <p> * <p>
* This is a local service. Methods of this service will not have security checks based on the * This is a local service. Methods of this service will not have security
* propagated JAAS credentials because this service can only be accessed from within the same VM. * checks based on the propagated JAAS credentials because this service can only
* be accessed from within the same VM.
* </p> * </p>
* *
* @author * @author
@ -55,96 +56,96 @@ import java.util.List;
* @see it.noovle.azimut.icf.mailmanager.service.EmailAttachmentLocalServiceUtil * @see it.noovle.azimut.icf.mailmanager.service.EmailAttachmentLocalServiceUtil
*/ */
public class EmailAttachmentLocalServiceImpl extends EmailAttachmentLocalServiceBaseImpl { public class EmailAttachmentLocalServiceImpl extends EmailAttachmentLocalServiceBaseImpl {
/* /*
* NOTE FOR DEVELOPERS: * NOTE FOR DEVELOPERS:
* *
* Never reference this interface directly. Always use {@link * Never reference this interface directly. Always use {@link
* it.noovle.azimut.icf.mailmanager.service.EmailAttachmentLocalServiceUtil} to access the * it.noovle.azimut.icf.mailmanager.service.EmailAttachmentLocalServiceUtil}
* email attachment local service. * to access the email attachment local service.
*/ */
public EmailAttachment addEmailAttachment(long companyId, long emailId, long folderId, String fileName, File file) public EmailAttachment addEmailAttachment(long companyId, long emailId, long folderId, String fileName,
throws PortalException, SystemException { 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 sourceFileName = file.getName();
String mimeType = MimeTypesUtil.getContentType(sourceFileName); String mimeType = MimeTypesUtil.getContentType(sourceFileName);
String title = fileName; String title = fileName;
if (Validator.isNull(title)) { if (Validator.isNull(title)) {
title = file.getName(); title = file.getName();
} }
ServiceContext serviceContext = new ServiceContext(); ServiceContext serviceContext = new ServiceContext();
serviceContext.setGroupPermissions(new String[] {ActionKeys.VIEW}); serviceContext.setGroupPermissions(new String[] { ActionKeys.VIEW });
serviceContext.setGuestPermissions(new String[] {ActionKeys.VIEW}); serviceContext.setGuestPermissions(new String[] { ActionKeys.VIEW });
FileEntry fileEntry = FileEntry fileEntry = dlAppLocalService.addFileEntry(defaultUser.getUserId(),
dlAppLocalService.addFileEntry(defaultUser.getUserId(), folder.getRepositoryId(), folder.getFolderId(), folder.getRepositoryId(), folder.getFolderId(), sourceFileName, mimeType, title,
sourceFileName, mimeType, title, StringPool.BLANK, StringPool.BLANK, file, serviceContext); StringPool.BLANK, StringPool.BLANK, file, serviceContext);
EmailAttachment emailAttachment = EmailAttachment emailAttachment = emailAttachmentLocalService
emailAttachmentLocalService.createEmailAttachment(new EmailAttachmentPK(emailId, fileEntry.getFileEntryId())); .createEmailAttachment(new EmailAttachmentPK(emailId, fileEntry.getFileEntryId()));
return emailAttachmentLocalService.addEmailAttachment(emailAttachment); return emailAttachmentLocalService.addEmailAttachment(emailAttachment);
} }
@Override @Override
public EmailAttachment deleteEmailAttachment(EmailAttachmentPK emailAttachmentPK) throws PortalException, public EmailAttachment deleteEmailAttachment(EmailAttachmentPK emailAttachmentPK) throws PortalException,
SystemException { SystemException {
EmailAttachment emailAttachment = emailAttachmentLocalService.getEmailAttachment(emailAttachmentPK); EmailAttachment emailAttachment = emailAttachmentLocalService.getEmailAttachment(emailAttachmentPK);
return deleteEmailAttachment(emailAttachment); return deleteEmailAttachment(emailAttachment);
} }
@Override @Override
public EmailAttachment deleteEmailAttachment(EmailAttachment emailAttachment) throws SystemException { public EmailAttachment deleteEmailAttachment(EmailAttachment emailAttachment) throws SystemException {
super.deleteEmailAttachment(emailAttachment); super.deleteEmailAttachment(emailAttachment);
// File Entry // File Entry
try { try {
dlAppLocalService.deleteFileEntry(emailAttachment.getFileEntryId()); dlAppLocalService.deleteFileEntry(emailAttachment.getFileEntryId());
} catch (PortalException e) { } catch (PortalException e) {
} }
return emailAttachment; return emailAttachment;
} }
public List<EmailAttachment> findByEmailId(long emailId) throws SystemException { public List<EmailAttachment> findByEmailId(long emailId) throws SystemException {
return emailAttachmentPersistence.findByEmailId(emailId); return emailAttachmentPersistence.findByEmailId(emailId);
} }
public List<EmailAttachment> findByEmailId(long emailId, int start, int end) throws SystemException { public List<EmailAttachment> findByEmailId(long emailId, int start, int end) throws SystemException {
return emailAttachmentPersistence.findByEmailId(emailId); return emailAttachmentPersistence.findByEmailId(emailId);
} }
public int countByEmailId(long emailId) throws SystemException { public int countByEmailId(long emailId) throws SystemException {
return emailAttachmentPersistence.countByEmailId(emailId); return emailAttachmentPersistence.countByEmailId(emailId);
} }
public EmailAttachment fetchByFileEntryId(long fileEntryId) throws SystemException { public EmailAttachment fetchByFileEntryId(long fileEntryId) throws SystemException {
return emailAttachmentPersistence.fetchByFileEntryId(fileEntryId); 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)) { if (Validator.isNull(emailId)) {
throw new NoSuchEmailException(); throw new NoSuchEmailException();
} }
if (Validator.isNull(fileName) && Validator.isNull(file)) { if (Validator.isNull(fileName) && Validator.isNull(file)) {
throw new EmailAttachmentTitleException(); throw new EmailAttachmentTitleException();
} }
if (Validator.isNull(file) || (Validator.isNotNull(file) && !FileUtil.exists(file))) { if (Validator.isNull(file) || (Validator.isNotNull(file) && !FileUtil.exists(file))) {
throw new EmailAttachmentFileException(); 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 { public Email cancelEmail(long emailId, ServiceContext serviceContext) throws PortalException, SystemException {
EmailPermission.check(getPermissionChecker(), serviceContext.getScopeGroupId(), ActionKeys.ADMIN_EMAIL); 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. * The implementation of the email template remote service.
* *
* <p> * <p>
* All custom service methods should be put in this class. Whenever methods are added, rerun * All custom service methods should be put in this class. Whenever methods are
* ServiceBuilder to copy their definitions into the * added, rerun ServiceBuilder to copy their definitions into the
* {@link it.noovle.azimut.icf.mailmanager.service.EmailTemplateService} interface. * {@link it.noovle.azimut.icf.mailmanager.service.EmailTemplateService}
* interface.
* *
* <p> * <p>
* This is a remote service. Methods of this service are expected to have security checks based on * This is a remote service. Methods of this service are expected to have
* the propagated JAAS credentials because this service can be accessed remotely. * security checks based on the propagated JAAS credentials because this service
* can be accessed remotely.
* </p> * </p>
* *
* @author * @author
@ -40,39 +42,40 @@ import it.tref.liferay.portos.mailmanager.service.base.EmailTemplateServiceBaseI
* @see it.noovle.azimut.icf.mailmanager.service.EmailTemplateServiceUtil * @see it.noovle.azimut.icf.mailmanager.service.EmailTemplateServiceUtil
*/ */
public class EmailTemplateServiceImpl extends EmailTemplateServiceBaseImpl { public class EmailTemplateServiceImpl extends EmailTemplateServiceBaseImpl {
/* /*
* NOTE FOR DEVELOPERS: * NOTE FOR DEVELOPERS:
* *
* Never reference this interface directly. Always use {@link * Never reference this interface directly. Always use {@link
* it.noovle.azimut.icf.mailmanager.service.EmailTemplateServiceUtil} to access the email * it.noovle.azimut.icf.mailmanager.service.EmailTemplateServiceUtil} to
* template remote service. * access the email template remote service.
*/ */
public EmailTemplate addEmailTemplate(String templateName, String from, String[] to, String[] cc, String[] ccn, public EmailTemplate addEmailTemplate(String templateName, String from, String[] to, String[] cc,
String subject, String body, boolean attachmentPermitted, ServiceContext serviceContext) throws SystemException, String[] ccn, String subject, String body, boolean attachmentPermitted,
PortalException { 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, return emailTemplateLocalService.addEmailTemplate(templateName, from, to, cc, ccn, subject, body,
attachmentPermitted, serviceContext); attachmentPermitted, serviceContext);
} }
public EmailTemplate updateEmailTemplate(long emailTemplateId, String templateName, String from, String[] to, public EmailTemplate updateEmailTemplate(long emailTemplateId, String templateName, String from,
String[] cc, String[] ccn, String subject, String body, boolean attachmentPermitted, ServiceContext serviceContext) String[] to, String[] cc, String[] ccn, String subject, String body, boolean attachmentPermitted,
throws SystemException, PortalException { 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, return emailTemplateLocalService.updateEmailTemplate(emailTemplateId, templateName, from, to, cc,
body, attachmentPermitted, serviceContext); 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 class MailEngine {
public static Session getSession() { public static Session getSession() {
return getSession(false); return getSession(false);
} }
public static Session getSession(Account account) { public static Session getSession(Account account) {
Properties properties = _getProperties(account); Properties properties = _getProperties(account);
Session session = Session.getInstance(properties); Session session = Session.getInstance(properties);
if (_log.isDebugEnabled()) { if (_log.isDebugEnabled()) {
session.setDebug(true); session.setDebug(true);
session.getProperties().list(System.out); session.getProperties().list(System.out);
} }
return session; return session;
} }
public static Session getSession(boolean cache) { public static Session getSession(boolean cache) {
Session session = null; Session session = null;
try { try {
session = MailServiceUtil.getSession(); session = MailServiceUtil.getSession();
} catch (SystemException se) { } catch (SystemException se) {
if (_log.isWarnEnabled()) { if (_log.isWarnEnabled()) {
_log.warn(se, se); _log.warn(se, se);
} }
session = InfrastructureUtil.getMailSession(); session = InfrastructureUtil.getMailSession();
} }
if (_log.isDebugEnabled()) { if (_log.isDebugEnabled()) {
session.setDebug(true); 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 { public static void send(byte[] bytes) throws MailEngineException {
try { try {
Session session = getSession(); 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); _send(session, message, null, _BATCH_SIZE);
} catch (Exception e) { } catch (Exception e) {
throw new MailEngineException(e); throw new MailEngineException(e);
} }
} }
public static void send(InternetAddress from, InternetAddress to, String subject, String body) public static void send(InternetAddress from, InternetAddress to, String subject, String body)
throws MailEngineException { 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) public static void send(InternetAddress from, InternetAddress to, String subject, String body,
throws MailEngineException { 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, public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc,
InternetAddress[] bulkAddresses, String subject, String body, boolean htmlFormat, InternetAddress[] replyTo, InternetAddress[] bcc, InternetAddress[] bulkAddresses, String subject, String body,
String messageId, String inReplyTo) throws MailEngineException { 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, public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc,
InternetAddress[] bulkAddresses, String subject, String body, boolean htmlFormat, InternetAddress[] replyTo, InternetAddress[] bcc, InternetAddress[] bulkAddresses, String subject, String body,
String messageId, String inReplyTo, List<FileAttachment> fileAttachments) throws MailEngineException { 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, send(from, to, cc, bcc, bulkAddresses, subject, body, htmlFormat, replyTo, messageId, inReplyTo,
null); fileAttachments, null);
} }
public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc, InternetAddress[] bcc, public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc,
InternetAddress[] bulkAddresses, String subject, String body, boolean htmlFormat, InternetAddress[] replyTo, InternetAddress[] bcc, InternetAddress[] bulkAddresses, String subject, String body,
String messageId, String inReplyTo, List<FileAttachment> fileAttachments, SMTPAccount smtpAccount) boolean htmlFormat, InternetAddress[] replyTo, String messageId, String inReplyTo,
throws MailEngineException { List<FileAttachment> fileAttachments, SMTPAccount smtpAccount) throws MailEngineException {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
if (_log.isDebugEnabled()) { if (_log.isDebugEnabled()) {
_log.debug("From: " + from); _log.debug("From: " + from);
_log.debug("To: " + Arrays.toString(to)); _log.debug("To: " + Arrays.toString(to));
_log.debug("CC: " + Arrays.toString(cc)); _log.debug("CC: " + Arrays.toString(cc));
_log.debug("BCC: " + Arrays.toString(bcc)); _log.debug("BCC: " + Arrays.toString(bcc));
_log.debug("List Addresses: " + Arrays.toString(bulkAddresses)); _log.debug("List Addresses: " + Arrays.toString(bulkAddresses));
_log.debug("Subject: " + subject); _log.debug("Subject: " + subject);
_log.debug("Body: " + body); _log.debug("Body: " + body);
_log.debug("HTML Format: " + htmlFormat); _log.debug("HTML Format: " + htmlFormat);
_log.debug("Reply to: " + Arrays.toString(replyTo)); _log.debug("Reply to: " + Arrays.toString(replyTo));
_log.debug("Message ID: " + messageId); _log.debug("Message ID: " + messageId);
_log.debug("In Reply To: " + inReplyTo); _log.debug("In Reply To: " + inReplyTo);
if ((fileAttachments != null) && _log.isDebugEnabled()) { if ((fileAttachments != null) && _log.isDebugEnabled()) {
for (int i = 0; i < fileAttachments.size(); i++) { for (int i = 0; i < fileAttachments.size(); i++) {
FileAttachment fileAttachment = fileAttachments.get(i); FileAttachment fileAttachment = fileAttachments.get(i);
if (fileAttachment instanceof it.tref.liferay.portos.mailmanager.shared.model.FileAttachment) { if (fileAttachment instanceof it.tref.liferay.portos.mailmanager.shared.model.FileAttachment) {
((it.tref.liferay.portos.mailmanager.shared.model.FileAttachment) fileAttachment).generateFile(); ((it.tref.liferay.portos.mailmanager.shared.model.FileAttachment) fileAttachment)
} .generateFile();
File file = fileAttachment.getFile(); }
File file = fileAttachment.getFile();
if (file == null) { if (file == null) {
continue; continue;
} }
_log.debug("Attachment " + i + " file " + file.getAbsolutePath() + " and file name " _log.debug("Attachment " + i + " file " + file.getAbsolutePath() + " and file name "
+ fileAttachment.getFileName()); + fileAttachment.getFileName());
} }
} }
} }
try { try {
InternetAddressUtil.validateAddress(from); InternetAddressUtil.validateAddress(from);
if (ArrayUtil.isNotEmpty(to)) { if (ArrayUtil.isNotEmpty(to)) {
InternetAddressUtil.validateAddresses(to); InternetAddressUtil.validateAddresses(to);
} }
if (ArrayUtil.isNotEmpty(cc)) { if (ArrayUtil.isNotEmpty(cc)) {
InternetAddressUtil.validateAddresses(cc); InternetAddressUtil.validateAddresses(cc);
} }
if (ArrayUtil.isNotEmpty(bcc)) { if (ArrayUtil.isNotEmpty(bcc)) {
InternetAddressUtil.validateAddresses(bcc); InternetAddressUtil.validateAddresses(bcc);
} }
if (ArrayUtil.isNotEmpty(replyTo)) { if (ArrayUtil.isNotEmpty(replyTo)) {
InternetAddressUtil.validateAddresses(replyTo); InternetAddressUtil.validateAddresses(replyTo);
} }
if (ArrayUtil.isNotEmpty(bulkAddresses)) { if (ArrayUtil.isNotEmpty(bulkAddresses)) {
InternetAddressUtil.validateAddresses(bulkAddresses); InternetAddressUtil.validateAddresses(bulkAddresses);
} }
Session session = null; Session session = null;
if (smtpAccount == null) { if (smtpAccount == null) {
session = getSession(); session = getSession();
} else { } else {
session = getSession(smtpAccount); 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)) { if (ArrayUtil.isNotEmpty(to)) {
message.setRecipients(Message.RecipientType.TO, to); message.setRecipients(Message.RecipientType.TO, to);
} }
if (ArrayUtil.isNotEmpty(cc)) { if (ArrayUtil.isNotEmpty(cc)) {
message.setRecipients(Message.RecipientType.CC, cc); message.setRecipients(Message.RecipientType.CC, cc);
} }
if (ArrayUtil.isNotEmpty(bcc)) { if (ArrayUtil.isNotEmpty(bcc)) {
message.setRecipients(Message.RecipientType.BCC, 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)) { if ((fileAttachments != null) && (fileAttachments.size() > 0)) {
MimeMultipart rootMultipart = new MimeMultipart(_MULTIPART_TYPE_MIXED); 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) { if (htmlFormat) {
MimeBodyPart bodyPart = new MimeBodyPart(); MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(body, _TEXT_HTML); bodyPart.setContent(body, _TEXT_HTML);
messageMultipart.addBodyPart(bodyPart); messageMultipart.addBodyPart(bodyPart);
} else { } else {
MimeBodyPart bodyPart = new MimeBodyPart(); MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setText(body); bodyPart.setText(body);
messageMultipart.addBodyPart(bodyPart); messageMultipart.addBodyPart(bodyPart);
} }
for (int i = 0; i < fileAttachments.size(); i++) { for (int i = 0; i < fileAttachments.size(); i++) {
FileAttachment fileAttachment = fileAttachments.get(i); FileAttachment fileAttachment = fileAttachments.get(i);
File file = fileAttachment.getFile(); File file = fileAttachment.getFile();
if (file == null) { if (file == null) {
continue; 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.setDataHandler(new DataHandler(dataSource));
mimeBodyPart.setDisposition(Part.ATTACHMENT); mimeBodyPart.setDisposition(Part.ATTACHMENT);
if (fileAttachment.getFileName() != null) { if (fileAttachment.getFileName() != null) {
mimeBodyPart.setFileName(fileAttachment.getFileName()); mimeBodyPart.setFileName(fileAttachment.getFileName());
} else { } else {
mimeBodyPart.setFileName(file.getName()); mimeBodyPart.setFileName(file.getName());
} }
rootMultipart.addBodyPart(mimeBodyPart); rootMultipart.addBodyPart(mimeBodyPart);
} }
message.setContent(rootMultipart); message.setContent(rootMultipart);
message.saveChanges(); message.saveChanges();
} else { } else {
if (htmlFormat) { if (htmlFormat) {
message.setContent(body, _TEXT_HTML); message.setContent(body, _TEXT_HTML);
} else { } else {
message.setContent(body, _TEXT_PLAIN); message.setContent(body, _TEXT_PLAIN);
} }
} }
message.setSentDate(new Date()); message.setSentDate(new Date());
if (ArrayUtil.isNotEmpty(replyTo)) { if (ArrayUtil.isNotEmpty(replyTo)) {
message.setReplyTo(replyTo); message.setReplyTo(replyTo);
} }
if (messageId != null) { if (messageId != null) {
message.setHeader("Message-ID", messageId); message.setHeader("Message-ID", messageId);
} }
if (inReplyTo != null) { if (inReplyTo != null) {
message.setHeader("In-Reply-To", inReplyTo); message.setHeader("In-Reply-To", inReplyTo);
message.setHeader("References", 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); _send(session, message, bulkAddresses, batchSize);
} catch (SendFailedException sfe) { } catch (SendFailedException sfe) {
_log.error(sfe); _log.error(sfe);
// if (_isThrowsExceptionOnFailure()) { // if (_isThrowsExceptionOnFailure()) {
// throw new MailEngineException(sfe); // throw new MailEngineException(sfe);
// } // }
throw new MailEngineException(sfe); throw new MailEngineException(sfe);
} catch (Exception e) { } catch (Exception e) {
throw new MailEngineException(e); throw new MailEngineException(e);
} }
if (_log.isDebugEnabled()) { if (_log.isDebugEnabled()) {
_log.debug("Sending mail takes " + (System.currentTimeMillis() - startTime) + " ms"); _log.debug("Sending mail takes " + (System.currentTimeMillis() - startTime) + " ms");
} }
} }
public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc, InternetAddress[] bcc, public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc,
String subject, String body) throws MailEngineException { 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, public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc,
String subject, String body, boolean htmlFormat, InternetAddress[] replyTo, String messageId, String inReplyTo) InternetAddress[] bcc, String subject, String body, boolean htmlFormat,
throws MailEngineException { 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 public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc, String subject,
send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc, String subject, String body) String body) throws MailEngineException {
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, public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc, String subject,
String body, boolean htmlFormat) throws MailEngineException { 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) public static void send(InternetAddress from, InternetAddress[] to, String subject, String body)
throws MailEngineException { 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) public static void send(InternetAddress from, InternetAddress[] to, String subject, String body,
throws MailEngineException { 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 send(mailMessage.getFrom(), mailMessage.getTo(), mailMessage.getCC(), mailMessage.getBCC(),
.getBulkAddresses(), mailMessage.getSubject(), mailMessage.getBody(), mailMessage.isHTMLFormat(), mailMessage mailMessage.getBulkAddresses(), mailMessage.getSubject(), mailMessage.getBody(),
.getReplyTo(), mailMessage.getMessageId(), mailMessage.getInReplyTo(), mailMessage.getFileAttachments(), mailMessage.isHTMLFormat(), mailMessage.getReplyTo(), mailMessage.getMessageId(),
mailMessage.getSMTPAccount()); 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 { try {
send(new InternetAddress(from), new InternetAddress(to), subject, body); send(new InternetAddress(from), new InternetAddress(to), subject, body);
} catch (AddressException ae) { } catch (AddressException ae) {
throw new MailEngineException(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)) { if ((batchSize == _BATCH_SIZE) && (index == 0)) {
return addresses; return addresses;
} else if (batchSize == _BATCH_SIZE) { } else if (batchSize == _BATCH_SIZE) {
return null; return null;
} }
int start = index * batchSize; int start = index * batchSize;
if (start > addresses.length) { if (start > addresses.length) {
return null; return null;
} }
int end = ((index + 1) * batchSize); int end = ((index + 1) * batchSize);
if (end > addresses.length) { if (end > addresses.length) {
end = addresses.length; end = addresses.length;
} }
return ArrayUtil.subset(addresses, start, end); return ArrayUtil.subset(addresses, start, end);
} }
private static Properties _getProperties(Account account) { private static Properties _getProperties(Account account) {
Properties properties = new Properties(); Properties properties = new Properties();
String protocol = account.getProtocol(); String protocol = account.getProtocol();
properties.setProperty("mail.transport.protocol", protocol); properties.setProperty("mail.transport.protocol", protocol);
properties.setProperty("mail." + protocol + ".host", account.getHost()); properties.setProperty("mail." + protocol + ".host", account.getHost());
properties.setProperty("mail." + protocol + ".port", String.valueOf(account.getPort())); properties.setProperty("mail." + protocol + ".port", String.valueOf(account.getPort()));
if (account.isRequiresAuthentication()) { if (account.isRequiresAuthentication()) {
properties.setProperty("mail." + protocol + ".auth", "true"); properties.setProperty("mail." + protocol + ".auth", "true");
properties.setProperty("mail." + protocol + ".user", account.getUser()); properties.setProperty("mail." + protocol + ".user", account.getUser());
properties.setProperty("mail." + protocol + ".password", account.getPassword()); properties.setProperty("mail." + protocol + ".password", account.getPassword());
} }
if (account.isSecure()) { if (account.isSecure()) {
properties.setProperty("mail." + protocol + ".socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.setProperty("mail." + protocol + ".socketFactory.class",
properties.setProperty("mail." + protocol + ".socketFactory.fallback", "false"); "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail." + protocol + ".socketFactory.port", String.valueOf(account.getPort())); 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) { private static String _getSMTPProperty(Session session, String suffix) {
String protocol = GetterUtil.getString(session.getProperty("mail.transport.protocol")); String protocol = GetterUtil.getString(session.getProperty("mail.transport.protocol"));
if (protocol.equals(Account.PROTOCOL_SMTPS)) { if (protocol.equals(Account.PROTOCOL_SMTPS)) {
return session.getProperty("mail.smtps." + suffix); return session.getProperty("mail.smtps." + suffix);
} else { } else {
return session.getProperty("mail.smtp." + suffix); return session.getProperty("mail.smtp." + suffix);
} }
} }
// private static boolean _isThrowsExceptionOnFailure() { // private static boolean _isThrowsExceptionOnFailure() {
// return GetterUtil.getBoolean(PropsUtil.get(PropsKeys.MAIL_THROWS_EXCEPTION_ON_FAILURE)); // return
// } // GetterUtil.getBoolean(PropsUtil.get(PropsKeys.MAIL_THROWS_EXCEPTION_ON_FAILURE));
// }
private static void _send(Session session, Message message, InternetAddress[] bulkAddresses, int batchSize) private static void _send(Session session, Message message, InternetAddress[] bulkAddresses, int batchSize)
throws MailEngineException { throws MailEngineException {
try { try {
boolean smtpAuth = GetterUtil.getBoolean(_getSMTPProperty(session, "auth"), false); boolean smtpAuth = GetterUtil.getBoolean(_getSMTPProperty(session, "auth"), false);
String smtpHost = _getSMTPProperty(session, "host"); String smtpHost = _getSMTPProperty(session, "host");
int smtpPort = GetterUtil.getInteger(_getSMTPProperty(session, "port"), Account.PORT_SMTP); int smtpPort = GetterUtil.getInteger(_getSMTPProperty(session, "port"), Account.PORT_SMTP);
String user = _getSMTPProperty(session, "user"); String user = _getSMTPProperty(session, "user");
String password = _getSMTPProperty(session, "password"); 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)) { if (ArrayUtil.isNotEmpty(bulkAddresses)) {
addresses = bulkAddresses; addresses = bulkAddresses;
} else { } else {
addresses = message.getAllRecipients(); addresses = message.getAllRecipients();
} }
for (int i = 0;; i++) { for (int i = 0;; i++) {
Address[] batchAddresses = _getBatchAddresses(addresses, i, batchSize); Address[] batchAddresses = _getBatchAddresses(addresses, i, batchSize);
if (ArrayUtil.isEmpty(batchAddresses)) { if (ArrayUtil.isEmpty(batchAddresses)) {
break; break;
} }
transport.sendMessage(message, batchAddresses); transport.sendMessage(message, batchAddresses);
} }
transport.close(); transport.close();
} else { } else {
if (ArrayUtil.isNotEmpty(bulkAddresses)) { if (ArrayUtil.isNotEmpty(bulkAddresses)) {
int curBatch = 0; int curBatch = 0;
Address[] portion = _getBatchAddresses(bulkAddresses, curBatch, batchSize); Address[] portion = _getBatchAddresses(bulkAddresses, curBatch, batchSize);
while (ArrayUtil.isNotEmpty(portion)) { while (ArrayUtil.isNotEmpty(portion)) {
Transport.send(message, portion); Transport.send(message, portion);
curBatch++; curBatch++;
portion = _getBatchAddresses(bulkAddresses, curBatch, batchSize); portion = _getBatchAddresses(bulkAddresses, curBatch, batchSize);
} }
} else { } else {
Transport.send(message); Transport.send(message);
} }
} }
} catch (MessagingException me) { } catch (MessagingException me) {
if (me.getNextException() instanceof SocketException) { if (me.getNextException() instanceof SocketException) {
if (_log.isWarnEnabled()) { if (_log.isWarnEnabled()) {
_log.warn("Failed to connect to a valid mail server. Please " + "make sure one is properly configured. " _log.warn("Failed to connect to a valid mail server. Please "
+ me.getMessage()); + "make sure one is properly configured. " + me.getMessage());
} }
} else { } else {
LogUtil.log(_log, me); LogUtil.log(_log, me);
} }
// if (_isThrowsExceptionOnFailure()) { // if (_isThrowsExceptionOnFailure()) {
// throw new MailEngineException(me); // 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 { 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 { 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 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 { public static String evaluate(String input) throws Exception {
return evaluate(input, null); 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, velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
com.liferay.portal.kernel.util.PropsUtil.get(PropsKeys.VELOCITY_ENGINE_LOGGER)); com.liferay.portal.kernel.util.PropsUtil.get(PropsKeys.VELOCITY_ENGINE_LOGGER));
velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM + ".log4j.category", velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM + ".log4j.category",
com.liferay.portal.kernel.util.PropsUtil.get(PropsKeys.VELOCITY_ENGINE_LOGGER_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()) { while (iteratiorKeys.hasNext()) {
String key = iteratiorKeys.next(); String key = iteratiorKeys.next();
if (Validator.isNotNull(key)) { if (Validator.isNotNull(key)) {
velocityContext.put(key, variables.getString(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.namespace=portos_Mail
build.number=75 build.number=76
build.date=1592823810355 build.date=1603286289030
build.auto.upgrade=true build.auto.upgrade=true
## ##

Caricamento…
Annulla
Salva