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. 684
      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/MailManagerUtil.java
  14. 8
      liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/util/MailSenderUtil.java
  15. 64
      liferay-plugins-sdk-6.2/portlets/portos-mail-manager-portlet/docroot/WEB-INF/src/it/tref/liferay/portos/mailmanager/util/VelocityUtil.java
  16. 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);
} }
} }

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

@ -97,7 +97,7 @@ public class MailManagerUtil {
if (Validator.isNull(ccn)) { if (Validator.isNull(ccn)) {
ccn = emailTemplate.getCcn(); ccn = emailTemplate.getCcn();
} }
return EmailLocalServiceUtil.addEmail(className, classPK, emailTemplate.getFrom(), return EmailLocalServiceUtil.addEmail(className, classPK, emailTemplate.getFrom(),
StringUtil.split(to, StringPool.COMMA), StringUtil.split(cc, StringPool.COMMA), StringUtil.split(to, StringPool.COMMA), StringUtil.split(cc, StringPool.COMMA),
StringUtil.split(ccn, StringPool.COMMA), subject, body, true, fileAttachments, sendSync, StringUtil.split(ccn, StringPool.COMMA), subject, body, true, fileAttachments, sendSync,

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

@ -29,13 +29,13 @@ import javax.mail.internet.InternetAddress;
import org.apache.commons.lang.StringUtils; 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 {
_log.info("sendMail to: " + StringUtils.join(email.getToArray(), ", ")); _log.info("sendMail to: " + StringUtils.join(email.getToArray(), ", "));
InternetAddress from = toInternetAddress(email.getFrom()); InternetAddress from = toInternetAddress(email.getFrom());
InternetAddress[] to = toInternetAddresses(email.getToArray()); InternetAddress[] to = toInternetAddresses(email.getToArray());
InternetAddress[] cc = toInternetAddresses(email.getCcArray()); InternetAddress[] cc = toInternetAddresses(email.getCcArray());

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