Faxtomail-commits
Threads by month
- ----- 2026 -----
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
August 2014
- 4 participants
- 141 discussions
r477 - in trunk: faxtomail-service/src/main/java/com/franciaflex/faxtomail/services faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job
by echatellier@users.forge.codelutin.com 06 Aug '14
by echatellier@users.forge.codelutin.com 06 Aug '14
06 Aug '14
Author: echatellier
Date: 2014-08-06 10:46:09 +0200 (Wed, 06 Aug 2014)
New Revision: 477
Url: http://forge.codelutin.com/projects/faxtomail/repository/revisions/477
Log:
call specific method to get service when possible
Modified:
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/FaxToMailApplicationContext.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/FaxToMailInterceptor.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/ClientUpdateJob.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/EDIManagementJob.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/MailFilterJob.java
Modified: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java 2014-08-06 08:16:34 UTC (rev 476)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java 2014-08-06 08:46:09 UTC (rev 477)
@@ -32,10 +32,12 @@
import java.util.Date;
import com.franciaflex.faxtomail.persistence.entities.FaxToMailTopiaApplicationContext;
+import com.franciaflex.faxtomail.services.service.ClientService;
import com.franciaflex.faxtomail.services.service.ConfigurationService;
import com.franciaflex.faxtomail.services.service.ConfigurationServiceImpl;
import com.franciaflex.faxtomail.services.service.EmailService;
import com.franciaflex.faxtomail.services.service.EmailServiceImpl;
+import com.franciaflex.faxtomail.services.service.InitFaxToMailService;
import com.franciaflex.faxtomail.services.service.LdapServiceImpl;
import com.franciaflex.faxtomail.services.service.MailFolderService;
import com.franciaflex.faxtomail.services.service.MailFolderServiceImpl;
@@ -45,6 +47,7 @@
import com.franciaflex.faxtomail.services.service.UserServiceImpl;
import com.franciaflex.faxtomail.services.service.ValidationService;
import com.franciaflex.faxtomail.services.service.ValidationServiceImpl;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.jaxx.application.ApplicationTechnicalException;
@@ -233,7 +236,15 @@
public ConfigurationService getConfigurationService() {
return newService(ConfigurationService.class);
}
+
+ public InitFaxToMailService getInitFaxToMailService() {
+ return newService(InitFaxToMailService.class);
+ }
+ public ClientService getClientService() {
+ return newService(ClientService.class);
+ }
+
@Override
public void close() throws IOException {
if (persistenceContext != null) {
Modified: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java 2014-08-06 08:16:34 UTC (rev 476)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java 2014-08-06 08:46:09 UTC (rev 477)
@@ -140,7 +140,7 @@
serviceContext.setApplicationConfig(getApplicationConfig());
- InitFaxToMailService initFaxToMailService = serviceContext.newService(InitFaxToMailService.class);
+ InitFaxToMailService initFaxToMailService = serviceContext.getInitFaxToMailService();
initFaxToMailService.init();
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java 2014-08-06 08:16:34 UTC (rev 476)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java 2014-08-06 08:46:09 UTC (rev 477)
@@ -215,11 +215,10 @@
topiaApplicationContext = new FaxToMailTopiaApplicationContext(config.getTopiaProperties());
FaxToMailServiceContext serviceContext = newServiceContext();
- InitFaxToMailService initExtranetService =
- serviceContext.newService(InitFaxToMailService.class);
+ InitFaxToMailService initFaxToMailService =
+ serviceContext.getInitFaxToMailService();
+ initFaxToMailService.init();
- initExtranetService.init();
-
Map<Class, State> additionalStates = Maps.newHashMap();
additionalStates.put(BeanFilterableComboBox.class, new BeanFilterableComboBoxState());
additionalStates.put(BeanDoubleList.class, new BeanDoubleListState());
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/FaxToMailApplicationContext.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/FaxToMailApplicationContext.java 2014-08-06 08:16:34 UTC (rev 476)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/FaxToMailApplicationContext.java 2014-08-06 08:46:09 UTC (rev 477)
@@ -152,10 +152,10 @@
FaxToMailServiceContext serviceContext = newServiceContext(persistenceContext);
- InitFaxToMailService initExtranetService =
- serviceContext.newService(InitFaxToMailService.class);
+ InitFaxToMailService initFaxToMailService =
+ serviceContext.getInitFaxToMailService();
- initExtranetService.init();
+ initFaxToMailService.init();
persistenceContext.close();
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/FaxToMailInterceptor.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/FaxToMailInterceptor.java 2014-08-06 08:16:34 UTC (rev 476)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/FaxToMailInterceptor.java 2014-08-06 08:46:09 UTC (rev 477)
@@ -144,7 +144,7 @@
protected void populateUser(FaxToMailSession faxToMailSession, FaxToMailServiceContext serviceContext) {
if (StringUtils.isNotBlank(faxToMailSession.getAuthenticatedUserId())) {
- LdapService ldapService = serviceContext.newService(LdapService.class);
+ LdapService ldapService = serviceContext.getLdapService();
// return can be null
FaxToMailUser user = ldapService.getUserBean(faxToMailSession.getAuthenticatedUserId());
faxToMailSession.setAuthenticatedFaxToMailUser(user);
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/ClientUpdateJob.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/ClientUpdateJob.java 2014-08-06 08:16:34 UTC (rev 476)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/ClientUpdateJob.java 2014-08-06 08:46:09 UTC (rev 477)
@@ -60,7 +60,7 @@
log.debug("Running ClientUpdateJob at " + serviceContext.getNow());
}
- ClientService clientService = serviceContext.newService(ClientService.class);
+ ClientService clientService = serviceContext.getClientService();
clientService.updateNewClients();
if (log.isDebugEnabled()) {
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/EDIManagementJob.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/EDIManagementJob.java 2014-08-06 08:16:34 UTC (rev 476)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/EDIManagementJob.java 2014-08-06 08:46:09 UTC (rev 477)
@@ -58,7 +58,7 @@
log.debug("Running EDIManagementJob at " + serviceContext.getNow());
}
- EmailService emailService = serviceContext.newService(EmailService.class);
+ EmailService emailService = serviceContext.getEmailService();
emailService.transmitPendingDemandsToEdi();
if (log.isDebugEnabled()) {
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/MailFilterJob.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/MailFilterJob.java 2014-08-06 08:16:34 UTC (rev 476)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/MailFilterJob.java 2014-08-06 08:46:09 UTC (rev 477)
@@ -144,11 +144,11 @@
log.debug("Running MailFilterJob at " + serviceContext.getNow());
}
- emailService = serviceContext.newService(EmailService.class);
- mailFolderService = serviceContext.newService(MailFolderService.class);
- configurationService = serviceContext.newService(ConfigurationService.class);
- clientService = serviceContext.newService(ClientService.class);
- decoratorService = serviceContext.newService(DecoratorService.class);
+ emailService = serviceContext.getEmailService();
+ mailFolderService = serviceContext.getMailFolderService();
+ configurationService = serviceContext.getConfigurationService();
+ clientService = serviceContext.getClientService();
+ decoratorService = serviceContext.getDecoratorService();
Collection<EmailAccount> emailAccounts = configurationService.getEmailAccounts();
1
0
r476 - in trunk: . faxtomail-persistence/src/main/java/com/franciaflex/faxtomail faxtomail-persistence/src/main/xmi faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/attachment faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande
by echatellier@users.forge.codelutin.com 06 Aug '14
by echatellier@users.forge.codelutin.com 06 Aug '14
06 Aug '14
Author: echatellier
Date: 2014-08-06 10:16:34 +0200 (Wed, 06 Aug 2014)
New Revision: 476
Url: http://forge.codelutin.com/projects/faxtomail/repository/revisions/476
Log:
Update libs. Fix build.
Modified:
trunk/faxtomail-persistence/src/main/java/com/franciaflex/faxtomail/FaxToMailConfiguration.java
trunk/faxtomail-persistence/src/main/xmi/faxtomail.properties
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/attachment/AttachmentEditorUIHandler.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandeUIModel.java
trunk/pom.xml
Modified: trunk/faxtomail-persistence/src/main/java/com/franciaflex/faxtomail/FaxToMailConfiguration.java
===================================================================
--- trunk/faxtomail-persistence/src/main/java/com/franciaflex/faxtomail/FaxToMailConfiguration.java 2014-08-06 06:00:57 UTC (rev 475)
+++ trunk/faxtomail-persistence/src/main/java/com/franciaflex/faxtomail/FaxToMailConfiguration.java 2014-08-06 08:16:34 UTC (rev 476)
@@ -49,7 +49,7 @@
import org.nuiton.jaxx.application.ApplicationConfiguration;
import org.nuiton.jaxx.application.ApplicationIOUtil;
import org.nuiton.jaxx.application.ApplicationTechnicalException;
-import org.nuiton.util.Version;
+import org.nuiton.util.version.Version;
import com.google.common.base.Charsets;
import com.google.common.collect.Maps;
Modified: trunk/faxtomail-persistence/src/main/xmi/faxtomail.properties
===================================================================
--- trunk/faxtomail-persistence/src/main/xmi/faxtomail.properties 2014-08-06 06:00:57 UTC (rev 475)
+++ trunk/faxtomail-persistence/src/main/xmi/faxtomail.properties 2014-08-06 08:16:34 UTC (rev 476)
@@ -25,7 +25,6 @@
model.tagValue.constantPrefix=PROPERTY_
model.tagValue.hibernateAttributeType.java.lang.String=text
model.tagValue.useEnumerationName=true
-model.tagValue.doNotGenerateBooleanGetMethods=true
# EtatAttente
com.franciaflex.faxtomail.persistence.entities.EtatAttente.attribute.label.tagvalue.naturalId=true
@@ -48,7 +47,7 @@
com.franciaflex.faxtomail.persistence.entities.NewClient.attribute.brand.tagvalue.notNull=true
com.franciaflex.faxtomail.persistence.entities.NewClient.attribute.type.tagvalue.notNull=true
-#�EdiReturn
+#\u00a0EdiReturn
com.franciaflex.faxtomail.persistence.entities.EdiReturn.attribute.rangeRowTopiaId.tagvalue.notNull=true
# EmailAccount
@@ -67,7 +66,7 @@
# AttachmentFile
com.franciaflex.faxtomail.persistence.entities.AttachmentFile.attribute.filename.tagvalue.notNull=true
com.franciaflex.faxtomail.persistence.entities.AttachmentFile.attribute.content.tagvalue.notNull=true
-# il faut mettre une valeur > � 8000 pour que la mapping g�n�re un type varbinary(max)
+# il faut mettre une valeur > \u00e0 8000 pour que la mapping g\u00e9n\u00e8re un type varbinary(max)
com.franciaflex.faxtomail.persistence.entities.AttachmentFile.attribute.content.tagValue.hibernateAttributeType=binary
com.franciaflex.faxtomail.persistence.entities.AttachmentFile.attribute.content.tagvalue.length=9999999
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/attachment/AttachmentEditorUIHandler.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/attachment/AttachmentEditorUIHandler.java 2014-08-06 06:00:57 UTC (rev 475)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/attachment/AttachmentEditorUIHandler.java 2014-08-06 08:16:34 UTC (rev 476)
@@ -244,7 +244,7 @@
if (attachment != null) {
JLabel label = getAttachmentNameLabel();
- String actionIconName = Boolean.TRUE.equals(attachment.getAddedByUser()) ? "user" : "email";
+ String actionIconName = attachment.isAddedByUser() ? "user" : "email";
Icon icon = SwingUtil.createActionIcon(actionIconName);
label.setIcon(icon);
}
@@ -271,7 +271,7 @@
if (attachment != null) {
JLabel label = attachmentItem.getAttachmentNameLabel();
- String actionIconName = Boolean.TRUE.equals(attachment.getAddedByUser()) ? "user" : "email";
+ String actionIconName = attachment.isAddedByUser() ? "user" : "email";
Icon icon = SwingUtil.createActionIcon(actionIconName);
label.setIcon(icon);
}
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandeUIModel.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandeUIModel.java 2014-08-06 06:00:57 UTC (rev 475)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandeUIModel.java 2014-08-06 08:16:34 UTC (rev 476)
@@ -224,14 +224,6 @@
return entity;
}
- public Boolean getFax() {
- return editObject.getFax();
- }
-
- public void setFax(Boolean fax) {
- editObject.setFax(fax);
- }
-
public String getTopiaId() {
return editObject.getTopiaId();
}
@@ -328,7 +320,7 @@
}
public void setFax(boolean fax) {
- Object oldValue = isFax();
+ boolean oldValue = isFax();
editObject.setFax(fax);
firePropertyChanged(Email.PROPERTY_FAX, oldValue, fax);
}
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2014-08-06 06:00:57 UTC (rev 475)
+++ trunk/pom.xml 2014-08-06 08:16:34 UTC (rev 476)
@@ -96,21 +96,21 @@
<!-- libraries version -->
- <nuitonI18nVersion>3.2</nuitonI18nVersion>
- <nuitonConfigVersion>3.0-alpha-2</nuitonConfigVersion>
- <nuitonCsvVersion>3.0-rc-2</nuitonCsvVersion>
+ <nuitonI18nVersion>3.3</nuitonI18nVersion>
+ <nuitonConfigVersion>3.0-alpha-4</nuitonConfigVersion>
+ <nuitonCsvVersion>3.0-rc-4</nuitonCsvVersion>
<nuitonDecoratorVersion>3.0-alpha-3</nuitonDecoratorVersion>
<nuitonUpdaterVersion>3.0-alpha-2</nuitonUpdaterVersion>
- <nuitonUtilsVersion>3.0-rc-4</nuitonUtilsVersion>
- <nuitonValidatorVersion>3.0-rc-1</nuitonValidatorVersion>
+ <nuitonUtilsVersion>3.0-rc-5</nuitonUtilsVersion>
+ <nuitonValidatorVersion>3.0-rc-2</nuitonValidatorVersion>
<nuitonWebVersion>1.16</nuitonWebVersion>
- <eugeneVersion>3.0-SNAPSHOT</eugeneVersion>
+ <eugeneVersion>2.13</eugeneVersion>
<topiaVersion>3.0-SNAPSHOT</topiaVersion>
<hibernateVersion>4.3.6.Final</hibernateVersion>
<h2Version>1.3.176</h2Version>
- <jaxxVersion>2.8.7</jaxxVersion>
+ <jaxxVersion>2.9</jaxxVersion>
<!-- do not upgrade to 1.6.5-1 -->
<swingXVersion>1.6.4</swingXVersion>
<xworkVersion>2.3.15.1</xworkVersion>
1
0
r475 - trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service
by athimel@users.forge.codelutin.com 06 Aug '14
by athimel@users.forge.codelutin.com 06 Aug '14
06 Aug '14
Author: athimel
Date: 2014-08-06 08:00:57 +0200 (Wed, 06 Aug 2014)
New Revision: 475
Url: http://forge.codelutin.com/projects/faxtomail/repository/revisions/475
Log:
Restore normal test behavior
Modified:
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/ClientServiceTest.java
Modified: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/ClientServiceTest.java
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/ClientServiceTest.java 2014-08-05 21:17:26 UTC (rev 474)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/ClientServiceTest.java 2014-08-06 06:00:57 UTC (rev 475)
@@ -64,9 +64,11 @@
public void testAddNewClientInTmpTable() {
ClientService clientService = newService(ClientService.class);
+ NewClientTopiaDao newClientDao = getServiceContext().getPersistenceContext().getNewClientDao();
+ ClientTopiaDao clientDao = getServiceContext().getPersistenceContext().getClientDao();
// asserts
- Assert.assertNull(getServiceContext().getPersistenceContext().getClientDao().forEmailAddressEquals("gerard.menvussa(a)lutin.com").findAnyOrNull());
+ Assert.assertNull(clientDao.forEmailAddressEquals("gerard.menvussa(a)lutin.com").findAnyOrNull());
// add new clients
NewClient newClient = new NewClientImpl();
@@ -74,25 +76,25 @@
newClient.setBrand("FX");
newClient.setEmailAddress("gerard.menvussa(a)lutin.com");
newClient.setType(NewClientType.UPDATE);
- newClient = getServiceContext().getPersistenceContext().getNewClientDao().create(newClient);
+ newClient = newClientDao.create(newClient);
// precedure de mise à jour
clientService.updateNewClients();
// asserts
- Assert.assertNotNull(getServiceContext().getPersistenceContext().getClientDao().forEmailAddressEquals("gerard.menvussa(a)lutin.com").findAnyOrNull());
+ Assert.assertNotNull(clientDao.forEmailAddressEquals("gerard.menvussa(a)lutin.com").findAnyOrNull());
// add new clients
NewClient deleteClient = new NewClientImpl();
deleteClient.setCode("99154");
deleteClient.setBrand("FX");
deleteClient.setType(NewClientType.DELETION);
- deleteClient = getServiceContext().getPersistenceContext().getNewClientDao().create(deleteClient);
+ deleteClient = newClientDao.create(deleteClient);
// precedure de mise à jour
clientService.updateNewClients();
// asserts
- Assert.assertNull(getServiceContext().getPersistenceContext().getClientDao().forCodeEquals("99154").findAnyOrNull());
+ Assert.assertNull(clientDao.forCodeEquals("99154").findAnyOrNull());
}
}
1
0
r474 - in trunk: faxtomail-service/src/main/java/com/franciaflex/faxtomail/services faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail
by athimel@users.forge.codelutin.com 05 Aug '14
by athimel@users.forge.codelutin.com 05 Aug '14
05 Aug '14
Author: athimel
Date: 2014-08-05 23:17:26 +0200 (Tue, 05 Aug 2014)
New Revision: 474
Url: http://forge.codelutin.com/projects/faxtomail/repository/revisions/474
Log:
Fix ServiceContext creation
Modified:
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceFactory.java
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/ClientServiceTest.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/FaxToMailApplicationContext.java
Modified: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java 2014-08-05 14:46:26 UTC (rev 473)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java 2014-08-05 21:17:26 UTC (rev 474)
@@ -69,15 +69,26 @@
protected FaxToMailServiceFactory serviceFactory;
- public FaxToMailServiceContext(FaxToMailTopiaApplicationContext topiaApplicationContext) {
+ public static FaxToMailServiceContext newServiceContext(FaxToMailTopiaApplicationContext applicationContext) {
+ return new FaxToMailServiceContext(applicationContext, new FaxToMailProxiedServiceFactory());
+ }
+
+ public static FaxToMailServiceContext newDirectServiceContext(FaxToMailTopiaApplicationContext applicationContext) {
+ return new FaxToMailServiceContext(applicationContext, new FaxToMailDefaultServiceFactory());
+ }
+
+ private FaxToMailServiceContext(FaxToMailTopiaApplicationContext topiaApplicationContext, FaxToMailServiceFactory serviceFactory) {
Preconditions.checkNotNull(topiaApplicationContext, "Cannot create an ServiceContext without an ApplicationContext");
+ Preconditions.checkNotNull(serviceFactory, "Cannot create an ServiceContext without a ServiceFactory");
this.topiaApplicationContext = topiaApplicationContext;
- this.serviceFactory = new FaxToMailProxiedServiceFactory();
+ this.serviceFactory = serviceFactory;
+ this.serviceFactory.setServiceContext(this);
}
private FaxToMailServiceContext(FaxToMailServiceContext delegateServiceContext, FaxToMailServiceFactory serviceFactory) {
this.delegateServiceContext = delegateServiceContext;
this.serviceFactory = serviceFactory;
+ this.serviceFactory.setServiceContext(this);
}
public FaxToMailConfiguration getApplicationConfig() {
@@ -115,10 +126,11 @@
return serviceFactory.newService(serviceInterfaceClass);
}
- public class FaxToMailDefaultServiceFactory implements FaxToMailServiceFactory {
+ public static class FaxToMailDefaultServiceFactory implements FaxToMailServiceFactory {
protected FaxToMailServiceContext serviceContext;
+ @Override
public void setServiceContext(FaxToMailServiceContext serviceContext) {
this.serviceContext = serviceContext;
}
@@ -153,25 +165,32 @@
}
}
- public class FaxToMailProxiedServiceFactory implements FaxToMailServiceFactory {
+ public static class FaxToMailProxiedServiceFactory implements FaxToMailServiceFactory {
protected FaxToMailDefaultServiceFactory defaultServiceFactory;
protected FaxToMailServiceContext subServiceContext;
+ protected FaxToMailServiceContext serviceContext;
+
@Override
+ public void setServiceContext(FaxToMailServiceContext serviceContext) {
+ this.serviceContext = serviceContext;
+ }
+
+ @Override
public <E extends FaxToMailService> E newService(Class<E> serviceInterfaceClass) {
if (defaultServiceFactory == null) {
defaultServiceFactory = new FaxToMailDefaultServiceFactory();
- subServiceContext = new FaxToMailServiceContext(FaxToMailServiceContext.this, defaultServiceFactory);
+ subServiceContext = new FaxToMailServiceContext(serviceContext, defaultServiceFactory);
defaultServiceFactory.setServiceContext(subServiceContext);
}
E realService = defaultServiceFactory.newService(serviceInterfaceClass);
E service = (E) Proxy.newProxyInstance(serviceInterfaceClass.getClassLoader(), new Class[]{serviceInterfaceClass},
- new FaxToMailServiceInvocationHandler(realService, FaxToMailServiceContext.this));
+ new FaxToMailServiceInvocationHandler(realService, serviceContext));
return service;
Modified: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceFactory.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceFactory.java 2014-08-05 14:46:26 UTC (rev 473)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceFactory.java 2014-08-05 21:17:26 UTC (rev 474)
@@ -5,6 +5,8 @@
*/
public interface FaxToMailServiceFactory {
+ void setServiceContext(FaxToMailServiceContext serviceContext);
+
public <E extends FaxToMailService> E newService(Class<E> serviceInterfaceClass);
}
Modified: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java 2014-08-05 14:46:26 UTC (rev 473)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java 2014-08-05 21:17:26 UTC (rev 474)
@@ -136,7 +136,7 @@
FaxToMailTopiaApplicationContext applicationContext = newApplicationContext(DATABASE_REF);
- FaxToMailServiceContext serviceContext = new FaxToMailServiceContext(applicationContext);
+ FaxToMailServiceContext serviceContext = FaxToMailServiceContext.newDirectServiceContext(applicationContext);
serviceContext.setApplicationConfig(getApplicationConfig());
@@ -256,7 +256,7 @@
if (serviceContext == null) {
- FaxToMailServiceContext serviceContext = new FaxToMailServiceContext(getApplicationContext());
+ FaxToMailServiceContext serviceContext = FaxToMailServiceContext.newDirectServiceContext(getApplicationContext());
serviceContext.setApplicationConfig(getApplicationConfig());
Modified: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/ClientServiceTest.java
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/ClientServiceTest.java 2014-08-05 14:46:26 UTC (rev 473)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/ClientServiceTest.java 2014-08-05 21:17:26 UTC (rev 474)
@@ -64,11 +64,9 @@
public void testAddNewClientInTmpTable() {
ClientService clientService = newService(ClientService.class);
- NewClientTopiaDao newClientDao = getServiceContext().getPersistenceContext().getNewClientDao();
- ClientTopiaDao clientDao = getServiceContext().getPersistenceContext().getClientDao();
// asserts
- Assert.assertNull(clientDao.forEmailAddressEquals("gerard.menvussa(a)lutin.com").findAnyOrNull());
+ Assert.assertNull(getServiceContext().getPersistenceContext().getClientDao().forEmailAddressEquals("gerard.menvussa(a)lutin.com").findAnyOrNull());
// add new clients
NewClient newClient = new NewClientImpl();
@@ -76,25 +74,25 @@
newClient.setBrand("FX");
newClient.setEmailAddress("gerard.menvussa(a)lutin.com");
newClient.setType(NewClientType.UPDATE);
- newClient = newClientDao.create(newClient);
+ newClient = getServiceContext().getPersistenceContext().getNewClientDao().create(newClient);
// precedure de mise à jour
clientService.updateNewClients();
// asserts
- Assert.assertNotNull(clientDao.forEmailAddressEquals("gerard.menvussa(a)lutin.com").findAnyOrNull());
+ Assert.assertNotNull(getServiceContext().getPersistenceContext().getClientDao().forEmailAddressEquals("gerard.menvussa(a)lutin.com").findAnyOrNull());
// add new clients
NewClient deleteClient = new NewClientImpl();
deleteClient.setCode("99154");
deleteClient.setBrand("FX");
deleteClient.setType(NewClientType.DELETION);
- deleteClient = newClientDao.create(deleteClient);
+ deleteClient = getServiceContext().getPersistenceContext().getNewClientDao().create(deleteClient);
// precedure de mise à jour
clientService.updateNewClients();
// asserts
- Assert.assertNull(clientDao.forCodeEquals("99154").findAnyOrNull());
+ Assert.assertNull(getServiceContext().getPersistenceContext().getClientDao().forCodeEquals("99154").findAnyOrNull());
}
}
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java 2014-08-05 14:46:26 UTC (rev 473)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java 2014-08-05 21:17:26 UTC (rev 474)
@@ -472,7 +472,7 @@
//------------------------------------------------------------------------//
public FaxToMailServiceContext newServiceContext() {
- FaxToMailServiceContext serviceContext = new FaxToMailServiceContext(topiaApplicationContext);
+ FaxToMailServiceContext serviceContext = FaxToMailServiceContext.newServiceContext(topiaApplicationContext);
serviceContext.setApplicationConfig(config);
return serviceContext;
}
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/FaxToMailApplicationContext.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/FaxToMailApplicationContext.java 2014-08-05 14:46:26 UTC (rev 473)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/FaxToMailApplicationContext.java 2014-08-05 21:17:26 UTC (rev 474)
@@ -71,8 +71,9 @@
public FaxToMailServiceContext newServiceContext(FaxToMailTopiaPersistenceContext persistenceContext) {
+ // FIXME AThimel 05/08/14 Check if newDirectServiceContext or newServiceContext must be used
FaxToMailServiceContext newServiceContext =
- new FaxToMailServiceContext(topiaApplicationContext);
+ FaxToMailServiceContext.newDirectServiceContext(topiaApplicationContext);
FaxToMailConfiguration applicationConfig = getApplicationConfig();
1
0
r473 - trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services
by athimel@users.forge.codelutin.com 05 Aug '14
by athimel@users.forge.codelutin.com 05 Aug '14
05 Aug '14
Author: athimel
Date: 2014-08-05 16:46:26 +0200 (Tue, 05 Aug 2014)
New Revision: 473
Url: http://forge.codelutin.com/projects/faxtomail/repository/revisions/473
Log:
Manage exception in InvocationHandler
Modified:
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceInvocationHandler.java
Modified: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceInvocationHandler.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceInvocationHandler.java 2014-08-05 14:36:30 UTC (rev 472)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceInvocationHandler.java 2014-08-05 14:46:26 UTC (rev 473)
@@ -3,6 +3,7 @@
import org.apache.commons.io.IOUtils;
import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
@@ -24,7 +25,8 @@
try {
Object result = method.invoke(wrappedService, args);
return result;
-
+ } catch (InvocationTargetException ex) {
+ throw ex.getCause();
} finally {
IOUtils.closeQuietly(serviceContext);
}
1
0
r472 - in trunk: . faxtomail-service/src/main/java/com/franciaflex/faxtomail/services faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service
by athimel@users.forge.codelutin.com 05 Aug '14
by athimel@users.forge.codelutin.com 05 Aug '14
05 Aug '14
Author: athimel
Date: 2014-08-05 16:36:30 +0200 (Tue, 05 Aug 2014)
New Revision: 472
Url: http://forge.codelutin.com/projects/faxtomail/repository/revisions/472
Log:
Fix service instantiation in module services
Added:
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestData.java
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestDataImpl.java
Removed:
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestData.java
Modified:
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceSupport.java
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/ClientServiceTest.java
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/EmailServiceTest.java
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/MailFolderServiceTest.java
trunk/pom.xml
Modified: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java 2014-08-05 13:13:51 UTC (rev 471)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java 2014-08-05 14:36:30 UTC (rev 472)
@@ -53,6 +53,7 @@
import com.franciaflex.faxtomail.persistence.entities.FaxToMailTopiaPersistenceContext;
import com.franciaflex.faxtomail.services.service.LdapService;
import com.franciaflex.faxtomail.services.service.ldap.LdapServiceMock;
+import com.google.common.base.Preconditions;
public class FaxToMailServiceContext implements Closeable {
@@ -69,6 +70,7 @@
protected FaxToMailServiceFactory serviceFactory;
public FaxToMailServiceContext(FaxToMailTopiaApplicationContext topiaApplicationContext) {
+ Preconditions.checkNotNull(topiaApplicationContext, "Cannot create an ServiceContext without an ApplicationContext");
this.topiaApplicationContext = topiaApplicationContext;
this.serviceFactory = new FaxToMailProxiedServiceFactory();
}
Modified: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceSupport.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceSupport.java 2014-08-05 13:13:51 UTC (rev 471)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceSupport.java 2014-08-05 14:36:30 UTC (rev 472)
@@ -65,26 +65,26 @@
}
protected DecoratorService getDecoratorService() {
- return newService(DecoratorServiceImpl.class);
+ return newService(DecoratorService.class);
}
protected ConfigurationService getConfigurationService() {
- return newService(ConfigurationServiceImpl.class);
+ return newService(ConfigurationService.class);
}
protected MailFolderService getMailFolderService() {
- return newService(MailFolderServiceImpl.class);
+ return newService(MailFolderService.class);
}
protected EmailService getEmailService() {
- return newService(EmailServiceImpl.class);
+ return newService(EmailService.class);
}
protected ReferentielService getReferentielService() {
- return newService(ReferentielServiceImpl.class);
+ return newService(ReferentielService.class);
}
protected ClientService getClientService() {
- return newService(ClientServiceImpl.class);
+ return newService(ClientService.class);
}
}
Modified: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java 2014-08-05 13:13:51 UTC (rev 471)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java 2014-08-05 14:36:30 UTC (rev 472)
@@ -256,7 +256,7 @@
if (serviceContext == null) {
- FaxToMailServiceContext serviceContext = new FaxToMailServiceContext(applicationContext);
+ FaxToMailServiceContext serviceContext = new FaxToMailServiceContext(getApplicationContext());
serviceContext.setApplicationConfig(getApplicationConfig());
Modified: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/ClientServiceTest.java
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/ClientServiceTest.java 2014-08-05 13:13:51 UTC (rev 471)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/ClientServiceTest.java 2014-08-05 14:36:30 UTC (rev 472)
@@ -63,7 +63,7 @@
@Test
public void testAddNewClientInTmpTable() {
- ClientService clientService = newService(ClientServiceImpl.class);
+ ClientService clientService = newService(ClientService.class);
NewClientTopiaDao newClientDao = getServiceContext().getPersistenceContext().getNewClientDao();
ClientTopiaDao clientDao = getServiceContext().getPersistenceContext().getClientDao();
Modified: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/EmailServiceTest.java
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/EmailServiceTest.java 2014-08-05 13:13:51 UTC (rev 471)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/EmailServiceTest.java 2014-08-05 14:36:30 UTC (rev 472)
@@ -53,9 +53,9 @@
@Before
public void setUp() throws IOException {
- service = newService(EmailServiceImpl.class);
- referentielService = newService(ReferentielServiceImpl.class);
- userService = newService(UserServiceImpl.class);
+ service = newService(EmailService.class);
+ referentielService = newService(ReferentielService.class);
+ userService = newService(UserService.class);
newService(InitTestData.class).initTestData();
}
Deleted: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestData.java
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestData.java 2014-08-05 13:13:51 UTC (rev 471)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestData.java 2014-08-05 14:36:30 UTC (rev 472)
@@ -1,309 +0,0 @@
-package com.franciaflex.faxtomail.services.service;
-
-/*
- * #%L
- * FaxToMail :: Service
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2014 Franciaflex, Code Lutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/gpl-3.0.html>.
- * #L%
- */
-
-import static org.nuiton.i18n.I18n.t;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import com.franciaflex.faxtomail.persistence.entities.MailField;
-
-import org.apache.commons.lang3.RandomStringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.decorator.Decorator;
-
-import com.franciaflex.faxtomail.persistence.entities.Client;
-import com.franciaflex.faxtomail.persistence.entities.DemandStatus;
-import com.franciaflex.faxtomail.persistence.entities.DemandType;
-import com.franciaflex.faxtomail.persistence.entities.Email;
-import com.franciaflex.faxtomail.persistence.entities.EmailTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.EtatAttente;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.History;
-import com.franciaflex.faxtomail.persistence.entities.HistoryTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.HistoryType;
-import com.franciaflex.faxtomail.persistence.entities.MailFolder;
-import com.franciaflex.faxtomail.persistence.entities.MailFolderTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.Priority;
-import com.franciaflex.faxtomail.persistence.entities.Range;
-import com.franciaflex.faxtomail.persistence.entities.RangeRow;
-import com.franciaflex.faxtomail.persistence.entities.RangeRowTopiaDao;
-import com.franciaflex.faxtomail.services.DecoratorService;
-import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
-import com.franciaflex.faxtomail.services.service.exceptions.InvalidClientException;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-
-/**
- * Test service to manage test data.
- *
- * @author Eric Chatellier
- */
-public class InitTestData extends FaxToMailServiceSupport {
-
- private static final Log log = LogFactory.getLog(InitTestData.class);
-
- /**
- * Import all test data.
- *
- * @throws IOException
- */
- public void initTestData() throws IOException {
- if (log.isDebugEnabled()) {
- log.debug("Init test data");
- }
- ReferentielService referentielService = newService(ReferentielServiceImpl.class);
-
- // import etat attentes
- List<EtatAttente> etatAttentes = null;
- try (InputStream is = InitTestData.class.getResourceAsStream("/csv/etatattentes.csv")) {
- etatAttentes = referentielService.importEtatAttentes(is);
- }
-
- // create folders
- MailFolderTopiaDao folderDao = getPersistenceContext().getMailFolderDao();
- Map<String, MailFolder> foldersByName = new HashMap<>();
- MailFolder franciaflex = folderDao.create(MailFolder.PROPERTY_NAME, "Franciaflex");
-
- // categories
- MailFolder chargesClientelle = folderDao.create(MailFolder.PROPERTY_NAME, "Chargés de clientèle",
- MailFolder.PROPERTY_PARENT, franciaflex,
- MailFolder.PROPERTY_REPLY_ADDRESSES, Lists.newArrayList("no-reply(a)franciaflex.com"));
- franciaflex.addChildren(chargesClientelle);
- foldersByName.put(chargesClientelle.getName(), chargesClientelle);
-
- MailFolder sav = folderDao.create(MailFolder.PROPERTY_NAME, "SAV",
- MailFolder.PROPERTY_PARENT, franciaflex,
- MailFolder.PROPERTY_ETAT_ATTENTES, etatAttentes.subList(0, 1));
- franciaflex.addChildren(sav);
- foldersByName.put(sav.getName(), sav);
-
- // user folders
- MailFolder cyrilFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Cyril",
- MailFolder.PROPERTY_PARENT, chargesClientelle,
- MailFolder.PROPERTY_ETAT_ATTENTES, etatAttentes.subList(1, 2));
- chargesClientelle.addChildren(cyrilFolder);
- foldersByName.put(cyrilFolder.getName(), cyrilFolder);
-
- MailFolder claireFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Claire",
- MailFolder.PROPERTY_PARENT, chargesClientelle);
- chargesClientelle.addChildren(claireFolder);
- foldersByName.put(claireFolder.getName(), claireFolder);
-
- MailFolder agatheFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Agathe",
- MailFolder.PROPERTY_PARENT, chargesClientelle,
- MailFolder.PROPERTY_ETAT_ATTENTES, etatAttentes.subList(2, 3));
- chargesClientelle.addChildren(agatheFolder);
- foldersByName.put(agatheFolder.getName(), agatheFolder);
-
- MailFolder marcFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Marc",
- MailFolder.PROPERTY_PARENT, sav);
- sav.addChildren(marcFolder);
- foldersByName.put(marcFolder.getName(), marcFolder);
-
- MailFolder fredericFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Frédéric",
- MailFolder.PROPERTY_PARENT, sav);
- sav.addChildren(fredericFolder);
- foldersByName.put(fredericFolder.getName(), fredericFolder);
-
- MailFolder jeanneFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Jeanne",
- MailFolder.PROPERTY_PARENT, sav);
- sav.addChildren(jeanneFolder);
- foldersByName.put(jeanneFolder.getName(), jeanneFolder);
-
- // create test users
- FaxToMailUserTopiaDao userDao = getPersistenceContext().getFaxToMailUserDao();
- FaxToMailUser marc = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Lefèbvre",
- FaxToMailUser.PROPERTY_FIRST_NAME, "Marc",
- FaxToMailUser.PROPERTY_LOGIN, "mlefebvre",
- FaxToMailUser.PROPERTY_TRIGRAPH, "MLE");
- FaxToMailUser cyril = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Baillet",
- FaxToMailUser.PROPERTY_FIRST_NAME, "Cyril",
- FaxToMailUser.PROPERTY_LOGIN, "cbaillet",
- FaxToMailUser.PROPERTY_TRIGRAPH, "CBA");
- FaxToMailUser frederic = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Viala",
- FaxToMailUser.PROPERTY_FIRST_NAME, "Frédéric",
- FaxToMailUser.PROPERTY_LOGIN, "fviala",
- FaxToMailUser.PROPERTY_TRIGRAPH, "FVI");
- FaxToMailUser claire = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Marquis",
- FaxToMailUser.PROPERTY_FIRST_NAME, "Claire",
- FaxToMailUser.PROPERTY_LOGIN, "cmarquis",
- FaxToMailUser.PROPERTY_TRIGRAPH, "CMA");
- FaxToMailUser agathe = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Borde",
- FaxToMailUser.PROPERTY_FIRST_NAME, "Agathe",
- FaxToMailUser.PROPERTY_LOGIN, "aborde",
- FaxToMailUser.PROPERTY_TRIGRAPH, "ABO");
- FaxToMailUser jeanne = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Bourgoin",
- FaxToMailUser.PROPERTY_FIRST_NAME, "Jeanne",
- FaxToMailUser.PROPERTY_LOGIN, "jbourgoin",
- FaxToMailUser.PROPERTY_TRIGRAPH, "JBO");
-
- // droits global à marc pour tout
- franciaflex.addReadRightUsers(marc);
- franciaflex = folderDao.update(franciaflex);
-
- // import test csv
- List<Range> ranges = null;
- try (InputStream is = InitTestData.class.getResourceAsStream("/csv/ranges.csv")) {
- ranges = referentielService.importRanges(is);
- }
- List<Priority> priorities = null;
- try (InputStream is = InitTestData.class.getResourceAsStream("/csv/priorities.csv")) {
- priorities = referentielService.importPriorities(is);
- }
- try (InputStream is = InitTestData.class.getResourceAsStream("/csv/email_accounts.csv")) {
- referentielService.importEmailAccounts(is);
- }
- List<Client> clients = null;
- try (InputStream is = InitTestData.class.getResourceAsStream("/csv/clients.csv")) {
- clients = referentielService.importClients(is);
- }
- List<DemandType> types = null;
- try (InputStream is = InitTestData.class.getResourceAsStream("/csv/demandtypes.csv")) {
- types = referentielService.importDemandTypes(is);
- }
- try (InputStream is = InitTestData.class.getResourceAsStream("/csv/email_filters.csv")) {
- referentielService.importEmailFilters(is, foldersByName);
- }
-
- // create test mail
- HistoryTopiaDao historyDao = getPersistenceContext().getHistoryDao();
- RangeRowTopiaDao rangeRowDao = getPersistenceContext().getRangeRowDao();
- EmailTopiaDao emailDao = getPersistenceContext().getEmailDao();
- createEmails(historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, cyrilFolder, cyril);
- }
-
- protected void createEmails(HistoryTopiaDao historyDao, RangeRowTopiaDao rangeRowDao, EmailTopiaDao emailDao, List<Range> ranges,
- List<Client> clients, List<DemandType> types, List<Priority> priorities, MailFolder folder, FaxToMailUser user)
- throws InvalidClientException {
- for (int i = 0; i < 5; i++) {
- createEmail(historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, folder, user);
- }
- }
-
- protected void createEmail(HistoryTopiaDao historyDao, RangeRowTopiaDao rangeRowDao, EmailTopiaDao emailDao, List<Range> ranges,
- List<Client> clients, List<DemandType> types, List<Priority> priorities, MailFolder folder, FaxToMailUser user)
- throws InvalidClientException {
-
- List<RangeRow> rangeRows = new ArrayList<>();
-
- Client client = clients.get(0);
- String sender = client.getEmailAddress();
- boolean fax = false;
- if (sender == null && client.getFaxNumber() != null) {
- sender = client.getFaxNumber();
- fax = true;
- }
-
- boolean opened = true; //random.nextBoolean();
-
- Decorator<Date> dateDecorator = getDecoratorService().getDecoratorByType(Date.class, DecoratorService.DATE);
-
- Date now = new Date();
- History history = historyDao.create(History.PROPERTY_TYPE, HistoryType.CREATION, History.PROPERTY_FIELDS, Sets.newHashSet(
- Email.PROPERTY_SENDER, Email.PROPERTY_CLIENT, Email.PROPERTY_PROJECT_REFERENCE, Email.PROPERTY_OBJECT, Email.PROPERTY_RECEPTION_DATE,
- Email.PROPERTY_MAIL_FOLDER, Email.PROPERTY_DEMAND_STATUS), History.PROPERTY_MODIFICATION_DATE, now);
- String projectRef = t("faxtomail.email.projectReference.default", dateDecorator.toString(now));
-
- Email email = emailDao.create(Email.PROPERTY_SENDER, sender,
- Email.PROPERTY_FAX, fax,
- Email.PROPERTY_CLIENT, client,
- Email.PROPERTY_PROJECT_REFERENCE, projectRef,
- Email.PROPERTY_OBJECT, client.getCaracteristic1() + " / " + client.getCode() + " / "
- + client.getName() + " / " + client.getFaxNumber() + " / " + dateDecorator.toString(now),
- Email.PROPERTY_RECEPTION_DATE, now,
- Email.PROPERTY_MAIL_FOLDER, folder,
- Email.PROPERTY_DEMAND_STATUS, opened ? DemandStatus.IN_PROGRESS : DemandStatus.UNTREATED,
- Email.PROPERTY_HISTORY, Lists.newArrayList(history),
- Email.PROPERTY_ORIGINAL_EMAIL, "test");
-
- if (opened) {
-
- getEmailService().addToHistory(email.getTopiaId(), HistoryType.OPENING, user, now);
- DemandType demandType = types.get(0);
- if (demandType.containsFields(MailField.RANGE_ROW)) {
- for (int j = 0; j < 4; j++) {
- RangeRow rangeRow = rangeRowDao.create(RangeRow.PROPERTY_RANGE, ranges.get(j),
- RangeRow.PROPERTY_COMMAND_NUMBER, RandomStringUtils.randomNumeric(6), RangeRow.PROPERTY_PRODUCT_QUANTITY,
- 50, RangeRow.PROPERTY_SAV_QUANTITY, 60);
- rangeRows.add(rangeRow);
- }
- email.setRangeRow(rangeRows);
- }
-
- email.setDemandType(demandType);
- email.setPriority(priorities.get(0));
- email.setRangeRow(rangeRows);
- getEmailService().saveEmail(email, user, Email.PROPERTY_DEMAND_TYPE, Email.PROPERTY_PRIORITY, Email.PROPERTY_RANGE_ROW);
- }
-
- Calendar cal = Calendar.getInstance();
- cal.add(Calendar.DAY_OF_MONTH, -1);
- Date yesterday = cal.getTime();
- history = historyDao.create(History.PROPERTY_TYPE, HistoryType.CREATION, History.PROPERTY_FIELDS, Sets.newHashSet(Email.PROPERTY_SENDER,
- Email.PROPERTY_CLIENT, Email.PROPERTY_PROJECT_REFERENCE, Email.PROPERTY_OBJECT, Email.PROPERTY_RECEPTION_DATE,
- Email.PROPERTY_MAIL_FOLDER, Email.PROPERTY_DEMAND_STATUS), History.PROPERTY_MODIFICATION_DATE, yesterday);
- projectRef = t("faxtomail.email.projectReference.default", dateDecorator.toString(yesterday));
-
- email = emailDao.create(Email.PROPERTY_SENDER, sender,
- Email.PROPERTY_FAX, fax,
- Email.PROPERTY_CLIENT,client,
- Email.PROPERTY_PROJECT_REFERENCE, projectRef, Email.PROPERTY_OBJECT, client.getCaracteristic1() + " / " + client.getCode() + " / "
- + client.getName() + " / " + client.getFaxNumber() + " / " + dateDecorator.toString(yesterday),
- Email.PROPERTY_RECEPTION_DATE, yesterday,
- Email.PROPERTY_MAIL_FOLDER, folder,
- Email.PROPERTY_DEMAND_STATUS, opened ? DemandStatus.IN_PROGRESS : DemandStatus.UNTREATED,
- Email.PROPERTY_HISTORY, Lists.newArrayList(history),
- Email.PROPERTY_ORIGINAL_EMAIL, "test");
-
- if (opened) {
- getEmailService().addToHistory(email.getTopiaId(), HistoryType.OPENING, user, now);
- DemandType demandType = types.get(0);
- if (demandType.containsFields(MailField.RANGE_ROW)) {
- for (int j = 0; j < 4; j++) {
- RangeRow rangeRow = rangeRowDao.create(RangeRow.PROPERTY_RANGE, ranges.get(j),
- RangeRow.PROPERTY_COMMAND_NUMBER, RandomStringUtils.randomNumeric(6), RangeRow.PROPERTY_PRODUCT_QUANTITY,
- 50, RangeRow.PROPERTY_SAV_QUANTITY, 60);
- rangeRows.add(rangeRow);
- }
- email.setRangeRow(rangeRows);
- }
- email.setDemandType(demandType);
- email.setPriority(priorities.get(0));
- email.setRangeRow(rangeRows);
- getEmailService().saveEmail(email, null, email.getClient().getCode(), user, Email.PROPERTY_DEMAND_TYPE, Email.PROPERTY_PRIORITY,
- Email.PROPERTY_RANGE_ROW);
- }
- }
-}
Added: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestData.java
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestData.java (rev 0)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestData.java 2014-08-05 14:36:30 UTC (rev 472)
@@ -0,0 +1,14 @@
+package com.franciaflex.faxtomail.services.service;
+
+import java.io.IOException;
+
+import com.franciaflex.faxtomail.services.FaxToMailService;
+
+/**
+ * @author Arnaud Thimel (Code Lutin)
+ */
+public interface InitTestData extends FaxToMailService {
+
+ void initTestData() throws IOException;
+
+}
Copied: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestDataImpl.java (from rev 471, trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestData.java)
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestDataImpl.java (rev 0)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestDataImpl.java 2014-08-05 14:36:30 UTC (rev 472)
@@ -0,0 +1,310 @@
+package com.franciaflex.faxtomail.services.service;
+
+/*
+ * #%L
+ * FaxToMail :: Service
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2014 Franciaflex, Code Lutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import static org.nuiton.i18n.I18n.t;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import com.franciaflex.faxtomail.persistence.entities.MailField;
+
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.decorator.Decorator;
+
+import com.franciaflex.faxtomail.persistence.entities.Client;
+import com.franciaflex.faxtomail.persistence.entities.DemandStatus;
+import com.franciaflex.faxtomail.persistence.entities.DemandType;
+import com.franciaflex.faxtomail.persistence.entities.Email;
+import com.franciaflex.faxtomail.persistence.entities.EmailTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.EtatAttente;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.History;
+import com.franciaflex.faxtomail.persistence.entities.HistoryTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.HistoryType;
+import com.franciaflex.faxtomail.persistence.entities.MailFolder;
+import com.franciaflex.faxtomail.persistence.entities.MailFolderTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.Priority;
+import com.franciaflex.faxtomail.persistence.entities.Range;
+import com.franciaflex.faxtomail.persistence.entities.RangeRow;
+import com.franciaflex.faxtomail.persistence.entities.RangeRowTopiaDao;
+import com.franciaflex.faxtomail.services.DecoratorService;
+import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
+import com.franciaflex.faxtomail.services.service.exceptions.InvalidClientException;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+
+/**
+ * Test service to manage test data.
+ *
+ * @author Eric Chatellier
+ */
+public class InitTestDataImpl extends FaxToMailServiceSupport implements InitTestData {
+
+ private static final Log log = LogFactory.getLog(InitTestDataImpl.class);
+
+ /**
+ * Import all test data.
+ *
+ * @throws IOException
+ */
+ @Override
+ public void initTestData() throws IOException {
+ if (log.isDebugEnabled()) {
+ log.debug("Init test data");
+ }
+ ReferentielService referentielService = newService(ReferentielService.class);
+
+ // import etat attentes
+ List<EtatAttente> etatAttentes = null;
+ try (InputStream is = InitTestDataImpl.class.getResourceAsStream("/csv/etatattentes.csv")) {
+ etatAttentes = referentielService.importEtatAttentes(is);
+ }
+
+ // create folders
+ MailFolderTopiaDao folderDao = getPersistenceContext().getMailFolderDao();
+ Map<String, MailFolder> foldersByName = new HashMap<>();
+ MailFolder franciaflex = folderDao.create(MailFolder.PROPERTY_NAME, "Franciaflex");
+
+ // categories
+ MailFolder chargesClientelle = folderDao.create(MailFolder.PROPERTY_NAME, "Chargés de clientèle",
+ MailFolder.PROPERTY_PARENT, franciaflex,
+ MailFolder.PROPERTY_REPLY_ADDRESSES, Lists.newArrayList("no-reply(a)franciaflex.com"));
+ franciaflex.addChildren(chargesClientelle);
+ foldersByName.put(chargesClientelle.getName(), chargesClientelle);
+
+ MailFolder sav = folderDao.create(MailFolder.PROPERTY_NAME, "SAV",
+ MailFolder.PROPERTY_PARENT, franciaflex,
+ MailFolder.PROPERTY_ETAT_ATTENTES, etatAttentes.subList(0, 1));
+ franciaflex.addChildren(sav);
+ foldersByName.put(sav.getName(), sav);
+
+ // user folders
+ MailFolder cyrilFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Cyril",
+ MailFolder.PROPERTY_PARENT, chargesClientelle,
+ MailFolder.PROPERTY_ETAT_ATTENTES, etatAttentes.subList(1, 2));
+ chargesClientelle.addChildren(cyrilFolder);
+ foldersByName.put(cyrilFolder.getName(), cyrilFolder);
+
+ MailFolder claireFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Claire",
+ MailFolder.PROPERTY_PARENT, chargesClientelle);
+ chargesClientelle.addChildren(claireFolder);
+ foldersByName.put(claireFolder.getName(), claireFolder);
+
+ MailFolder agatheFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Agathe",
+ MailFolder.PROPERTY_PARENT, chargesClientelle,
+ MailFolder.PROPERTY_ETAT_ATTENTES, etatAttentes.subList(2, 3));
+ chargesClientelle.addChildren(agatheFolder);
+ foldersByName.put(agatheFolder.getName(), agatheFolder);
+
+ MailFolder marcFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Marc",
+ MailFolder.PROPERTY_PARENT, sav);
+ sav.addChildren(marcFolder);
+ foldersByName.put(marcFolder.getName(), marcFolder);
+
+ MailFolder fredericFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Frédéric",
+ MailFolder.PROPERTY_PARENT, sav);
+ sav.addChildren(fredericFolder);
+ foldersByName.put(fredericFolder.getName(), fredericFolder);
+
+ MailFolder jeanneFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Jeanne",
+ MailFolder.PROPERTY_PARENT, sav);
+ sav.addChildren(jeanneFolder);
+ foldersByName.put(jeanneFolder.getName(), jeanneFolder);
+
+ // create test users
+ FaxToMailUserTopiaDao userDao = getPersistenceContext().getFaxToMailUserDao();
+ FaxToMailUser marc = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Lefèbvre",
+ FaxToMailUser.PROPERTY_FIRST_NAME, "Marc",
+ FaxToMailUser.PROPERTY_LOGIN, "mlefebvre",
+ FaxToMailUser.PROPERTY_TRIGRAPH, "MLE");
+ FaxToMailUser cyril = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Baillet",
+ FaxToMailUser.PROPERTY_FIRST_NAME, "Cyril",
+ FaxToMailUser.PROPERTY_LOGIN, "cbaillet",
+ FaxToMailUser.PROPERTY_TRIGRAPH, "CBA");
+ FaxToMailUser frederic = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Viala",
+ FaxToMailUser.PROPERTY_FIRST_NAME, "Frédéric",
+ FaxToMailUser.PROPERTY_LOGIN, "fviala",
+ FaxToMailUser.PROPERTY_TRIGRAPH, "FVI");
+ FaxToMailUser claire = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Marquis",
+ FaxToMailUser.PROPERTY_FIRST_NAME, "Claire",
+ FaxToMailUser.PROPERTY_LOGIN, "cmarquis",
+ FaxToMailUser.PROPERTY_TRIGRAPH, "CMA");
+ FaxToMailUser agathe = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Borde",
+ FaxToMailUser.PROPERTY_FIRST_NAME, "Agathe",
+ FaxToMailUser.PROPERTY_LOGIN, "aborde",
+ FaxToMailUser.PROPERTY_TRIGRAPH, "ABO");
+ FaxToMailUser jeanne = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Bourgoin",
+ FaxToMailUser.PROPERTY_FIRST_NAME, "Jeanne",
+ FaxToMailUser.PROPERTY_LOGIN, "jbourgoin",
+ FaxToMailUser.PROPERTY_TRIGRAPH, "JBO");
+
+ // droits global à marc pour tout
+ franciaflex.addReadRightUsers(marc);
+ franciaflex = folderDao.update(franciaflex);
+
+ // import test csv
+ List<Range> ranges = null;
+ try (InputStream is = InitTestDataImpl.class.getResourceAsStream("/csv/ranges.csv")) {
+ ranges = referentielService.importRanges(is);
+ }
+ List<Priority> priorities = null;
+ try (InputStream is = InitTestDataImpl.class.getResourceAsStream("/csv/priorities.csv")) {
+ priorities = referentielService.importPriorities(is);
+ }
+ try (InputStream is = InitTestDataImpl.class.getResourceAsStream("/csv/email_accounts.csv")) {
+ referentielService.importEmailAccounts(is);
+ }
+ List<Client> clients = null;
+ try (InputStream is = InitTestDataImpl.class.getResourceAsStream("/csv/clients.csv")) {
+ clients = referentielService.importClients(is);
+ }
+ List<DemandType> types = null;
+ try (InputStream is = InitTestDataImpl.class.getResourceAsStream("/csv/demandtypes.csv")) {
+ types = referentielService.importDemandTypes(is);
+ }
+ try (InputStream is = InitTestDataImpl.class.getResourceAsStream("/csv/email_filters.csv")) {
+ referentielService.importEmailFilters(is, foldersByName);
+ }
+
+ // create test mail
+ HistoryTopiaDao historyDao = getPersistenceContext().getHistoryDao();
+ RangeRowTopiaDao rangeRowDao = getPersistenceContext().getRangeRowDao();
+ EmailTopiaDao emailDao = getPersistenceContext().getEmailDao();
+ createEmails(historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, cyrilFolder, cyril);
+ }
+
+ protected void createEmails(HistoryTopiaDao historyDao, RangeRowTopiaDao rangeRowDao, EmailTopiaDao emailDao, List<Range> ranges,
+ List<Client> clients, List<DemandType> types, List<Priority> priorities, MailFolder folder, FaxToMailUser user)
+ throws InvalidClientException {
+ for (int i = 0; i < 5; i++) {
+ createEmail(historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, folder, user);
+ }
+ }
+
+ protected void createEmail(HistoryTopiaDao historyDao, RangeRowTopiaDao rangeRowDao, EmailTopiaDao emailDao, List<Range> ranges,
+ List<Client> clients, List<DemandType> types, List<Priority> priorities, MailFolder folder, FaxToMailUser user)
+ throws InvalidClientException {
+
+ List<RangeRow> rangeRows = new ArrayList<>();
+
+ Client client = clients.get(0);
+ String sender = client.getEmailAddress();
+ boolean fax = false;
+ if (sender == null && client.getFaxNumber() != null) {
+ sender = client.getFaxNumber();
+ fax = true;
+ }
+
+ boolean opened = true; //random.nextBoolean();
+
+ Decorator<Date> dateDecorator = getDecoratorService().getDecoratorByType(Date.class, DecoratorService.DATE);
+
+ Date now = new Date();
+ History history = historyDao.create(History.PROPERTY_TYPE, HistoryType.CREATION, History.PROPERTY_FIELDS, Sets.newHashSet(
+ Email.PROPERTY_SENDER, Email.PROPERTY_CLIENT, Email.PROPERTY_PROJECT_REFERENCE, Email.PROPERTY_OBJECT, Email.PROPERTY_RECEPTION_DATE,
+ Email.PROPERTY_MAIL_FOLDER, Email.PROPERTY_DEMAND_STATUS), History.PROPERTY_MODIFICATION_DATE, now);
+ String projectRef = t("faxtomail.email.projectReference.default", dateDecorator.toString(now));
+
+ Email email = emailDao.create(Email.PROPERTY_SENDER, sender,
+ Email.PROPERTY_FAX, fax,
+ Email.PROPERTY_CLIENT, client,
+ Email.PROPERTY_PROJECT_REFERENCE, projectRef,
+ Email.PROPERTY_OBJECT, client.getCaracteristic1() + " / " + client.getCode() + " / "
+ + client.getName() + " / " + client.getFaxNumber() + " / " + dateDecorator.toString(now),
+ Email.PROPERTY_RECEPTION_DATE, now,
+ Email.PROPERTY_MAIL_FOLDER, folder,
+ Email.PROPERTY_DEMAND_STATUS, opened ? DemandStatus.IN_PROGRESS : DemandStatus.UNTREATED,
+ Email.PROPERTY_HISTORY, Lists.newArrayList(history),
+ Email.PROPERTY_ORIGINAL_EMAIL, "test");
+
+ if (opened) {
+
+ getEmailService().addToHistory(email.getTopiaId(), HistoryType.OPENING, user, now);
+ DemandType demandType = types.get(0);
+ if (demandType.containsFields(MailField.RANGE_ROW)) {
+ for (int j = 0; j < 4; j++) {
+ RangeRow rangeRow = rangeRowDao.create(RangeRow.PROPERTY_RANGE, ranges.get(j),
+ RangeRow.PROPERTY_COMMAND_NUMBER, RandomStringUtils.randomNumeric(6), RangeRow.PROPERTY_PRODUCT_QUANTITY,
+ 50, RangeRow.PROPERTY_SAV_QUANTITY, 60);
+ rangeRows.add(rangeRow);
+ }
+ email.setRangeRow(rangeRows);
+ }
+
+ email.setDemandType(demandType);
+ email.setPriority(priorities.get(0));
+ email.setRangeRow(rangeRows);
+ getEmailService().saveEmail(email, user, Email.PROPERTY_DEMAND_TYPE, Email.PROPERTY_PRIORITY, Email.PROPERTY_RANGE_ROW);
+ }
+
+ Calendar cal = Calendar.getInstance();
+ cal.add(Calendar.DAY_OF_MONTH, -1);
+ Date yesterday = cal.getTime();
+ history = historyDao.create(History.PROPERTY_TYPE, HistoryType.CREATION, History.PROPERTY_FIELDS, Sets.newHashSet(Email.PROPERTY_SENDER,
+ Email.PROPERTY_CLIENT, Email.PROPERTY_PROJECT_REFERENCE, Email.PROPERTY_OBJECT, Email.PROPERTY_RECEPTION_DATE,
+ Email.PROPERTY_MAIL_FOLDER, Email.PROPERTY_DEMAND_STATUS), History.PROPERTY_MODIFICATION_DATE, yesterday);
+ projectRef = t("faxtomail.email.projectReference.default", dateDecorator.toString(yesterday));
+
+ email = emailDao.create(Email.PROPERTY_SENDER, sender,
+ Email.PROPERTY_FAX, fax,
+ Email.PROPERTY_CLIENT,client,
+ Email.PROPERTY_PROJECT_REFERENCE, projectRef, Email.PROPERTY_OBJECT, client.getCaracteristic1() + " / " + client.getCode() + " / "
+ + client.getName() + " / " + client.getFaxNumber() + " / " + dateDecorator.toString(yesterday),
+ Email.PROPERTY_RECEPTION_DATE, yesterday,
+ Email.PROPERTY_MAIL_FOLDER, folder,
+ Email.PROPERTY_DEMAND_STATUS, opened ? DemandStatus.IN_PROGRESS : DemandStatus.UNTREATED,
+ Email.PROPERTY_HISTORY, Lists.newArrayList(history),
+ Email.PROPERTY_ORIGINAL_EMAIL, "test");
+
+ if (opened) {
+ getEmailService().addToHistory(email.getTopiaId(), HistoryType.OPENING, user, now);
+ DemandType demandType = types.get(0);
+ if (demandType.containsFields(MailField.RANGE_ROW)) {
+ for (int j = 0; j < 4; j++) {
+ RangeRow rangeRow = rangeRowDao.create(RangeRow.PROPERTY_RANGE, ranges.get(j),
+ RangeRow.PROPERTY_COMMAND_NUMBER, RandomStringUtils.randomNumeric(6), RangeRow.PROPERTY_PRODUCT_QUANTITY,
+ 50, RangeRow.PROPERTY_SAV_QUANTITY, 60);
+ rangeRows.add(rangeRow);
+ }
+ email.setRangeRow(rangeRows);
+ }
+ email.setDemandType(demandType);
+ email.setPriority(priorities.get(0));
+ email.setRangeRow(rangeRows);
+ getEmailService().saveEmail(email, null, email.getClient().getCode(), user, Email.PROPERTY_DEMAND_TYPE, Email.PROPERTY_PRIORITY,
+ Email.PROPERTY_RANGE_ROW);
+ }
+ }
+}
Modified: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/MailFolderServiceTest.java
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/MailFolderServiceTest.java 2014-08-05 13:13:51 UTC (rev 471)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/MailFolderServiceTest.java 2014-08-05 14:36:30 UTC (rev 472)
@@ -46,7 +46,7 @@
@Before
public void setUp() throws IOException {
- service = newService(MailFolderServiceImpl.class);
+ service = newService(MailFolderService.class);
newService(InitTestData.class).initTestData();
}
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2014-08-05 13:13:51 UTC (rev 471)
+++ trunk/pom.xml 2014-08-05 14:36:30 UTC (rev 472)
@@ -105,8 +105,8 @@
<nuitonValidatorVersion>3.0-rc-1</nuitonValidatorVersion>
<nuitonWebVersion>1.16</nuitonWebVersion>
- <eugeneVersion>2.12</eugeneVersion>
- <topiaVersion>3.0-beta-11</topiaVersion>
+ <eugeneVersion>3.0-SNAPSHOT</eugeneVersion>
+ <topiaVersion>3.0-SNAPSHOT</topiaVersion>
<hibernateVersion>4.3.6.Final</hibernateVersion>
<h2Version>1.3.176</h2Version>
1
0
05 Aug '14
Author: kmorin
Date: 2014-08-05 15:13:51 +0200 (Tue, 05 Aug 2014)
New Revision: 471
Url: http://forge.codelutin.com/projects/faxtomail/repository/revisions/471
Log:
make it build
Removed:
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/Command.java
Modified:
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationServiceImpl.java
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/ComputeQuantitiesByRangeAction.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/GenerateAnnotatedAttachmentAction.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/GroupAction.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/LoadFolderEmailsAction.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/PrintOnDefaultPrinterAction.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/ReplyAction.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/SaveDemandeAction.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/SaveDemandeFromListAction.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/SearchAction.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/SearchToGroupAction.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/ShowDemandeAction.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/attachment/AttachmentCellEditor.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/attachment/AttachmentEditorUIHandler.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandeListUIHandler.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandeUIHandler.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/demandgroup/DemandGroupUIHandler.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/pdfeditor/PDFEditorUIHandler.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/print/AttachmentToPrintChooserUIHandler.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/reply/ReplyFormUIHandler.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/search/SearchToGroupUIHandler.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/search/SearchUIHandler.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/transmit/MailFolderChooserUIHandler.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/AbstractFaxToMailDemandListHandler.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/FaxToMailUIUtil.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/FaxToMailApplicationContext.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/FaxToMailInterceptor.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/action/admin/LdapAction.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/ClientUpdateJob.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/EDIManagementJob.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/MailFilterJob.java
Modified: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationService.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationService.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -6,6 +6,7 @@
import com.franciaflex.faxtomail.persistence.entities.EtatAttente;
import com.franciaflex.faxtomail.persistence.entities.ExtensionCommand;
import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+import com.franciaflex.faxtomail.persistence.entities.MailField;
import com.franciaflex.faxtomail.persistence.entities.MailFilter;
import com.franciaflex.faxtomail.persistence.entities.MailFolder;
import com.franciaflex.faxtomail.services.FaxToMailService;
@@ -39,4 +40,8 @@
Map<String, Object> checkDirectory(String path);
Map<String, Object> checkMailaccount(EmailAccount account);
+
+ long getEmailMaxSize();
+
+ List<MailField> getSearchDisplayColumns();
}
Modified: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationServiceImpl.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationServiceImpl.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationServiceImpl.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -38,6 +38,7 @@
import javax.mail.Session;
import javax.mail.Store;
+import com.franciaflex.faxtomail.persistence.entities.MailField;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -589,4 +590,16 @@
}
return result;
}
+
+ @Override
+ public long getEmailMaxSize() {
+ Configuration conf = getConfiguration();
+ return conf.getEmailMaxSize();
+ }
+
+ @Override
+ public List<MailField> getSearchDisplayColumns() {
+ Configuration conf = getConfiguration();
+ return conf.getSearchDisplayColumns();
+ }
}
Modified: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -136,31 +136,15 @@
FaxToMailTopiaApplicationContext applicationContext = newApplicationContext(DATABASE_REF);
- FaxToMailTopiaPersistenceContext persistenceContext;
+ FaxToMailServiceContext serviceContext = new FaxToMailServiceContext(applicationContext);
- persistenceContext = applicationContext.newPersistenceContext();
-
- if (log.isTraceEnabled()) {
- log.trace("opened transaction " + persistenceContext);
- }
-
- FaxToMailServiceContext serviceContext = new FaxToMailServiceContext();
-
serviceContext.setApplicationConfig(getApplicationConfig());
- serviceContext.setPersistenceContext(persistenceContext);
+ InitFaxToMailService initFaxToMailService = serviceContext.newService(InitFaxToMailService.class);
- InitFaxToMailService initFaxToMailService = serviceContext.newService(InitFaxToMailServiceImpl.class);
-
initFaxToMailService.init();
if (log.isTraceEnabled()) {
- log.trace("closing transaction " + persistenceContext);
- }
-
- persistenceContext.close();
-
- if (log.isTraceEnabled()) {
log.trace("closing transaction " + applicationContext);
}
@@ -272,16 +256,11 @@
if (serviceContext == null) {
- FaxToMailServiceContext serviceContext = new FaxToMailServiceContext();
+ FaxToMailServiceContext serviceContext = new FaxToMailServiceContext(applicationContext);
serviceContext.setApplicationConfig(getApplicationConfig());
- FaxToMailTopiaPersistenceContext persistenceContext = newPersistenceContext();
-
- serviceContext.setPersistenceContext(persistenceContext);
-
this.serviceContext = serviceContext;
-
}
return serviceContext;
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -216,7 +216,7 @@
FaxToMailServiceContext serviceContext = newServiceContext();
InitFaxToMailService initExtranetService =
- serviceContext.newService(InitFaxToMailServiceImpl.class);
+ serviceContext.newService(InitFaxToMailService.class);
initExtranetService.init();
@@ -472,8 +472,7 @@
//------------------------------------------------------------------------//
public FaxToMailServiceContext newServiceContext() {
- FaxToMailServiceContext serviceContext = new FaxToMailServiceContext();
- serviceContext.setTopiaApplicationContext(topiaApplicationContext);
+ FaxToMailServiceContext serviceContext = new FaxToMailServiceContext(topiaApplicationContext);
serviceContext.setApplicationConfig(config);
return serviceContext;
}
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/ComputeQuantitiesByRangeAction.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/ComputeQuantitiesByRangeAction.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/ComputeQuantitiesByRangeAction.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -26,6 +26,7 @@
import com.franciaflex.faxtomail.persistence.entities.MailFolder;
import com.franciaflex.faxtomail.persistence.entities.Range;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import com.franciaflex.faxtomail.ui.swing.content.demande.QuantitiesByRangeUI;
import com.franciaflex.faxtomail.ui.swing.content.demande.QuantitiesByRangeUIHandler;
import com.franciaflex.faxtomail.ui.swing.content.demande.QuantitiesByRangeUIModel;
@@ -56,7 +57,8 @@
@Override
public void doAction() throws Exception {
MailFolder folder = getModel().getRootFolder();
- Map<Range, Long[]> quantitiesByRange = getContext().getEmailService().computeQuantitiesByRange(folder);
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ Map<Range, Long[]> quantitiesByRange = serviceContext.getEmailService().computeQuantitiesByRange(folder);
List<RangeRowModel> rangeRows = new ArrayList<>();
for (Range range : quantitiesByRange.keySet()) {
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/GenerateAnnotatedAttachmentAction.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/GenerateAnnotatedAttachmentAction.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/GenerateAnnotatedAttachmentAction.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -33,6 +33,7 @@
import javax.swing.JTextArea;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import com.franciaflex.faxtomail.ui.swing.util.FaxToMailUIUtil;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
@@ -250,7 +251,8 @@
// convert content to blob
InputStream is = new BufferedInputStream(new FileInputStream(target));
- AttachmentFile attachmentFileNew = getContext().getEmailService().getAttachmentFileFromStream(is);
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ AttachmentFile attachmentFileNew = serviceContext.getEmailService().getAttachmentFileFromStream(is);
attachmentFileNew.setRotation(rotation);
String fileName = getModel().getNotNullFile().getFilename();
attachmentFileNew.setFilename(FaxToMailUIUtil.getEditedFileName(fileName));
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/GroupAction.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/GroupAction.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/GroupAction.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -26,6 +26,7 @@
import com.franciaflex.faxtomail.persistence.entities.Email;
import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import com.franciaflex.faxtomail.services.service.EmailService;
import com.franciaflex.faxtomail.ui.swing.content.demande.DemandeUIModel;
import com.franciaflex.faxtomail.ui.swing.content.search.SearchToGroupUI;
@@ -75,7 +76,8 @@
@Override
public void doAction() throws Exception {
- EmailService emailService = getContext().getEmailService();
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ EmailService emailService = serviceContext.getEmailService();
Email email2 = emailService.getEmailById(selectedEmail.getTopiaId());
Email email1 = emailService.getEmailById(currentEmail.getTopiaId());
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/LoadFolderEmailsAction.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/LoadFolderEmailsAction.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/LoadFolderEmailsAction.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -85,7 +85,8 @@
MailFolder folder = model.getSelectedFolder();
FaxToMailUser currentUser = getContext().getCurrentUser();
- PaginationResult<Email> paginationResult = getContext().getEmailService().getEmailForFolder(folder, currentUser, model.getPaginationParameter());
+ PaginationResult<Email> paginationResult = getContext().newServiceContext().getEmailService()
+ .getEmailForFolder(folder, currentUser, model.getPaginationParameter());
List<Email> emails = paginationResult.getElements();
if (log.isDebugEnabled()) {
log.debug(emails.size() + " emails in folder " + folder.getName());
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/PrintOnDefaultPrinterAction.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/PrintOnDefaultPrinterAction.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/PrintOnDefaultPrinterAction.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -28,6 +28,7 @@
import com.franciaflex.faxtomail.persistence.entities.Email;
import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
import com.franciaflex.faxtomail.persistence.entities.HistoryType;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import com.franciaflex.faxtomail.services.service.EmailService;
import com.franciaflex.faxtomail.ui.swing.content.demande.DemandeUIModel;
import com.franciaflex.faxtomail.ui.swing.util.AbstractFaxToMailUIHandler;
@@ -87,9 +88,10 @@
List<String> printedFiles = new ArrayList<String>();
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
if (printDemandDetails) {
// generate details as pdf
- EmailService emailService = getContext().getEmailService();
+ EmailService emailService = serviceContext.getEmailService();
Email email = demandeUIModel.toEntity();
final AttachmentFile demandDetailAttachment = emailService.getEmailDetailAsAttachment(email);
// print details
@@ -109,7 +111,7 @@
}
}
- Email email = getContext().getEmailService().addToHistory(demandeUIModel.getTopiaId(),
+ Email email = serviceContext.getEmailService().addToHistory(demandeUIModel.getTopiaId(),
HistoryType.PRINTING,
getContext().getCurrentUser(),
new Date(),
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/ReplyAction.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/ReplyAction.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/ReplyAction.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -26,6 +26,7 @@
import com.franciaflex.faxtomail.persistence.entities.AttachmentFile;
import com.franciaflex.faxtomail.persistence.entities.Email;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import com.franciaflex.faxtomail.services.service.EmailService;
import com.franciaflex.faxtomail.ui.swing.content.demande.DemandeUIModel;
import com.franciaflex.faxtomail.ui.swing.content.reply.ReplyAttachmentModel;
@@ -60,7 +61,8 @@
log.info("do reply");
ReplyFormUIModel model = getModel();
- emailService = getContext().getEmailService();
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ emailService = serviceContext.getEmailService();
DemandeUIModel originalDemand = getModel().getOriginalDemand();
Collection<AttachmentFile> attachmentFiles = Collections2.transform(model.getAttachments(), new Function<ReplyAttachmentModel, AttachmentFile>() {
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/SaveDemandeAction.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/SaveDemandeAction.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/SaveDemandeAction.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -28,6 +28,7 @@
import java.util.Collection;
import java.util.Map;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import org.apache.commons.lang3.StringUtils;
import org.nuiton.topia.persistence.TopiaEntities;
import org.nuiton.util.beans.BeanMonitor;
@@ -65,8 +66,9 @@
Email persistedEmail;
String topiaId = model.getTopiaId();
+ FaxToMailServiceContext serviceContext = context.newServiceContext();
if (!StringUtils.isBlank(topiaId)) {
- persistedEmail = context.getEmailService().getEmailById(topiaId);
+ persistedEmail = serviceContext.getEmailService().getEmailById(topiaId);
} else {
persistedEmail = new EmailImpl();
}
@@ -97,7 +99,7 @@
BeanMonitor monitor = getHandler().getMonitor();
String[] modifiedProperties = monitor.getModifiedProperties();
- email = context.getEmailService().saveEmail(email, attachments, clientCode, currentUser, modifiedProperties);
+ email = serviceContext.getEmailService().saveEmail(email, attachments, clientCode, currentUser, modifiedProperties);
model.fromEntity(email);
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/SaveDemandeFromListAction.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/SaveDemandeFromListAction.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/SaveDemandeFromListAction.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -26,6 +26,7 @@
import com.franciaflex.faxtomail.persistence.entities.Email;
import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import com.franciaflex.faxtomail.ui.swing.FaxToMailUIContext;
import com.franciaflex.faxtomail.ui.swing.content.demande.DemandeListUI;
import com.franciaflex.faxtomail.ui.swing.content.demande.DemandeListUIHandler;
@@ -55,12 +56,13 @@
for (DemandeUIModel model : getModel().getCurrentEmails()) {
String topiaId = model.getTopiaId();
- Email persistedEmail = context.getEmailService().getEmailById(topiaId);
+ FaxToMailServiceContext serviceContext = context.newServiceContext();
+ Email persistedEmail = serviceContext.getEmailService().getEmailById(topiaId);
FaxToMailUser currentUser = context.getCurrentUser();
Email email = model.toEntity(persistedEmail);
- email = context.getEmailService().saveEmail(email, currentUser, modifiedProperties);
+ email = serviceContext.getEmailService().saveEmail(email, currentUser, modifiedProperties);
model.fromEntity(email);
}
}
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/SearchAction.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/SearchAction.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/SearchAction.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -29,6 +29,7 @@
import java.util.ArrayList;
import java.util.List;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import org.nuiton.util.pagination.PaginationResult;
import com.franciaflex.faxtomail.persistence.entities.Email;
@@ -56,7 +57,8 @@
EmailFilter emailFilter = model.toEntity();
- PaginationResult<Email> paginationResult = getContext().getEmailService().search(emailFilter,
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ PaginationResult<Email> paginationResult = serviceContext.getEmailService().search(emailFilter,
getContext().getCurrentUser(), getModel().getPaginationParameter());
List<Email> emails = paginationResult.getElements();
List<DemandeUIModel> result = new ArrayList<>();
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/SearchToGroupAction.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/SearchToGroupAction.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/SearchToGroupAction.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -26,6 +26,7 @@
import com.franciaflex.faxtomail.persistence.entities.Email;
import com.franciaflex.faxtomail.persistence.entities.EmailFilter;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import com.franciaflex.faxtomail.ui.swing.content.demande.DemandeUIModel;
import com.franciaflex.faxtomail.ui.swing.content.search.SearchToGroupUI;
import com.franciaflex.faxtomail.ui.swing.content.search.SearchToGroupUIHandler;
@@ -55,7 +56,8 @@
getContext().setSearch(model);
EmailFilter emailFilter = model.toEntity();
- PaginationResult<Email> paginationResult = getContext().getEmailService().search(emailFilter,
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ PaginationResult<Email> paginationResult = serviceContext.getEmailService().search(emailFilter,
getContext().getCurrentUser(), getModel().getPaginationParameter());
List<Email> emails = paginationResult.getElements();
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/ShowDemandeAction.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/ShowDemandeAction.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/ShowDemandeAction.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -25,6 +25,7 @@
import com.franciaflex.faxtomail.persistence.entities.Email;
import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
import com.franciaflex.faxtomail.persistence.entities.MailFolder;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import com.franciaflex.faxtomail.services.service.exceptions.AlreadyLockedMailException;
import com.franciaflex.faxtomail.ui.swing.FaxToMailScreen;
import com.franciaflex.faxtomail.ui.swing.content.MainUIHandler;
@@ -61,7 +62,8 @@
FaxToMailUser currentUser = getContext().getCurrentUser();
try {
- getContext().getEmailService().lockEmail(currentEmail.getTopiaId(), currentUser);
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ serviceContext.getEmailService().lockEmail(currentEmail.getTopiaId(), currentUser);
} catch (AlreadyLockedMailException ex) {
result = false;
@@ -82,7 +84,8 @@
DemandeUIModel currentEmail = getContext().getCurrentEmail();
if (StringUtils.isNotBlank(currentEmail.getTopiaId())) {
- Email email = getContext().getEmailService().getEmailById(currentEmail.getTopiaId());
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ Email email = serviceContext.getEmailService().getEmailById(currentEmail.getTopiaId());
currentEmail.setGroupedDemandes(email.getEmailGroup());
}
}
@@ -128,7 +131,8 @@
break;
case JOptionPane.YES_OPTION:
- Email email = getContext().getEmailService().takeEmail(currentEmail.getTopiaId(), currentUser);
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ Email email = serviceContext.getEmailService().takeEmail(currentEmail.getTopiaId(), currentUser);
currentEmail.fromEntity(email);
currentEmail.setEditable(true);
break;
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/attachment/AttachmentCellEditor.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/attachment/AttachmentCellEditor.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/attachment/AttachmentCellEditor.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -27,6 +27,7 @@
import com.franciaflex.faxtomail.persistence.entities.Attachment;
import com.franciaflex.faxtomail.persistence.entities.Email;
import com.franciaflex.faxtomail.persistence.entities.HistoryType;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import com.franciaflex.faxtomail.ui.swing.FaxToMailUIContext;
import com.franciaflex.faxtomail.ui.swing.content.demande.DemandeUIModel;
import com.franciaflex.faxtomail.ui.swing.util.AbstractFaxToMailBeanUIModel;
@@ -113,7 +114,8 @@
} else {
filename = FaxToMailUIUtil.getEditedFileName(attachment.getOriginalFileName());
}
- Email email = context.getEmailService().addToHistory(topiaId,
+ FaxToMailServiceContext serviceContext = context.newServiceContext();
+ Email email = serviceContext.getEmailService().addToHistory(topiaId,
HistoryType.ATTACHMENT_OPENING,
context.getCurrentUser(),
new Date(),
@@ -125,7 +127,8 @@
@Override
public void onAttachmentEdited(Attachment attachment) {
String topiaId = model.getTopiaId();
- Email email = context.getEmailService().addToHistory(topiaId,
+ FaxToMailServiceContext serviceContext = context.newServiceContext();
+ Email email = serviceContext.getEmailService().addToHistory(topiaId,
HistoryType.ATTACHMENT_MODIFICATION,
context.getCurrentUser(),
new Date(),
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/attachment/AttachmentEditorUIHandler.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/attachment/AttachmentEditorUIHandler.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/attachment/AttachmentEditorUIHandler.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -26,6 +26,7 @@
import com.franciaflex.faxtomail.persistence.entities.Attachment;
import com.franciaflex.faxtomail.persistence.entities.AttachmentImpl;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import com.franciaflex.faxtomail.ui.swing.actions.EditAttachmentAction;
import com.franciaflex.faxtomail.ui.swing.actions.OpenAttachmentAction;
import com.franciaflex.faxtomail.ui.swing.util.AbstractToolbarPopupHandler;
@@ -159,7 +160,8 @@
try {
// warning, this not NOT be closed (will be by blob on commit)
InputStream is = new FileInputStream(file);
- AttachmentFile attachmentFile = getContext().getEmailService().getAttachmentFileFromStream(is);
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ AttachmentFile attachmentFile = serviceContext.getEmailService().getAttachmentFileFromStream(is);
attachmentFile.setFilename(file.getName());
attachment.setOriginalFile(attachmentFile);
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandeListUIHandler.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandeListUIHandler.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandeListUIHandler.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -136,11 +136,9 @@
super.beforeInit(ui);
- // open new transaction for current folder
- getContext().createNewTransaction();
-
DemandeListUIModel model = new DemandeListUIModel();
- Collection<MailFolder> folders = getContext().getMailFolderService().getRootMailFoldersWithReadingRights(getContext().getCurrentUser());
+ Collection<MailFolder> folders = getContext().newServiceContext().getMailFolderService()
+ .getRootMailFoldersWithReadingRights(getContext().getCurrentUser());
model.setFolders(new ArrayList<MailFolder>(folders));
this.ui.setContextValue(model);
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandeUIHandler.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandeUIHandler.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandeUIHandler.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -47,6 +47,7 @@
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableCellEditor;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import jaxx.runtime.validator.swing.SwingValidator;
import org.apache.commons.collections4.CollectionUtils;
@@ -134,7 +135,8 @@
});
MailFolder folder = model.getMailFolder();
- ReferentielService referentielService = getContext().getReferentielService();
+ final FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ ReferentielService referentielService = serviceContext.getReferentielService();
initBeanFilterableComboBox(ui.getPriorityComboBox(), referentielService.getAllPriority(), model.getPriority());
initBeanFilterableComboBox(ui.getStatusComboBox(), Arrays.asList(DemandStatus.values()), model.getDemandStatus());
@@ -361,7 +363,7 @@
} else {
filename = FaxToMailUIUtil.getEditedFileName(attachment.getOriginalFileName());
}
- Email email = getContext().getEmailService().addToHistory(topiaId,
+ Email email = serviceContext.getEmailService().addToHistory(topiaId,
HistoryType.ATTACHMENT_OPENING,
getContext().getCurrentUser(),
new Date(),
@@ -374,7 +376,7 @@
public void onAttachmentEdited(Attachment attachment) {
String topiaId = getModel().getTopiaId();
if (topiaId != null) {
- Email email = getContext().getEmailService().addToHistory(topiaId,
+ Email email = serviceContext.getEmailService().addToHistory(topiaId,
HistoryType.ATTACHMENT_MODIFICATION,
getContext().getCurrentUser(),
new Date(),
@@ -449,7 +451,8 @@
// mettre ca ici et non dans le close, car pour un onglet, le close n'est pas appelé
if (result) {
- getContext().getEmailService().unlockEmail(getModel().getTopiaId());
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ serviceContext.getEmailService().unlockEmail(getModel().getTopiaId());
}
return result;
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/demandgroup/DemandGroupUIHandler.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/demandgroup/DemandGroupUIHandler.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/demandgroup/DemandGroupUIHandler.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -26,6 +26,7 @@
import com.franciaflex.faxtomail.persistence.entities.Email;
import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import com.franciaflex.faxtomail.services.service.exceptions.AlreadyLockedMailException;
import com.franciaflex.faxtomail.ui.swing.FaxToMailUIContext;
import com.franciaflex.faxtomail.ui.swing.content.MainUIHandler;
@@ -162,7 +163,8 @@
try {
// tentative de verrouillage de la demande
- getContext().getEmailService().lockEmail(demande.getTopiaId(), currentUser);
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ serviceContext.getEmailService().lockEmail(demande.getTopiaId(), currentUser);
if (demande.getArchiveDate() != null) {
demande.setEditable(false);
@@ -188,7 +190,7 @@
break;
case JOptionPane.YES_OPTION:
- Email email = getContext().getEmailService().takeEmail(demande.getTopiaId(), currentUser);
+ Email email = serviceContext.getEmailService().takeEmail(demande.getTopiaId(), currentUser);
demande.fromEntity(email);
demande.setEditable(true);
break;
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/pdfeditor/PDFEditorUIHandler.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/pdfeditor/PDFEditorUIHandler.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/pdfeditor/PDFEditorUIHandler.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -55,6 +55,7 @@
import javax.swing.JComponent;
import javax.swing.JPanel;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import jaxx.runtime.swing.ComponentMover;
import jaxx.runtime.swing.ComponentResizer;
import jaxx.runtime.validator.swing.SwingValidator;
@@ -532,7 +533,8 @@
writer.close();
// convert content to blob
- AttachmentFile attachmentFileNew = getContext().getEmailService().getAttachmentFileFromStream(new FileInputStream(target));
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ AttachmentFile attachmentFileNew = serviceContext.getEmailService().getAttachmentFileFromStream(new FileInputStream(target));
attachmentFileNew.setFilename(attachmentFile.getFilename() + ".pdf");
attachmentFileNew.setRotation(0);
getModel().setEditedFile(attachmentFileNew);
@@ -572,7 +574,8 @@
// j'ai essayé une action vite fait mais ca ferme l'éditeur à la fin de l'action
if (print) {
DemandeUIModel demand = model.getDemand();
- Email email = getContext().getEmailService().addToHistory(demand.getTopiaId(),
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ Email email = serviceContext.getEmailService().addToHistory(demand.getTopiaId(),
HistoryType.PRINTING,
getContext().getCurrentUser(),
new Date(),
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/print/AttachmentToPrintChooserUIHandler.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/print/AttachmentToPrintChooserUIHandler.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/print/AttachmentToPrintChooserUIHandler.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -30,6 +30,7 @@
import javax.swing.JCheckBox;
import javax.swing.JComponent;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import com.franciaflex.faxtomail.ui.swing.actions.PrintOnDefaultPrinterAction;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
@@ -64,7 +65,8 @@
DemandeUIModel demand = model.getDemand();
// add demand details
- EmailService emailService = getContext().getEmailService();
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ EmailService emailService = serviceContext.getEmailService();
Email email = getModel().getDemand().toEntity();
final AttachmentFile demandDetailAttachment = emailService.getEmailDetailAsAttachment(email);
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/reply/ReplyFormUIHandler.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/reply/ReplyFormUIHandler.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/reply/ReplyFormUIHandler.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -97,7 +97,7 @@
super.beforeInit(ui);
ReplyFormUIModel model = new ReplyFormUIModel();
- long maxSize = getContext().getFaxToMailConfiguration().getEmailMaxSize();
+ long maxSize = getContext().newServiceContext().getConfigurationService().getEmailMaxSize();
model.setMaxAttachmentLength(maxSize);
this.ui.setContextValue(model);
@@ -248,7 +248,7 @@
Attachment attachment = replyAttachmentModel.getAttachment();
if (replyAttachmentModel.getAttachmentFile() == null && attachment.isPersisted()) {
// TODO action ?
- EmailService service = getContext().getEmailService();
+ EmailService service = getContext().newServiceContext().getEmailService();
boolean original = replyAttachmentModel.isOriginal();
AttachmentFile file = service.getAttachmentFile(attachment.getTopiaId(),
original);
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/search/SearchToGroupUIHandler.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/search/SearchToGroupUIHandler.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/search/SearchToGroupUIHandler.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -37,7 +37,6 @@
import com.franciaflex.faxtomail.ui.swing.util.AbstractFaxToMailDemandListHandler;
import com.franciaflex.faxtomail.ui.swing.util.Cancelable;
-import com.franciaflex.faxtomail.ui.swing.util.Command;
import jaxx.runtime.validator.swing.SwingValidator;
import org.apache.commons.logging.Log;
@@ -78,6 +77,8 @@
/** Logger. */
private static final Log log = LogFactory.getLog(SearchToGroupUIHandler.class);
+ protected List<MailField> tableColumns;
+
@Override
public void beforeInit(SearchToGroupUI ui) {
super.beforeInit(ui);
@@ -114,136 +115,128 @@
initUI(ui);
FaxToMailServiceContext serviceContext = getContext().newServiceContext();
- Command command = new Command(serviceContext) {
- @Override
- protected void doAction() {
+ ReferentielService referentielService = serviceContext.getReferentielService();
- SearchToGroupUI ui = getUI();
- ReferentielService referentielService = serviceContext.getReferentielService();
+ List<FaxToMailUser> users = serviceContext.getUserService().getAllActiveUsers();
+ SearchUIModel model = getModel();
+ initBeanFilterableComboBox(ui.getTakenByComboBox(),
+ users,
+ model.getTakenBy());
+ initBeanFilterableComboBox(ui.getModifiedByComboBox(),
+ users,
+ model.getModifiedBy());
+ initBeanFilterableComboBox(ui.getArchivedByComboBox(),
+ users,
+ model.getArchivedBy());
+ initBeanFilterableComboBox(ui.getTransferByComboBox(),
+ users,
+ model.getTransferBy());
+ initBeanFilterableComboBox(ui.getPrintedByComboBox(),
+ users,
+ model.getPrintingBy());
+ initBeanFilterableComboBox(ui.getRepliedByComboBox(),
+ users,
+ model.getReplyBy());
- List<FaxToMailUser> users = serviceContext.getUserService().getAllActiveUsers();
- SearchUIModel model = getModel();
- initBeanFilterableComboBox(ui.getTakenByComboBox(),
- users,
- model.getTakenBy());
- initBeanFilterableComboBox(ui.getModifiedByComboBox(),
- users,
- model.getModifiedBy());
- initBeanFilterableComboBox(ui.getArchivedByComboBox(),
- users,
- model.getArchivedBy());
- initBeanFilterableComboBox(ui.getTransferByComboBox(),
- users,
- model.getTransferBy());
- initBeanFilterableComboBox(ui.getPrintedByComboBox(),
- users,
- model.getPrintingBy());
- initBeanFilterableComboBox(ui.getRepliedByComboBox(),
- users,
- model.getReplyBy());
+ initCheckBoxComboBox(ui.getDocTypeComboBox(),
+ referentielService.getAllDemandType(),
+ model.getDemandType(),
+ EmailFilter.PROPERTY_DEMAND_TYPE,
+ true);
+ initCheckBoxComboBox(ui.getPriorityComboBox(),
+ referentielService.getAllPriority(),
+ model.getPriority(),
+ EmailFilter.PROPERTY_PRIORITY,
+ true);
+ initCheckBoxComboBox(ui.getEtatAttenteComboBox(),
+ referentielService.getAllEtatAttente(),
+ model.getEtatAttente(),
+ EmailFilter.PROPERTY_ETAT_ATTENTE,
+ true);
+ initCheckBoxComboBox(ui.getStatusComboBox(),
+ Arrays.asList(DemandStatus.values()),
+ model.getDemandStatus(),
+ EmailFilter.PROPERTY_DEMAND_STATUS,
+ false);
+ initCheckBoxComboBox(ui.getGammeComboBox(),
+ referentielService.getAllRange(),
+ model.getGamme(),
+ EmailFilter.PROPERTY_GAMME,
+ false);
- initCheckBoxComboBox(ui.getDocTypeComboBox(),
- referentielService.getAllDemandType(),
- model.getDemandType(),
- EmailFilter.PROPERTY_DEMAND_TYPE,
- true);
- initCheckBoxComboBox(ui.getPriorityComboBox(),
- referentielService.getAllPriority(),
- model.getPriority(),
- EmailFilter.PROPERTY_PRIORITY,
- true);
- initCheckBoxComboBox(ui.getEtatAttenteComboBox(),
- referentielService.getAllEtatAttente(),
- model.getEtatAttente(),
- EmailFilter.PROPERTY_ETAT_ATTENTE,
- true);
- initCheckBoxComboBox(ui.getStatusComboBox(),
- Arrays.asList(DemandStatus.values()),
- model.getDemandStatus(),
- EmailFilter.PROPERTY_DEMAND_STATUS,
- false);
- initCheckBoxComboBox(ui.getGammeComboBox(),
- referentielService.getAllRange(),
- model.getGamme(),
- EmailFilter.PROPERTY_GAMME,
- false);
+ final JXTable dataTable = getUI().getDataTable();
+ dataTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
- final JXTable dataTable = getUI().getDataTable();
- dataTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ initDemandeTable(dataTable, true);
- initDemandeTable(dataTable, true);
+ model.addPropertyChangeListener(SearchUIModel.PROPERTY_RESULTS, new PropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+ List<DemandeUIModel> emails = (List<DemandeUIModel>) evt.getNewValue();
+ AbstractApplicationTableModel<DemandeUIModel> dataTableModel = (AbstractApplicationTableModel<DemandeUIModel>) dataTable.getModel();
+ dataTableModel.setRows(emails);
+ showInformationMessage(t("faxtomail.search.resultNb", emails.size()));
- model.addPropertyChangeListener(SearchUIModel.PROPERTY_RESULTS, new PropertyChangeListener() {
- @Override
- public void propertyChange(PropertyChangeEvent evt) {
- List<DemandeUIModel> emails = (List<DemandeUIModel>) evt.getNewValue();
- AbstractApplicationTableModel<DemandeUIModel> dataTableModel = (AbstractApplicationTableModel<DemandeUIModel>) dataTable.getModel();
- dataTableModel.setRows(emails);
- showInformationMessage(t("faxtomail.search.resultNb", emails.size()));
-
- DemandeUIModel currentEmail = getContext().getCurrentEmail();
- if (currentEmail != null) {
- int row = dataTableModel.getRowIndex(currentEmail);
- if (row > 0) {
- dataTable.setRowSelectionInterval(row, row);
- }
+ DemandeUIModel currentEmail = getContext().getCurrentEmail();
+ if (currentEmail != null) {
+ int row = dataTableModel.getRowIndex(currentEmail);
+ if (row > 0) {
+ dataTable.setRowSelectionInterval(row, row);
}
}
- });
+ }
+ });
- if (getContext().getSearch() != null) {
- try {
- SearchToGroupAction searchAction = getContext().getActionFactory().createLogicAction(SearchToGroupUIHandler.this, SearchToGroupAction.class);
- searchAction.doAction();
+ if (getContext().getSearch() != null) {
+ try {
+ SearchToGroupAction searchAction = getContext().getActionFactory().createLogicAction(SearchToGroupUIHandler.this, SearchToGroupAction.class);
+ searchAction.doAction();
- } catch (Exception e) {
- if (log.isErrorEnabled()) {
- log.error("error while searching", e);
- }
- getContext().getErrorHelper().showErrorDialog(t("faxtomail.search.action.error"));
+ } catch (Exception e) {
+ if (log.isErrorEnabled()) {
+ log.error("error while searching", e);
}
+ getContext().getErrorHelper().showErrorDialog(t("faxtomail.search.action.error"));
}
+ }
- dataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
- @Override
- public void valueChanged(ListSelectionEvent e) {
- if (!e.getValueIsAdjusting()) {
- ListSelectionModel selectionModel = (ListSelectionModel) e.getSource();
- SearchUIModel model = getModel();
- int selectedIndex = selectionModel.getLeadSelectionIndex();
- AbstractApplicationTableModel<DemandeUIModel> dataTableModel = (AbstractApplicationTableModel<DemandeUIModel>) dataTable.getModel();
- DemandeUIModel selectedModel = selectedIndex < 0 ? null : dataTableModel.getEntry(selectedIndex);
- model.setGroupEnabled(!selectionModel.isSelectionEmpty() && isDemandSelectable(selectedModel));
- }
- }
- });
-
- HighlightPredicate rowAlreadyInGroupPredicate = new HighlightPredicate() {
- @Override
- public boolean isHighlighted(Component renderer, ComponentAdapter adapter) {
- int viewRow = adapter.row;
- int modelRow = adapter.convertRowIndexToModel(viewRow);
+ dataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
+ @Override
+ public void valueChanged(ListSelectionEvent e) {
+ if (!e.getValueIsAdjusting()) {
+ ListSelectionModel selectionModel = (ListSelectionModel) e.getSource();
+ SearchUIModel model = getModel();
+ int selectedIndex = selectionModel.getLeadSelectionIndex();
AbstractApplicationTableModel<DemandeUIModel> dataTableModel = (AbstractApplicationTableModel<DemandeUIModel>) dataTable.getModel();
- DemandeUIModel row = dataTableModel.getEntry(modelRow);
- return !isDemandSelectable(row);
+ DemandeUIModel selectedModel = selectedIndex < 0 ? null : dataTableModel.getEntry(selectedIndex);
+ model.setGroupEnabled(!selectionModel.isSelectionEmpty() && isDemandSelectable(selectedModel));
}
- };
- dataTable.addHighlighter(new ColorHighlighter(rowAlreadyInGroupPredicate, null, Color.GRAY, Color.GRAY, Color.WHITE));
+ }
+ });
- // int combo box for result per page
- ui.getResultPerPageCombo().setModel(new DefaultComboBoxModel<Integer>(new Integer[] {10, 20, 30, 40, 50}));
- int resultPerPage = getConfig().getResultPerPage();
- ui.getModel().setResultPerPage(resultPerPage);
- ui.getResultPerPageCombo().setSelectedItem(resultPerPage);
- ui.getResultPerPageCombo().addItemListener(new ItemListener() {
- @Override
- public void itemStateChanged(ItemEvent e) {
- updateResultPerPage(e);
- }
- });
+ HighlightPredicate rowAlreadyInGroupPredicate = new HighlightPredicate() {
+ @Override
+ public boolean isHighlighted(Component renderer, ComponentAdapter adapter) {
+ int viewRow = adapter.row;
+ int modelRow = adapter.convertRowIndexToModel(viewRow);
+ AbstractApplicationTableModel<DemandeUIModel> dataTableModel = (AbstractApplicationTableModel<DemandeUIModel>) dataTable.getModel();
+ DemandeUIModel row = dataTableModel.getEntry(modelRow);
+ return !isDemandSelectable(row);
}
};
- command.execute();
+ dataTable.addHighlighter(new ColorHighlighter(rowAlreadyInGroupPredicate, null, Color.GRAY, Color.GRAY, Color.WHITE));
+
+ // int combo box for result per page
+ ui.getResultPerPageCombo().setModel(new DefaultComboBoxModel<Integer>(new Integer[] {10, 20, 30, 40, 50}));
+ int resultPerPage = getConfig().getResultPerPage();
+ ui.getModel().setResultPerPage(resultPerPage);
+ ui.getResultPerPageCombo().setSelectedItem(resultPerPage);
+ ui.getResultPerPageCombo().addItemListener(new ItemListener() {
+ @Override
+ public void itemStateChanged(ItemEvent e) {
+ updateResultPerPage(e);
+ }
+ });
}
public void searchDemandes() {
@@ -263,7 +256,6 @@
public void updateResultPerPage(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
- getContext().createNewTransaction();
int resultPerPage = (Integer)event.getItem();
getConfig().setResultPerPage(resultPerPage);
getConfig().save();
@@ -288,7 +280,9 @@
@Override
protected List<MailField> getColumns() {
- List<MailField> tableColumns = getContext().getFaxToMailConfiguration().getSearchDisplayColumns();
+ if (tableColumns == null) {
+ tableColumns = getContext().newServiceContext().getConfigurationService().getSearchDisplayColumns();
+ }
return tableColumns;
}
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/search/SearchUIHandler.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/search/SearchUIHandler.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/search/SearchUIHandler.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -67,6 +67,8 @@
/** Logger. */
private static final Log log = LogFactory.getLog(SearchUIHandler.class);
+ protected List<MailField> tableColumns;
+
@Override
public void beforeInit(SearchUI ui) {
super.beforeInit(ui);
@@ -98,10 +100,10 @@
initUI(ui);
- final ReferentielService referentielService = getContext().getReferentielService();
+ final ReferentielService referentielService = getContext().newServiceContext().getReferentielService();
// this loading take 1,5 seconds
- List<FaxToMailUser> users = getContext().getUserService().getAllActiveUsers();
+ List<FaxToMailUser> users = getContext().newServiceContext().getUserService().getAllActiveUsers();
SearchUIModel model = getModel();
initBeanFilterableComboBox(ui.getTakenByComboBox(),
users,
@@ -198,7 +200,6 @@
}
public void searchDemandes() {
- getContext().createNewTransaction();
getModel().resetPaginationParameter();
runSearchAction();
}
@@ -215,7 +216,6 @@
public void updateResultPerPage(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
- getContext().createNewTransaction();
int resultPerPage = (Integer)event.getItem();
getConfig().setResultPerPage(resultPerPage);
getConfig().save();
@@ -240,7 +240,9 @@
@Override
protected List<MailField> getColumns() {
- List<MailField> tableColumns = getContext().getFaxToMailConfiguration().getSearchDisplayColumns();
+ if (tableColumns == null) {
+ tableColumns = getContext().newServiceContext().getConfigurationService().getSearchDisplayColumns();
+ }
return tableColumns;
}
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/transmit/MailFolderChooserUIHandler.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/transmit/MailFolderChooserUIHandler.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/transmit/MailFolderChooserUIHandler.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -26,6 +26,7 @@
import com.franciaflex.faxtomail.persistence.entities.EtatAttente;
import com.franciaflex.faxtomail.persistence.entities.MailFolder;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import com.franciaflex.faxtomail.ui.swing.content.demande.DemandeUIModel;
import com.franciaflex.faxtomail.ui.swing.util.AbstractFaxToMailUIHandler;
import com.franciaflex.faxtomail.ui.swing.util.Cancelable;
@@ -60,14 +61,15 @@
EtatAttente etatAttente = model.getEtatAttente();
final Collection<MailFolder> foldersWithEtatAttente;
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
if (etatAttente != null) {
- foldersWithEtatAttente = getContext().getMailFolderService().getFoldersWithEtatAttente(etatAttente);
+ foldersWithEtatAttente = serviceContext.getMailFolderService().getFoldersWithEtatAttente(etatAttente);
} else {
foldersWithEtatAttente = new HashSet<MailFolder>();
}
// init tree
- Collection<MailFolder> folders = getContext().getMailFolderService().
+ Collection<MailFolder> folders = serviceContext.getMailFolderService().
getRootMailFoldersWithMoveRights(getContext().getCurrentUser());
JTree navigationTree = ui.getNavigationTree();
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/AbstractFaxToMailDemandListHandler.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/AbstractFaxToMailDemandListHandler.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/AbstractFaxToMailDemandListHandler.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -34,6 +34,7 @@
import com.franciaflex.faxtomail.persistence.entities.Priority;
import com.franciaflex.faxtomail.persistence.entities.RangeRow;
import com.franciaflex.faxtomail.persistence.entities.Reply;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import com.franciaflex.faxtomail.ui.swing.FaxToMailUIContext;
import com.franciaflex.faxtomail.ui.swing.actions.ShowDemandeAction;
import com.franciaflex.faxtomail.ui.swing.content.demande.DemandeUIModel;
@@ -171,10 +172,11 @@
for (MailField columnName : columns) {
if (MailField.PRIORITY.equals(columnName)) {
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
addComboDataColumnToModel(columnModel,
DemandeTableModel.COLUMN_IDENTIFIERS.get(columnName),
getDecorator(Priority.class, null),
- getContext().getReferentielService().getAllPriority()).setSortable(sortable);
+ serviceContext.getReferentielService().getAllPriority()).setSortable(sortable);
} else if (MailField.ATTACHMENT.equals(columnName)) {
addColumnToModel(columnModel,
@@ -267,8 +269,8 @@
FaxToMailUIContext context = getContext();
// reset transaction
- context.createNewTransaction();
- Email email = context.getEmailService().addToHistory(selectedEmail.getTopiaId(),
+ FaxToMailServiceContext serviceContext = context.newServiceContext();
+ Email email = serviceContext.getEmailService().addToHistory(selectedEmail.getTopiaId(),
HistoryType.OPENING,
context.getCurrentUser(),
new Date());
Deleted: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/Command.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/Command.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/Command.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -1,29 +0,0 @@
-package com.franciaflex.faxtomail.ui.swing.util;
-
-import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
-import org.apache.commons.io.IOUtils;
-
-/**
- * @author Kevin Morin (Code Lutin)
- * @since x.x
- */
-public abstract class Command {
-
- protected FaxToMailServiceContext serviceContext;
-
- protected Command(FaxToMailServiceContext serviceContext) {
- this.serviceContext = serviceContext;
- }
-
- protected abstract void doAction();
-
- public void execute() {
- try {
- doAction();
-
- } finally {
- IOUtils.closeQuietly(serviceContext);
- }
- }
-
-}
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/FaxToMailUIUtil.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/FaxToMailUIUtil.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/FaxToMailUIUtil.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -64,6 +64,7 @@
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import jaxx.runtime.JAXXObject;
import jaxx.runtime.JAXXUtil;
@@ -355,7 +356,8 @@
log.debug("Force attachment loading " + attachment.getOriginalFileName());
}
if (attachment.isPersisted()) {
- EmailService service = context.getEmailService();
+ FaxToMailServiceContext serviceContext = context.newServiceContext();
+ EmailService service = serviceContext.getEmailService();
if (attachment.getOriginalFile() == null) {
AttachmentFile file = service.getAttachmentFile(attachment.getTopiaId(), true);
attachment.setOriginalFile(file);
@@ -491,7 +493,8 @@
// get configuration extension command
ExtensionCommand extCommand = null;
if (StringUtils.isNotBlank(extension)) {
- ConfigurationService service = context.getConfigurationService();
+ FaxToMailServiceContext serviceContext = context.newServiceContext();
+ ConfigurationService service = serviceContext.getConfigurationService();
extCommand = service.getExtensionCommand(extension);
}
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/FaxToMailApplicationContext.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/FaxToMailApplicationContext.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/FaxToMailApplicationContext.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -72,14 +72,12 @@
public FaxToMailServiceContext newServiceContext(FaxToMailTopiaPersistenceContext persistenceContext) {
FaxToMailServiceContext newServiceContext =
- new FaxToMailServiceContext();
+ new FaxToMailServiceContext(topiaApplicationContext);
FaxToMailConfiguration applicationConfig = getApplicationConfig();
newServiceContext.setApplicationConfig(applicationConfig);
- newServiceContext.setPersistenceContext(persistenceContext);
-
return newServiceContext;
}
@@ -154,7 +152,7 @@
FaxToMailServiceContext serviceContext = newServiceContext(persistenceContext);
InitFaxToMailService initExtranetService =
- serviceContext.newService(InitFaxToMailServiceImpl.class);
+ serviceContext.newService(InitFaxToMailService.class);
initExtranetService.init();
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/FaxToMailInterceptor.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/FaxToMailInterceptor.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/FaxToMailInterceptor.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -144,7 +144,7 @@
protected void populateUser(FaxToMailSession faxToMailSession, FaxToMailServiceContext serviceContext) {
if (StringUtils.isNotBlank(faxToMailSession.getAuthenticatedUserId())) {
- LdapService ldapService = serviceContext.newService(LdapServiceImpl.class);
+ LdapService ldapService = serviceContext.newService(LdapService.class);
// return can be null
FaxToMailUser user = ldapService.getUserBean(faxToMailSession.getAuthenticatedUserId());
faxToMailSession.setAuthenticatedFaxToMailUser(user);
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/action/admin/LdapAction.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/action/admin/LdapAction.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/action/admin/LdapAction.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -103,7 +103,7 @@
try {
persistenceContext = applicationContext.newPersistenceContext();
FaxToMailServiceContext serviceContext = applicationContext.newServiceContext(persistenceContext);
- LdapService ldapService2 = serviceContext.newService(LdapServiceImpl.class);
+ LdapService ldapService2 = serviceContext.newService(LdapService.class);
ldapService2.updateLdapData();
} finally {
persistenceContext.close();
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/ClientUpdateJob.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/ClientUpdateJob.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/ClientUpdateJob.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -60,7 +60,7 @@
log.debug("Running ClientUpdateJob at " + serviceContext.getNow());
}
- ClientService clientService = serviceContext.newService(ClientServiceImpl.class);
+ ClientService clientService = serviceContext.newService(ClientService.class);
clientService.updateNewClients();
if (log.isDebugEnabled()) {
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/EDIManagementJob.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/EDIManagementJob.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/EDIManagementJob.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -58,7 +58,7 @@
log.debug("Running EDIManagementJob at " + serviceContext.getNow());
}
- EmailService emailService = serviceContext.newService(EmailServiceImpl.class);
+ EmailService emailService = serviceContext.newService(EmailService.class);
emailService.transmitPendingDemandsToEdi();
if (log.isDebugEnabled()) {
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/MailFilterJob.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/MailFilterJob.java 2014-08-05 12:56:55 UTC (rev 470)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/MailFilterJob.java 2014-08-05 13:13:51 UTC (rev 471)
@@ -144,11 +144,11 @@
log.debug("Running MailFilterJob at " + serviceContext.getNow());
}
- emailService = serviceContext.newService(EmailServiceImpl.class);
- mailFolderService = serviceContext.newService(MailFolderServiceImpl.class);
- configurationService = serviceContext.newService(ConfigurationServiceImpl.class);
- clientService = serviceContext.newService(ClientServiceImpl.class);
- decoratorService = serviceContext.newService(DecoratorServiceImpl.class);
+ emailService = serviceContext.newService(EmailService.class);
+ mailFolderService = serviceContext.newService(MailFolderService.class);
+ configurationService = serviceContext.newService(ConfigurationService.class);
+ clientService = serviceContext.newService(ClientService.class);
+ decoratorService = serviceContext.newService(DecoratorService.class);
Collection<EmailAccount> emailAccounts = configurationService.getEmailAccounts();
1
0
r470 - trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services
by athimel@users.forge.codelutin.com 05 Aug '14
by athimel@users.forge.codelutin.com 05 Aug '14
05 Aug '14
Author: athimel
Date: 2014-08-05 14:56:55 +0200 (Tue, 05 Aug 2014)
New Revision: 470
Url: http://forge.codelutin.com/projects/faxtomail/repository/revisions/470
Log:
Introduce ServiceFactory
Added:
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceFactory.java
Modified:
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceInvocationHandler.java
Modified: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java 2014-08-05 12:11:22 UTC (rev 469)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java 2014-08-05 12:56:55 UTC (rev 470)
@@ -58,72 +58,122 @@
private static final Log log = LogFactory.getLog(FaxToMailServiceContext.class);
+ protected FaxToMailServiceContext delegateServiceContext;
+
protected FaxToMailConfiguration applicationConfig;
protected FaxToMailTopiaApplicationContext topiaApplicationContext;
protected FaxToMailTopiaPersistenceContext persistenceContext;
- protected boolean calledFromProxy = false;
+ protected FaxToMailServiceFactory serviceFactory;
public FaxToMailServiceContext(FaxToMailTopiaApplicationContext topiaApplicationContext) {
this.topiaApplicationContext = topiaApplicationContext;
+ this.serviceFactory = new FaxToMailProxiedServiceFactory();
}
+ private FaxToMailServiceContext(FaxToMailServiceContext delegateServiceContext, FaxToMailServiceFactory serviceFactory) {
+ this.delegateServiceContext = delegateServiceContext;
+ this.serviceFactory = serviceFactory;
+ }
+
public FaxToMailConfiguration getApplicationConfig() {
- return applicationConfig;
+ if (delegateServiceContext != null) {
+ return delegateServiceContext.getApplicationConfig();
+ } else {
+ return applicationConfig;
+ }
}
public FaxToMailTopiaPersistenceContext getPersistenceContext() {
- if (persistenceContext == null) {
- persistenceContext = topiaApplicationContext.newPersistenceContext();
+ if (delegateServiceContext != null) {
+ return delegateServiceContext.getPersistenceContext();
+ } else {
+ if (persistenceContext == null) {
+ persistenceContext = topiaApplicationContext.newPersistenceContext();
+ }
+ return persistenceContext;
}
- return persistenceContext;
}
- public FaxToMailTopiaApplicationContext getTopiaApplicationContext() {
- return topiaApplicationContext;
- }
+// public FaxToMailTopiaApplicationContext getTopiaApplicationContext() {
+// return topiaApplicationContext;
+// }
public void setApplicationConfig(FaxToMailConfiguration applicationConfig) {
- this.applicationConfig = applicationConfig;
+ if (delegateServiceContext != null) {
+ delegateServiceContext.setApplicationConfig(applicationConfig);
+ } else {
+ this.applicationConfig = applicationConfig;
+ }
}
- public void setCalledFromProxy(boolean calledFromProxy) {
- this.calledFromProxy = calledFromProxy;
+ public <E extends FaxToMailService> E newService(Class<E> serviceInterfaceClass) {
+ return serviceFactory.newService(serviceInterfaceClass);
}
- public <E extends FaxToMailService> E newService(Class<E> serviceInterfaceClass) {
+ public class FaxToMailDefaultServiceFactory implements FaxToMailServiceFactory {
- E service;
- try {
- Class<E> serviceImplClass = (Class<E>) Class.forName(serviceInterfaceClass.getCanonicalName() + "Impl");
+ protected FaxToMailServiceContext serviceContext;
- // special case for mock services
- if (serviceImplClass.equals(LdapServiceImpl.class) && applicationConfig.isLdapMock()) {
- serviceImplClass = (Class<E>) LdapServiceMock.class;
- }
+ public void setServiceContext(FaxToMailServiceContext serviceContext) {
+ this.serviceContext = serviceContext;
+ }
- Constructor<E> constructor = serviceImplClass.getConstructor();
- service = constructor.newInstance();
+ @Override
+ public <E extends FaxToMailService> E newService(Class<E> serviceInterfaceClass) {
- if (!calledFromProxy) {
- service = (E) Proxy.newProxyInstance(serviceInterfaceClass.getClassLoader(), new Class[]{serviceInterfaceClass},
- new FaxToMailServiceInvocationHandler(service, this));
+ E service;
+ try {
+ Class<E> serviceImplClass = (Class<E>) Class.forName(serviceInterfaceClass.getCanonicalName() + "Impl");
+
+ // special case for mock services
+ if (serviceImplClass.equals(LdapServiceImpl.class) && serviceContext.getApplicationConfig().isLdapMock()) {
+ serviceImplClass = (Class<E>) LdapServiceMock.class;
+ }
+
+ Constructor<E> constructor = serviceImplClass.getConstructor();
+ service = constructor.newInstance();
+
+ } catch (NoSuchMethodException e) {
+ throw new ApplicationTechnicalException("all services must provide a non-argument constructor", e);
+ } catch (InvocationTargetException|InstantiationException|IllegalAccessException e) {
+ throw new ApplicationTechnicalException("unable to instantiate service", e);
+ } catch (ClassNotFoundException e) {
+ throw new ApplicationTechnicalException("unable to find the implementation of the service", e);
}
- } catch (NoSuchMethodException e) {
- throw new ApplicationTechnicalException("all services must provide a non-argument constructor", e);
- } catch (InvocationTargetException|InstantiationException|IllegalAccessException e) {
- throw new ApplicationTechnicalException("unable to instantiate service", e);
- } catch (ClassNotFoundException e) {
- throw new ApplicationTechnicalException("unable to find the implementation of the service", e);
+ service.setServiceContext(serviceContext);
+
+ return service;
+
}
+ }
- service.setServiceContext(this);
+ public class FaxToMailProxiedServiceFactory implements FaxToMailServiceFactory {
- return service;
+ protected FaxToMailDefaultServiceFactory defaultServiceFactory;
+ protected FaxToMailServiceContext subServiceContext;
+
+ @Override
+ public <E extends FaxToMailService> E newService(Class<E> serviceInterfaceClass) {
+
+ if (defaultServiceFactory == null) {
+ defaultServiceFactory = new FaxToMailDefaultServiceFactory();
+ subServiceContext = new FaxToMailServiceContext(FaxToMailServiceContext.this, defaultServiceFactory);
+ defaultServiceFactory.setServiceContext(subServiceContext);
+ }
+
+ E realService = defaultServiceFactory.newService(serviceInterfaceClass);
+
+ E service = (E) Proxy.newProxyInstance(serviceInterfaceClass.getClassLoader(), new Class[]{serviceInterfaceClass},
+ new FaxToMailServiceInvocationHandler(realService, FaxToMailServiceContext.this));
+
+ return service;
+
+ }
}
public Date getNow() {
@@ -132,35 +182,35 @@
}
public DecoratorService getDecoratorService() {
- return newService(DecoratorServiceImpl.class);
+ return newService(DecoratorService.class);
}
public ValidationService getValidationService() {
- return newService(ValidationServiceImpl.class);
+ return newService(ValidationService.class);
}
public MailFolderService getMailFolderService() {
- return newService(MailFolderServiceImpl.class);
+ return newService(MailFolderService.class);
}
public UserService getUserService() {
- return newService(UserServiceImpl.class);
+ return newService(UserService.class);
}
public LdapService getLdapService() {
- return newService(LdapServiceImpl.class);
+ return newService(LdapService.class);
}
public EmailService getEmailService() {
- return newService(EmailServiceImpl.class);
+ return newService(EmailService.class);
}
public ReferentielService getReferentielService() {
- return newService(ReferentielServiceImpl.class);
+ return newService(ReferentielService.class);
}
public ConfigurationService getConfigurationService() {
- return newService(ConfigurationServiceImpl.class);
+ return newService(ConfigurationService.class);
}
@Override
Added: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceFactory.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceFactory.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceFactory.java 2014-08-05 12:56:55 UTC (rev 470)
@@ -0,0 +1,10 @@
+package com.franciaflex.faxtomail.services;
+
+/**
+ * @author Arnaud Thimel (Code Lutin)
+ */
+public interface FaxToMailServiceFactory {
+
+ public <E extends FaxToMailService> E newService(Class<E> serviceInterfaceClass);
+
+}
Modified: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceInvocationHandler.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceInvocationHandler.java 2014-08-05 12:11:22 UTC (rev 469)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceInvocationHandler.java 2014-08-05 12:56:55 UTC (rev 470)
@@ -22,13 +22,11 @@
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
- serviceContext.setCalledFromProxy(true);
Object result = method.invoke(wrappedService, args);
return result;
} finally {
IOUtils.closeQuietly(serviceContext);
- serviceContext.setCalledFromProxy(false);
}
}
}
1
0
05 Aug '14
Author: kmorin
Date: 2014-08-05 14:11:22 +0200 (Tue, 05 Aug 2014)
New Revision: 469
Url: http://forge.codelutin.com/projects/faxtomail/repository/revisions/469
Log:
ajout des interfaces de service et du proxy
Added:
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/DecoratorService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/DecoratorServiceImpl.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceInvocationHandler.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ClientService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ClientServiceImpl.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationServiceImpl.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/EmailService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/EmailServiceImpl.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/InitFaxToMailService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/InitFaxToMailServiceImpl.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/LdapService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/LdapServiceImpl.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/MailFolderService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/MailFolderServiceImpl.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ReferentielService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ReferentielServiceImpl.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/UserService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/UserServiceImpl.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ValidationService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ValidationServiceImpl.java
Removed:
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/DecoratorService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ClientService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/EmailService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/InitFaxToMailService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/LdapService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/MailFolderService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ReferentielService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/UserService.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ValidationService.java
Modified:
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceSupport.java
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ldap/LdapServiceMock.java
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/ClientServiceTest.java
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/EmailServiceTest.java
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestData.java
trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/MailFolderServiceTest.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/FaxToMailApplicationContext.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/FaxToMailInterceptor.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/action/admin/LdapAction.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/ClientUpdateJob.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/EDIManagementJob.java
trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/MailFilterJob.java
Deleted: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/DecoratorService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/DecoratorService.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/DecoratorService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -1,143 +0,0 @@
-package com.franciaflex.faxtomail.services;
-
-/*
- * #%L
- * FaxToMail :: Service
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2014 Franciaflex, Code Lutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/gpl-3.0.html>.
- * #L%
- */
-
-import java.text.DateFormat;
-import java.util.Date;
-
-import org.nuiton.decorator.Decorator;
-import org.nuiton.decorator.DecoratorProvider;
-
-import com.franciaflex.faxtomail.persistence.entities.Attachment;
-import com.franciaflex.faxtomail.persistence.entities.AttachmentFile;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
-import com.franciaflex.faxtomail.persistence.entities.HasLabel;
-import com.franciaflex.faxtomail.persistence.entities.Reply;
-
-/**
- * FaxToMail decorator service.
- *
- * @author Kevin Morin - morin(a)codelutin.com
- */
-public class DecoratorService extends FaxToMailServiceSupport {
-
- public static final String SEPARATOR = "#";
-
- public static final String DATE = "date";
-
- /** Delegate decorator provider. */
- protected DecoratorProvider decoratorProvider;
-
- public <O> Decorator<O> getDecorator(O object) {
- return decoratorProvider.getDecorator(object);
- }
-
- public <O> Decorator<O> getDecorator(O object, String name) {
- return decoratorProvider.getDecorator(object, name);
- }
-
- public <O> Decorator<O> getDecoratorByType(Class<O> type) {
- return decoratorProvider.getDecoratorByType(type);
- }
-
- public <O> Decorator<O> getDecoratorByType(Class<O> type, String name) {
- return decoratorProvider.getDecoratorByType(type, name);
- }
-
- @Override
- public void setServiceContext(FaxToMailServiceContext context) {
- super.setServiceContext(context);
-
- decoratorProvider = new DecoratorProvider() {
- @Override
- protected void loadDecorators() {
-
- registerDecorator(new Decorator<Float>(Float.class) {
- private static final long serialVersionUID = 1L;
-
- @Override
- public String toString(Object bean) {
- return bean == null ? "" : String.valueOf(bean);
- }
- });
- registerDecorator(new Decorator<Number>(Number.class) {
- private static final long serialVersionUID = 1L;
-
- @Override
- public String toString(Object bean) {
- return bean == null ? "" : String.valueOf(bean);
- }
- });
- registerDecorator(new Decorator<Date>(Date.class) {
- private static final long serialVersionUID = 1L;
-
- @Override
- public String toString(Object bean) {
- if (bean == null) {
- return "";
- }
- return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(bean);
- }
- });
- registerDecorator(DATE, new Decorator<Date>(Date.class) {
- private static final long serialVersionUID = 1L;
-
- @Override
- public String toString(Object bean) {
- if (bean == null) {
- return "";
- }
- return DateFormat.getDateInstance(DateFormat.MEDIUM).format(bean);
- }
- });
- registerMultiJXPathDecorator(HasLabel.class, "${label}$s", SEPARATOR, " - ");
- registerDecorator(new Decorator<Attachment>(Attachment.class) {
- private static final long serialVersionUID = 1L;
-
- @Override
- public String toString(Object bean) {
- if (bean == null) {
- return "";
- }
- return ((Attachment) bean).getOriginalFileName();
- }
- });
- registerDecorator(new Decorator<AttachmentFile>(AttachmentFile.class) {
- private static final long serialVersionUID = 1L;
-
- @Override
- public String toString(Object bean) {
- if (bean == null) {
- return "";
- }
- return ((AttachmentFile) bean).getFilename();
- }
- });
- registerMultiJXPathDecorator(Reply.class, "${sentDate}$s#${subject}$s", SEPARATOR, " - ");
- registerMultiJXPathDecorator(FaxToMailUser.class, "${trigraph}$s#${firstName}$s#${lastName}$s", SEPARATOR, " ");
- }
- };
- }
-}
Added: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/DecoratorService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/DecoratorService.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/DecoratorService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,22 @@
+package com.franciaflex.faxtomail.services;
+
+import org.nuiton.decorator.Decorator;
+
+/**
+ * @author Kevin Morin (Code Lutin)
+ */
+public interface DecoratorService extends FaxToMailService {
+ String SEPARATOR = "#";
+ String DATE = "date";
+
+ <O> Decorator<O> getDecorator(O object);
+
+ <O> Decorator<O> getDecorator(O object, String name);
+
+ <O> Decorator<O> getDecoratorByType(Class<O> type);
+
+ <O> Decorator<O> getDecoratorByType(Class<O> type, String name);
+
+ @Override
+ void setServiceContext(FaxToMailServiceContext context);
+}
Copied: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/DecoratorServiceImpl.java (from rev 468, trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/DecoratorService.java)
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/DecoratorServiceImpl.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/DecoratorServiceImpl.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,143 @@
+package com.franciaflex.faxtomail.services;
+
+/*
+ * #%L
+ * FaxToMail :: Service
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2014 Franciaflex, Code Lutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import java.text.DateFormat;
+import java.util.Date;
+
+import org.nuiton.decorator.Decorator;
+import org.nuiton.decorator.DecoratorProvider;
+
+import com.franciaflex.faxtomail.persistence.entities.Attachment;
+import com.franciaflex.faxtomail.persistence.entities.AttachmentFile;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+import com.franciaflex.faxtomail.persistence.entities.HasLabel;
+import com.franciaflex.faxtomail.persistence.entities.Reply;
+
+/**
+ * FaxToMail decorator service.
+ *
+ * @author Kevin Morin - morin(a)codelutin.com
+ */
+public class DecoratorServiceImpl extends FaxToMailServiceSupport implements DecoratorService {
+
+ /** Delegate decorator provider. */
+ protected DecoratorProvider decoratorProvider;
+
+ @Override
+ public <O> Decorator<O> getDecorator(O object) {
+ return decoratorProvider.getDecorator(object);
+ }
+
+ @Override
+ public <O> Decorator<O> getDecorator(O object, String name) {
+ return decoratorProvider.getDecorator(object, name);
+ }
+
+ @Override
+ public <O> Decorator<O> getDecoratorByType(Class<O> type) {
+ return decoratorProvider.getDecoratorByType(type);
+ }
+
+ @Override
+ public <O> Decorator<O> getDecoratorByType(Class<O> type, String name) {
+ return decoratorProvider.getDecoratorByType(type, name);
+ }
+
+ @Override
+ public void setServiceContext(FaxToMailServiceContext context) {
+ super.setServiceContext(context);
+
+ decoratorProvider = new DecoratorProvider() {
+ @Override
+ protected void loadDecorators() {
+
+ registerDecorator(new Decorator<Float>(Float.class) {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public String toString(Object bean) {
+ return bean == null ? "" : String.valueOf(bean);
+ }
+ });
+ registerDecorator(new Decorator<Number>(Number.class) {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public String toString(Object bean) {
+ return bean == null ? "" : String.valueOf(bean);
+ }
+ });
+ registerDecorator(new Decorator<Date>(Date.class) {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public String toString(Object bean) {
+ if (bean == null) {
+ return "";
+ }
+ return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(bean);
+ }
+ });
+ registerDecorator(DATE, new Decorator<Date>(Date.class) {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public String toString(Object bean) {
+ if (bean == null) {
+ return "";
+ }
+ return DateFormat.getDateInstance(DateFormat.MEDIUM).format(bean);
+ }
+ });
+ registerMultiJXPathDecorator(HasLabel.class, "${label}$s", SEPARATOR, " - ");
+ registerDecorator(new Decorator<Attachment>(Attachment.class) {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public String toString(Object bean) {
+ if (bean == null) {
+ return "";
+ }
+ return ((Attachment) bean).getOriginalFileName();
+ }
+ });
+ registerDecorator(new Decorator<AttachmentFile>(AttachmentFile.class) {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public String toString(Object bean) {
+ if (bean == null) {
+ return "";
+ }
+ return ((AttachmentFile) bean).getFilename();
+ }
+ });
+ registerMultiJXPathDecorator(Reply.class, "${sentDate}$s#${subject}$s", SEPARATOR, " - ");
+ registerMultiJXPathDecorator(FaxToMailUser.class, "${trigraph}$s#${firstName}$s#${lastName}$s", SEPARATOR, " ");
+ }
+ };
+ }
+}
Property changes on: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/DecoratorServiceImpl.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -28,15 +28,23 @@
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Proxy;
import java.util.Date;
import com.franciaflex.faxtomail.persistence.entities.FaxToMailTopiaApplicationContext;
import com.franciaflex.faxtomail.services.service.ConfigurationService;
+import com.franciaflex.faxtomail.services.service.ConfigurationServiceImpl;
import com.franciaflex.faxtomail.services.service.EmailService;
+import com.franciaflex.faxtomail.services.service.EmailServiceImpl;
+import com.franciaflex.faxtomail.services.service.LdapServiceImpl;
import com.franciaflex.faxtomail.services.service.MailFolderService;
+import com.franciaflex.faxtomail.services.service.MailFolderServiceImpl;
import com.franciaflex.faxtomail.services.service.ReferentielService;
+import com.franciaflex.faxtomail.services.service.ReferentielServiceImpl;
import com.franciaflex.faxtomail.services.service.UserService;
+import com.franciaflex.faxtomail.services.service.UserServiceImpl;
import com.franciaflex.faxtomail.services.service.ValidationService;
+import com.franciaflex.faxtomail.services.service.ValidationServiceImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.jaxx.application.ApplicationTechnicalException;
@@ -56,6 +64,8 @@
protected FaxToMailTopiaPersistenceContext persistenceContext;
+ protected boolean calledFromProxy = false;
+
public FaxToMailServiceContext(FaxToMailTopiaApplicationContext topiaApplicationContext) {
this.topiaApplicationContext = topiaApplicationContext;
}
@@ -79,21 +89,35 @@
this.applicationConfig = applicationConfig;
}
- public <E extends FaxToMailService> E newService(Class<E> serviceClass) {
+ public void setCalledFromProxy(boolean calledFromProxy) {
+ this.calledFromProxy = calledFromProxy;
+ }
- // special case for mock services
- if (serviceClass.equals(LdapService.class) && applicationConfig.isLdapMock()) {
- serviceClass = (Class<E>)LdapServiceMock.class;
- }
+ public <E extends FaxToMailService> E newService(Class<E> serviceInterfaceClass) {
E service;
try {
- Constructor<E> constructor = serviceClass.getConstructor();
+ Class<E> serviceImplClass = (Class<E>) Class.forName(serviceInterfaceClass.getCanonicalName() + "Impl");
+
+ // special case for mock services
+ if (serviceImplClass.equals(LdapServiceImpl.class) && applicationConfig.isLdapMock()) {
+ serviceImplClass = (Class<E>) LdapServiceMock.class;
+ }
+
+ Constructor<E> constructor = serviceImplClass.getConstructor();
service = constructor.newInstance();
+
+ if (!calledFromProxy) {
+ service = (E) Proxy.newProxyInstance(serviceInterfaceClass.getClassLoader(), new Class[]{serviceInterfaceClass},
+ new FaxToMailServiceInvocationHandler(service, this));
+ }
+
} catch (NoSuchMethodException e) {
throw new ApplicationTechnicalException("all services must provide a non-argument constructor", e);
} catch (InvocationTargetException|InstantiationException|IllegalAccessException e) {
throw new ApplicationTechnicalException("unable to instantiate service", e);
+ } catch (ClassNotFoundException e) {
+ throw new ApplicationTechnicalException("unable to find the implementation of the service", e);
}
service.setServiceContext(this);
@@ -108,41 +132,42 @@
}
public DecoratorService getDecoratorService() {
- return newService(DecoratorService.class);
+ return newService(DecoratorServiceImpl.class);
}
public ValidationService getValidationService() {
- return newService(ValidationService.class);
+ return newService(ValidationServiceImpl.class);
}
public MailFolderService getMailFolderService() {
- return newService(MailFolderService.class);
+ return newService(MailFolderServiceImpl.class);
}
public UserService getUserService() {
- return newService(UserService.class);
+ return newService(UserServiceImpl.class);
}
public LdapService getLdapService() {
- return newService(LdapService.class);
+ return newService(LdapServiceImpl.class);
}
public EmailService getEmailService() {
- return newService(EmailService.class);
+ return newService(EmailServiceImpl.class);
}
public ReferentielService getReferentielService() {
- return newService(ReferentielService.class);
+ return newService(ReferentielServiceImpl.class);
}
public ConfigurationService getConfigurationService() {
- return newService(ConfigurationService.class);
+ return newService(ConfigurationServiceImpl.class);
}
@Override
public void close() throws IOException {
if (persistenceContext != null) {
persistenceContext.close();
+ persistenceContext = null;
}
}
}
Added: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceInvocationHandler.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceInvocationHandler.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceInvocationHandler.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,34 @@
+package com.franciaflex.faxtomail.services;
+
+import org.apache.commons.io.IOUtils;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+
+/**
+ * @author Kevin Morin (Code Lutin)
+ * @since x.x
+ */
+public class FaxToMailServiceInvocationHandler implements InvocationHandler {
+
+ protected Object wrappedService;
+ protected FaxToMailServiceContext serviceContext;
+
+ public FaxToMailServiceInvocationHandler(Object service, FaxToMailServiceContext serviceContext) {
+ this.wrappedService = service;
+ this.serviceContext = serviceContext;
+ }
+
+ @Override
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ try {
+ serviceContext.setCalledFromProxy(true);
+ Object result = method.invoke(wrappedService, args);
+ return result;
+
+ } finally {
+ IOUtils.closeQuietly(serviceContext);
+ serviceContext.setCalledFromProxy(false);
+ }
+ }
+}
Modified: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceSupport.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceSupport.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceSupport.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -27,10 +27,15 @@
import com.franciaflex.faxtomail.FaxToMailConfiguration;
import com.franciaflex.faxtomail.persistence.entities.FaxToMailTopiaPersistenceContext;
import com.franciaflex.faxtomail.services.service.ClientService;
+import com.franciaflex.faxtomail.services.service.ClientServiceImpl;
import com.franciaflex.faxtomail.services.service.ConfigurationService;
+import com.franciaflex.faxtomail.services.service.ConfigurationServiceImpl;
import com.franciaflex.faxtomail.services.service.EmailService;
+import com.franciaflex.faxtomail.services.service.EmailServiceImpl;
import com.franciaflex.faxtomail.services.service.MailFolderService;
+import com.franciaflex.faxtomail.services.service.MailFolderServiceImpl;
import com.franciaflex.faxtomail.services.service.ReferentielService;
+import com.franciaflex.faxtomail.services.service.ReferentielServiceImpl;
import java.util.Date;
@@ -60,26 +65,26 @@
}
protected DecoratorService getDecoratorService() {
- return newService(DecoratorService.class);
+ return newService(DecoratorServiceImpl.class);
}
protected ConfigurationService getConfigurationService() {
- return newService(ConfigurationService.class);
+ return newService(ConfigurationServiceImpl.class);
}
protected MailFolderService getMailFolderService() {
- return newService(MailFolderService.class);
+ return newService(MailFolderServiceImpl.class);
}
protected EmailService getEmailService() {
- return newService(EmailService.class);
+ return newService(EmailServiceImpl.class);
}
protected ReferentielService getReferentielService() {
- return newService(ReferentielService.class);
+ return newService(ReferentielServiceImpl.class);
}
protected ClientService getClientService() {
- return newService(ClientService.class);
+ return newService(ClientServiceImpl.class);
}
}
Deleted: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ClientService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ClientService.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ClientService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -1,191 +0,0 @@
-package com.franciaflex.faxtomail.services.service;
-
-/*
- * #%L
- * FaxToMail :: Service
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2014 Franciaflex, Code Lutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/gpl-3.0.html>.
- * #L%
- */
-
-import java.util.List;
-
-import org.apache.commons.collections4.CollectionUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.util.beans.Binder;
-import org.nuiton.util.beans.BinderFactory;
-
-import com.franciaflex.faxtomail.persistence.entities.Client;
-import com.franciaflex.faxtomail.persistence.entities.ClientImpl;
-import com.franciaflex.faxtomail.persistence.entities.ClientTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.Email;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.NewClient;
-import com.franciaflex.faxtomail.persistence.entities.NewClientTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.NewClientType;
-import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
-import com.google.common.base.Preconditions;
-
-/**
- * Service de gestion des clients.
- *
- * @author Kevin Morin (Code Lutin)
- */
-public class ClientService extends FaxToMailServiceSupport {
-
- private static final Log log = LogFactory.getLog(ClientService.class);
-
- /**
- * Recherche le client qui correspond à l'adresse email de l'expediteur du mail.
- *
- * This method is a getter, but modify input {@code email} !
- *
- * @param emailAddress sender address
- * @param email email
- * @return client for emailAddress (can be {@code null})
- */
- public Client getClientForEmailAddress(String emailAddress, Email email) {
- Preconditions.checkNotNull(email);
- Preconditions.checkNotNull(emailAddress);
-
- ClientTopiaDao clientDao = getPersistenceContext().getClientDao();
-
- Client client = null;
- List<Client> clients;
- if (StringUtils.isNotBlank(emailAddress)) {
- clients = clientDao.forEmailAddressEquals(emailAddress).findAll();
-
- // on essaye de voir si on peut gérer l'adresse de l'expediteur comme un fax
- if (CollectionUtils.isEmpty(clients)) {
- String faxNumber = emailAddress.substring(0, emailAddress.indexOf('@')).replaceAll(" ", "");
- // NumberUtils.isNumber peut echouer (notation octal)
- if (StringUtils.isNumeric(faxNumber)) {
- emailAddress = StringUtils.leftPad(faxNumber, 10, '0');
- clients = clientDao.forFaxNumberEquals(emailAddress).findAll();
- email.setFax(true);
- }
- }
-
- if (CollectionUtils.isNotEmpty(clients)) {
- client = clients.get(0);
- }
- }
-
- // on doit faire l'affectation ici car emailAddress a pu etre remplacé par le numero de fax
- email.setSender(emailAddress);
- return client;
- }
-
- /**
- * Recherche un client par code.
- *
- * FIXME echatellier 20140709 cette methodé récupére un client au hazard car le code peut être dupliqué par société
- *
- * @param code client code
- * @return un client au hasard
- */
- public Client getClientForCode(String code) {
- ClientTopiaDao clientDao = getPersistenceContext().getClientDao();
- Client client = null;
- if (StringUtils.isNotBlank(code)) {
- client = clientDao.forCodeEquals(code).findAnyOrNull();
- }
- return client;
- }
-
- /**
- * Récupère les information de la table NewClient pour mettre à jour la table Client.
- */
- public void updateNewClients() {
- NewClientTopiaDao newClientDao = getPersistenceContext().getNewClientDao();
- ClientTopiaDao clientDao = getPersistenceContext().getClientDao();
- FaxToMailUserTopiaDao faxToMailUserDao = getPersistenceContext().getFaxToMailUserDao();
- Iterable<NewClient> newClients = newClientDao.findAll();
- Binder<NewClient, Client> binder = BinderFactory.newBinder(NewClient.class, Client.class);
-
- for (NewClient newClient : newClients) {
-
- NewClientType type = newClient.getType();
- switch (type) {
- case CREATION:
- case UPDATE:
-
- // find client to create or update
- Client client = clientDao.forCodeEquals(newClient.getCode())
- .addEquals(Client.PROPERTY_BRAND, newClient.getBrand()).findUniqueOrNull();
- if (client == null) {
- client = new ClientImpl();
- if (type == NewClientType.UPDATE && log.isWarnEnabled()) {
- log.warn(String.format("Can't find client code %s/%s to update. Client created.", newClient.getCode(), newClient.getBrand()));
- }
- } else {
- if (type == NewClientType.CREATION && log.isWarnEnabled()) {
- log.warn(String.format("Creating a already existing client %s/%s. Client updated.", newClient.getCode(), newClient.getBrand()));
- }
- }
-
- // update client instance
- binder.copyExcluding(newClient, client,
- Client.PROPERTY_TOPIA_ID,
- Client.PROPERTY_TOPIA_CREATE_DATE,
- Client.PROPERTY_TOPIA_VERSION);
-
- // update person in charge
- FaxToMailUser personInCharge = null;
- if (StringUtils.isNotBlank(newClient.getPersonInCharge())) {
- personInCharge = faxToMailUserDao.forLoginEquals(newClient.getPersonInCharge()).findUniqueOrNull();
- }
- client.setPersonInCharge(personInCharge);
-
- // persist
- if (client.isPersisted()) {
- clientDao.update(client);
- } else {
- clientDao.create(client);
- }
-
- break;
-
- case DELETION:
- Client deleteClient = clientDao.forCodeEquals(newClient.getCode())
- .addEquals(Client.PROPERTY_BRAND, newClient.getBrand()).findUniqueOrNull();
- if (deleteClient == null) {
- if (log.isWarnEnabled()) {
- log.warn(String.format("Can't find client code %s/%s to delete", newClient.getCode(), newClient.getBrand()));
- }
- } else {
- // FIXME le delete ne fonctionnera pas si des mails porte sur ce client
- clientDao.delete(deleteClient);
- if (log.isDebugEnabled()) {
- log.debug(String.format("Client %s/%s deleted", newClient.getCode(), newClient.getBrand()));
- }
- }
- break;
- }
-
- }
-
- newClientDao.deleteAll(newClients);
- getPersistenceContext().commit();
- }
-
-}
Added: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ClientService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ClientService.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ClientService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,16 @@
+package com.franciaflex.faxtomail.services.service;
+
+import com.franciaflex.faxtomail.persistence.entities.Client;
+import com.franciaflex.faxtomail.persistence.entities.Email;
+import com.franciaflex.faxtomail.services.FaxToMailService;
+
+/**
+ * @author Kevin Morin (Code Lutin)
+ */
+public interface ClientService extends FaxToMailService {
+ Client getClientForEmailAddress(String emailAddress, Email email);
+
+ Client getClientForCode(String code);
+
+ void updateNewClients();
+}
Copied: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ClientServiceImpl.java (from rev 468, trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ClientService.java)
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ClientServiceImpl.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ClientServiceImpl.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,194 @@
+package com.franciaflex.faxtomail.services.service;
+
+/*
+ * #%L
+ * FaxToMail :: Service
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2014 Franciaflex, Code Lutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import java.util.List;
+
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.util.beans.Binder;
+import org.nuiton.util.beans.BinderFactory;
+
+import com.franciaflex.faxtomail.persistence.entities.Client;
+import com.franciaflex.faxtomail.persistence.entities.ClientImpl;
+import com.franciaflex.faxtomail.persistence.entities.ClientTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.Email;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.NewClient;
+import com.franciaflex.faxtomail.persistence.entities.NewClientTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.NewClientType;
+import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
+import com.google.common.base.Preconditions;
+
+/**
+ * Service de gestion des clients.
+ *
+ * @author Kevin Morin (Code Lutin)
+ */
+public class ClientServiceImpl extends FaxToMailServiceSupport implements ClientService {
+
+ private static final Log log = LogFactory.getLog(ClientServiceImpl.class);
+
+ /**
+ * Recherche le client qui correspond à l'adresse email de l'expediteur du mail.
+ *
+ * This method is a getter, but modify input {@code email} !
+ *
+ * @param emailAddress sender address
+ * @param email email
+ * @return client for emailAddress (can be {@code null})
+ */
+ @Override
+ public Client getClientForEmailAddress(String emailAddress, Email email) {
+ Preconditions.checkNotNull(email);
+ Preconditions.checkNotNull(emailAddress);
+
+ ClientTopiaDao clientDao = getPersistenceContext().getClientDao();
+
+ Client client = null;
+ List<Client> clients;
+ if (StringUtils.isNotBlank(emailAddress)) {
+ clients = clientDao.forEmailAddressEquals(emailAddress).findAll();
+
+ // on essaye de voir si on peut gérer l'adresse de l'expediteur comme un fax
+ if (CollectionUtils.isEmpty(clients)) {
+ String faxNumber = emailAddress.substring(0, emailAddress.indexOf('@')).replaceAll(" ", "");
+ // NumberUtils.isNumber peut echouer (notation octal)
+ if (StringUtils.isNumeric(faxNumber)) {
+ emailAddress = StringUtils.leftPad(faxNumber, 10, '0');
+ clients = clientDao.forFaxNumberEquals(emailAddress).findAll();
+ email.setFax(true);
+ }
+ }
+
+ if (CollectionUtils.isNotEmpty(clients)) {
+ client = clients.get(0);
+ }
+ }
+
+ // on doit faire l'affectation ici car emailAddress a pu etre remplacé par le numero de fax
+ email.setSender(emailAddress);
+ return client;
+ }
+
+ /**
+ * Recherche un client par code.
+ *
+ * FIXME echatellier 20140709 cette methodé récupére un client au hazard car le code peut être dupliqué par société
+ *
+ * @param code client code
+ * @return un client au hasard
+ */
+ @Override
+ public Client getClientForCode(String code) {
+ ClientTopiaDao clientDao = getPersistenceContext().getClientDao();
+ Client client = null;
+ if (StringUtils.isNotBlank(code)) {
+ client = clientDao.forCodeEquals(code).findAnyOrNull();
+ }
+ return client;
+ }
+
+ /**
+ * Récupère les information de la table NewClient pour mettre à jour la table Client.
+ */
+ @Override
+ public void updateNewClients() {
+ NewClientTopiaDao newClientDao = getPersistenceContext().getNewClientDao();
+ ClientTopiaDao clientDao = getPersistenceContext().getClientDao();
+ FaxToMailUserTopiaDao faxToMailUserDao = getPersistenceContext().getFaxToMailUserDao();
+ Iterable<NewClient> newClients = newClientDao.findAll();
+ Binder<NewClient, Client> binder = BinderFactory.newBinder(NewClient.class, Client.class);
+
+ for (NewClient newClient : newClients) {
+
+ NewClientType type = newClient.getType();
+ switch (type) {
+ case CREATION:
+ case UPDATE:
+
+ // find client to create or update
+ Client client = clientDao.forCodeEquals(newClient.getCode())
+ .addEquals(Client.PROPERTY_BRAND, newClient.getBrand()).findUniqueOrNull();
+ if (client == null) {
+ client = new ClientImpl();
+ if (type == NewClientType.UPDATE && log.isWarnEnabled()) {
+ log.warn(String.format("Can't find client code %s/%s to update. Client created.", newClient.getCode(), newClient.getBrand()));
+ }
+ } else {
+ if (type == NewClientType.CREATION && log.isWarnEnabled()) {
+ log.warn(String.format("Creating a already existing client %s/%s. Client updated.", newClient.getCode(), newClient.getBrand()));
+ }
+ }
+
+ // update client instance
+ binder.copyExcluding(newClient, client,
+ Client.PROPERTY_TOPIA_ID,
+ Client.PROPERTY_TOPIA_CREATE_DATE,
+ Client.PROPERTY_TOPIA_VERSION);
+
+ // update person in charge
+ FaxToMailUser personInCharge = null;
+ if (StringUtils.isNotBlank(newClient.getPersonInCharge())) {
+ personInCharge = faxToMailUserDao.forLoginEquals(newClient.getPersonInCharge()).findUniqueOrNull();
+ }
+ client.setPersonInCharge(personInCharge);
+
+ // persist
+ if (client.isPersisted()) {
+ clientDao.update(client);
+ } else {
+ clientDao.create(client);
+ }
+
+ break;
+
+ case DELETION:
+ Client deleteClient = clientDao.forCodeEquals(newClient.getCode())
+ .addEquals(Client.PROPERTY_BRAND, newClient.getBrand()).findUniqueOrNull();
+ if (deleteClient == null) {
+ if (log.isWarnEnabled()) {
+ log.warn(String.format("Can't find client code %s/%s to delete", newClient.getCode(), newClient.getBrand()));
+ }
+ } else {
+ // FIXME le delete ne fonctionnera pas si des mails porte sur ce client
+ clientDao.delete(deleteClient);
+ if (log.isDebugEnabled()) {
+ log.debug(String.format("Client %s/%s deleted", newClient.getCode(), newClient.getBrand()));
+ }
+ }
+ break;
+ }
+
+ }
+
+ newClientDao.deleteAll(newClients);
+ getPersistenceContext().commit();
+ }
+
+}
Property changes on: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ClientServiceImpl.java
___________________________________________________________________
Added: svn:eol-style
+ native
Added: svn:keywords
+ Author Date Id Revision HeadURL
Deleted: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationService.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -1,583 +0,0 @@
-package com.franciaflex.faxtomail.services.service;
-
-/*
- * #%L
- * FaxToMail :: Service
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2014 Franciaflex, Code Lutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/gpl-3.0.html>.
- * #L%
- */
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-
-import javax.mail.MessagingException;
-import javax.mail.Session;
-import javax.mail.Store;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.persistence.TopiaEntities;
-import org.nuiton.util.beans.Binder;
-import org.nuiton.util.beans.BinderFactory;
-
-import com.franciaflex.faxtomail.persistence.entities.Configuration;
-import com.franciaflex.faxtomail.persistence.entities.ConfigurationImpl;
-import com.franciaflex.faxtomail.persistence.entities.ConfigurationTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.DemandType;
-import com.franciaflex.faxtomail.persistence.entities.DemandTypeImpl;
-import com.franciaflex.faxtomail.persistence.entities.DemandTypeTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.EmailAccount;
-import com.franciaflex.faxtomail.persistence.entities.EmailAccountImpl;
-import com.franciaflex.faxtomail.persistence.entities.EmailAccountTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.EmailProtocol;
-import com.franciaflex.faxtomail.persistence.entities.EtatAttente;
-import com.franciaflex.faxtomail.persistence.entities.EtatAttenteImpl;
-import com.franciaflex.faxtomail.persistence.entities.EtatAttenteTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.ExtensionCommand;
-import com.franciaflex.faxtomail.persistence.entities.ExtensionCommandTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroup;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroupTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.GroupChef;
-import com.franciaflex.faxtomail.persistence.entities.GroupChefTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.MailFilter;
-import com.franciaflex.faxtomail.persistence.entities.MailFilterTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.MailFolder;
-import com.franciaflex.faxtomail.persistence.entities.MailFolderImpl;
-import com.franciaflex.faxtomail.persistence.entities.MailFolderTopiaDao;
-import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
-import com.google.common.base.Function;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-
-/**
- * @author kmorin - kmorin(a)codelutin.com
- */
-public class ConfigurationService extends FaxToMailServiceSupport {
-
- private static final Log log = LogFactory.getLog(ConfigurationService.class);
-
-
- protected static final Function<MailFilter, String> GET_EXPRESSION = new Function<MailFilter, String>() {
- @Override
- public String apply(MailFilter input) {
- return input == null ? null : input.getExpression();
- }
- };
-
- /**
- * Return unique database configuration.
- *
- * @return configuration (not {@code null}, created on not found in database)
- */
- public Configuration getConfiguration() {
- ConfigurationTopiaDao dao = getPersistenceContext().getConfigurationDao();
- Configuration config = dao.forAll().findUniqueOrNull();
- if (config == null) {
- config = new ConfigurationImpl();
- }
- return config;
- }
-
- /**
- * Get all mail filter ordered by position.
- *
- * @return all mail filter
- */
- public List<MailFilter> getMailFilters() {
- MailFilterTopiaDao mailFilterDao = getPersistenceContext().getMailFilterDao();
- List<MailFilter> result = mailFilterDao.forAll().setOrderByArguments(MailFilter.PROPERTY_POSITION + " asc").findAll();
- return result;
- }
-
- /**
- * Save configuration.
- *
- * @param config configuration to save
- */
- protected void saveConfiguration(Configuration config) {
- ConfigurationTopiaDao dao = getPersistenceContext().getConfigurationDao();
- if (config.isPersisted()) {
- config = dao.update(config);
- } else {
- config = dao.create(config);
- }
- }
-
- /**
- * Sauve l'ensemble de la configuration.
- *
- * @param configuration configuration
- * @param demandTypes types de demande
- * @param etatAttentes etat d'attentes
- * @param mailFolders mail folder
- * @param mailFilters mail filters
- * @param emailAccounts mail accounts
- */
- public void save(Configuration configuration, List<DemandType> demandTypes, List<EtatAttente> etatAttentes, List<MailFolder> mailFolders,
- List<MailFilter> mailFilters, List<EmailAccount> emailAccounts) {
-
- Collection<MailFolder> toDeleteMailFolder = new ArrayList<>();
-
- // sauvegarde
- saveConfiguration(configuration);
- saveDemandTypes(demandTypes);
- Map<String, EtatAttente> etatAttenteCache = saveEtatAttente(etatAttentes);
- Map<String, MailFolder> mailFolderCache = saveMailFolders(etatAttenteCache, mailFolders, toDeleteMailFolder);
- saveMailFilters(mailFolderCache, mailFilters);
- saveEmailAccounts(emailAccounts);
-
- // delete after loop
- MailFolderTopiaDao mailFilterDao = getPersistenceContext().getMailFolderDao();
- mailFilterDao.deleteAll(toDeleteMailFolder);
-
- // unique commit pour toute la conf
- getPersistenceContext().commit();
- }
-
- protected void saveDemandTypes(List<DemandType> demandTypes) {
- Binder<DemandType, DemandType> binderDemandType = BinderFactory.newBinder(DemandType.class);
- DemandTypeTopiaDao demandTypeDAO = getPersistenceContext().getDemandTypeDao();
-
- List<DemandType> allDemandType = demandTypeDAO.findAll();
- Map<String, DemandType> allDemandTypeIndex = new HashMap<>(Maps.uniqueIndex(allDemandType, TopiaEntities.getTopiaIdFunction()));
- for (DemandType demandType : demandTypes) {
- // get current etat attente
- DemandType currentDemandType;
- if (StringUtils.isBlank(demandType.getTopiaId()) || demandType.getTopiaId().startsWith("new_")) {
- currentDemandType = new DemandTypeImpl();
- } else {
- currentDemandType = allDemandTypeIndex.remove(demandType.getTopiaId());
- }
-
- // copy
- binderDemandType.copyExcluding(demandType, currentDemandType,
- EtatAttente.PROPERTY_TOPIA_ID,
- EtatAttente.PROPERTY_TOPIA_CREATE_DATE,
- EtatAttente.PROPERTY_TOPIA_VERSION);
-
- // persist
- if (currentDemandType.isPersisted()) {
- demandTypeDAO.update(currentDemandType);
- } else {
- demandTypeDAO.create(currentDemandType);
- }
- }
- }
-
- /**
- *
- * @param etatAttentes
- */
- protected Map<String, EtatAttente> saveEtatAttente(Collection<EtatAttente> etatAttentes) {
-
- Map<String, EtatAttente> cache = new HashMap<>();
- Binder<EtatAttente, EtatAttente> binderEtatAttente = BinderFactory.newBinder(EtatAttente.class);
- EtatAttenteTopiaDao etatAttenteDAO = getPersistenceContext().getEtatAttenteDao();
-
- List<EtatAttente> allEtatAttente = etatAttenteDAO.findAll();
- Map<String, EtatAttente> allEtatAttenteIndex = new HashMap<>(Maps.uniqueIndex(allEtatAttente, TopiaEntities.getTopiaIdFunction()));
- for (EtatAttente etatAttente : etatAttentes) {
- // get current etat attente
- EtatAttente currentEtatAttente;
- if (StringUtils.isBlank(etatAttente.getTopiaId()) || etatAttente.getTopiaId().startsWith("new_")) {
- currentEtatAttente = new EtatAttenteImpl();
- } else {
- currentEtatAttente = allEtatAttenteIndex.remove(etatAttente.getTopiaId());
- }
-
- // copy
- binderEtatAttente.copyExcluding(etatAttente, currentEtatAttente,
- EtatAttente.PROPERTY_TOPIA_ID,
- EtatAttente.PROPERTY_TOPIA_CREATE_DATE,
- EtatAttente.PROPERTY_TOPIA_VERSION);
-
- // persist
- if (currentEtatAttente.isPersisted()) {
- etatAttenteDAO.update(currentEtatAttente);
- } else {
- etatAttenteDAO.create(currentEtatAttente);
- }
-
- // cache
- cache.put(etatAttente.getTopiaId(), currentEtatAttente);
- }
-
- // delete remaining (not done here, done after reference cleaning)
- etatAttenteDAO.deleteAll(allEtatAttenteIndex.values());
-
- return cache;
- }
-
- /**
- * Save mail folder without commit.
- *
- * @param etatAttenteCache cache etat attente
- * @param newMailFolders mail folders
- * @return mail folder cache with input ids
- */
- protected Map<String, MailFolder> saveMailFolders(Map<String, EtatAttente> etatAttenteCache, Collection<MailFolder> newMailFolders, Collection<MailFolder> toDeleteMailFolder) {
- // get current folders
- MailFolderTopiaDao dao = getPersistenceContext().getMailFolderDao();
- List<MailFolder> mailFolders = dao.findAll();
- Map<String, MailFolder> mailFolderMap = new HashMap<>(Maps.uniqueIndex(mailFolders, TopiaEntities.getTopiaIdFunction()));
-
- // recursive update
- Map<String, MailFolder> mailFolderCache = new HashMap<>();
- saveMailFolders(dao, etatAttenteCache, mailFolderMap, null, newMailFolders, mailFolderCache);
-
- // if map is not empty after recursive iteration, remaining folder must be deleted
- toDeleteMailFolder.addAll(mailFolderMap.values());
-
- return mailFolderCache;
- }
-
- /**
- * Save mail folder without commit.
- *
- * @param dao
- * @param etatAttenteCache
- * @param mailFolderMap
- * @param parent
- * @param mailFolders
- * @param mailFolderCache
- * @return
- */
- protected Collection<MailFolder> saveMailFolders(MailFolderTopiaDao dao, Map<String, EtatAttente> etatAttenteCache,
- Map<String, MailFolder> mailFolderMap, MailFolder parent, Collection<MailFolder> mailFolders, Map<String, MailFolder> mailFolderCache) {
-
- Collection<MailFolder> result = Lists.newArrayList();
- if (mailFolders == null) {
- return result;
- }
-
- Binder<MailFolder, MailFolder> binderMailFolder = BinderFactory.newBinder(MailFolder.class);
- for (MailFolder mailFolder : mailFolders) {
-
- MailFolder currentMailFolder;
- if (StringUtils.isBlank(mailFolder.getTopiaId()) || mailFolder.getTopiaId().startsWith("new_")) {
- currentMailFolder = new MailFolderImpl();
- } else {
- currentMailFolder = mailFolderMap.remove(mailFolder.getTopiaId());
- }
-
- binderMailFolder.copyExcluding(mailFolder, currentMailFolder,
- MailFolder.PROPERTY_TOPIA_ID,
- MailFolder.PROPERTY_TOPIA_CREATE_DATE,
- MailFolder.PROPERTY_TOPIA_VERSION,
- MailFolder.PROPERTY_CHILDREN,
- MailFolder.PROPERTY_ETAT_ATTENTES,
- MailFolder.PROPERTY_PARENT);
-
- // gestion des bonnes références des états d'attente (surtout le cas "new_")
- currentMailFolder.clearEtatAttentes();
- if (mailFolder.getEtatAttentes() != null) {
- for (EtatAttente etatAttente : mailFolder.getEtatAttentes()) {
- // etatAttente.getTopiaId() peut retourner un id qui commence par new_
- currentMailFolder.addEtatAttentes(etatAttenteCache.get(etatAttente.getTopiaId()));
- }
- }
-
- currentMailFolder.setParent(parent);
-
- if (!currentMailFolder.isPersisted()) {
- currentMailFolder = dao.create(currentMailFolder);
- }
-
- Collection<MailFolder> children = saveMailFolders(dao, etatAttenteCache, mailFolderMap, currentMailFolder, mailFolder.getChildren(), mailFolderCache);
- currentMailFolder.setChildren(children);
- dao.update(currentMailFolder);
-
- result.add(currentMailFolder);
-
- // add in cache
- mailFolderCache.put(mailFolder.getTopiaId(), currentMailFolder);
- }
-
- return result;
- }
-
- /**
- * Save all mail filters without commit.
- *
- * @param mailFolderCache mail folder cache (with corrects ids)
- * @param mailFilters mail filters to save
- */
- protected void saveMailFilters(Map<String, MailFolder> mailFolderCache, List<MailFilter> mailFilters) {
- MailFilterTopiaDao dao = getPersistenceContext().getMailFilterDao();
-
- int position = 0;
- List<MailFilter> filters = dao.findAll();
- // order by naturalId
- Map<String, MailFilter> filterByExpression = new HashMap<>(Maps.uniqueIndex(filters, GET_EXPRESSION));
- for (MailFilter mailFilter : mailFilters) {
-
- MailFilter filter = filterByExpression.remove(mailFilter.getExpression().toLowerCase());
- boolean create = filter == null;
- if (create) {
- filter = dao.newInstance();
- }
-
- filter.setExpression(mailFilter.getExpression().toLowerCase());
- filter.setFilterFolderPriority(mailFilter.isFilterFolderPriority());
-
- // mailFilter.getMailFolder().getTopiaId() can start with new_
- MailFolder mailFolder = mailFolderCache.get(mailFilter.getMailFolder().getTopiaId());
- filter.setMailFolder(mailFolder);
- filter.setPosition(position);
-
- if (create) {
- filter = dao.create(filter);
- } else {
- filter = dao.update(filter);
- }
- position++;
- }
-
- dao.deleteAll(filterByExpression.values());
- }
-
- /**
- * Return all email accounts (without password info).
- *
- * @return all email account
- */
- public List<EmailAccount> getEmailAccountsWithoutPasswords() {
- List<EmailAccount> accounts = getEmailAccounts();
- // remove password information from bean
- final Binder<EmailAccount, EmailAccount> binderEmailAccount = BinderFactory.newBinder(EmailAccount.class);
- List<EmailAccount> result = Lists.transform(accounts, new Function<EmailAccount, EmailAccount>() {
- @Override
- public EmailAccount apply(EmailAccount input) {
- EmailAccount account = new EmailAccountImpl();
- binderEmailAccount.copyExcluding(input, account, EmailAccount.PROPERTY_PASSWORD);
- return account;
- }
- });
-
- return result;
- }
-
- public List<EmailAccount> getEmailAccounts() {
- EmailAccountTopiaDao emailAccountTopiaDao = getPersistenceContext().getEmailAccountDao();
- List<EmailAccount> result = emailAccountTopiaDao.findAll();
- return result;
- }
-
- /**
- * Save email account without commit.
- *
- * @param newEmailAccounts new email account list to save
- */
- protected void saveEmailAccounts(List<EmailAccount> newEmailAccounts) {
- EmailAccountTopiaDao emailAccountTopiaDao = getPersistenceContext().getEmailAccountDao();
- List<EmailAccount> emailAccounts = emailAccountTopiaDao.findAll();
- Map<String, EmailAccount> emailAccountMap = new HashMap<>(Maps.uniqueIndex(emailAccounts, TopiaEntities.getTopiaIdFunction()));
- Binder<EmailAccount, EmailAccount> binder = BinderFactory.newBinder(EmailAccount.class);
-
- for (EmailAccount newEmailAccount : newEmailAccounts) {
- EmailAccount emailAccount;
- if (StringUtils.isNotBlank(newEmailAccount.getTopiaId())) {
- emailAccount = emailAccountMap.remove(newEmailAccount.getTopiaId());
- } else {
- emailAccount = new EmailAccountImpl();
- }
-
- binder.copyExcluding(newEmailAccount, emailAccount,
- EmailAccount.PROPERTY_TOPIA_ID,
- EmailAccount.PROPERTY_TOPIA_CREATE_DATE,
- EmailAccount.PROPERTY_TOPIA_VERSION,
- EmailAccount.PROPERTY_PASSWORD);
-
- // password is only present for new account (not for edited ones)
- if (StringUtils.isNotEmpty(newEmailAccount.getPassword())) {
- emailAccount.setPassword(newEmailAccount.getPassword());
- }
-
- if (emailAccount.isPersisted()) {
- emailAccountTopiaDao.update(emailAccount);
- } else {
- emailAccountTopiaDao.create(emailAccount);
- }
- }
-
- emailAccountTopiaDao.deleteAll(emailAccountMap.values());
- }
-
- public void saveUserFolders(Map<String, Collection<MailFolder>> userFolders) {
- FaxToMailUserTopiaDao faxToMailUserTopiaDao = getPersistenceContext().getFaxToMailUserDao();
-
- for (Map.Entry<String, Collection<MailFolder>> entry : userFolders.entrySet()) {
- String userId = entry.getKey();
- Collection<MailFolder> mailFolders = entry.getValue();
-
- FaxToMailUser user = faxToMailUserTopiaDao.forTopiaIdEquals(userId).findUnique();
- user.clearAffectedFolders();
- for (MailFolder mailFolder : mailFolders) {
- user.addAffectedFolders(mailFolder);
- }
- faxToMailUserTopiaDao.update(user);
- }
-
- getPersistenceContext().commit();
- }
-
- public ExtensionCommand getExtensionCommand(String extension) {
- ExtensionCommandTopiaDao extensionCommandDao = getPersistenceContext().getExtensionCommandDao();
- ExtensionCommand result = extensionCommandDao.findByExtension(extension);
- return result;
- }
-
- /**
- * Retourne l'ensemble des utilisateurs appartenant aux groupes gérés par les groupes chef.
- *
- * @param user current user
- * @return all managed users
- */
- public Set<FaxToMailUser> getUserManagedUsers(FaxToMailUser user) {
-
- Set<FaxToMailUser> result = new HashSet<>();
-
- // s'il n'y a pas de group, il ne peut pas y avoir de droits
- if (user.getUserGroups() != null) {
-
- // recuperation de tout les groupes chef dont l'utilsateur est membre
- GroupChefTopiaDao groupChefTopiaDao = getPersistenceContext().getGroupChefDao();
- List<GroupChef> groupChefs = groupChefTopiaDao.forUserGroupIn(user.getUserGroups()).findAll();
-
- // recuperation de tous les users des groups gérés
- FaxToMailUserTopiaDao faxToMailUserTopiaDao = getPersistenceContext().getFaxToMailUserDao();
- for (GroupChef groupChef : groupChefs) {
- // groups
- if (groupChef.getManagedGroups() != null) {
- for (FaxToMailUserGroup group : groupChef.getManagedGroups()) {
- List<FaxToMailUser> users = faxToMailUserTopiaDao.forUserGroupsContains(group).findAll();
- result.addAll(users);
- }
- }
- // users
- if (groupChef.getManagedUsers() != null) {
- result.addAll(groupChef.getManagedUsers());
- }
- }
- }
-
- return result;
- }
-
- /**
- * Return file information on file path.
- *
- * @param path path
- * @return file info
- */
- public Map<String, Object> checkDirectory(String path) {
- Map<String, Object> result = new HashMap<>();
- File file = new File(path);
- result.put("path", path);
- result.put("exist", file.exists());
- result.put("isDirectory", file.isDirectory());
- result.put("canRead", file.canRead());
- result.put("canWrite", file.canWrite());
- result.put("canExecute", file.canExecute());
- return result;
- }
-
- /**
- * Verification de la connexion à un serveur de mail.
- *
- * @param account email account to check
- * @return
- */
- public Map<String, Object> checkMailaccount(EmailAccount account) {
- Map<String, Object> result = new HashMap<>();
-
- long before = System.currentTimeMillis();
- if (log.isDebugEnabled()) {
- log.debug("Check account " + account.getProtocol() + " : " + account.getHost());
- }
-
- Properties properties = new Properties();
-
- if (account.getProtocol() == EmailProtocol.POP3S) {
- properties.setProperty("mail.pop3.ssl.enable", "true");
- }
-
- switch (account.getProtocol()) {
- case IMAPS:
- properties.setProperty("mail.imap.ssl.enable", "true");
- case IMAP:
- properties.setProperty("mail.store.protocol", "imap");
- properties.setProperty("mail.imap.host", account.getHost());
- properties.setProperty("mail.imap.port", String.valueOf(account.getPort()));
- properties.setProperty("mail.imap.connectiontimeout", "2000");
- break;
- case POP3S:
- properties.setProperty("mail.pop3.ssl.enable", "true");
- case POP3:
- properties.setProperty("mail.store.protocol", "pop3");
- properties.setProperty("mail.pop3.host", account.getHost());
- properties.setProperty("mail.pop3.port", String.valueOf(account.getPort()));
- properties.setProperty("mail.pop3.connectiontimeout", "2000");
- break;
- }
-
- Session session = Session.getInstance(properties);
- Store store = null;
-
- try {
- store = session.getStore();
- store.connect(account.getLogin(), account.getPassword());
- store.close();
-
- // set result map
- result.put("ok", true);
- } catch (MessagingException e) {
- log.error("Error while getting emails from the mailbox", e);
-
- // set result map
- result.put("ok", false);
- result.put("error", e.getMessage());
- } finally {
- if (store != null) {
- try {
- store.close();
- } catch (MessagingException ex) {
- // silent close
- }
- }
- }
-
- if (log.isDebugEnabled()) {
- long after = System.currentTimeMillis();
- log.debug("Checked in " + (after - before) + " ms");
- }
- return result;
- }
-}
Added: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationService.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,42 @@
+package com.franciaflex.faxtomail.services.service;
+
+import com.franciaflex.faxtomail.persistence.entities.Configuration;
+import com.franciaflex.faxtomail.persistence.entities.DemandType;
+import com.franciaflex.faxtomail.persistence.entities.EmailAccount;
+import com.franciaflex.faxtomail.persistence.entities.EtatAttente;
+import com.franciaflex.faxtomail.persistence.entities.ExtensionCommand;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+import com.franciaflex.faxtomail.persistence.entities.MailFilter;
+import com.franciaflex.faxtomail.persistence.entities.MailFolder;
+import com.franciaflex.faxtomail.services.FaxToMailService;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @author Kevin Morin (Code Lutin)
+ */
+public interface ConfigurationService extends FaxToMailService {
+ Configuration getConfiguration();
+
+ List<MailFilter> getMailFilters();
+
+ void save(Configuration configuration, List<DemandType> demandTypes, List<EtatAttente> etatAttentes, List<MailFolder> mailFolders,
+ List<MailFilter> mailFilters, List<EmailAccount> emailAccounts);
+
+ List<EmailAccount> getEmailAccountsWithoutPasswords();
+
+ List<EmailAccount> getEmailAccounts();
+
+ void saveUserFolders(Map<String, Collection<MailFolder>> userFolders);
+
+ ExtensionCommand getExtensionCommand(String extension);
+
+ Set<FaxToMailUser> getUserManagedUsers(FaxToMailUser user);
+
+ Map<String, Object> checkDirectory(String path);
+
+ Map<String, Object> checkMailaccount(EmailAccount account);
+}
Copied: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationServiceImpl.java (from rev 468, trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationService.java)
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationServiceImpl.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationServiceImpl.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,592 @@
+package com.franciaflex.faxtomail.services.service;
+
+/*
+ * #%L
+ * FaxToMail :: Service
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2014 Franciaflex, Code Lutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+
+import javax.mail.MessagingException;
+import javax.mail.Session;
+import javax.mail.Store;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.topia.persistence.TopiaEntities;
+import org.nuiton.util.beans.Binder;
+import org.nuiton.util.beans.BinderFactory;
+
+import com.franciaflex.faxtomail.persistence.entities.Configuration;
+import com.franciaflex.faxtomail.persistence.entities.ConfigurationImpl;
+import com.franciaflex.faxtomail.persistence.entities.ConfigurationTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.DemandType;
+import com.franciaflex.faxtomail.persistence.entities.DemandTypeImpl;
+import com.franciaflex.faxtomail.persistence.entities.DemandTypeTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.EmailAccount;
+import com.franciaflex.faxtomail.persistence.entities.EmailAccountImpl;
+import com.franciaflex.faxtomail.persistence.entities.EmailAccountTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.EmailProtocol;
+import com.franciaflex.faxtomail.persistence.entities.EtatAttente;
+import com.franciaflex.faxtomail.persistence.entities.EtatAttenteImpl;
+import com.franciaflex.faxtomail.persistence.entities.EtatAttenteTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.ExtensionCommand;
+import com.franciaflex.faxtomail.persistence.entities.ExtensionCommandTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroup;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.GroupChef;
+import com.franciaflex.faxtomail.persistence.entities.GroupChefTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.MailFilter;
+import com.franciaflex.faxtomail.persistence.entities.MailFilterTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.MailFolder;
+import com.franciaflex.faxtomail.persistence.entities.MailFolderImpl;
+import com.franciaflex.faxtomail.persistence.entities.MailFolderTopiaDao;
+import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
+import com.google.common.base.Function;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+
+/**
+ * @author kmorin - kmorin(a)codelutin.com
+ */
+public class ConfigurationServiceImpl extends FaxToMailServiceSupport implements ConfigurationService {
+
+ private static final Log log = LogFactory.getLog(ConfigurationServiceImpl.class);
+
+
+ protected static final Function<MailFilter, String> GET_EXPRESSION = new Function<MailFilter, String>() {
+ @Override
+ public String apply(MailFilter input) {
+ return input == null ? null : input.getExpression();
+ }
+ };
+
+ /**
+ * Return unique database configuration.
+ *
+ * @return configuration (not {@code null}, created on not found in database)
+ */
+ @Override
+ public Configuration getConfiguration() {
+ ConfigurationTopiaDao dao = getPersistenceContext().getConfigurationDao();
+ Configuration config = dao.forAll().findUniqueOrNull();
+ if (config == null) {
+ config = new ConfigurationImpl();
+ }
+ return config;
+ }
+
+ /**
+ * Get all mail filter ordered by position.
+ *
+ * @return all mail filter
+ */
+ @Override
+ public List<MailFilter> getMailFilters() {
+ MailFilterTopiaDao mailFilterDao = getPersistenceContext().getMailFilterDao();
+ List<MailFilter> result = mailFilterDao.forAll().setOrderByArguments(MailFilter.PROPERTY_POSITION + " asc").findAll();
+ return result;
+ }
+
+ /**
+ * Save configuration.
+ *
+ * @param config configuration to save
+ */
+ protected void saveConfiguration(Configuration config) {
+ ConfigurationTopiaDao dao = getPersistenceContext().getConfigurationDao();
+ if (config.isPersisted()) {
+ config = dao.update(config);
+ } else {
+ config = dao.create(config);
+ }
+ }
+
+ /**
+ * Sauve l'ensemble de la configuration.
+ *
+ * @param configuration configuration
+ * @param demandTypes types de demande
+ * @param etatAttentes etat d'attentes
+ * @param mailFolders mail folder
+ * @param mailFilters mail filters
+ * @param emailAccounts mail accounts
+ */
+ @Override
+ public void save(Configuration configuration, List<DemandType> demandTypes, List<EtatAttente> etatAttentes, List<MailFolder> mailFolders,
+ List<MailFilter> mailFilters, List<EmailAccount> emailAccounts) {
+
+ Collection<MailFolder> toDeleteMailFolder = new ArrayList<>();
+
+ // sauvegarde
+ saveConfiguration(configuration);
+ saveDemandTypes(demandTypes);
+ Map<String, EtatAttente> etatAttenteCache = saveEtatAttente(etatAttentes);
+ Map<String, MailFolder> mailFolderCache = saveMailFolders(etatAttenteCache, mailFolders, toDeleteMailFolder);
+ saveMailFilters(mailFolderCache, mailFilters);
+ saveEmailAccounts(emailAccounts);
+
+ // delete after loop
+ MailFolderTopiaDao mailFilterDao = getPersistenceContext().getMailFolderDao();
+ mailFilterDao.deleteAll(toDeleteMailFolder);
+
+ // unique commit pour toute la conf
+ getPersistenceContext().commit();
+ }
+
+ protected void saveDemandTypes(List<DemandType> demandTypes) {
+ Binder<DemandType, DemandType> binderDemandType = BinderFactory.newBinder(DemandType.class);
+ DemandTypeTopiaDao demandTypeDAO = getPersistenceContext().getDemandTypeDao();
+
+ List<DemandType> allDemandType = demandTypeDAO.findAll();
+ Map<String, DemandType> allDemandTypeIndex = new HashMap<>(Maps.uniqueIndex(allDemandType, TopiaEntities.getTopiaIdFunction()));
+ for (DemandType demandType : demandTypes) {
+ // get current etat attente
+ DemandType currentDemandType;
+ if (StringUtils.isBlank(demandType.getTopiaId()) || demandType.getTopiaId().startsWith("new_")) {
+ currentDemandType = new DemandTypeImpl();
+ } else {
+ currentDemandType = allDemandTypeIndex.remove(demandType.getTopiaId());
+ }
+
+ // copy
+ binderDemandType.copyExcluding(demandType, currentDemandType,
+ EtatAttente.PROPERTY_TOPIA_ID,
+ EtatAttente.PROPERTY_TOPIA_CREATE_DATE,
+ EtatAttente.PROPERTY_TOPIA_VERSION);
+
+ // persist
+ if (currentDemandType.isPersisted()) {
+ demandTypeDAO.update(currentDemandType);
+ } else {
+ demandTypeDAO.create(currentDemandType);
+ }
+ }
+ }
+
+ /**
+ *
+ * @param etatAttentes
+ */
+ protected Map<String, EtatAttente> saveEtatAttente(Collection<EtatAttente> etatAttentes) {
+
+ Map<String, EtatAttente> cache = new HashMap<>();
+ Binder<EtatAttente, EtatAttente> binderEtatAttente = BinderFactory.newBinder(EtatAttente.class);
+ EtatAttenteTopiaDao etatAttenteDAO = getPersistenceContext().getEtatAttenteDao();
+
+ List<EtatAttente> allEtatAttente = etatAttenteDAO.findAll();
+ Map<String, EtatAttente> allEtatAttenteIndex = new HashMap<>(Maps.uniqueIndex(allEtatAttente, TopiaEntities.getTopiaIdFunction()));
+ for (EtatAttente etatAttente : etatAttentes) {
+ // get current etat attente
+ EtatAttente currentEtatAttente;
+ if (StringUtils.isBlank(etatAttente.getTopiaId()) || etatAttente.getTopiaId().startsWith("new_")) {
+ currentEtatAttente = new EtatAttenteImpl();
+ } else {
+ currentEtatAttente = allEtatAttenteIndex.remove(etatAttente.getTopiaId());
+ }
+
+ // copy
+ binderEtatAttente.copyExcluding(etatAttente, currentEtatAttente,
+ EtatAttente.PROPERTY_TOPIA_ID,
+ EtatAttente.PROPERTY_TOPIA_CREATE_DATE,
+ EtatAttente.PROPERTY_TOPIA_VERSION);
+
+ // persist
+ if (currentEtatAttente.isPersisted()) {
+ etatAttenteDAO.update(currentEtatAttente);
+ } else {
+ etatAttenteDAO.create(currentEtatAttente);
+ }
+
+ // cache
+ cache.put(etatAttente.getTopiaId(), currentEtatAttente);
+ }
+
+ // delete remaining (not done here, done after reference cleaning)
+ etatAttenteDAO.deleteAll(allEtatAttenteIndex.values());
+
+ return cache;
+ }
+
+ /**
+ * Save mail folder without commit.
+ *
+ * @param etatAttenteCache cache etat attente
+ * @param newMailFolders mail folders
+ * @return mail folder cache with input ids
+ */
+ protected Map<String, MailFolder> saveMailFolders(Map<String, EtatAttente> etatAttenteCache, Collection<MailFolder> newMailFolders, Collection<MailFolder> toDeleteMailFolder) {
+ // get current folders
+ MailFolderTopiaDao dao = getPersistenceContext().getMailFolderDao();
+ List<MailFolder> mailFolders = dao.findAll();
+ Map<String, MailFolder> mailFolderMap = new HashMap<>(Maps.uniqueIndex(mailFolders, TopiaEntities.getTopiaIdFunction()));
+
+ // recursive update
+ Map<String, MailFolder> mailFolderCache = new HashMap<>();
+ saveMailFolders(dao, etatAttenteCache, mailFolderMap, null, newMailFolders, mailFolderCache);
+
+ // if map is not empty after recursive iteration, remaining folder must be deleted
+ toDeleteMailFolder.addAll(mailFolderMap.values());
+
+ return mailFolderCache;
+ }
+
+ /**
+ * Save mail folder without commit.
+ *
+ * @param dao
+ * @param etatAttenteCache
+ * @param mailFolderMap
+ * @param parent
+ * @param mailFolders
+ * @param mailFolderCache
+ * @return
+ */
+ protected Collection<MailFolder> saveMailFolders(MailFolderTopiaDao dao, Map<String, EtatAttente> etatAttenteCache,
+ Map<String, MailFolder> mailFolderMap, MailFolder parent, Collection<MailFolder> mailFolders, Map<String, MailFolder> mailFolderCache) {
+
+ Collection<MailFolder> result = Lists.newArrayList();
+ if (mailFolders == null) {
+ return result;
+ }
+
+ Binder<MailFolder, MailFolder> binderMailFolder = BinderFactory.newBinder(MailFolder.class);
+ for (MailFolder mailFolder : mailFolders) {
+
+ MailFolder currentMailFolder;
+ if (StringUtils.isBlank(mailFolder.getTopiaId()) || mailFolder.getTopiaId().startsWith("new_")) {
+ currentMailFolder = new MailFolderImpl();
+ } else {
+ currentMailFolder = mailFolderMap.remove(mailFolder.getTopiaId());
+ }
+
+ binderMailFolder.copyExcluding(mailFolder, currentMailFolder,
+ MailFolder.PROPERTY_TOPIA_ID,
+ MailFolder.PROPERTY_TOPIA_CREATE_DATE,
+ MailFolder.PROPERTY_TOPIA_VERSION,
+ MailFolder.PROPERTY_CHILDREN,
+ MailFolder.PROPERTY_ETAT_ATTENTES,
+ MailFolder.PROPERTY_PARENT);
+
+ // gestion des bonnes références des états d'attente (surtout le cas "new_")
+ currentMailFolder.clearEtatAttentes();
+ if (mailFolder.getEtatAttentes() != null) {
+ for (EtatAttente etatAttente : mailFolder.getEtatAttentes()) {
+ // etatAttente.getTopiaId() peut retourner un id qui commence par new_
+ currentMailFolder.addEtatAttentes(etatAttenteCache.get(etatAttente.getTopiaId()));
+ }
+ }
+
+ currentMailFolder.setParent(parent);
+
+ if (!currentMailFolder.isPersisted()) {
+ currentMailFolder = dao.create(currentMailFolder);
+ }
+
+ Collection<MailFolder> children = saveMailFolders(dao, etatAttenteCache, mailFolderMap, currentMailFolder, mailFolder.getChildren(), mailFolderCache);
+ currentMailFolder.setChildren(children);
+ dao.update(currentMailFolder);
+
+ result.add(currentMailFolder);
+
+ // add in cache
+ mailFolderCache.put(mailFolder.getTopiaId(), currentMailFolder);
+ }
+
+ return result;
+ }
+
+ /**
+ * Save all mail filters without commit.
+ *
+ * @param mailFolderCache mail folder cache (with corrects ids)
+ * @param mailFilters mail filters to save
+ */
+ protected void saveMailFilters(Map<String, MailFolder> mailFolderCache, List<MailFilter> mailFilters) {
+ MailFilterTopiaDao dao = getPersistenceContext().getMailFilterDao();
+
+ int position = 0;
+ List<MailFilter> filters = dao.findAll();
+ // order by naturalId
+ Map<String, MailFilter> filterByExpression = new HashMap<>(Maps.uniqueIndex(filters, GET_EXPRESSION));
+ for (MailFilter mailFilter : mailFilters) {
+
+ MailFilter filter = filterByExpression.remove(mailFilter.getExpression().toLowerCase());
+ boolean create = filter == null;
+ if (create) {
+ filter = dao.newInstance();
+ }
+
+ filter.setExpression(mailFilter.getExpression().toLowerCase());
+ filter.setFilterFolderPriority(mailFilter.isFilterFolderPriority());
+
+ // mailFilter.getMailFolder().getTopiaId() can start with new_
+ MailFolder mailFolder = mailFolderCache.get(mailFilter.getMailFolder().getTopiaId());
+ filter.setMailFolder(mailFolder);
+ filter.setPosition(position);
+
+ if (create) {
+ filter = dao.create(filter);
+ } else {
+ filter = dao.update(filter);
+ }
+ position++;
+ }
+
+ dao.deleteAll(filterByExpression.values());
+ }
+
+ /**
+ * Return all email accounts (without password info).
+ *
+ * @return all email account
+ */
+ @Override
+ public List<EmailAccount> getEmailAccountsWithoutPasswords() {
+ List<EmailAccount> accounts = getEmailAccounts();
+ // remove password information from bean
+ final Binder<EmailAccount, EmailAccount> binderEmailAccount = BinderFactory.newBinder(EmailAccount.class);
+ List<EmailAccount> result = Lists.transform(accounts, new Function<EmailAccount, EmailAccount>() {
+ @Override
+ public EmailAccount apply(EmailAccount input) {
+ EmailAccount account = new EmailAccountImpl();
+ binderEmailAccount.copyExcluding(input, account, EmailAccount.PROPERTY_PASSWORD);
+ return account;
+ }
+ });
+
+ return result;
+ }
+
+ @Override
+ public List<EmailAccount> getEmailAccounts() {
+ EmailAccountTopiaDao emailAccountTopiaDao = getPersistenceContext().getEmailAccountDao();
+ List<EmailAccount> result = emailAccountTopiaDao.findAll();
+ return result;
+ }
+
+ /**
+ * Save email account without commit.
+ *
+ * @param newEmailAccounts new email account list to save
+ */
+ protected void saveEmailAccounts(List<EmailAccount> newEmailAccounts) {
+ EmailAccountTopiaDao emailAccountTopiaDao = getPersistenceContext().getEmailAccountDao();
+ List<EmailAccount> emailAccounts = emailAccountTopiaDao.findAll();
+ Map<String, EmailAccount> emailAccountMap = new HashMap<>(Maps.uniqueIndex(emailAccounts, TopiaEntities.getTopiaIdFunction()));
+ Binder<EmailAccount, EmailAccount> binder = BinderFactory.newBinder(EmailAccount.class);
+
+ for (EmailAccount newEmailAccount : newEmailAccounts) {
+ EmailAccount emailAccount;
+ if (StringUtils.isNotBlank(newEmailAccount.getTopiaId())) {
+ emailAccount = emailAccountMap.remove(newEmailAccount.getTopiaId());
+ } else {
+ emailAccount = new EmailAccountImpl();
+ }
+
+ binder.copyExcluding(newEmailAccount, emailAccount,
+ EmailAccount.PROPERTY_TOPIA_ID,
+ EmailAccount.PROPERTY_TOPIA_CREATE_DATE,
+ EmailAccount.PROPERTY_TOPIA_VERSION,
+ EmailAccount.PROPERTY_PASSWORD);
+
+ // password is only present for new account (not for edited ones)
+ if (StringUtils.isNotEmpty(newEmailAccount.getPassword())) {
+ emailAccount.setPassword(newEmailAccount.getPassword());
+ }
+
+ if (emailAccount.isPersisted()) {
+ emailAccountTopiaDao.update(emailAccount);
+ } else {
+ emailAccountTopiaDao.create(emailAccount);
+ }
+ }
+
+ emailAccountTopiaDao.deleteAll(emailAccountMap.values());
+ }
+
+ @Override
+ public void saveUserFolders(Map<String, Collection<MailFolder>> userFolders) {
+ FaxToMailUserTopiaDao faxToMailUserTopiaDao = getPersistenceContext().getFaxToMailUserDao();
+
+ for (Map.Entry<String, Collection<MailFolder>> entry : userFolders.entrySet()) {
+ String userId = entry.getKey();
+ Collection<MailFolder> mailFolders = entry.getValue();
+
+ FaxToMailUser user = faxToMailUserTopiaDao.forTopiaIdEquals(userId).findUnique();
+ user.clearAffectedFolders();
+ for (MailFolder mailFolder : mailFolders) {
+ user.addAffectedFolders(mailFolder);
+ }
+ faxToMailUserTopiaDao.update(user);
+ }
+
+ getPersistenceContext().commit();
+ }
+
+ @Override
+ public ExtensionCommand getExtensionCommand(String extension) {
+ ExtensionCommandTopiaDao extensionCommandDao = getPersistenceContext().getExtensionCommandDao();
+ ExtensionCommand result = extensionCommandDao.findByExtension(extension);
+ return result;
+ }
+
+ /**
+ * Retourne l'ensemble des utilisateurs appartenant aux groupes gérés par les groupes chef.
+ *
+ * @param user current user
+ * @return all managed users
+ */
+ @Override
+ public Set<FaxToMailUser> getUserManagedUsers(FaxToMailUser user) {
+
+ Set<FaxToMailUser> result = new HashSet<>();
+
+ // s'il n'y a pas de group, il ne peut pas y avoir de droits
+ if (user.getUserGroups() != null) {
+
+ // recuperation de tout les groupes chef dont l'utilsateur est membre
+ GroupChefTopiaDao groupChefTopiaDao = getPersistenceContext().getGroupChefDao();
+ List<GroupChef> groupChefs = groupChefTopiaDao.forUserGroupIn(user.getUserGroups()).findAll();
+
+ // recuperation de tous les users des groups gérés
+ FaxToMailUserTopiaDao faxToMailUserTopiaDao = getPersistenceContext().getFaxToMailUserDao();
+ for (GroupChef groupChef : groupChefs) {
+ // groups
+ if (groupChef.getManagedGroups() != null) {
+ for (FaxToMailUserGroup group : groupChef.getManagedGroups()) {
+ List<FaxToMailUser> users = faxToMailUserTopiaDao.forUserGroupsContains(group).findAll();
+ result.addAll(users);
+ }
+ }
+ // users
+ if (groupChef.getManagedUsers() != null) {
+ result.addAll(groupChef.getManagedUsers());
+ }
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Return file information on file path.
+ *
+ * @param path path
+ * @return file info
+ */
+ @Override
+ public Map<String, Object> checkDirectory(String path) {
+ Map<String, Object> result = new HashMap<>();
+ File file = new File(path);
+ result.put("path", path);
+ result.put("exist", file.exists());
+ result.put("isDirectory", file.isDirectory());
+ result.put("canRead", file.canRead());
+ result.put("canWrite", file.canWrite());
+ result.put("canExecute", file.canExecute());
+ return result;
+ }
+
+ /**
+ * Verification de la connexion à un serveur de mail.
+ *
+ * @param account email account to check
+ * @return
+ */
+ @Override
+ public Map<String, Object> checkMailaccount(EmailAccount account) {
+ Map<String, Object> result = new HashMap<>();
+
+ long before = System.currentTimeMillis();
+ if (log.isDebugEnabled()) {
+ log.debug("Check account " + account.getProtocol() + " : " + account.getHost());
+ }
+
+ Properties properties = new Properties();
+
+ if (account.getProtocol() == EmailProtocol.POP3S) {
+ properties.setProperty("mail.pop3.ssl.enable", "true");
+ }
+
+ switch (account.getProtocol()) {
+ case IMAPS:
+ properties.setProperty("mail.imap.ssl.enable", "true");
+ case IMAP:
+ properties.setProperty("mail.store.protocol", "imap");
+ properties.setProperty("mail.imap.host", account.getHost());
+ properties.setProperty("mail.imap.port", String.valueOf(account.getPort()));
+ properties.setProperty("mail.imap.connectiontimeout", "2000");
+ break;
+ case POP3S:
+ properties.setProperty("mail.pop3.ssl.enable", "true");
+ case POP3:
+ properties.setProperty("mail.store.protocol", "pop3");
+ properties.setProperty("mail.pop3.host", account.getHost());
+ properties.setProperty("mail.pop3.port", String.valueOf(account.getPort()));
+ properties.setProperty("mail.pop3.connectiontimeout", "2000");
+ break;
+ }
+
+ Session session = Session.getInstance(properties);
+ Store store = null;
+
+ try {
+ store = session.getStore();
+ store.connect(account.getLogin(), account.getPassword());
+ store.close();
+
+ // set result map
+ result.put("ok", true);
+ } catch (MessagingException e) {
+ log.error("Error while getting emails from the mailbox", e);
+
+ // set result map
+ result.put("ok", false);
+ result.put("error", e.getMessage());
+ } finally {
+ if (store != null) {
+ try {
+ store.close();
+ } catch (MessagingException ex) {
+ // silent close
+ }
+ }
+ }
+
+ if (log.isDebugEnabled()) {
+ long after = System.currentTimeMillis();
+ log.debug("Checked in " + (after - before) + " ms");
+ }
+ return result;
+ }
+}
Property changes on: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ConfigurationServiceImpl.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Deleted: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/EmailService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/EmailService.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/EmailService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -1,1003 +0,0 @@
-package com.franciaflex.faxtomail.services.service;
-
-/*
- * #%L
- * FaxToMail :: Service
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2014 Franciaflex, Code Lutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/gpl-3.0.html>.
- * #L%
- */
-
-import static org.nuiton.i18n.I18n.t;
-
-import java.io.BufferedWriter;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Writer;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.activation.DataSource;
-import javax.activation.FileDataSource;
-import javax.mail.MessagingException;
-
-import org.apache.commons.collections4.CollectionUtils;
-import org.apache.commons.collections4.Predicate;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang3.BooleanUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.time.DateFormatUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.commons.mail.DefaultAuthenticator;
-import org.apache.commons.mail.EmailConstants;
-import org.apache.commons.mail.EmailException;
-import org.apache.commons.mail.MultiPartEmail;
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
-import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
-import org.apache.pdfbox.pdmodel.interactive.form.PDField;
-import org.nuiton.topia.persistence.TopiaEntities;
-import org.nuiton.util.beans.Binder;
-import org.nuiton.util.beans.BinderFactory;
-import org.nuiton.util.pagination.PaginationParameter;
-import org.nuiton.util.pagination.PaginationResult;
-
-import com.franciaflex.faxtomail.persistence.entities.*;
-import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
-import com.franciaflex.faxtomail.services.service.exceptions.AlreadyLockedMailException;
-import com.franciaflex.faxtomail.services.service.exceptions.InvalidClientException;
-import com.google.common.base.Function;
-import com.google.common.base.Joiner;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-
-/**
- * @author kmorin - kmorin(a)codelutin.com
- */
-public class EmailService extends FaxToMailServiceSupport {
-
- private static final Log log = LogFactory.getLog(EmailService.class);
-
- protected Binder<Attachment, Attachment> attachmentBinder =
- BinderFactory.newBinder(Attachment.class, Attachment.class);
-
- public Email getEmailById(String id) {
- Email email = getPersistenceContext().getEmailDao().forTopiaIdEquals(id).findUnique();
- return email;
- }
-
- /**
- * Save email with default email client code.
- *
- * @param email email
- * @param user user
- * @param modifiedFields modified fields
- * @return updated email instance
- * @throws InvalidClientException if client code is not valid
- */
- public Email saveEmail(Email email, FaxToMailUser user, String... modifiedFields) throws InvalidClientException {
- Client client = email.getClient();
- return saveEmail(email, null, client != null ? client.getCode() : null, user, modifiedFields);
- }
-
- public Email saveEmail(Email email, Collection<Attachment> attachments, String clientCode, FaxToMailUser user, String... modifiedFields) throws InvalidClientException {
- Date now = getNow();
- EmailTopiaDao dao = getPersistenceContext().getEmailDao();
- HistoryTopiaDao historyDao = getPersistenceContext().getHistoryDao();
-
- // if client code is null, do not manage client at all
- Client client = null;
- if (StringUtils.isNotBlank(clientCode)) {
- client = getClientService().getClientForCode(clientCode);
- if (client == null) {
- String message = t("faxtomail.service.email.save.clientCode.error", clientCode);
- throw new InvalidClientException(message);
- }
- }
- email.setClient(client);
-
- if (attachments != null) {
- Collection<Attachment> currentAttachments = CollectionUtils.emptyIfNull(email.getAttachment());
- Map<String, Attachment> currentAttachmentIndex = new HashMap<>(Maps.uniqueIndex(currentAttachments, TopiaEntities.getTopiaIdFunction()));
-
- AttachmentFileTopiaDao attachementFileTopiaDao = getPersistenceContext().getAttachmentFileDao();
- for (Attachment attachment : attachments) {
-
- // get attachment BEFORE for flush
- AttachmentFile originalFile = null;
- AttachmentFile editedFile = null;
- if (attachment.isPersisted()) {
- originalFile = getAttachmentFile(attachment.getTopiaId(), true);
- editedFile = getAttachmentFile(attachment.getTopiaId(), false);
- }
-
- // get session attachment from id
- Attachment currentAttachment;
- if (StringUtils.isNoneBlank(attachment.getTopiaId())) {
- currentAttachment = currentAttachmentIndex.remove(attachment.getTopiaId());
- } else {
- currentAttachment = new AttachmentImpl();
- }
-
- // dans tout les cas, les pieces jointes courante de l'attchent prévale
- // sur celles en base
- if (attachment.getOriginalFile() != null) {
- originalFile = attachment.getOriginalFile();
- }
- if (attachment.getEditedFile() != null) {
- editedFile = attachment.getEditedFile();
- }
-
- // copy new data
- attachmentBinder.copyExcluding(attachment, currentAttachment,
- Attachment.PROPERTY_EDITED_FILE,
- Attachment.PROPERTY_EDITED_FILE_NAME,
- Attachment.PROPERTY_ORIGINAL_FILE,
- Attachment.PROPERTY_ORIGINAL_FILE_NAME,
- Attachment.PROPERTY_TOPIA_CREATE_DATE,
- Attachment.PROPERTY_TOPIA_ID,
- Attachment.PROPERTY_TOPIA_VERSION);
-
- currentAttachment.setEditedFile(editedFile);
- currentAttachment.setOriginalFile(originalFile);
-
- // ici les pieces jointes peuvent être sauvegardées sans que les pièces jointes
- // soit présentes dans les entités car l'ui ne les a pas copiées
- // pour ne pas les charger inutilement
- // donc on les remet manuellement
-
- if (!originalFile.isPersisted()) {
- attachementFileTopiaDao.create(originalFile);
- } else {
- attachementFileTopiaDao.update(originalFile);
- }
-
- if (editedFile != null) {
- if (!editedFile.isPersisted()) {
- attachementFileTopiaDao.create(editedFile);
- } else {
- attachementFileTopiaDao.update(editedFile);
- }
- }
-
- if (!currentAttachment.isPersisted()) {
- // persist using cascade
- email.addAttachment(currentAttachment);
- }
- }
-
- // delete not found attachments
- for (Attachment attachment : currentAttachmentIndex.values()) {
- email.removeAttachment(attachment);
- }
- }
-
- if (email.getRangeRow() != null) {
- RangeRowTopiaDao rangeRowDao = getPersistenceContext().getRangeRowDao();
- for (RangeRow rangeRow : email.getRangeRow()) {
- if (!rangeRow.isPersisted()) {
- rangeRowDao.create(rangeRow);
- } else {
- rangeRowDao.update(rangeRow);
- }
- }
- }
-
- if (!email.isPersisted()) {
- if (email.getHistory() != null) {
- historyDao.createAll(email.getHistory());
- }
-
- email = dao.create(email);
- }
-
- Set<String> fieldSet = Sets.newHashSet(modifiedFields);
-
- History transmissionToEdi = CollectionUtils.find(email.getHistory(), new Predicate<History>() {
- @Override
- public boolean evaluate(History object) {
- return object.getType() == HistoryType.TRANSMISSION_TO_EDI;
- }
- });
-
- // we transmit to EDI if:
- // - it has never been transmitted before
- // - all the required fields are filled
- if (transmissionToEdi == null
- && email.getClient() != null
- && email.getDemandType() != null
- && StringUtils.isNotBlank(email.getProjectReference())) {
-
- if (email.getDemandType().containsFields(MailField.RANGE_ROW)) {
-
- // si les gammes sont vides, la demande n'est pas valide, on ne fait rien dans ce cas
- // sinon on transfer à edi
- if (email.isRangeRowNotEmpty()) {
-
- // recherche parmis les dossiers parent, si la configuration ediTranfer à été demandée
- Boolean ediTranfer = null;
- MailFolder loopFolder = email.getMailFolder();
- do {
- ediTranfer = loopFolder.getEdiTransfer();
- loopFolder = loopFolder.getParent();
- } while (ediTranfer == null && loopFolder != null);
-
- if (BooleanUtils.isTrue(ediTranfer)) {
- // ajout d'un historique
- transmissionToEdi = historyDao.create(History.PROPERTY_TYPE, HistoryType.TRANSMISSION_TO_EDI,
- History.PROPERTY_MODIFICATION_DATE, new Date());
- email.addHistory(transmissionToEdi);
-
- // changement du status
- email.setDemandStatus(DemandStatus.TRANSMISSION_TO_EDI);
- fieldSet.add(Email.PROPERTY_DEMAND_STATUS);
- } else {
- // TODO echatellier : pas sur qu'il faille l'ajouter tout le temps, mais sinon, le transfer se reproduira
- transmissionToEdi = historyDao.create(History.PROPERTY_TYPE, HistoryType.TRANSMISSION_TO_EDI,
- History.PROPERTY_MODIFICATION_DATE, new Date());
- email.addHistory(transmissionToEdi);
-
- // passage en status
- email.setDemandStatus(DemandStatus.IN_PROGRESS);
- fieldSet.add(Email.PROPERTY_DEMAND_STATUS);
- }
- }
-
- } else {
-
- // TODO echatellier : pas sur qu'il faille l'ajouter tout le temps, mais sinon, le transfer se reproduira
- transmissionToEdi = historyDao.create(History.PROPERTY_TYPE, HistoryType.TRANSMISSION_TO_EDI,
- History.PROPERTY_MODIFICATION_DATE, new Date());
- email.addHistory(transmissionToEdi);
-
- // passage en status
- email.setDemandStatus(DemandStatus.IN_PROGRESS);
- fieldSet.add(Email.PROPERTY_DEMAND_STATUS);
- }
- }
-
- History history;
- if (fieldSet.contains(Email.PROPERTY_ARCHIVE_DATE)) {
- history = historyDao.create(History.PROPERTY_TYPE, HistoryType.ARCHIVED,
- History.PROPERTY_FAX_TO_MAIL_USER, user,
- History.PROPERTY_MODIFICATION_DATE, now);
-
- } else if (fieldSet.contains(Email.PROPERTY_MAIL_FOLDER)) {
- history = historyDao.create(History.PROPERTY_TYPE, HistoryType.TRANSMISSION,
- History.PROPERTY_FAX_TO_MAIL_USER, user,
- History.PROPERTY_MODIFICATION_DATE, now);
-
- } else {
- if (email.getTakenBy() == null &&
- !fieldSet.isEmpty() && !fieldSet.contains(Email.PROPERTY_TAKEN_BY)) {
- email.setTakenBy(user);
- fieldSet.add(Email.PROPERTY_TAKEN_BY);
- }
-
- history = historyDao.create(History.PROPERTY_TYPE, email.isHistoryEmpty() ? HistoryType.CREATION : HistoryType.MODIFICATION,
- History.PROPERTY_FAX_TO_MAIL_USER, user,
- History.PROPERTY_FIELDS, fieldSet,
- History.PROPERTY_MODIFICATION_DATE, now);
- }
- email.addHistory(history);
-
- Email result = dao.update(email);
- getPersistenceContext().commit();
-
- return result;
- }
-
- public void transmitPendingDemandsToEdi() {
- EmailTopiaDao dao = getPersistenceContext().getEmailDao();
-
- List<Email> toTransmitToEdi = dao.forDemandStatusEquals(DemandStatus.TRANSMISSION_TO_EDI).findAll();
- if (log.isDebugEnabled()) {
- log.debug(toTransmitToEdi.size() + " demands to transmit to edi");
- }
- for (Email email : toTransmitToEdi) {
- transmitDemandToEdi(email);
- }
- }
-
- /**
- * Generate txt file to send demand to EDI system.
- *
- * @param email email to send
- */
- protected void transmitDemandToEdi(Email email) {
- Preconditions.checkArgument(email.getDemandStatus() == DemandStatus.TRANSMISSION_TO_EDI);
- Preconditions.checkArgument(!email.getRangeRow().isEmpty());
-
- // recherche du dossier ou deposer les demandes EDI
- MailFolder folder = email.getMailFolder();
- while (!folder.isUseCurrentLevelEdiFolder() && folder.getParent() != null) {
- folder = folder.getParent();
- }
- String ediFolder = folder.getEdiFolder();
- if (StringUtils.isBlank(ediFolder)) {
- if (log.isFatalEnabled()) {
- log.fatal("Aucun dossier de depot des demandes EDI défini pour le dossier " + folder.getName());
- }
- return;
- }
- File ediFolderDirectory = new File(ediFolder);
- if (!ediFolderDirectory.canWrite()) {
- if (log.isFatalEnabled()) {
- log.fatal("Le dossier " + ediFolderDirectory.getAbsolutePath() + " ne dispose pas des droits d'écriture !");
- }
- return;
- }
-
- //TODO kmorin 20140521 maybe check if the file is not being read
-
- // get output file with pattern name depending on date
- Date now = serviceContext.getNow();
- String fileDate = DateFormatUtils.format(now, "yyMMddHHmmss");
-
- // create a file for each commande
- for (RangeRow rangeRow : email.getRangeRow()) {
-
- String fileName = "ORD_FAX_" + fileDate + "_" + rangeRow.getTopiaId() + ".txt";
-
- File ediFile = new File(ediFolderDirectory, fileName);
-
- // generate output content
- String separator = ";";
- try (Writer ediWriter = new BufferedWriter(new FileWriter(ediFile))) {
-
- ediWriter.write("%BEGIN_ENTETE_QUOTE\n");
-
- //N° Champ/Champ/Type/Longueur/Observation
- //01/Id Enregistrement/Alpha/1/Cst : E (En-tête)
- ediWriter.write("E" + separator);
- //02/N° d’ordre achat/Numérique/6/Cst : OARFAX
- ediWriter.write("OARFAX" + separator);
- //03/Date traitement/Date/6/JJMMAA dte système
- ediWriter.write(DateFormatUtils.format(now, "ddMMyy") + separator);
- //04/Date livraison prévue/Date/6/JJMMAA dte système
- ediWriter.write(DateFormatUtils.format(now, "ddMMyy") + separator);
- //05/Commentaire/Alpha/70/Vide
- ediWriter.write(separator);
- //06/Commentaire/Alpha/70/Vide
- ediWriter.write(separator);
- //07/Commentaire/Alpha/70/Vide
- ediWriter.write(separator);
- //08/Commentaire/Alpha/70/Vide
- ediWriter.write(separator);
- //09//Référence client FX/Alpha/36/Référence Chantier
- ediWriter.write(Strings.nullToEmpty(email.getProjectReference()) + separator);
- //10/Nom du contact/Alpha/35/Vide
- ediWriter.write(separator);
- //11/Téléphone contact/Alpha/15/Vide
- ediWriter.write(separator);
- //12/Fax contact/Alpha/15/Vide
- ediWriter.write(separator);
- //13/Devise/Alpha/3/Cst : EUR
- ediWriter.write("EUR" + separator);
- //14/Condition de livraison/Alpha/3/Vide
- ediWriter.write(separator);
- //15/Type de commande/Alpha/Type de document
- ediWriter.write(email.getDemandType().getLabel() + separator);
- //16/Adresse livr : Nom/Alpha/35/Vide
- ediWriter.write(separator);
- //18/Adresse livr : adr1/Alpha/30/Vide
- ediWriter.write(separator);
- //19/Adresse livr : adr2/Alpha/30/Vide
- ediWriter.write(separator);
- //20/Adresse livr : cp ville/Alpha/30/Vide
- ediWriter.write(separator);
- //21/Adresse livr : compl./Alpha/30/Vide
- ediWriter.write(separator);
- //22/Adresse livr : Code postal/Alpha/10/Vide
- ediWriter.write(separator);
- //23/Adresse livr : Code Pays/Alpha/3/Vide
- ediWriter.write(separator);
- //24/Code Ean acheteur/Alpha/13/Code client
- ediWriter.write(email.getClient().getCode() + separator);
- //25/Code Ean facturé/Alpha/13/Code client
- ediWriter.write(email.getClient().getCode() + separator);
- //26/Code Ean fournisseur/Alpha/13/Gamme
- ediWriter.write(rangeRow.getRange().getLabel() + separator);
- //27/Identifiant Unique
- ediWriter.write(rangeRow.getRange().getTopiaId() + "\n");
-
- ediWriter.write("%END_ENTETE_QUOTE\n");
-
- } catch (IOException ex) {
- throw new RuntimeException("Can't generate EDI file");
- }
-
- }
-
- // changement du status
- EmailTopiaDao dao = getPersistenceContext().getEmailDao();
- email.setDemandStatus(DemandStatus.TRANSMITTED_TO_EDI);
- dao.update(email);
- }
-
- /**
- * Recupère les demandes d'un dossier visible par un utilisateur.
- *
- * La methode et les résultats sont paginés.
- *
- * @param folder folder to get demande
- * @param currentUser user to check rigth
- * @param page pagination
- * @return paginated results
- */
- public PaginationResult<Email> getEmailForFolder(MailFolder folder, FaxToMailUser currentUser, PaginationParameter page) {
-
- // check if user can read current folder
- MailFolder loopFolder = folder;
- boolean readable = false;
- while (!readable && loopFolder != null) {
- // user
- readable = (loopFolder.getReadRightUsers() != null && loopFolder.getReadRightUsers().contains(currentUser)) ||
- // groups
- (currentUser.getUserGroups() != null && loopFolder.getReadRightGroups() != null && CollectionUtils.containsAny(currentUser.getUserGroups(), loopFolder.getReadRightGroups()));
-
- loopFolder = loopFolder.getParent();
- }
-
- // perform request or not depending on rigths
- PaginationResult<Email> result;
- if (readable) {
- EmailTopiaDao dao = getPersistenceContext().getEmailDao();
- result = dao.forMailFolderEquals(folder)
- .addNull(Email.PROPERTY_ARCHIVE_DATE)
- .addNotEquals(Email.PROPERTY_DEMAND_STATUS, DemandStatus.ARCHIVED)
- .findPage(page);
- } else {
- List<Email> elements = Collections.emptyList();
- result = PaginationResult.of(elements, 0, page);
- }
- return result;
- }
-
- public List<MailFolder> getChildrenRecursively(MailFolder folder) {
- List<MailFolder> folders = new ArrayList<>();
- folders.add(folder);
- Collection<MailFolder> children = folder.getChildren();
- for (MailFolder child : children) {
- folders.addAll(getChildrenRecursively(child));
- }
- return folders;
- }
-
- public Map<Range, Long[]> computeQuantitiesByRange(MailFolder rootFolder) {
- List<MailFolder> folders = getChildrenRecursively(rootFolder);
- EmailTopiaDao emailDao = getPersistenceContext().getEmailDao();
- return emailDao.computeQuantitiesByRange(folders);
- }
-
- public Email addToHistory(String emailId, HistoryType type, FaxToMailUser user, Date date, String... fields) {
- EmailTopiaDao emailDao = getPersistenceContext().getEmailDao();
- Email email = emailDao.forTopiaIdEquals(emailId).findUnique();
-
- HistoryTopiaDao historyDao = getPersistenceContext().getHistoryDao();
- History history = historyDao.create(History.PROPERTY_TYPE, type,
- History.PROPERTY_FAX_TO_MAIL_USER, user,
- History.PROPERTY_FIELDS, Sets.newHashSet(fields),
- History.PROPERTY_MODIFICATION_DATE, date);
-
- email.addHistory(history);
-
- email = emailDao.update(email);
- getPersistenceContext().commit();
-
- return email;
- }
-
- /**
- * Take email (takenBy).
- *
- * @param emailId
- * @param user
- * @return
- */
- public Email takeEmail(String emailId, FaxToMailUser user) {
- EmailTopiaDao emailDao = getPersistenceContext().getEmailDao();
- Email email = emailDao.forTopiaIdEquals(emailId).findUnique();
- email.setTakenBy(user);
-
- HistoryTopiaDao historyDao = getPersistenceContext().getHistoryDao();
- History history = historyDao.create(History.PROPERTY_TYPE, HistoryType.MODIFICATION,
- History.PROPERTY_FAX_TO_MAIL_USER, user,
- History.PROPERTY_FIELDS, Sets.newHashSet(Email.PROPERTY_TAKEN_BY),
- History.PROPERTY_MODIFICATION_DATE, new Date());
- email.addHistory(history);
-
- email = emailDao.update(email);
- getPersistenceContext().commit();
- return email;
- }
-
- /**
- * Vérrouille une demande par un utilisateur empechant les autres de l'ouvrir.
- *
- * @param emailId topiaId de la demande à vérouiller
- * @param currentUser user
- * @return email
- * @throws AlreadyLockedMailException if email is already locked by another user
- */
- public Email lockEmail(String emailId, FaxToMailUser currentUser) throws AlreadyLockedMailException {
-
- // get current lock on mail if any
- EmailTopiaDao emailDao = getPersistenceContext().getEmailDao();
- MailLockTopiaDao mailLockDao = getPersistenceContext().getMailLockDao();
- Email email = emailDao.forTopiaIdEquals(emailId).findUnique();
- MailLock mailLock = mailLockDao.forLockOnEquals(email).findUniqueOrNull();
-
- // if no lock found, create new one
- if (mailLock == null) {
- mailLock = new MailLockImpl();
- mailLock.setLockBy(currentUser);
- mailLock.setLockOn(email);
- mailLock = mailLockDao.create(mailLock);
-
- if (log.isDebugEnabled()) {
- log.debug("[LOCK] " + emailId + " locked by " + currentUser.getLogin());
- }
-
- // dévérouillage automatique des mails qui ne font pas partit du même group que celui du mail
- // qui vient d'être locké
- List<MailLock> mailLocksToRemove = mailLockDao.forLockByEquals(currentUser)
- .addNotEquals(MailLock.PROPERTY_LOCK_ON + "." + Email.PROPERTY_EMAIL_GROUP, email.getEmailGroup()).findAll();
- if (log.isDebugEnabled()) {
- for (MailLock mailLockToRemove : mailLocksToRemove) {
- log.debug("[UNLOCK] " + mailLockToRemove.getLockOn().getTopiaId() + " unlocked (automatic)");
- }
- }
- mailLockDao.deleteAll(mailLocksToRemove);
-
- getPersistenceContext().commit();
- } else if (!mailLock.getLockBy().equals(currentUser)) {
- // throw exception if already locked by another user
- throw new AlreadyLockedMailException(String.format("Mail %s already locked by %s", emailId, mailLock.getLockBy().getTopiaId()), mailLock.getLockBy());
- }
-
- return email;
- }
-
- /**
- * Dévérrouille une demande.
- *
- * @param emailId topiaId de la demande à devérouiller
- */
- public void unlockEmail(String emailId) {
- MailLockTopiaDao mailLockDao = getPersistenceContext().getMailLockDao();
- MailLock mailLock = mailLockDao.forAll().addEquals(MailLock.PROPERTY_LOCK_ON + "." + Email.PROPERTY_TOPIA_ID, emailId).findUniqueOrNull();
- // ca peut être null si c'est un emailId qui est valorisé suite à une creation et donc
- // qui n'a pas été vérrouillé avant
- if (mailLock != null) {
- mailLockDao.delete(mailLock);
- if (log.isDebugEnabled()) {
- log.debug("[UNLOCK] " + emailId + " unlocked");
- }
- getPersistenceContext().commit();
- }
- }
-
- /**
- * Calcule recursivement l'ensemble des répertoires lisible par un utilisateur récursivement.
- *
- * @param readMailFolders result mail folders
- * @param mailFolders mail folder to allow
- */
- protected void computeUserReadableFolder(Set<MailFolder> readMailFolders, Iterable<MailFolder> mailFolders) {
- if (mailFolders != null) {
- for (MailFolder mailFolder : mailFolders) {
- readMailFolders.add(mailFolder);
- computeUserReadableFolder(readMailFolders, mailFolder.getChildren());
- }
- }
- }
-
- public PaginationResult<Email> search(EmailFilter emailFilter, FaxToMailUser user, PaginationParameter pagination) {
-
- // compute rigths
- MailFolderTopiaDao mailFolderDao = getPersistenceContext().getMailFolderDao();
- Set<MailFolder> readMailFolders = new HashSet<MailFolder>();
- // read rights for user
- Iterable<MailFolder> mailFolders = mailFolderDao.forReadRightUsersContains(user).findAll();
- computeUserReadableFolder(readMailFolders, mailFolders);
- // read rigths for groups
- if (user.getUserGroups() != null) {
- for (FaxToMailUserGroup group : user.getUserGroups()) {
- mailFolders = mailFolderDao.forReadRightGroupsContains(group).findAll();
- computeUserReadableFolder(readMailFolders, mailFolders);
- }
- }
-
- // compute search
- EmailTopiaDao emailDao = getPersistenceContext().getEmailDao();
- PaginationResult<Email> result = emailDao.search(emailFilter, readMailFolders, pagination);
-
- return result;
- }
-
- public Email groupEmails(Email email1, Email email2, FaxToMailUser user) {
- EmailGroupTopiaDao groupDao = getPersistenceContext().getEmailGroupDao();
-
- EmailGroup group1 = email1.getEmailGroup();
- EmailGroup group2 = email2.getEmailGroup();
-
- // if both groups are null
- if (group1 == null && group2 == null) {
- EmailGroup group = groupDao.create(EmailGroup.PROPERTY_EMAIL, Lists.newArrayList(email1, email2));
- email1.setEmailGroup(group);
- email2.setEmailGroup(group);
-
- // if only group 1 is null
- } else if (group1 == null) {
- email1.setEmailGroup(group2);
- group2.addEmail(email1);
- groupDao.update(group2);
-
- // if only group 2 is null
- } else if (group2 == null) {
- email2.setEmailGroup(group1);
- group1.addEmail(email2);
- groupDao.update(group1);
-
- // if the groups are equals, do nothing
- } else if (group1.equals(group2)) {
- return email1;
-
- // if both groups exist, merge them
- } else {
- group1.addAllEmail(group2.getEmail());
- email2.setEmailGroup(group1);
- group2.clearEmail();
- groupDao.delete(group2);
- groupDao.update(group1);
- }
-
- EmailTopiaDao emailDao = getPersistenceContext().getEmailDao();
- HistoryTopiaDao historyDao = getPersistenceContext().getHistoryDao();
- Date now = new Date();
-
- email1.addHistory(historyDao.create(History.PROPERTY_TYPE, HistoryType.GROUP,
- History.PROPERTY_FAX_TO_MAIL_USER, user,
- History.PROPERTY_FIELDS, Sets.newHashSet(email2.getObject()),
- History.PROPERTY_MODIFICATION_DATE, now));
- Email result = emailDao.update(email1);
-
- email2.addHistory(historyDao.create(History.PROPERTY_TYPE, HistoryType.GROUP,
- History.PROPERTY_FAX_TO_MAIL_USER, user,
- History.PROPERTY_FIELDS, Sets.newHashSet(email1.getObject()),
- History.PROPERTY_MODIFICATION_DATE, now));
- emailDao.update(email2);
-
- getPersistenceContext().commit();
-
- return result;
- }
-
- /**
- * Envoi une réponse et retourne l'email.
- *
- * FIXME echatellier 20140804 : pourquoi retourner l'email ? la réponse ne devrait absolument pas modifier l'email
- *
- * @param from from
- * @param to to
- * @param cc cc
- * @param bcc bcc
- * @param subject subject
- * @param content content
- * @param attachments attachement
- * @param originalEmailId mail topia id
- * @param user user to add new history entry for user
- * @return modified email
- * @throws EmailException if message can't be sent
- * @throws MessagingException if message can't be sent
- * @throws IOException if message can't be sent
- */
- public Email reply(String from, String to, String cc, String bcc, String subject,
- String content, Collection<AttachmentFile> attachments,
- String originalEmailId, FaxToMailUser user) throws EmailException, MessagingException, IOException {
-
- Email email = getEmailById(originalEmailId);
-
- final String smtpUser = getApplicationConfig().getSmtpUser();
- final String password = getApplicationConfig().getSmtpPassword();
- final boolean useSsl = getApplicationConfig().isSmtpUseSsl();
-
- MultiPartEmail message = new MultiPartEmail();
- message.setHostName(getApplicationConfig().getSmtpHost());
- message.setSmtpPort(getApplicationConfig().getSmtpPort());
- if (StringUtils.isNotBlank(smtpUser) && password != null) {
- message.setAuthenticator(new DefaultAuthenticator(smtpUser, password));
- }
- message.setSSLOnConnect(useSsl);
-
- message.setCharset(EmailConstants.UTF_8);
- message.setFrom(from);
- message.addTo(to);
- if (StringUtils.isNotBlank(cc)) {
- message.addCc(cc);
- }
- if (StringUtils.isNotBlank(bcc)) {
- message.addBcc(bcc);
- }
- message.setSubject(subject);
- message.setMsg(content);
-
- for (AttachmentFile attachmentFile : attachments) {
- // Create the attachment
- File file = attachmentFile.getFile();
- DataSource source = new FileDataSource(file);
- message.attach(source, attachmentFile.getFilename(), null);
- }
-
- message.send();
-
- ReplyTopiaDao replyTopiaDao = getPersistenceContext().getReplyDao();
- Date now = new Date();
-
- StringBuilder emailSource = new StringBuilder();
- Enumeration<String> headerLines = message.getMimeMessage().getAllHeaderLines();
- while (headerLines.hasMoreElements()) {
- String headerLine = headerLines.nextElement();
- emailSource.append(headerLine).append("\n");
- }
- // TODO echatellier 20140804 : est volontaire et sûr de stocker l'email sous forme textuelle ?
- emailSource.append("\n").append(IOUtils.toString(message.getMimeMessage().getInputStream()));
-
- Reply reply = replyTopiaDao.create(Reply.PROPERTY_EMAIL_SOURCE, emailSource.toString(),
- Reply.PROPERTY_SENT_DATE, now,
- Reply.PROPERTY_SUBJECT, subject);
-
- email.addReplies(reply);
-
- HistoryTopiaDao historyDao = getPersistenceContext().getHistoryDao();
- History history = historyDao.create(History.PROPERTY_TYPE, HistoryType.REPLY,
- History.PROPERTY_FAX_TO_MAIL_USER, user,
- History.PROPERTY_MODIFICATION_DATE, now);
- email.addHistory(history);
-
- email = saveEmail(email, user);
-
- return email;
- }
-
- /**
- * Save content stream into attachment file content.
- *
- * @param contentStream content
- * @return attachmentFile filled by content
- */
- public AttachmentFile getAttachmentFileFromStream(InputStream contentStream) {
- AttachmentFile attachmentFile = new AttachmentFileImpl();
- try {
- //Session hibernateSession = getPersistenceContext().getHibernateSupport().getHibernateSession();
- //Blob contentBlob = Hibernate.getLobCreator(hibernateSession).createBlob(contentStream, contentStream.available());
- ByteArrayOutputStream output = new ByteArrayOutputStream();
- IOUtils.copy(contentStream, output);
- attachmentFile.setContent(output.toByteArray());
- } catch (Exception ex) {
- throw new RuntimeException("Can't save content", ex);
- }
- return attachmentFile;
- }
-
- public AttachmentFile getAttachmentFile(String attachmentId, boolean original) {
- AttachmentTopiaDao dao = getPersistenceContext().getAttachmentDao();
- Attachment attachment = dao.forTopiaIdEquals(attachmentId).findUnique();
- return original ? attachment.getOriginalFile() : attachment.getEditedFile();
- }
-
-
- /**
- * Retourne la liste des vérrouillages actifs.
- *
- * @return email list
- */
- public List<MailLock> getAllMailLocks() {
- MailLockTopiaDao mailLockDao = getPersistenceContext().getMailLockDao();
- List<MailLock> result = mailLockDao.findAll();
- return result;
- }
-
- /**
- * Dévérrouille les mails specifiés.
- *
- * @param mailLockIds mail lock ids to unlock
- */
- public void unlockMails(List<String> mailLockIds) {
- MailLockTopiaDao mailLockDao = getPersistenceContext().getMailLockDao();
- Collection<MailLock> mailLocks = mailLockDao.forTopiaIdIn(mailLockIds).findAll();
- mailLockDao.deleteAll(mailLocks);
-
- getPersistenceContext().commit();
- }
-
- public void rejectEmail(String from, String to, String subject, String content)
- throws EmailException, MessagingException, IOException {
-
- final String smtpUser = getApplicationConfig().getSmtpUser();
- final String password = getApplicationConfig().getSmtpPassword();
- final boolean useSsl = getApplicationConfig().isSmtpUseSsl();
-
- MultiPartEmail message = new MultiPartEmail();
- message.setHostName(getApplicationConfig().getSmtpHost());
- message.setSmtpPort(getApplicationConfig().getSmtpPort());
- if (StringUtils.isNotBlank(smtpUser) && password != null) {
- message.setAuthenticator(new DefaultAuthenticator(smtpUser, password));
- }
- message.setSSLOnConnect(useSsl);
-
- message.setCharset(EmailConstants.UTF_8);
- message.setFrom(from);
- message.addTo(to);
- message.setSubject(subject);
- message.setMsg(content);
-
- message.send();
- }
-
- public void updateRangeRowsWithEdiReturns() {
- EdiReturnTopiaDao ediReturnDao = getPersistenceContext().getEdiReturnDao();
- RangeRowTopiaDao rangeRowTopiaDao = getPersistenceContext().getRangeRowDao();
- EmailTopiaDao emailTopiaDao = getPersistenceContext().getEmailDao();
-
- Set<Email> emailsToUpdate = new HashSet<>();
-
- List<EdiReturn> ediReturns = ediReturnDao.findAll();
- if (log.isDebugEnabled()) {
- log.debug(ediReturns.size() + " returns from edi");
- }
- List<String> rangeRowsIds = Lists.transform(ediReturns,new Function<EdiReturn, String>() {
- @Override
- public String apply(EdiReturn ediReturn) {
- return ediReturn.getRangeRowTopiaId();
- }
- });
-
- List<RangeRow> rangeRows = rangeRowTopiaDao.forTopiaIdIn(rangeRowsIds).findAll();
- Map<String, RangeRow> rangeRowsById = Maps.uniqueIndex(rangeRows, TopiaEntities.getTopiaIdFunction());
-
- for (EdiReturn ediReturn : ediReturns) {
- RangeRow rangeRow = rangeRowsById.get(ediReturn.getRangeRowTopiaId());
- Email email = emailTopiaDao.forRangeRowContains(rangeRow).findUnique();
-
- if (StringUtils.isNotBlank(ediReturn.getError())) {
- //error
- email.setEdiError(ediReturn.getError());
-
- } else {
- rangeRow.setCommandNumber(ediReturn.getCommandNumber());
- }
-
- email.setDemandStatus(DemandStatus.IN_PROGRESS);
- emailsToUpdate.add(email);
- }
-
- rangeRowTopiaDao.updateAll(rangeRows);
- emailTopiaDao.updateAll(emailsToUpdate);
- ediReturnDao.deleteAll(ediReturns);
- getPersistenceContext().commit();
- }
-
- /**
- * Generate email details as PDF and return it as an printable attachment.
- *
- * @param email email
- * @return attachment filled with pdf content
- */
- public AttachmentFile getEmailDetailAsAttachment(Email email) {
- Map<String, String> pdfFieldValues = Maps.newHashMap();
- InputStream emptyPage = null;
- PDDocument resultDocument;
-
- AttachmentFile result = null;
-
- try {
-
- emptyPage = getClass().getResourceAsStream("/pdf/demande.pdf");
- resultDocument = PDDocument.load(emptyPage);
- /*SetField fields = new SetField();
- if (log.isTraceEnabled()) {
- log.trace("fields in document are:");
- PrintFields printFields = new PrintFields();
- printFields.printFields(resultDocument);
- }*/
-
- loadDocumentDedails(pdfFieldValues, email);
-
-
- if (log.isDebugEnabled()) {
- log.debug("will fill form document:\n" + pdfFieldValues);
- }
-
- for (Map.Entry<String, String> field : pdfFieldValues.entrySet()) {
- String fieldName = field.getKey();
- String fieldValue = field.getValue();
- setField(resultDocument, fieldName, fieldValue);
- }
-
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- resultDocument.save(out);
- resultDocument.close();
-
- result = new AttachmentFileImpl();
- result.setContent(out.toByteArray());
- result.setFilename(t("faxtomail.attachment.demand.filename") + ".pdf");
- result.getFile();
-
- } catch (Exception e) {
- if (log.isErrorEnabled()) {
- log.error("", e);
- }
- } finally {
- IOUtils.closeQuietly(emptyPage);
- }
- return result;
- }
-
- protected void loadDocumentDedails(Map<String, String> pdfFieldValues, Email email) {
- setField(pdfFieldValues, "demand", email.getObject());
- setField(pdfFieldValues, "receivedDate", DateFormatUtils.format(email.getReceptionDate(), "dd/MM/yyyy"));
- setField(pdfFieldValues, "sender", email.getSender());
- setField(pdfFieldValues, "object", email.getObject());
- setField(pdfFieldValues, "clientCode", email.getClient() == null ? "" : email.getClient().getCode());
- setField(pdfFieldValues, "demandType", email.getDemandType() == null ? "" : email.getDemandType().getLabel());
- setField(pdfFieldValues, "priority", email.getPriority() == null ? "" : email.getPriority().getLabel());
- setField(pdfFieldValues, "projectReference", email.getProjectReference());
- setField(pdfFieldValues, "companyReference", email.getCompanyReference());
- setField(pdfFieldValues, "etatAttente", email.getEtatAttente() == null ? "" : email.getEtatAttente().getLabel());
- setField(pdfFieldValues, "status", email.getDemandStatus() == null ? "" : email.getDemandStatus().getLabel());
- setField(pdfFieldValues, "takenBy", email.getTakenBy() == null ? "" : (email.getTakenBy().getLogin() + " " + email.getTakenBy().getFirstName() + " " + email.getTakenBy().getLastName()));
- }
-
- protected void setField(Map<String, String> pdfFieldValues, String fieldName, String... value) {
- if (value == null) {
- pdfFieldValues.put(fieldName, "");
- } else {
- pdfFieldValues.put(fieldName, Joiner.on(" ").skipNulls().join(value));
- }
- }
-
- protected void setField( PDDocument pdfDocument, String name, String value ) throws IOException {
- PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog();
- PDAcroForm acroForm = docCatalog.getAcroForm();
- PDField field = acroForm.getField( name );
- if ( field != null ) {
- field.setValue( value );
- } else if (log.isWarnEnabled()) {
- log.warn("Can't find field " + name + " in pdf form");
- }
- }
-}
Added: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/EmailService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/EmailService.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/EmailService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,75 @@
+package com.franciaflex.faxtomail.services.service;
+
+import com.franciaflex.faxtomail.persistence.entities.Attachment;
+import com.franciaflex.faxtomail.persistence.entities.AttachmentFile;
+import com.franciaflex.faxtomail.persistence.entities.Email;
+import com.franciaflex.faxtomail.persistence.entities.EmailFilter;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+import com.franciaflex.faxtomail.persistence.entities.HistoryType;
+import com.franciaflex.faxtomail.persistence.entities.MailFolder;
+import com.franciaflex.faxtomail.persistence.entities.MailLock;
+import com.franciaflex.faxtomail.persistence.entities.Range;
+import com.franciaflex.faxtomail.services.FaxToMailService;
+import com.franciaflex.faxtomail.services.service.exceptions.AlreadyLockedMailException;
+import com.franciaflex.faxtomail.services.service.exceptions.InvalidClientException;
+import org.apache.commons.mail.EmailException;
+import org.nuiton.util.pagination.PaginationParameter;
+import org.nuiton.util.pagination.PaginationResult;
+
+import javax.mail.MessagingException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @author Kevin Morin (Code Lutin)
+ */
+public interface EmailService extends FaxToMailService {
+ Email getEmailById(String id);
+
+ Email saveEmail(Email email, FaxToMailUser user, String... modifiedFields) throws InvalidClientException;
+
+ Email saveEmail(Email email, Collection<Attachment> attachments, String clientCode, FaxToMailUser user, String... modifiedFields) throws InvalidClientException;
+
+ void transmitPendingDemandsToEdi();
+
+ PaginationResult<Email> getEmailForFolder(MailFolder folder, FaxToMailUser currentUser, PaginationParameter page);
+
+ List<MailFolder> getChildrenRecursively(MailFolder folder);
+
+ Map<Range, Long[]> computeQuantitiesByRange(MailFolder rootFolder);
+
+ Email addToHistory(String emailId, HistoryType type, FaxToMailUser user, Date date, String... fields);
+
+ Email takeEmail(String emailId, FaxToMailUser user);
+
+ Email lockEmail(String emailId, FaxToMailUser currentUser) throws AlreadyLockedMailException;
+
+ void unlockEmail(String emailId);
+
+ PaginationResult<Email> search(EmailFilter emailFilter, FaxToMailUser user, PaginationParameter pagination);
+
+ Email groupEmails(Email email1, Email email2, FaxToMailUser user);
+
+ Email reply(String from, String to, String cc, String bcc, String subject,
+ String content, Collection<AttachmentFile> attachments,
+ String originalEmailId, FaxToMailUser user) throws EmailException, MessagingException, IOException;
+
+ AttachmentFile getAttachmentFileFromStream(InputStream contentStream);
+
+ AttachmentFile getAttachmentFile(String attachmentId, boolean original);
+
+ List<MailLock> getAllMailLocks();
+
+ void unlockMails(List<String> mailLockIds);
+
+ void rejectEmail(String from, String to, String subject, String content)
+ throws EmailException, MessagingException, IOException;
+
+ void updateRangeRowsWithEdiReturns();
+
+ AttachmentFile getEmailDetailAsAttachment(Email email);
+}
Copied: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/EmailServiceImpl.java (from rev 468, trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/EmailService.java)
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/EmailServiceImpl.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/EmailServiceImpl.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,1024 @@
+package com.franciaflex.faxtomail.services.service;
+
+/*
+ * #%L
+ * FaxToMail :: Service
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2014 Franciaflex, Code Lutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import static org.nuiton.i18n.I18n.t;
+
+import java.io.BufferedWriter;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.activation.DataSource;
+import javax.activation.FileDataSource;
+import javax.mail.MessagingException;
+
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.commons.collections4.Predicate;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.BooleanUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.time.DateFormatUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.mail.DefaultAuthenticator;
+import org.apache.commons.mail.EmailConstants;
+import org.apache.commons.mail.EmailException;
+import org.apache.commons.mail.MultiPartEmail;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
+import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
+import org.apache.pdfbox.pdmodel.interactive.form.PDField;
+import org.nuiton.topia.persistence.TopiaEntities;
+import org.nuiton.util.beans.Binder;
+import org.nuiton.util.beans.BinderFactory;
+import org.nuiton.util.pagination.PaginationParameter;
+import org.nuiton.util.pagination.PaginationResult;
+
+import com.franciaflex.faxtomail.persistence.entities.*;
+import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
+import com.franciaflex.faxtomail.services.service.exceptions.AlreadyLockedMailException;
+import com.franciaflex.faxtomail.services.service.exceptions.InvalidClientException;
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+
+/**
+ * @author kmorin - kmorin(a)codelutin.com
+ */
+public class EmailServiceImpl extends FaxToMailServiceSupport implements EmailService {
+
+ private static final Log log = LogFactory.getLog(EmailServiceImpl.class);
+
+ protected Binder<Attachment, Attachment> attachmentBinder =
+ BinderFactory.newBinder(Attachment.class, Attachment.class);
+
+ @Override
+ public Email getEmailById(String id) {
+ Email email = getPersistenceContext().getEmailDao().forTopiaIdEquals(id).findUnique();
+ return email;
+ }
+
+ /**
+ * Save email with default email client code.
+ *
+ * @param email email
+ * @param user user
+ * @param modifiedFields modified fields
+ * @return updated email instance
+ * @throws InvalidClientException if client code is not valid
+ */
+ @Override
+ public Email saveEmail(Email email, FaxToMailUser user, String... modifiedFields) throws InvalidClientException {
+ Client client = email.getClient();
+ return saveEmail(email, null, client != null ? client.getCode() : null, user, modifiedFields);
+ }
+
+ @Override
+ public Email saveEmail(Email email, Collection<Attachment> attachments, String clientCode, FaxToMailUser user, String... modifiedFields) throws InvalidClientException {
+ Date now = getNow();
+ EmailTopiaDao dao = getPersistenceContext().getEmailDao();
+ HistoryTopiaDao historyDao = getPersistenceContext().getHistoryDao();
+
+ // if client code is null, do not manage client at all
+ Client client = null;
+ if (StringUtils.isNotBlank(clientCode)) {
+ client = getClientService().getClientForCode(clientCode);
+ if (client == null) {
+ String message = t("faxtomail.service.email.save.clientCode.error", clientCode);
+ throw new InvalidClientException(message);
+ }
+ }
+ email.setClient(client);
+
+ if (attachments != null) {
+ Collection<Attachment> currentAttachments = CollectionUtils.emptyIfNull(email.getAttachment());
+ Map<String, Attachment> currentAttachmentIndex = new HashMap<>(Maps.uniqueIndex(currentAttachments, TopiaEntities.getTopiaIdFunction()));
+
+ AttachmentFileTopiaDao attachementFileTopiaDao = getPersistenceContext().getAttachmentFileDao();
+ for (Attachment attachment : attachments) {
+
+ // get attachment BEFORE for flush
+ AttachmentFile originalFile = null;
+ AttachmentFile editedFile = null;
+ if (attachment.isPersisted()) {
+ originalFile = getAttachmentFile(attachment.getTopiaId(), true);
+ editedFile = getAttachmentFile(attachment.getTopiaId(), false);
+ }
+
+ // get session attachment from id
+ Attachment currentAttachment;
+ if (StringUtils.isNoneBlank(attachment.getTopiaId())) {
+ currentAttachment = currentAttachmentIndex.remove(attachment.getTopiaId());
+ } else {
+ currentAttachment = new AttachmentImpl();
+ }
+
+ // dans tout les cas, les pieces jointes courante de l'attchent prévale
+ // sur celles en base
+ if (attachment.getOriginalFile() != null) {
+ originalFile = attachment.getOriginalFile();
+ }
+ if (attachment.getEditedFile() != null) {
+ editedFile = attachment.getEditedFile();
+ }
+
+ // copy new data
+ attachmentBinder.copyExcluding(attachment, currentAttachment,
+ Attachment.PROPERTY_EDITED_FILE,
+ Attachment.PROPERTY_EDITED_FILE_NAME,
+ Attachment.PROPERTY_ORIGINAL_FILE,
+ Attachment.PROPERTY_ORIGINAL_FILE_NAME,
+ Attachment.PROPERTY_TOPIA_CREATE_DATE,
+ Attachment.PROPERTY_TOPIA_ID,
+ Attachment.PROPERTY_TOPIA_VERSION);
+
+ currentAttachment.setEditedFile(editedFile);
+ currentAttachment.setOriginalFile(originalFile);
+
+ // ici les pieces jointes peuvent être sauvegardées sans que les pièces jointes
+ // soit présentes dans les entités car l'ui ne les a pas copiées
+ // pour ne pas les charger inutilement
+ // donc on les remet manuellement
+
+ if (!originalFile.isPersisted()) {
+ attachementFileTopiaDao.create(originalFile);
+ } else {
+ attachementFileTopiaDao.update(originalFile);
+ }
+
+ if (editedFile != null) {
+ if (!editedFile.isPersisted()) {
+ attachementFileTopiaDao.create(editedFile);
+ } else {
+ attachementFileTopiaDao.update(editedFile);
+ }
+ }
+
+ if (!currentAttachment.isPersisted()) {
+ // persist using cascade
+ email.addAttachment(currentAttachment);
+ }
+ }
+
+ // delete not found attachments
+ for (Attachment attachment : currentAttachmentIndex.values()) {
+ email.removeAttachment(attachment);
+ }
+ }
+
+ if (email.getRangeRow() != null) {
+ RangeRowTopiaDao rangeRowDao = getPersistenceContext().getRangeRowDao();
+ for (RangeRow rangeRow : email.getRangeRow()) {
+ if (!rangeRow.isPersisted()) {
+ rangeRowDao.create(rangeRow);
+ } else {
+ rangeRowDao.update(rangeRow);
+ }
+ }
+ }
+
+ if (!email.isPersisted()) {
+ if (email.getHistory() != null) {
+ historyDao.createAll(email.getHistory());
+ }
+
+ email = dao.create(email);
+ }
+
+ Set<String> fieldSet = Sets.newHashSet(modifiedFields);
+
+ History transmissionToEdi = CollectionUtils.find(email.getHistory(), new Predicate<History>() {
+ @Override
+ public boolean evaluate(History object) {
+ return object.getType() == HistoryType.TRANSMISSION_TO_EDI;
+ }
+ });
+
+ // we transmit to EDI if:
+ // - it has never been transmitted before
+ // - all the required fields are filled
+ if (transmissionToEdi == null
+ && email.getClient() != null
+ && email.getDemandType() != null
+ && StringUtils.isNotBlank(email.getProjectReference())) {
+
+ if (email.getDemandType().containsFields(MailField.RANGE_ROW)) {
+
+ // si les gammes sont vides, la demande n'est pas valide, on ne fait rien dans ce cas
+ // sinon on transfer à edi
+ if (email.isRangeRowNotEmpty()) {
+
+ // recherche parmis les dossiers parent, si la configuration ediTranfer à été demandée
+ Boolean ediTranfer = null;
+ MailFolder loopFolder = email.getMailFolder();
+ do {
+ ediTranfer = loopFolder.getEdiTransfer();
+ loopFolder = loopFolder.getParent();
+ } while (ediTranfer == null && loopFolder != null);
+
+ if (BooleanUtils.isTrue(ediTranfer)) {
+ // ajout d'un historique
+ transmissionToEdi = historyDao.create(History.PROPERTY_TYPE, HistoryType.TRANSMISSION_TO_EDI,
+ History.PROPERTY_MODIFICATION_DATE, new Date());
+ email.addHistory(transmissionToEdi);
+
+ // changement du status
+ email.setDemandStatus(DemandStatus.TRANSMISSION_TO_EDI);
+ fieldSet.add(Email.PROPERTY_DEMAND_STATUS);
+ } else {
+ // TODO echatellier : pas sur qu'il faille l'ajouter tout le temps, mais sinon, le transfer se reproduira
+ transmissionToEdi = historyDao.create(History.PROPERTY_TYPE, HistoryType.TRANSMISSION_TO_EDI,
+ History.PROPERTY_MODIFICATION_DATE, new Date());
+ email.addHistory(transmissionToEdi);
+
+ // passage en status
+ email.setDemandStatus(DemandStatus.IN_PROGRESS);
+ fieldSet.add(Email.PROPERTY_DEMAND_STATUS);
+ }
+ }
+
+ } else {
+
+ // TODO echatellier : pas sur qu'il faille l'ajouter tout le temps, mais sinon, le transfer se reproduira
+ transmissionToEdi = historyDao.create(History.PROPERTY_TYPE, HistoryType.TRANSMISSION_TO_EDI,
+ History.PROPERTY_MODIFICATION_DATE, new Date());
+ email.addHistory(transmissionToEdi);
+
+ // passage en status
+ email.setDemandStatus(DemandStatus.IN_PROGRESS);
+ fieldSet.add(Email.PROPERTY_DEMAND_STATUS);
+ }
+ }
+
+ History history;
+ if (fieldSet.contains(Email.PROPERTY_ARCHIVE_DATE)) {
+ history = historyDao.create(History.PROPERTY_TYPE, HistoryType.ARCHIVED,
+ History.PROPERTY_FAX_TO_MAIL_USER, user,
+ History.PROPERTY_MODIFICATION_DATE, now);
+
+ } else if (fieldSet.contains(Email.PROPERTY_MAIL_FOLDER)) {
+ history = historyDao.create(History.PROPERTY_TYPE, HistoryType.TRANSMISSION,
+ History.PROPERTY_FAX_TO_MAIL_USER, user,
+ History.PROPERTY_MODIFICATION_DATE, now);
+
+ } else {
+ if (email.getTakenBy() == null &&
+ !fieldSet.isEmpty() && !fieldSet.contains(Email.PROPERTY_TAKEN_BY)) {
+ email.setTakenBy(user);
+ fieldSet.add(Email.PROPERTY_TAKEN_BY);
+ }
+
+ history = historyDao.create(History.PROPERTY_TYPE, email.isHistoryEmpty() ? HistoryType.CREATION : HistoryType.MODIFICATION,
+ History.PROPERTY_FAX_TO_MAIL_USER, user,
+ History.PROPERTY_FIELDS, fieldSet,
+ History.PROPERTY_MODIFICATION_DATE, now);
+ }
+ email.addHistory(history);
+
+ Email result = dao.update(email);
+ getPersistenceContext().commit();
+
+ return result;
+ }
+
+ @Override
+ public void transmitPendingDemandsToEdi() {
+ EmailTopiaDao dao = getPersistenceContext().getEmailDao();
+
+ List<Email> toTransmitToEdi = dao.forDemandStatusEquals(DemandStatus.TRANSMISSION_TO_EDI).findAll();
+ if (log.isDebugEnabled()) {
+ log.debug(toTransmitToEdi.size() + " demands to transmit to edi");
+ }
+ for (Email email : toTransmitToEdi) {
+ transmitDemandToEdi(email);
+ }
+ }
+
+ /**
+ * Generate txt file to send demand to EDI system.
+ *
+ * @param email email to send
+ */
+ protected void transmitDemandToEdi(Email email) {
+ Preconditions.checkArgument(email.getDemandStatus() == DemandStatus.TRANSMISSION_TO_EDI);
+ Preconditions.checkArgument(!email.getRangeRow().isEmpty());
+
+ // recherche du dossier ou deposer les demandes EDI
+ MailFolder folder = email.getMailFolder();
+ while (!folder.isUseCurrentLevelEdiFolder() && folder.getParent() != null) {
+ folder = folder.getParent();
+ }
+ String ediFolder = folder.getEdiFolder();
+ if (StringUtils.isBlank(ediFolder)) {
+ if (log.isFatalEnabled()) {
+ log.fatal("Aucun dossier de depot des demandes EDI défini pour le dossier " + folder.getName());
+ }
+ return;
+ }
+ File ediFolderDirectory = new File(ediFolder);
+ if (!ediFolderDirectory.canWrite()) {
+ if (log.isFatalEnabled()) {
+ log.fatal("Le dossier " + ediFolderDirectory.getAbsolutePath() + " ne dispose pas des droits d'écriture !");
+ }
+ return;
+ }
+
+ //TODO kmorin 20140521 maybe check if the file is not being read
+
+ // get output file with pattern name depending on date
+ Date now = serviceContext.getNow();
+ String fileDate = DateFormatUtils.format(now, "yyMMddHHmmss");
+
+ // create a file for each commande
+ for (RangeRow rangeRow : email.getRangeRow()) {
+
+ String fileName = "ORD_FAX_" + fileDate + "_" + rangeRow.getTopiaId() + ".txt";
+
+ File ediFile = new File(ediFolderDirectory, fileName);
+
+ // generate output content
+ String separator = ";";
+ try (Writer ediWriter = new BufferedWriter(new FileWriter(ediFile))) {
+
+ ediWriter.write("%BEGIN_ENTETE_QUOTE\n");
+
+ //N° Champ/Champ/Type/Longueur/Observation
+ //01/Id Enregistrement/Alpha/1/Cst : E (En-tête)
+ ediWriter.write("E" + separator);
+ //02/N° d’ordre achat/Numérique/6/Cst : OARFAX
+ ediWriter.write("OARFAX" + separator);
+ //03/Date traitement/Date/6/JJMMAA dte système
+ ediWriter.write(DateFormatUtils.format(now, "ddMMyy") + separator);
+ //04/Date livraison prévue/Date/6/JJMMAA dte système
+ ediWriter.write(DateFormatUtils.format(now, "ddMMyy") + separator);
+ //05/Commentaire/Alpha/70/Vide
+ ediWriter.write(separator);
+ //06/Commentaire/Alpha/70/Vide
+ ediWriter.write(separator);
+ //07/Commentaire/Alpha/70/Vide
+ ediWriter.write(separator);
+ //08/Commentaire/Alpha/70/Vide
+ ediWriter.write(separator);
+ //09//Référence client FX/Alpha/36/Référence Chantier
+ ediWriter.write(Strings.nullToEmpty(email.getProjectReference()) + separator);
+ //10/Nom du contact/Alpha/35/Vide
+ ediWriter.write(separator);
+ //11/Téléphone contact/Alpha/15/Vide
+ ediWriter.write(separator);
+ //12/Fax contact/Alpha/15/Vide
+ ediWriter.write(separator);
+ //13/Devise/Alpha/3/Cst : EUR
+ ediWriter.write("EUR" + separator);
+ //14/Condition de livraison/Alpha/3/Vide
+ ediWriter.write(separator);
+ //15/Type de commande/Alpha/Type de document
+ ediWriter.write(email.getDemandType().getLabel() + separator);
+ //16/Adresse livr : Nom/Alpha/35/Vide
+ ediWriter.write(separator);
+ //18/Adresse livr : adr1/Alpha/30/Vide
+ ediWriter.write(separator);
+ //19/Adresse livr : adr2/Alpha/30/Vide
+ ediWriter.write(separator);
+ //20/Adresse livr : cp ville/Alpha/30/Vide
+ ediWriter.write(separator);
+ //21/Adresse livr : compl./Alpha/30/Vide
+ ediWriter.write(separator);
+ //22/Adresse livr : Code postal/Alpha/10/Vide
+ ediWriter.write(separator);
+ //23/Adresse livr : Code Pays/Alpha/3/Vide
+ ediWriter.write(separator);
+ //24/Code Ean acheteur/Alpha/13/Code client
+ ediWriter.write(email.getClient().getCode() + separator);
+ //25/Code Ean facturé/Alpha/13/Code client
+ ediWriter.write(email.getClient().getCode() + separator);
+ //26/Code Ean fournisseur/Alpha/13/Gamme
+ ediWriter.write(rangeRow.getRange().getLabel() + separator);
+ //27/Identifiant Unique
+ ediWriter.write(rangeRow.getRange().getTopiaId() + "\n");
+
+ ediWriter.write("%END_ENTETE_QUOTE\n");
+
+ } catch (IOException ex) {
+ throw new RuntimeException("Can't generate EDI file");
+ }
+
+ }
+
+ // changement du status
+ EmailTopiaDao dao = getPersistenceContext().getEmailDao();
+ email.setDemandStatus(DemandStatus.TRANSMITTED_TO_EDI);
+ dao.update(email);
+ }
+
+ /**
+ * Recupère les demandes d'un dossier visible par un utilisateur.
+ *
+ * La methode et les résultats sont paginés.
+ *
+ * @param folder folder to get demande
+ * @param currentUser user to check rigth
+ * @param page pagination
+ * @return paginated results
+ */
+ @Override
+ public PaginationResult<Email> getEmailForFolder(MailFolder folder, FaxToMailUser currentUser, PaginationParameter page) {
+
+ // check if user can read current folder
+ MailFolder loopFolder = folder;
+ boolean readable = false;
+ while (!readable && loopFolder != null) {
+ // user
+ readable = (loopFolder.getReadRightUsers() != null && loopFolder.getReadRightUsers().contains(currentUser)) ||
+ // groups
+ (currentUser.getUserGroups() != null && loopFolder.getReadRightGroups() != null && CollectionUtils.containsAny(currentUser.getUserGroups(), loopFolder.getReadRightGroups()));
+
+ loopFolder = loopFolder.getParent();
+ }
+
+ // perform request or not depending on rigths
+ PaginationResult<Email> result;
+ if (readable) {
+ EmailTopiaDao dao = getPersistenceContext().getEmailDao();
+ result = dao.forMailFolderEquals(folder)
+ .addNull(Email.PROPERTY_ARCHIVE_DATE)
+ .addNotEquals(Email.PROPERTY_DEMAND_STATUS, DemandStatus.ARCHIVED)
+ .findPage(page);
+ } else {
+ List<Email> elements = Collections.emptyList();
+ result = PaginationResult.of(elements, 0, page);
+ }
+ return result;
+ }
+
+ @Override
+ public List<MailFolder> getChildrenRecursively(MailFolder folder) {
+ List<MailFolder> folders = new ArrayList<>();
+ folders.add(folder);
+ Collection<MailFolder> children = folder.getChildren();
+ for (MailFolder child : children) {
+ folders.addAll(getChildrenRecursively(child));
+ }
+ return folders;
+ }
+
+ @Override
+ public Map<Range, Long[]> computeQuantitiesByRange(MailFolder rootFolder) {
+ List<MailFolder> folders = getChildrenRecursively(rootFolder);
+ EmailTopiaDao emailDao = getPersistenceContext().getEmailDao();
+ return emailDao.computeQuantitiesByRange(folders);
+ }
+
+ @Override
+ public Email addToHistory(String emailId, HistoryType type, FaxToMailUser user, Date date, String... fields) {
+ EmailTopiaDao emailDao = getPersistenceContext().getEmailDao();
+ Email email = emailDao.forTopiaIdEquals(emailId).findUnique();
+
+ HistoryTopiaDao historyDao = getPersistenceContext().getHistoryDao();
+ History history = historyDao.create(History.PROPERTY_TYPE, type,
+ History.PROPERTY_FAX_TO_MAIL_USER, user,
+ History.PROPERTY_FIELDS, Sets.newHashSet(fields),
+ History.PROPERTY_MODIFICATION_DATE, date);
+
+ email.addHistory(history);
+
+ email = emailDao.update(email);
+ getPersistenceContext().commit();
+
+ return email;
+ }
+
+ /**
+ * Take email (takenBy).
+ *
+ * @param emailId
+ * @param user
+ * @return
+ */
+ @Override
+ public Email takeEmail(String emailId, FaxToMailUser user) {
+ EmailTopiaDao emailDao = getPersistenceContext().getEmailDao();
+ Email email = emailDao.forTopiaIdEquals(emailId).findUnique();
+ email.setTakenBy(user);
+
+ HistoryTopiaDao historyDao = getPersistenceContext().getHistoryDao();
+ History history = historyDao.create(History.PROPERTY_TYPE, HistoryType.MODIFICATION,
+ History.PROPERTY_FAX_TO_MAIL_USER, user,
+ History.PROPERTY_FIELDS, Sets.newHashSet(Email.PROPERTY_TAKEN_BY),
+ History.PROPERTY_MODIFICATION_DATE, new Date());
+ email.addHistory(history);
+
+ email = emailDao.update(email);
+ getPersistenceContext().commit();
+ return email;
+ }
+
+ /**
+ * Vérrouille une demande par un utilisateur empechant les autres de l'ouvrir.
+ *
+ * @param emailId topiaId de la demande à vérouiller
+ * @param currentUser user
+ * @return email
+ * @throws AlreadyLockedMailException if email is already locked by another user
+ */
+ @Override
+ public Email lockEmail(String emailId, FaxToMailUser currentUser) throws AlreadyLockedMailException {
+
+ // get current lock on mail if any
+ EmailTopiaDao emailDao = getPersistenceContext().getEmailDao();
+ MailLockTopiaDao mailLockDao = getPersistenceContext().getMailLockDao();
+ Email email = emailDao.forTopiaIdEquals(emailId).findUnique();
+ MailLock mailLock = mailLockDao.forLockOnEquals(email).findUniqueOrNull();
+
+ // if no lock found, create new one
+ if (mailLock == null) {
+ mailLock = new MailLockImpl();
+ mailLock.setLockBy(currentUser);
+ mailLock.setLockOn(email);
+ mailLock = mailLockDao.create(mailLock);
+
+ if (log.isDebugEnabled()) {
+ log.debug("[LOCK] " + emailId + " locked by " + currentUser.getLogin());
+ }
+
+ // dévérouillage automatique des mails qui ne font pas partit du même group que celui du mail
+ // qui vient d'être locké
+ List<MailLock> mailLocksToRemove = mailLockDao.forLockByEquals(currentUser)
+ .addNotEquals(MailLock.PROPERTY_LOCK_ON + "." + Email.PROPERTY_EMAIL_GROUP, email.getEmailGroup()).findAll();
+ if (log.isDebugEnabled()) {
+ for (MailLock mailLockToRemove : mailLocksToRemove) {
+ log.debug("[UNLOCK] " + mailLockToRemove.getLockOn().getTopiaId() + " unlocked (automatic)");
+ }
+ }
+ mailLockDao.deleteAll(mailLocksToRemove);
+
+ getPersistenceContext().commit();
+ } else if (!mailLock.getLockBy().equals(currentUser)) {
+ // throw exception if already locked by another user
+ throw new AlreadyLockedMailException(String.format("Mail %s already locked by %s", emailId, mailLock.getLockBy().getTopiaId()), mailLock.getLockBy());
+ }
+
+ return email;
+ }
+
+ /**
+ * Dévérrouille une demande.
+ *
+ * @param emailId topiaId de la demande à devérouiller
+ */
+ @Override
+ public void unlockEmail(String emailId) {
+ MailLockTopiaDao mailLockDao = getPersistenceContext().getMailLockDao();
+ MailLock mailLock = mailLockDao.forAll().addEquals(MailLock.PROPERTY_LOCK_ON + "." + Email.PROPERTY_TOPIA_ID, emailId).findUniqueOrNull();
+ // ca peut être null si c'est un emailId qui est valorisé suite à une creation et donc
+ // qui n'a pas été vérrouillé avant
+ if (mailLock != null) {
+ mailLockDao.delete(mailLock);
+ if (log.isDebugEnabled()) {
+ log.debug("[UNLOCK] " + emailId + " unlocked");
+ }
+ getPersistenceContext().commit();
+ }
+ }
+
+ /**
+ * Calcule recursivement l'ensemble des répertoires lisible par un utilisateur récursivement.
+ *
+ * @param readMailFolders result mail folders
+ * @param mailFolders mail folder to allow
+ */
+ protected void computeUserReadableFolder(Set<MailFolder> readMailFolders, Iterable<MailFolder> mailFolders) {
+ if (mailFolders != null) {
+ for (MailFolder mailFolder : mailFolders) {
+ readMailFolders.add(mailFolder);
+ computeUserReadableFolder(readMailFolders, mailFolder.getChildren());
+ }
+ }
+ }
+
+ @Override
+ public PaginationResult<Email> search(EmailFilter emailFilter, FaxToMailUser user, PaginationParameter pagination) {
+
+ // compute rigths
+ MailFolderTopiaDao mailFolderDao = getPersistenceContext().getMailFolderDao();
+ Set<MailFolder> readMailFolders = new HashSet<MailFolder>();
+ // read rights for user
+ Iterable<MailFolder> mailFolders = mailFolderDao.forReadRightUsersContains(user).findAll();
+ computeUserReadableFolder(readMailFolders, mailFolders);
+ // read rigths for groups
+ if (user.getUserGroups() != null) {
+ for (FaxToMailUserGroup group : user.getUserGroups()) {
+ mailFolders = mailFolderDao.forReadRightGroupsContains(group).findAll();
+ computeUserReadableFolder(readMailFolders, mailFolders);
+ }
+ }
+
+ // compute search
+ EmailTopiaDao emailDao = getPersistenceContext().getEmailDao();
+ PaginationResult<Email> result = emailDao.search(emailFilter, readMailFolders, pagination);
+
+ return result;
+ }
+
+ @Override
+ public Email groupEmails(Email email1, Email email2, FaxToMailUser user) {
+ EmailGroupTopiaDao groupDao = getPersistenceContext().getEmailGroupDao();
+
+ EmailGroup group1 = email1.getEmailGroup();
+ EmailGroup group2 = email2.getEmailGroup();
+
+ // if both groups are null
+ if (group1 == null && group2 == null) {
+ EmailGroup group = groupDao.create(EmailGroup.PROPERTY_EMAIL, Lists.newArrayList(email1, email2));
+ email1.setEmailGroup(group);
+ email2.setEmailGroup(group);
+
+ // if only group 1 is null
+ } else if (group1 == null) {
+ email1.setEmailGroup(group2);
+ group2.addEmail(email1);
+ groupDao.update(group2);
+
+ // if only group 2 is null
+ } else if (group2 == null) {
+ email2.setEmailGroup(group1);
+ group1.addEmail(email2);
+ groupDao.update(group1);
+
+ // if the groups are equals, do nothing
+ } else if (group1.equals(group2)) {
+ return email1;
+
+ // if both groups exist, merge them
+ } else {
+ group1.addAllEmail(group2.getEmail());
+ email2.setEmailGroup(group1);
+ group2.clearEmail();
+ groupDao.delete(group2);
+ groupDao.update(group1);
+ }
+
+ EmailTopiaDao emailDao = getPersistenceContext().getEmailDao();
+ HistoryTopiaDao historyDao = getPersistenceContext().getHistoryDao();
+ Date now = new Date();
+
+ email1.addHistory(historyDao.create(History.PROPERTY_TYPE, HistoryType.GROUP,
+ History.PROPERTY_FAX_TO_MAIL_USER, user,
+ History.PROPERTY_FIELDS, Sets.newHashSet(email2.getObject()),
+ History.PROPERTY_MODIFICATION_DATE, now));
+ Email result = emailDao.update(email1);
+
+ email2.addHistory(historyDao.create(History.PROPERTY_TYPE, HistoryType.GROUP,
+ History.PROPERTY_FAX_TO_MAIL_USER, user,
+ History.PROPERTY_FIELDS, Sets.newHashSet(email1.getObject()),
+ History.PROPERTY_MODIFICATION_DATE, now));
+ emailDao.update(email2);
+
+ getPersistenceContext().commit();
+
+ return result;
+ }
+
+ /**
+ * Envoi une réponse et retourne l'email.
+ *
+ * FIXME echatellier 20140804 : pourquoi retourner l'email ? la réponse ne devrait absolument pas modifier l'email
+ *
+ * @param from from
+ * @param to to
+ * @param cc cc
+ * @param bcc bcc
+ * @param subject subject
+ * @param content content
+ * @param attachments attachement
+ * @param originalEmailId mail topia id
+ * @param user user to add new history entry for user
+ * @return modified email
+ * @throws EmailException if message can't be sent
+ * @throws MessagingException if message can't be sent
+ * @throws IOException if message can't be sent
+ */
+ @Override
+ public Email reply(String from, String to, String cc, String bcc, String subject,
+ String content, Collection<AttachmentFile> attachments,
+ String originalEmailId, FaxToMailUser user) throws EmailException, MessagingException, IOException {
+
+ Email email = getEmailById(originalEmailId);
+
+ final String smtpUser = getApplicationConfig().getSmtpUser();
+ final String password = getApplicationConfig().getSmtpPassword();
+ final boolean useSsl = getApplicationConfig().isSmtpUseSsl();
+
+ MultiPartEmail message = new MultiPartEmail();
+ message.setHostName(getApplicationConfig().getSmtpHost());
+ message.setSmtpPort(getApplicationConfig().getSmtpPort());
+ if (StringUtils.isNotBlank(smtpUser) && password != null) {
+ message.setAuthenticator(new DefaultAuthenticator(smtpUser, password));
+ }
+ message.setSSLOnConnect(useSsl);
+
+ message.setCharset(EmailConstants.UTF_8);
+ message.setFrom(from);
+ message.addTo(to);
+ if (StringUtils.isNotBlank(cc)) {
+ message.addCc(cc);
+ }
+ if (StringUtils.isNotBlank(bcc)) {
+ message.addBcc(bcc);
+ }
+ message.setSubject(subject);
+ message.setMsg(content);
+
+ for (AttachmentFile attachmentFile : attachments) {
+ // Create the attachment
+ File file = attachmentFile.getFile();
+ DataSource source = new FileDataSource(file);
+ message.attach(source, attachmentFile.getFilename(), null);
+ }
+
+ message.send();
+
+ ReplyTopiaDao replyTopiaDao = getPersistenceContext().getReplyDao();
+ Date now = new Date();
+
+ StringBuilder emailSource = new StringBuilder();
+ Enumeration<String> headerLines = message.getMimeMessage().getAllHeaderLines();
+ while (headerLines.hasMoreElements()) {
+ String headerLine = headerLines.nextElement();
+ emailSource.append(headerLine).append("\n");
+ }
+ // TODO echatellier 20140804 : est volontaire et sûr de stocker l'email sous forme textuelle ?
+ emailSource.append("\n").append(IOUtils.toString(message.getMimeMessage().getInputStream()));
+
+ Reply reply = replyTopiaDao.create(Reply.PROPERTY_EMAIL_SOURCE, emailSource.toString(),
+ Reply.PROPERTY_SENT_DATE, now,
+ Reply.PROPERTY_SUBJECT, subject);
+
+ email.addReplies(reply);
+
+ HistoryTopiaDao historyDao = getPersistenceContext().getHistoryDao();
+ History history = historyDao.create(History.PROPERTY_TYPE, HistoryType.REPLY,
+ History.PROPERTY_FAX_TO_MAIL_USER, user,
+ History.PROPERTY_MODIFICATION_DATE, now);
+ email.addHistory(history);
+
+ email = saveEmail(email, user);
+
+ return email;
+ }
+
+ /**
+ * Save content stream into attachment file content.
+ *
+ * @param contentStream content
+ * @return attachmentFile filled by content
+ */
+ @Override
+ public AttachmentFile getAttachmentFileFromStream(InputStream contentStream) {
+ AttachmentFile attachmentFile = new AttachmentFileImpl();
+ try {
+ //Session hibernateSession = getPersistenceContext().getHibernateSupport().getHibernateSession();
+ //Blob contentBlob = Hibernate.getLobCreator(hibernateSession).createBlob(contentStream, contentStream.available());
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ IOUtils.copy(contentStream, output);
+ attachmentFile.setContent(output.toByteArray());
+ } catch (Exception ex) {
+ throw new RuntimeException("Can't save content", ex);
+ }
+ return attachmentFile;
+ }
+
+ @Override
+ public AttachmentFile getAttachmentFile(String attachmentId, boolean original) {
+ AttachmentTopiaDao dao = getPersistenceContext().getAttachmentDao();
+ Attachment attachment = dao.forTopiaIdEquals(attachmentId).findUnique();
+ return original ? attachment.getOriginalFile() : attachment.getEditedFile();
+ }
+
+
+ /**
+ * Retourne la liste des vérrouillages actifs.
+ *
+ * @return email list
+ */
+ @Override
+ public List<MailLock> getAllMailLocks() {
+ MailLockTopiaDao mailLockDao = getPersistenceContext().getMailLockDao();
+ List<MailLock> result = mailLockDao.findAll();
+ return result;
+ }
+
+ /**
+ * Dévérrouille les mails specifiés.
+ *
+ * @param mailLockIds mail lock ids to unlock
+ */
+ @Override
+ public void unlockMails(List<String> mailLockIds) {
+ MailLockTopiaDao mailLockDao = getPersistenceContext().getMailLockDao();
+ Collection<MailLock> mailLocks = mailLockDao.forTopiaIdIn(mailLockIds).findAll();
+ mailLockDao.deleteAll(mailLocks);
+
+ getPersistenceContext().commit();
+ }
+
+ @Override
+ public void rejectEmail(String from, String to, String subject, String content)
+ throws EmailException, MessagingException, IOException {
+
+ final String smtpUser = getApplicationConfig().getSmtpUser();
+ final String password = getApplicationConfig().getSmtpPassword();
+ final boolean useSsl = getApplicationConfig().isSmtpUseSsl();
+
+ MultiPartEmail message = new MultiPartEmail();
+ message.setHostName(getApplicationConfig().getSmtpHost());
+ message.setSmtpPort(getApplicationConfig().getSmtpPort());
+ if (StringUtils.isNotBlank(smtpUser) && password != null) {
+ message.setAuthenticator(new DefaultAuthenticator(smtpUser, password));
+ }
+ message.setSSLOnConnect(useSsl);
+
+ message.setCharset(EmailConstants.UTF_8);
+ message.setFrom(from);
+ message.addTo(to);
+ message.setSubject(subject);
+ message.setMsg(content);
+
+ message.send();
+ }
+
+ @Override
+ public void updateRangeRowsWithEdiReturns() {
+ EdiReturnTopiaDao ediReturnDao = getPersistenceContext().getEdiReturnDao();
+ RangeRowTopiaDao rangeRowTopiaDao = getPersistenceContext().getRangeRowDao();
+ EmailTopiaDao emailTopiaDao = getPersistenceContext().getEmailDao();
+
+ Set<Email> emailsToUpdate = new HashSet<>();
+
+ List<EdiReturn> ediReturns = ediReturnDao.findAll();
+ if (log.isDebugEnabled()) {
+ log.debug(ediReturns.size() + " returns from edi");
+ }
+ List<String> rangeRowsIds = Lists.transform(ediReturns,new Function<EdiReturn, String>() {
+ @Override
+ public String apply(EdiReturn ediReturn) {
+ return ediReturn.getRangeRowTopiaId();
+ }
+ });
+
+ List<RangeRow> rangeRows = rangeRowTopiaDao.forTopiaIdIn(rangeRowsIds).findAll();
+ Map<String, RangeRow> rangeRowsById = Maps.uniqueIndex(rangeRows, TopiaEntities.getTopiaIdFunction());
+
+ for (EdiReturn ediReturn : ediReturns) {
+ RangeRow rangeRow = rangeRowsById.get(ediReturn.getRangeRowTopiaId());
+ Email email = emailTopiaDao.forRangeRowContains(rangeRow).findUnique();
+
+ if (StringUtils.isNotBlank(ediReturn.getError())) {
+ //error
+ email.setEdiError(ediReturn.getError());
+
+ } else {
+ rangeRow.setCommandNumber(ediReturn.getCommandNumber());
+ }
+
+ email.setDemandStatus(DemandStatus.IN_PROGRESS);
+ emailsToUpdate.add(email);
+ }
+
+ rangeRowTopiaDao.updateAll(rangeRows);
+ emailTopiaDao.updateAll(emailsToUpdate);
+ ediReturnDao.deleteAll(ediReturns);
+ getPersistenceContext().commit();
+ }
+
+ /**
+ * Generate email details as PDF and return it as an printable attachment.
+ *
+ * @param email email
+ * @return attachment filled with pdf content
+ */
+ @Override
+ public AttachmentFile getEmailDetailAsAttachment(Email email) {
+ Map<String, String> pdfFieldValues = Maps.newHashMap();
+ InputStream emptyPage = null;
+ PDDocument resultDocument;
+
+ AttachmentFile result = null;
+
+ try {
+
+ emptyPage = getClass().getResourceAsStream("/pdf/demande.pdf");
+ resultDocument = PDDocument.load(emptyPage);
+ /*SetField fields = new SetField();
+ if (log.isTraceEnabled()) {
+ log.trace("fields in document are:");
+ PrintFields printFields = new PrintFields();
+ printFields.printFields(resultDocument);
+ }*/
+
+ loadDocumentDedails(pdfFieldValues, email);
+
+
+ if (log.isDebugEnabled()) {
+ log.debug("will fill form document:\n" + pdfFieldValues);
+ }
+
+ for (Map.Entry<String, String> field : pdfFieldValues.entrySet()) {
+ String fieldName = field.getKey();
+ String fieldValue = field.getValue();
+ setField(resultDocument, fieldName, fieldValue);
+ }
+
+
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ resultDocument.save(out);
+ resultDocument.close();
+
+ result = new AttachmentFileImpl();
+ result.setContent(out.toByteArray());
+ result.setFilename(t("faxtomail.attachment.demand.filename") + ".pdf");
+ result.getFile();
+
+ } catch (Exception e) {
+ if (log.isErrorEnabled()) {
+ log.error("", e);
+ }
+ } finally {
+ IOUtils.closeQuietly(emptyPage);
+ }
+ return result;
+ }
+
+ protected void loadDocumentDedails(Map<String, String> pdfFieldValues, Email email) {
+ setField(pdfFieldValues, "demand", email.getObject());
+ setField(pdfFieldValues, "receivedDate", DateFormatUtils.format(email.getReceptionDate(), "dd/MM/yyyy"));
+ setField(pdfFieldValues, "sender", email.getSender());
+ setField(pdfFieldValues, "object", email.getObject());
+ setField(pdfFieldValues, "clientCode", email.getClient() == null ? "" : email.getClient().getCode());
+ setField(pdfFieldValues, "demandType", email.getDemandType() == null ? "" : email.getDemandType().getLabel());
+ setField(pdfFieldValues, "priority", email.getPriority() == null ? "" : email.getPriority().getLabel());
+ setField(pdfFieldValues, "projectReference", email.getProjectReference());
+ setField(pdfFieldValues, "companyReference", email.getCompanyReference());
+ setField(pdfFieldValues, "etatAttente", email.getEtatAttente() == null ? "" : email.getEtatAttente().getLabel());
+ setField(pdfFieldValues, "status", email.getDemandStatus() == null ? "" : email.getDemandStatus().getLabel());
+ setField(pdfFieldValues, "takenBy", email.getTakenBy() == null ? "" : (email.getTakenBy().getLogin() + " " + email.getTakenBy().getFirstName() + " " + email.getTakenBy().getLastName()));
+ }
+
+ protected void setField(Map<String, String> pdfFieldValues, String fieldName, String... value) {
+ if (value == null) {
+ pdfFieldValues.put(fieldName, "");
+ } else {
+ pdfFieldValues.put(fieldName, Joiner.on(" ").skipNulls().join(value));
+ }
+ }
+
+ protected void setField( PDDocument pdfDocument, String name, String value ) throws IOException {
+ PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog();
+ PDAcroForm acroForm = docCatalog.getAcroForm();
+ PDField field = acroForm.getField( name );
+ if ( field != null ) {
+ field.setValue( value );
+ } else if (log.isWarnEnabled()) {
+ log.warn("Can't find field " + name + " in pdf form");
+ }
+ }
+}
Property changes on: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/EmailServiceImpl.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Deleted: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/InitFaxToMailService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/InitFaxToMailService.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/InitFaxToMailService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -1,452 +0,0 @@
-package com.franciaflex.faxtomail.services.service;
-
-/*
- * #%L
- * FaxToMail :: Service
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2014 Franciaflex, Code Lutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/gpl-3.0.html>.
- * #L%
- */
-
-import static org.nuiton.i18n.I18n.t;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-
-import com.franciaflex.faxtomail.persistence.entities.MailField;
-
-import org.apache.commons.lang3.RandomStringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.decorator.Decorator;
-
-import com.franciaflex.faxtomail.persistence.entities.Client;
-import com.franciaflex.faxtomail.persistence.entities.DemandStatus;
-import com.franciaflex.faxtomail.persistence.entities.DemandType;
-import com.franciaflex.faxtomail.persistence.entities.DemandTypeTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.Email;
-import com.franciaflex.faxtomail.persistence.entities.EmailTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.EtatAttente;
-import com.franciaflex.faxtomail.persistence.entities.EtatAttenteTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroup;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroupTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.History;
-import com.franciaflex.faxtomail.persistence.entities.HistoryTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.HistoryType;
-import com.franciaflex.faxtomail.persistence.entities.MailFolder;
-import com.franciaflex.faxtomail.persistence.entities.MailFolderTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.Priority;
-import com.franciaflex.faxtomail.persistence.entities.PriorityTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.Range;
-import com.franciaflex.faxtomail.persistence.entities.RangeRow;
-import com.franciaflex.faxtomail.persistence.entities.RangeRowTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.RangeTopiaDao;
-import com.franciaflex.faxtomail.services.DecoratorService;
-import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
-import com.franciaflex.faxtomail.services.service.exceptions.InvalidClientException;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-
-public class InitFaxToMailService extends FaxToMailServiceSupport {
-
- private static final Log log = LogFactory.getLog(InitFaxToMailService.class);
-
- public void init() {
-
- if (log.isInfoEnabled()) {
- log.info("faxtomail initialization started");
- }
-
- boolean devMode = serviceContext.getApplicationConfig().isDevMode();
-
- if (devMode) {
- initSampleData();
- }
-
- // Reset the value stack used, if required, a new will be recreated using the struts ActionContext.
- // Need to do it here, if we want to be synched between the struts ActionContext and the value stack.
-// XWork2ValidatorUtil.setSharedValueStack(null);
-
- if (log.isInfoEnabled()) {
- log.info("faxtomail initialization done");
- }
-
- }
-
- protected void initSampleData() {
- log.debug("init Sample Data");
-
- DemandTypeTopiaDao demandTypeDao = getPersistenceContext().getDemandTypeDao();
- long count = demandTypeDao.count();
-
- if (count == 0) {
-
- List<DemandType> types = Lists.newArrayList(
- demandTypeDao.create(DemandType.PROPERTY_LABEL, "Commande", DemandType.PROPERTY_FIELDS, Lists.newArrayList(MailField.RANGE_ROW)),
- demandTypeDao.create(DemandType.PROPERTY_LABEL, "Commande Réponse"),
- demandTypeDao.create(DemandType.PROPERTY_LABEL, "Commande Annulation/Modification"),
- demandTypeDao.create(DemandType.PROPERTY_LABEL, "Devis Diffus"),
- demandTypeDao.create(DemandType.PROPERTY_LABEL, "Devis Chantier"),
- demandTypeDao.create(DemandType.PROPERTY_LABEL, "Devis Gros Chantier"),
- demandTypeDao.create(DemandType.PROPERTY_LABEL, "Devis Réponse/Modification"),
- demandTypeDao.create(DemandType.PROPERTY_LABEL, "Réclamation"),
- demandTypeDao.create(DemandType.PROPERTY_LABEL, "Autres")
- );
-
- EtatAttenteTopiaDao etatAttenteDao = getPersistenceContext().getEtatAttenteDao();
- List<EtatAttente> etatAttentes = Lists.newArrayList(
- etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "BAT attente retour BAT lettrage-logo"),
- etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "CLT attente réponse client"),
- etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "DAC attente pour assistance chantier"),
- etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "DAV attente analyse avoir"),
- etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "EXP attente expertise"),
- etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "GAB attente reception gabarit"),
- etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "GRA attente accord gratuit"),
- etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "ODC attente Ouverture de Compte"),
- etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "PPC attente chiffrage BEI PPC"),
- etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "PROFORMA attente paiement proforma"),
- etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "PROTO attente accord proto"),
- etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "REM Attente Remise-accord expo"),
- etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "RET attente retour materiel"),
- etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "SIGN attente réponse BEI signature"),
- etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "SPAM")
- );
-
- PriorityTopiaDao priorityDao = getPersistenceContext().getPriorityDao();
- List<Priority> priorities = Lists.newArrayList(
- priorityDao.create(Priority.PROPERTY_LABEL, "!"),
- priorityDao.create(Priority.PROPERTY_LABEL, "F")
- );
-
- RangeTopiaDao rangeDao = getPersistenceContext().getRangeDao();
- List<Range> ranges = Lists.newArrayList(
- rangeDao.create(Range.PROPERTY_LABEL, "FFE VR"),
- rangeDao.create(Range.PROPERTY_LABEL, "FFE AUTRE"),
- rangeDao.create(Range.PROPERTY_LABEL, "FME FX DROIT"),
- rangeDao.create(Range.PROPERTY_LABEL, "FME FX CINTRE"),
- rangeDao.create(Range.PROPERTY_LABEL, "FME NOEL"),
- rangeDao.create(Range.PROPERTY_LABEL, "FSE BANNE"),
- rangeDao.create(Range.PROPERTY_LABEL, "FSE ROCH AUTRE"),
- rangeDao.create(Range.PROPERTY_LABEL, "FSE CHECY"),
- rangeDao.create(Range.PROPERTY_LABEL, "FSI"),
- rangeDao.create(Range.PROPERTY_LABEL, "FSI FMI")
- );
-
- // user groups
- FaxToMailUserGroupTopiaDao userGroupDao = getPersistenceContext().getFaxToMailUserGroupDao();
- userGroupDao.create(FaxToMailUserGroup.PROPERTY_NAME, "Chargés de clientèle",
- FaxToMailUserGroup.PROPERTY_COMPLETE_NAME, "Franciaflex/Chargés de clientèle");
- FaxToMailUserGroup commerciauxGroup = userGroupDao.create(FaxToMailUserGroup.PROPERTY_NAME, "Commerciaux",
- FaxToMailUserGroup.PROPERTY_COMPLETE_NAME, "Franciaflex/Commerciaux");
- FaxToMailUserGroup savGroup = userGroupDao.create(FaxToMailUserGroup.PROPERTY_NAME, "SAV",
- FaxToMailUserGroup.PROPERTY_COMPLETE_NAME, "Franciaflex/SAV");
- userGroupDao.create(FaxToMailUserGroup.PROPERTY_NAME, "Administrateurs",
- FaxToMailUserGroup.PROPERTY_COMPLETE_NAME, "Franciaflex/Administrateurs");
-
- FaxToMailUserTopiaDao userDao = getPersistenceContext().getFaxToMailUserDao();
- FaxToMailUser marc = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Lefèbvre",
- FaxToMailUser.PROPERTY_FIRST_NAME, "Marc",
- FaxToMailUser.PROPERTY_LOGIN, "mlefebvre",
- FaxToMailUser.PROPERTY_TRIGRAPH, "MLE",
- FaxToMailUser.PROPERTY_USER_GROUPS, Collections.singletonList(commerciauxGroup));
- FaxToMailUser cyril = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Baillet",
- FaxToMailUser.PROPERTY_FIRST_NAME, "Cyril",
- FaxToMailUser.PROPERTY_LOGIN, "cbaillet",
- FaxToMailUser.PROPERTY_TRIGRAPH, "CBA");
- FaxToMailUser frederic = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Viala",
- FaxToMailUser.PROPERTY_FIRST_NAME, "Frédéric",
- FaxToMailUser.PROPERTY_LOGIN, "fviala",
- FaxToMailUser.PROPERTY_TRIGRAPH, "FVI",
- FaxToMailUser.PROPERTY_USER_GROUPS, Collections.singletonList(commerciauxGroup));
- FaxToMailUser claire = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Marquis",
- FaxToMailUser.PROPERTY_FIRST_NAME, "Claire",
- FaxToMailUser.PROPERTY_LOGIN, "cmarquis",
- FaxToMailUser.PROPERTY_TRIGRAPH, "CMA");
- FaxToMailUser agathe = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Borde",
- FaxToMailUser.PROPERTY_FIRST_NAME, "Agathe",
- FaxToMailUser.PROPERTY_LOGIN, "aborde",
- FaxToMailUser.PROPERTY_TRIGRAPH, "ABO",
- FaxToMailUser.PROPERTY_USER_GROUPS, Collections.singletonList(savGroup));
- FaxToMailUser jeanne = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Bourgoin",
- FaxToMailUser.PROPERTY_FIRST_NAME, "Jeanne",
- FaxToMailUser.PROPERTY_LOGIN, "jbourgoin",
- FaxToMailUser.PROPERTY_TRIGRAPH, "JBO",
- FaxToMailUser.PROPERTY_USER_GROUPS, Collections.singletonList(commerciauxGroup));
-
- MailFolderTopiaDao folderDao = getPersistenceContext().getMailFolderDao();
- Map<String, MailFolder> folders = new HashMap<>();
-
- // fixme seed to be used in test
- Random random = new Random(1234);
- EmailTopiaDao emailDao = getPersistenceContext().getEmailDao();
- HistoryTopiaDao historyDao = getPersistenceContext().getHistoryDao();
- RangeRowTopiaDao rangeRowDao = getPersistenceContext().getRangeRowDao();
-
- int etatAttenteSize = etatAttentes.size();
-
- // root folders (~companies)
- MailFolder franciaflex = folderDao.create(MailFolder.PROPERTY_NAME, "Franciaflex",
- MailFolder.PROPERTY_USE_CURRENT_LEVEL_REJECT_RESPONSE_MAIL_ADDRESS, true,
- MailFolder.PROPERTY_USE_CURRENT_LEVEL_REJECT_RESPONSE_MESSAGE, true);
- MailFolder faber = folderDao.create(MailFolder.PROPERTY_NAME, "Faber");
- MailFolder franceFermeture = folderDao.create(MailFolder.PROPERTY_NAME, "France-fermeture");
-
- // categories
- MailFolder chargesClientelle = folderDao.create(MailFolder.PROPERTY_NAME, "Chargés de clientèle",
- MailFolder.PROPERTY_PARENT, franciaflex,
- MailFolder.PROPERTY_REPLY_ADDRESSES, Lists.newArrayList("no-reply(a)franciaflex.com"));
- franciaflex.addChildren(chargesClientelle);
- folders.put("Chargés de clientèle", chargesClientelle);
-
- Collections.shuffle(etatAttentes);
- MailFolder sav = folderDao.create(MailFolder.PROPERTY_NAME, "SAV",
- MailFolder.PROPERTY_PARENT, franciaflex,
- MailFolder.PROPERTY_ETAT_ATTENTES, etatAttentes.subList(0, random.nextInt(etatAttenteSize - 8) + 2),
- MailFolder.PROPERTY_USE_CURRENT_LEVEL_ETAT_ATTENTE, true);
- franciaflex.addChildren(sav);
- folders.put("SAV", sav);
-
- // user folders
- Collections.shuffle(etatAttentes);
- MailFolder cyrilFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Cyril",
- MailFolder.PROPERTY_PARENT, chargesClientelle,
- MailFolder.PROPERTY_ETAT_ATTENTES, etatAttentes.subList(0, random.nextInt(etatAttenteSize - 8) + 2),
- MailFolder.PROPERTY_USE_CURRENT_LEVEL_ETAT_ATTENTE, true);
- chargesClientelle.addChildren(cyrilFolder);
- folders.put("Cyril", cyrilFolder);
-
- MailFolder claireFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Claire",
- MailFolder.PROPERTY_PARENT, chargesClientelle);
- chargesClientelle.addChildren(claireFolder);
- folders.put("Claire", claireFolder);
-
- Collections.shuffle(etatAttentes);
- MailFolder agatheFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Agathe",
- MailFolder.PROPERTY_PARENT, chargesClientelle,
- MailFolder.PROPERTY_ETAT_ATTENTES, etatAttentes.subList(0, random.nextInt(etatAttenteSize - 8) + 2),
- MailFolder.PROPERTY_USE_CURRENT_LEVEL_ETAT_ATTENTE, true);
- chargesClientelle.addChildren(agatheFolder);
- folders.put("Agathe", agatheFolder);
-
- MailFolder marcFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Marc",
- MailFolder.PROPERTY_PARENT, sav);
- sav.addChildren(marcFolder);
- folders.put("Marc", marcFolder);
-
- MailFolder fredericFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Frédéric",
- MailFolder.PROPERTY_PARENT, sav);
- sav.addChildren(fredericFolder);
- folders.put("Frédéric", fredericFolder);
-
- MailFolder jeanneFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Jeanne",
- MailFolder.PROPERTY_PARENT, sav);
- sav.addChildren(jeanneFolder);
- folders.put("Jeanne", jeanneFolder);
-
- // email accounts
- File demoDirectory = getApplicationConfig().getDemoDirectory();
- File emailAcountFile = new File(demoDirectory, "email_accounts.csv");
- try {
- InputStream emailAccountsPropertiesStream = new FileInputStream(emailAcountFile);
- if (emailAccountsPropertiesStream != null) {
- getReferentielService().importEmailAccounts(emailAccountsPropertiesStream);
- }
-
- } catch(Exception e) {
- log.error("error getting the email accounts", e);
- }
-
- // email filters
- File emailFilterFile = new File(demoDirectory, "email_filters.csv");
- try {
- InputStream emailFiltersPropertiesStream = new FileInputStream(emailFilterFile);
- if (emailFiltersPropertiesStream != null) {
- getReferentielService().importEmailFilters(emailFiltersPropertiesStream, folders);
- }
-
- } catch(Exception e) {
- log.error("error getting the email filters", e);
- }
-
- // clients and emails
- File clientFile = new File(demoDirectory, "fx_clients.csv");
- try {
- InputStream fxClientsStream = new FileInputStream(clientFile);
- if (fxClientsStream != null) {
- List<Client> clients = getReferentielService().importClients(fxClientsStream);
-
- createEmails(random, historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, cyrilFolder, cyril);
- createEmails(random, historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, claireFolder, claire);
- createEmails(random, historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, agatheFolder, agathe);
- createEmails(random, historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, marcFolder, marc);
- createEmails(random, historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, fredericFolder, frederic);
- createEmails(random, historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, jeanneFolder, jeanne);
- }
-
- } catch(Exception e) {
- log.error("error getting the client file", e);
- }
-
- getPersistenceContext().commit();
- }
- }
-
- protected void createEmails(Random random, HistoryTopiaDao historyDao, RangeRowTopiaDao rangeRowDao, EmailTopiaDao emailDao,
- List<Range> ranges, List<Client> clients, List<DemandType> types, List<Priority> priorities,
- MailFolder folder, FaxToMailUser user) throws InvalidClientException {
- int r = random.nextInt(10) + 5;
- for (int i = 0 ; i < r ; i++) {
- createEmail(random, historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, folder, user);
- }
- }
-
- protected void createEmail(Random random,
- HistoryTopiaDao historyDao,
- RangeRowTopiaDao rangeRowDao,
- EmailTopiaDao emailDao,
- List<Range> ranges,
- List<Client> clients,
- List<DemandType> types,
- List<Priority> priorities,
- MailFolder folder,
- FaxToMailUser user) throws InvalidClientException {
-
- List<RangeRow> rangeRows = new ArrayList<>();
-
- Client client = clients.get(random.nextInt(clients.size()));
- String sender = client.getEmailAddress();
- boolean fax = false;
- if (sender == null && client.getFaxNumber() != null) {
- sender = client.getFaxNumber();
- fax = true;
- }
-
- boolean opened = random.nextBoolean();
-
- Decorator<Date> dateDecorator = getDecoratorService().getDecoratorByType(Date.class, DecoratorService.DATE);
-
- Date now = new Date();
- History history = historyDao.create(History.PROPERTY_TYPE, HistoryType.CREATION,
- History.PROPERTY_FIELDS, Sets.newHashSet(Email.PROPERTY_SENDER,
- Email.PROPERTY_CLIENT,
- Email.PROPERTY_PROJECT_REFERENCE,
- Email.PROPERTY_OBJECT,
- Email.PROPERTY_RECEPTION_DATE,
- Email.PROPERTY_MAIL_FOLDER,
- Email.PROPERTY_DEMAND_STATUS),
- History.PROPERTY_MODIFICATION_DATE, now);
- String projectRef = t("faxtomail.email.projectReference.default", dateDecorator.toString(now));
-
- Email email = emailDao.create(Email.PROPERTY_SENDER, sender,
- Email.PROPERTY_FAX, fax,
- Email.PROPERTY_CLIENT, client,
- Email.PROPERTY_PROJECT_REFERENCE, projectRef,
- Email.PROPERTY_OBJECT, client.getCaracteristic1() + " / " + client.getCode() + " / " + client.getName() + " / " + client.getFaxNumber() + " / " + dateDecorator.toString(now),
- Email.PROPERTY_RECEPTION_DATE, now,
- Email.PROPERTY_MAIL_FOLDER, folder,
- Email.PROPERTY_DEMAND_STATUS, opened ? DemandStatus.IN_PROGRESS : DemandStatus.UNTREATED,
- Email.PROPERTY_HISTORY, Lists.newArrayList(history),
- Email.PROPERTY_ORIGINAL_EMAIL, "Demo data");
-
-
- if (opened) {
-
- getEmailService().addToHistory(email.getTopiaId(), HistoryType.OPENING, user, now);
- DemandType demandType = types.get(random.nextInt(types.size()));
- if (demandType.containsFields(MailField.RANGE_ROW)) {
- for (int j = 0; j < random.nextInt(4) + 1; j++) {
- RangeRow rangeRow = rangeRowDao.create(RangeRow.PROPERTY_RANGE, ranges.get(random.nextInt(ranges.size())),
- RangeRow.PROPERTY_COMMAND_NUMBER, RandomStringUtils.randomNumeric(6),
- RangeRow.PROPERTY_PRODUCT_QUANTITY, random.nextInt(100),
- RangeRow.PROPERTY_SAV_QUANTITY, random.nextInt(100));
- rangeRows.add(rangeRow);
- }
- email.setRangeRow(rangeRows);
- }
-
- email.setDemandType(demandType);
- email.setPriority(priorities.get(random.nextInt(priorities.size())));
- email.setRangeRow(rangeRows);
- getEmailService().saveEmail(email, user,
- Email.PROPERTY_DEMAND_TYPE, Email.PROPERTY_PRIORITY, Email.PROPERTY_RANGE_ROW);
- }
-
- Calendar cal = Calendar.getInstance();
- cal.add(Calendar.DAY_OF_MONTH, -1);
- Date yesterday = cal.getTime();
- history = historyDao.create(History.PROPERTY_TYPE, HistoryType.CREATION,
- History.PROPERTY_FIELDS, Sets.newHashSet(Email.PROPERTY_SENDER,
- Email.PROPERTY_CLIENT,
- Email.PROPERTY_PROJECT_REFERENCE,
- Email.PROPERTY_OBJECT,
- Email.PROPERTY_RECEPTION_DATE,
- Email.PROPERTY_MAIL_FOLDER,
- Email.PROPERTY_DEMAND_STATUS),
- History.PROPERTY_MODIFICATION_DATE, yesterday);
- projectRef = t("faxtomail.email.projectReference.default", dateDecorator.toString(yesterday));
-
- email = emailDao.create(Email.PROPERTY_SENDER, sender,
- Email.PROPERTY_FAX, fax,
- Email.PROPERTY_CLIENT, client,
- Email.PROPERTY_PROJECT_REFERENCE, projectRef,
- Email.PROPERTY_OBJECT, client.getCaracteristic1() + " / " + client.getCode() + " / " + client.getName() + " / " + client.getFaxNumber() + " / " + dateDecorator.toString(yesterday),
- Email.PROPERTY_RECEPTION_DATE, yesterday,
- Email.PROPERTY_MAIL_FOLDER, folder,
- Email.PROPERTY_DEMAND_STATUS, opened ? DemandStatus.IN_PROGRESS : DemandStatus.UNTREATED,
- Email.PROPERTY_HISTORY, Lists.newArrayList(history),
- Email.PROPERTY_ORIGINAL_EMAIL, "Demo data");
-
-
- if (opened) {
- getEmailService().addToHistory(email.getTopiaId(), HistoryType.OPENING, user, now);
- DemandType demandType = types.get(random.nextInt(types.size()));
- if (demandType.containsFields(MailField.RANGE_ROW)) {
- for (int j = 0; j < random.nextInt(4) + 1; j++) {
- RangeRow rangeRow = rangeRowDao.create(RangeRow.PROPERTY_RANGE, ranges.get(random.nextInt(ranges.size())),
- RangeRow.PROPERTY_COMMAND_NUMBER, RandomStringUtils.randomNumeric(6),
- RangeRow.PROPERTY_PRODUCT_QUANTITY, random.nextInt(100),
- RangeRow.PROPERTY_SAV_QUANTITY, random.nextInt(100));
- rangeRows.add(rangeRow);
- }
- email.setRangeRow(rangeRows);
-
- if (random.nextBoolean()) {
- email.setEdiError("error 42");
- }
- }
- email.setDemandType(demandType);
- email.setPriority(priorities.get(random.nextInt(priorities.size())));
- email.setRangeRow(rangeRows);
- getEmailService().saveEmail(email, null, email.getClient().getCode(), user,
- Email.PROPERTY_DEMAND_TYPE, Email.PROPERTY_PRIORITY, Email.PROPERTY_RANGE_ROW);
- }
- }
-
-}
Added: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/InitFaxToMailService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/InitFaxToMailService.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/InitFaxToMailService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,10 @@
+package com.franciaflex.faxtomail.services.service;
+
+import com.franciaflex.faxtomail.services.FaxToMailService;
+
+/**
+ * @author Kevin Morin (Code Lutin)
+ */
+public interface InitFaxToMailService extends FaxToMailService {
+ void init();
+}
Copied: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/InitFaxToMailServiceImpl.java (from rev 468, trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/InitFaxToMailService.java)
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/InitFaxToMailServiceImpl.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/InitFaxToMailServiceImpl.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,453 @@
+package com.franciaflex.faxtomail.services.service;
+
+/*
+ * #%L
+ * FaxToMail :: Service
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2014 Franciaflex, Code Lutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import static org.nuiton.i18n.I18n.t;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+
+import com.franciaflex.faxtomail.persistence.entities.MailField;
+
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.decorator.Decorator;
+
+import com.franciaflex.faxtomail.persistence.entities.Client;
+import com.franciaflex.faxtomail.persistence.entities.DemandStatus;
+import com.franciaflex.faxtomail.persistence.entities.DemandType;
+import com.franciaflex.faxtomail.persistence.entities.DemandTypeTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.Email;
+import com.franciaflex.faxtomail.persistence.entities.EmailTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.EtatAttente;
+import com.franciaflex.faxtomail.persistence.entities.EtatAttenteTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroup;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroupTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.History;
+import com.franciaflex.faxtomail.persistence.entities.HistoryTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.HistoryType;
+import com.franciaflex.faxtomail.persistence.entities.MailFolder;
+import com.franciaflex.faxtomail.persistence.entities.MailFolderTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.Priority;
+import com.franciaflex.faxtomail.persistence.entities.PriorityTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.Range;
+import com.franciaflex.faxtomail.persistence.entities.RangeRow;
+import com.franciaflex.faxtomail.persistence.entities.RangeRowTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.RangeTopiaDao;
+import com.franciaflex.faxtomail.services.DecoratorService;
+import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
+import com.franciaflex.faxtomail.services.service.exceptions.InvalidClientException;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+
+public class InitFaxToMailServiceImpl extends FaxToMailServiceSupport implements InitFaxToMailService {
+
+ private static final Log log = LogFactory.getLog(InitFaxToMailServiceImpl.class);
+
+ @Override
+ public void init() {
+
+ if (log.isInfoEnabled()) {
+ log.info("faxtomail initialization started");
+ }
+
+ boolean devMode = serviceContext.getApplicationConfig().isDevMode();
+
+ if (devMode) {
+ initSampleData();
+ }
+
+ // Reset the value stack used, if required, a new will be recreated using the struts ActionContext.
+ // Need to do it here, if we want to be synched between the struts ActionContext and the value stack.
+// XWork2ValidatorUtil.setSharedValueStack(null);
+
+ if (log.isInfoEnabled()) {
+ log.info("faxtomail initialization done");
+ }
+
+ }
+
+ protected void initSampleData() {
+ log.debug("init Sample Data");
+
+ DemandTypeTopiaDao demandTypeDao = getPersistenceContext().getDemandTypeDao();
+ long count = demandTypeDao.count();
+
+ if (count == 0) {
+
+ List<DemandType> types = Lists.newArrayList(
+ demandTypeDao.create(DemandType.PROPERTY_LABEL, "Commande", DemandType.PROPERTY_FIELDS, Lists.newArrayList(MailField.RANGE_ROW)),
+ demandTypeDao.create(DemandType.PROPERTY_LABEL, "Commande Réponse"),
+ demandTypeDao.create(DemandType.PROPERTY_LABEL, "Commande Annulation/Modification"),
+ demandTypeDao.create(DemandType.PROPERTY_LABEL, "Devis Diffus"),
+ demandTypeDao.create(DemandType.PROPERTY_LABEL, "Devis Chantier"),
+ demandTypeDao.create(DemandType.PROPERTY_LABEL, "Devis Gros Chantier"),
+ demandTypeDao.create(DemandType.PROPERTY_LABEL, "Devis Réponse/Modification"),
+ demandTypeDao.create(DemandType.PROPERTY_LABEL, "Réclamation"),
+ demandTypeDao.create(DemandType.PROPERTY_LABEL, "Autres")
+ );
+
+ EtatAttenteTopiaDao etatAttenteDao = getPersistenceContext().getEtatAttenteDao();
+ List<EtatAttente> etatAttentes = Lists.newArrayList(
+ etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "BAT attente retour BAT lettrage-logo"),
+ etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "CLT attente réponse client"),
+ etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "DAC attente pour assistance chantier"),
+ etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "DAV attente analyse avoir"),
+ etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "EXP attente expertise"),
+ etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "GAB attente reception gabarit"),
+ etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "GRA attente accord gratuit"),
+ etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "ODC attente Ouverture de Compte"),
+ etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "PPC attente chiffrage BEI PPC"),
+ etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "PROFORMA attente paiement proforma"),
+ etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "PROTO attente accord proto"),
+ etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "REM Attente Remise-accord expo"),
+ etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "RET attente retour materiel"),
+ etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "SIGN attente réponse BEI signature"),
+ etatAttenteDao.create(EtatAttente.PROPERTY_LABEL, "SPAM")
+ );
+
+ PriorityTopiaDao priorityDao = getPersistenceContext().getPriorityDao();
+ List<Priority> priorities = Lists.newArrayList(
+ priorityDao.create(Priority.PROPERTY_LABEL, "!"),
+ priorityDao.create(Priority.PROPERTY_LABEL, "F")
+ );
+
+ RangeTopiaDao rangeDao = getPersistenceContext().getRangeDao();
+ List<Range> ranges = Lists.newArrayList(
+ rangeDao.create(Range.PROPERTY_LABEL, "FFE VR"),
+ rangeDao.create(Range.PROPERTY_LABEL, "FFE AUTRE"),
+ rangeDao.create(Range.PROPERTY_LABEL, "FME FX DROIT"),
+ rangeDao.create(Range.PROPERTY_LABEL, "FME FX CINTRE"),
+ rangeDao.create(Range.PROPERTY_LABEL, "FME NOEL"),
+ rangeDao.create(Range.PROPERTY_LABEL, "FSE BANNE"),
+ rangeDao.create(Range.PROPERTY_LABEL, "FSE ROCH AUTRE"),
+ rangeDao.create(Range.PROPERTY_LABEL, "FSE CHECY"),
+ rangeDao.create(Range.PROPERTY_LABEL, "FSI"),
+ rangeDao.create(Range.PROPERTY_LABEL, "FSI FMI")
+ );
+
+ // user groups
+ FaxToMailUserGroupTopiaDao userGroupDao = getPersistenceContext().getFaxToMailUserGroupDao();
+ userGroupDao.create(FaxToMailUserGroup.PROPERTY_NAME, "Chargés de clientèle",
+ FaxToMailUserGroup.PROPERTY_COMPLETE_NAME, "Franciaflex/Chargés de clientèle");
+ FaxToMailUserGroup commerciauxGroup = userGroupDao.create(FaxToMailUserGroup.PROPERTY_NAME, "Commerciaux",
+ FaxToMailUserGroup.PROPERTY_COMPLETE_NAME, "Franciaflex/Commerciaux");
+ FaxToMailUserGroup savGroup = userGroupDao.create(FaxToMailUserGroup.PROPERTY_NAME, "SAV",
+ FaxToMailUserGroup.PROPERTY_COMPLETE_NAME, "Franciaflex/SAV");
+ userGroupDao.create(FaxToMailUserGroup.PROPERTY_NAME, "Administrateurs",
+ FaxToMailUserGroup.PROPERTY_COMPLETE_NAME, "Franciaflex/Administrateurs");
+
+ FaxToMailUserTopiaDao userDao = getPersistenceContext().getFaxToMailUserDao();
+ FaxToMailUser marc = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Lefèbvre",
+ FaxToMailUser.PROPERTY_FIRST_NAME, "Marc",
+ FaxToMailUser.PROPERTY_LOGIN, "mlefebvre",
+ FaxToMailUser.PROPERTY_TRIGRAPH, "MLE",
+ FaxToMailUser.PROPERTY_USER_GROUPS, Collections.singletonList(commerciauxGroup));
+ FaxToMailUser cyril = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Baillet",
+ FaxToMailUser.PROPERTY_FIRST_NAME, "Cyril",
+ FaxToMailUser.PROPERTY_LOGIN, "cbaillet",
+ FaxToMailUser.PROPERTY_TRIGRAPH, "CBA");
+ FaxToMailUser frederic = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Viala",
+ FaxToMailUser.PROPERTY_FIRST_NAME, "Frédéric",
+ FaxToMailUser.PROPERTY_LOGIN, "fviala",
+ FaxToMailUser.PROPERTY_TRIGRAPH, "FVI",
+ FaxToMailUser.PROPERTY_USER_GROUPS, Collections.singletonList(commerciauxGroup));
+ FaxToMailUser claire = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Marquis",
+ FaxToMailUser.PROPERTY_FIRST_NAME, "Claire",
+ FaxToMailUser.PROPERTY_LOGIN, "cmarquis",
+ FaxToMailUser.PROPERTY_TRIGRAPH, "CMA");
+ FaxToMailUser agathe = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Borde",
+ FaxToMailUser.PROPERTY_FIRST_NAME, "Agathe",
+ FaxToMailUser.PROPERTY_LOGIN, "aborde",
+ FaxToMailUser.PROPERTY_TRIGRAPH, "ABO",
+ FaxToMailUser.PROPERTY_USER_GROUPS, Collections.singletonList(savGroup));
+ FaxToMailUser jeanne = userDao.create(FaxToMailUser.PROPERTY_LAST_NAME, "Bourgoin",
+ FaxToMailUser.PROPERTY_FIRST_NAME, "Jeanne",
+ FaxToMailUser.PROPERTY_LOGIN, "jbourgoin",
+ FaxToMailUser.PROPERTY_TRIGRAPH, "JBO",
+ FaxToMailUser.PROPERTY_USER_GROUPS, Collections.singletonList(commerciauxGroup));
+
+ MailFolderTopiaDao folderDao = getPersistenceContext().getMailFolderDao();
+ Map<String, MailFolder> folders = new HashMap<>();
+
+ // fixme seed to be used in test
+ Random random = new Random(1234);
+ EmailTopiaDao emailDao = getPersistenceContext().getEmailDao();
+ HistoryTopiaDao historyDao = getPersistenceContext().getHistoryDao();
+ RangeRowTopiaDao rangeRowDao = getPersistenceContext().getRangeRowDao();
+
+ int etatAttenteSize = etatAttentes.size();
+
+ // root folders (~companies)
+ MailFolder franciaflex = folderDao.create(MailFolder.PROPERTY_NAME, "Franciaflex",
+ MailFolder.PROPERTY_USE_CURRENT_LEVEL_REJECT_RESPONSE_MAIL_ADDRESS, true,
+ MailFolder.PROPERTY_USE_CURRENT_LEVEL_REJECT_RESPONSE_MESSAGE, true);
+ MailFolder faber = folderDao.create(MailFolder.PROPERTY_NAME, "Faber");
+ MailFolder franceFermeture = folderDao.create(MailFolder.PROPERTY_NAME, "France-fermeture");
+
+ // categories
+ MailFolder chargesClientelle = folderDao.create(MailFolder.PROPERTY_NAME, "Chargés de clientèle",
+ MailFolder.PROPERTY_PARENT, franciaflex,
+ MailFolder.PROPERTY_REPLY_ADDRESSES, Lists.newArrayList("no-reply(a)franciaflex.com"));
+ franciaflex.addChildren(chargesClientelle);
+ folders.put("Chargés de clientèle", chargesClientelle);
+
+ Collections.shuffle(etatAttentes);
+ MailFolder sav = folderDao.create(MailFolder.PROPERTY_NAME, "SAV",
+ MailFolder.PROPERTY_PARENT, franciaflex,
+ MailFolder.PROPERTY_ETAT_ATTENTES, etatAttentes.subList(0, random.nextInt(etatAttenteSize - 8) + 2),
+ MailFolder.PROPERTY_USE_CURRENT_LEVEL_ETAT_ATTENTE, true);
+ franciaflex.addChildren(sav);
+ folders.put("SAV", sav);
+
+ // user folders
+ Collections.shuffle(etatAttentes);
+ MailFolder cyrilFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Cyril",
+ MailFolder.PROPERTY_PARENT, chargesClientelle,
+ MailFolder.PROPERTY_ETAT_ATTENTES, etatAttentes.subList(0, random.nextInt(etatAttenteSize - 8) + 2),
+ MailFolder.PROPERTY_USE_CURRENT_LEVEL_ETAT_ATTENTE, true);
+ chargesClientelle.addChildren(cyrilFolder);
+ folders.put("Cyril", cyrilFolder);
+
+ MailFolder claireFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Claire",
+ MailFolder.PROPERTY_PARENT, chargesClientelle);
+ chargesClientelle.addChildren(claireFolder);
+ folders.put("Claire", claireFolder);
+
+ Collections.shuffle(etatAttentes);
+ MailFolder agatheFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Agathe",
+ MailFolder.PROPERTY_PARENT, chargesClientelle,
+ MailFolder.PROPERTY_ETAT_ATTENTES, etatAttentes.subList(0, random.nextInt(etatAttenteSize - 8) + 2),
+ MailFolder.PROPERTY_USE_CURRENT_LEVEL_ETAT_ATTENTE, true);
+ chargesClientelle.addChildren(agatheFolder);
+ folders.put("Agathe", agatheFolder);
+
+ MailFolder marcFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Marc",
+ MailFolder.PROPERTY_PARENT, sav);
+ sav.addChildren(marcFolder);
+ folders.put("Marc", marcFolder);
+
+ MailFolder fredericFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Frédéric",
+ MailFolder.PROPERTY_PARENT, sav);
+ sav.addChildren(fredericFolder);
+ folders.put("Frédéric", fredericFolder);
+
+ MailFolder jeanneFolder = folderDao.create(MailFolder.PROPERTY_NAME, "Jeanne",
+ MailFolder.PROPERTY_PARENT, sav);
+ sav.addChildren(jeanneFolder);
+ folders.put("Jeanne", jeanneFolder);
+
+ // email accounts
+ File demoDirectory = getApplicationConfig().getDemoDirectory();
+ File emailAcountFile = new File(demoDirectory, "email_accounts.csv");
+ try {
+ InputStream emailAccountsPropertiesStream = new FileInputStream(emailAcountFile);
+ if (emailAccountsPropertiesStream != null) {
+ getReferentielService().importEmailAccounts(emailAccountsPropertiesStream);
+ }
+
+ } catch(Exception e) {
+ log.error("error getting the email accounts", e);
+ }
+
+ // email filters
+ File emailFilterFile = new File(demoDirectory, "email_filters.csv");
+ try {
+ InputStream emailFiltersPropertiesStream = new FileInputStream(emailFilterFile);
+ if (emailFiltersPropertiesStream != null) {
+ getReferentielService().importEmailFilters(emailFiltersPropertiesStream, folders);
+ }
+
+ } catch(Exception e) {
+ log.error("error getting the email filters", e);
+ }
+
+ // clients and emails
+ File clientFile = new File(demoDirectory, "fx_clients.csv");
+ try {
+ InputStream fxClientsStream = new FileInputStream(clientFile);
+ if (fxClientsStream != null) {
+ List<Client> clients = getReferentielService().importClients(fxClientsStream);
+
+ createEmails(random, historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, cyrilFolder, cyril);
+ createEmails(random, historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, claireFolder, claire);
+ createEmails(random, historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, agatheFolder, agathe);
+ createEmails(random, historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, marcFolder, marc);
+ createEmails(random, historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, fredericFolder, frederic);
+ createEmails(random, historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, jeanneFolder, jeanne);
+ }
+
+ } catch(Exception e) {
+ log.error("error getting the client file", e);
+ }
+
+ getPersistenceContext().commit();
+ }
+ }
+
+ protected void createEmails(Random random, HistoryTopiaDao historyDao, RangeRowTopiaDao rangeRowDao, EmailTopiaDao emailDao,
+ List<Range> ranges, List<Client> clients, List<DemandType> types, List<Priority> priorities,
+ MailFolder folder, FaxToMailUser user) throws InvalidClientException {
+ int r = random.nextInt(10) + 5;
+ for (int i = 0 ; i < r ; i++) {
+ createEmail(random, historyDao, rangeRowDao, emailDao, ranges, clients, types, priorities, folder, user);
+ }
+ }
+
+ protected void createEmail(Random random,
+ HistoryTopiaDao historyDao,
+ RangeRowTopiaDao rangeRowDao,
+ EmailTopiaDao emailDao,
+ List<Range> ranges,
+ List<Client> clients,
+ List<DemandType> types,
+ List<Priority> priorities,
+ MailFolder folder,
+ FaxToMailUser user) throws InvalidClientException {
+
+ List<RangeRow> rangeRows = new ArrayList<>();
+
+ Client client = clients.get(random.nextInt(clients.size()));
+ String sender = client.getEmailAddress();
+ boolean fax = false;
+ if (sender == null && client.getFaxNumber() != null) {
+ sender = client.getFaxNumber();
+ fax = true;
+ }
+
+ boolean opened = random.nextBoolean();
+
+ Decorator<Date> dateDecorator = getDecoratorService().getDecoratorByType(Date.class, DecoratorService.DATE);
+
+ Date now = new Date();
+ History history = historyDao.create(History.PROPERTY_TYPE, HistoryType.CREATION,
+ History.PROPERTY_FIELDS, Sets.newHashSet(Email.PROPERTY_SENDER,
+ Email.PROPERTY_CLIENT,
+ Email.PROPERTY_PROJECT_REFERENCE,
+ Email.PROPERTY_OBJECT,
+ Email.PROPERTY_RECEPTION_DATE,
+ Email.PROPERTY_MAIL_FOLDER,
+ Email.PROPERTY_DEMAND_STATUS),
+ History.PROPERTY_MODIFICATION_DATE, now);
+ String projectRef = t("faxtomail.email.projectReference.default", dateDecorator.toString(now));
+
+ Email email = emailDao.create(Email.PROPERTY_SENDER, sender,
+ Email.PROPERTY_FAX, fax,
+ Email.PROPERTY_CLIENT, client,
+ Email.PROPERTY_PROJECT_REFERENCE, projectRef,
+ Email.PROPERTY_OBJECT, client.getCaracteristic1() + " / " + client.getCode() + " / " + client.getName() + " / " + client.getFaxNumber() + " / " + dateDecorator.toString(now),
+ Email.PROPERTY_RECEPTION_DATE, now,
+ Email.PROPERTY_MAIL_FOLDER, folder,
+ Email.PROPERTY_DEMAND_STATUS, opened ? DemandStatus.IN_PROGRESS : DemandStatus.UNTREATED,
+ Email.PROPERTY_HISTORY, Lists.newArrayList(history),
+ Email.PROPERTY_ORIGINAL_EMAIL, "Demo data");
+
+
+ if (opened) {
+
+ getEmailService().addToHistory(email.getTopiaId(), HistoryType.OPENING, user, now);
+ DemandType demandType = types.get(random.nextInt(types.size()));
+ if (demandType.containsFields(MailField.RANGE_ROW)) {
+ for (int j = 0; j < random.nextInt(4) + 1; j++) {
+ RangeRow rangeRow = rangeRowDao.create(RangeRow.PROPERTY_RANGE, ranges.get(random.nextInt(ranges.size())),
+ RangeRow.PROPERTY_COMMAND_NUMBER, RandomStringUtils.randomNumeric(6),
+ RangeRow.PROPERTY_PRODUCT_QUANTITY, random.nextInt(100),
+ RangeRow.PROPERTY_SAV_QUANTITY, random.nextInt(100));
+ rangeRows.add(rangeRow);
+ }
+ email.setRangeRow(rangeRows);
+ }
+
+ email.setDemandType(demandType);
+ email.setPriority(priorities.get(random.nextInt(priorities.size())));
+ email.setRangeRow(rangeRows);
+ getEmailService().saveEmail(email, user,
+ Email.PROPERTY_DEMAND_TYPE, Email.PROPERTY_PRIORITY, Email.PROPERTY_RANGE_ROW);
+ }
+
+ Calendar cal = Calendar.getInstance();
+ cal.add(Calendar.DAY_OF_MONTH, -1);
+ Date yesterday = cal.getTime();
+ history = historyDao.create(History.PROPERTY_TYPE, HistoryType.CREATION,
+ History.PROPERTY_FIELDS, Sets.newHashSet(Email.PROPERTY_SENDER,
+ Email.PROPERTY_CLIENT,
+ Email.PROPERTY_PROJECT_REFERENCE,
+ Email.PROPERTY_OBJECT,
+ Email.PROPERTY_RECEPTION_DATE,
+ Email.PROPERTY_MAIL_FOLDER,
+ Email.PROPERTY_DEMAND_STATUS),
+ History.PROPERTY_MODIFICATION_DATE, yesterday);
+ projectRef = t("faxtomail.email.projectReference.default", dateDecorator.toString(yesterday));
+
+ email = emailDao.create(Email.PROPERTY_SENDER, sender,
+ Email.PROPERTY_FAX, fax,
+ Email.PROPERTY_CLIENT, client,
+ Email.PROPERTY_PROJECT_REFERENCE, projectRef,
+ Email.PROPERTY_OBJECT, client.getCaracteristic1() + " / " + client.getCode() + " / " + client.getName() + " / " + client.getFaxNumber() + " / " + dateDecorator.toString(yesterday),
+ Email.PROPERTY_RECEPTION_DATE, yesterday,
+ Email.PROPERTY_MAIL_FOLDER, folder,
+ Email.PROPERTY_DEMAND_STATUS, opened ? DemandStatus.IN_PROGRESS : DemandStatus.UNTREATED,
+ Email.PROPERTY_HISTORY, Lists.newArrayList(history),
+ Email.PROPERTY_ORIGINAL_EMAIL, "Demo data");
+
+
+ if (opened) {
+ getEmailService().addToHistory(email.getTopiaId(), HistoryType.OPENING, user, now);
+ DemandType demandType = types.get(random.nextInt(types.size()));
+ if (demandType.containsFields(MailField.RANGE_ROW)) {
+ for (int j = 0; j < random.nextInt(4) + 1; j++) {
+ RangeRow rangeRow = rangeRowDao.create(RangeRow.PROPERTY_RANGE, ranges.get(random.nextInt(ranges.size())),
+ RangeRow.PROPERTY_COMMAND_NUMBER, RandomStringUtils.randomNumeric(6),
+ RangeRow.PROPERTY_PRODUCT_QUANTITY, random.nextInt(100),
+ RangeRow.PROPERTY_SAV_QUANTITY, random.nextInt(100));
+ rangeRows.add(rangeRow);
+ }
+ email.setRangeRow(rangeRows);
+
+ if (random.nextBoolean()) {
+ email.setEdiError("error 42");
+ }
+ }
+ email.setDemandType(demandType);
+ email.setPriority(priorities.get(random.nextInt(priorities.size())));
+ email.setRangeRow(rangeRows);
+ getEmailService().saveEmail(email, null, email.getClient().getCode(), user,
+ Email.PROPERTY_DEMAND_TYPE, Email.PROPERTY_PRIORITY, Email.PROPERTY_RANGE_ROW);
+ }
+ }
+
+}
Property changes on: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/InitFaxToMailServiceImpl.java
___________________________________________________________________
Added: svn:eol-style
+ native
Added: svn:keywords
+ Author Date Id Revision HeadURL
Deleted: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/LdapService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/LdapService.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/LdapService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -1,391 +0,0 @@
-package com.franciaflex.faxtomail.services.service;
-
-/*
- * #%L
- * FaxToMail :: Service
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2014 Franciaflex, Code Lutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/gpl-3.0.html>.
- * #L%
- */
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.lang3.ArrayUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.util.beans.Binder;
-import org.nuiton.util.beans.BinderFactory;
-
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroup;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroupTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserImpl;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserTopiaDao;
-import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
-import com.franciaflex.faxtomail.services.service.ldap.AuthenticationException;
-import com.unboundid.ldap.sdk.LDAPConnection;
-import com.unboundid.ldap.sdk.LDAPException;
-import com.unboundid.ldap.sdk.SearchResult;
-import com.unboundid.ldap.sdk.SearchResultEntry;
-import com.unboundid.ldap.sdk.SearchScope;
-
-public class LdapService extends FaxToMailServiceSupport {
-
- private static final Log log = LogFactory.getLog(LdapService.class);
-
- /**
- * Update all user and group from ldap.
- */
- public void updateLdapData() {
-
- LDAPConnection connection = null;
- try {
- connection = new LDAPConnection(getApplicationConfig().getLdapHost(),
- getApplicationConfig().getLdapPort(),
- getApplicationConfig().getLdapUser(),
- getApplicationConfig().getLdapPassword());
- if (connection.isConnected()) {
-
- FaxToMailUserTopiaDao faxtomailUserDao = getPersistenceContext().getFaxToMailUserDao();
- FaxToMailUserGroupTopiaDao faxtomailUserGroupDao = getPersistenceContext().getFaxToMailUserGroupDao();
-
- // cache group DN > faxtomail user group instance
- Map<String, FaxToMailUserGroup> groupCache = new HashMap<>();
- // cache user DN > faxtomail user instance
- Map<String, FaxToMailUser> userCache = new HashMap<>();
-
- // get all groups
- String groupsBaseDN = "OU=Mac-Groupe,DC=mac-groupe,DC=net";
- String groupsFilter = "(objectCategory=CN=Group,CN=Schema,CN=Configuration,DC=mac-groupe,DC=net)";
- SearchResult groupsResult = connection.search(groupsBaseDN, SearchScope.SUB, groupsFilter);
- List<SearchResultEntry> groupEntries = groupsResult.getSearchEntries();
- for (SearchResultEntry groupEntry : groupEntries) {
- String groupDN = groupEntry.getDN();
- String groupPath = getGroupCompleteName(groupDN);
- String groupName = StringUtils.substringAfterLast(groupPath, "/");
- FaxToMailUserGroup userGroup = faxtomailUserGroupDao.forNameEquals(groupName).findUniqueOrNull();
- if (userGroup == null) {
- userGroup = faxtomailUserGroupDao.create(
- FaxToMailUserGroup.PROPERTY_NAME, groupName,
- FaxToMailUserGroup.PROPERTY_COMPLETE_NAME, groupPath);
- }
- groupCache.put(groupDN, userGroup);
- }
-
- // get all users (
- String usersBaseDN = "OU=Mac-Groupe,DC=mac-groupe,DC=net";
- String usersFilter = "(objectCategory=CN=Person,CN=Schema,CN=Configuration,DC=mac-groupe,DC=net)";
- // on recupere d'abord les organisationUnit pour fractionner les requettes
- // sinon au dela de 1000 resultats ca veux plus
- SearchResult usersResult = connection.search(usersBaseDN, SearchScope.SUB, "(objectClass=organizationalUnit)");
- List<SearchResultEntry> unitEntries = usersResult.getSearchEntries();
- for (SearchResultEntry unitEntry : unitEntries) {
- if (log.isDebugEnabled()) {
- log.debug("Search for unit " + unitEntry.getDN());
- }
- SearchResult userResult = connection.search(unitEntry.getDN(), SearchScope.ONE, usersFilter);
-
- List<SearchResultEntry> userEntries = userResult.getSearchEntries();
- for (SearchResultEntry userEntry : userEntries) {
-
- String login = userEntry.getAttributeValue("sAMAccountName");
- String userDN = userEntry.getDN();
- if (login == null) {
- if (log.isWarnEnabled()) {
- log.warn("Null sAMAccountName for DN " + userDN);
- }
- } else {
- login = login.toLowerCase();
- FaxToMailUser user = updateUserFormLdap(connection, userEntry, login, groupCache);
- userCache.put(userDN, user);
- }
- }
- }
-
- // make remaining user and groups in database as 'hidden'
- Collection<FaxToMailUser> usersToHide = faxtomailUserDao.forNotIn(userCache.values());
- for (FaxToMailUser userToHide : usersToHide) {
- userToHide.setHidden(true);
- faxtomailUserDao.update(userToHide);
- }
- Collection<FaxToMailUserGroup> userGroupsToHide = faxtomailUserGroupDao.forNotIn(groupCache.values());
- for (FaxToMailUserGroup userGroupToHide : userGroupsToHide) {
- userGroupToHide.setHidden(true);
- faxtomailUserGroupDao.update(userGroupToHide);
- }
- getPersistenceContext().commit();
- }
-
- } catch (LDAPException ex) {
- throw new RuntimeException("Can't connect to ldap", ex);
- } finally {
- if (connection != null) {
- connection.close();
- }
- }
- }
-
- /**
- * Transform group CN to group path.
- *
- * Example:
- * CN=Tout Franciaflex,OU=Listes de distribution,OU=Comptes Spéciaux,OU=Mac-Groupe,DC=mac-groupe,DC=net
- * net/mac-groupe/Mac-Groupe/Comptes Spéciaux/Listes de distribution/Tout Franciaflex
- *
- * @param groupCN
- * @return
- */
- protected String getGroupCompleteName(String groupCN) {
- String[] parts = groupCN.split(",");
- ArrayUtils.reverse(parts);
-
- // join tab
- String separator = "";
- StringBuilder result = new StringBuilder();
- for (String part : parts) {
- result.append(separator);
- result.append(StringUtils.substringAfter(part, "="));
- separator = "/";
- }
- return result.toString();
- }
-
- /**
- * Return user for given user id.
- *
- * @param userTopiaId userTopiaId
- * @return user bean (without password)
- */
- public FaxToMailUser getUserBean(String userTopiaId) {
- FaxToMailUser result = null;
-
- FaxToMailUserTopiaDao faxtomailUserDao = getPersistenceContext().getFaxToMailUserDao();
- FaxToMailUser user = faxtomailUserDao.forTopiaIdEquals(userTopiaId).findUniqueOrNull();
- if (user != null) {
- Binder<FaxToMailUser, FaxToMailUser> faxToMailUserBinder = BinderFactory.newBinder(FaxToMailUser.class);
- result = new FaxToMailUserImpl();
- faxToMailUserBinder.copyExcluding(user, result);
- }
- return result;
- }
-
- /**
- * Authenticate and update ldap user.
- *
- * @param login login
- * @param password password
- * @return authenticated user
- * @throws AuthenticationException if authentication fails
- */
- public FaxToMailUser authenticateUser(String login, String password) throws AuthenticationException {
-
- FaxToMailUser result;
-
- login = login.toLowerCase();
- try {
- // first connexion to get full user login
- LDAPConnection adminConnect = new LDAPConnection();
- adminConnect.connect(getApplicationConfig().getLdapHost(), getApplicationConfig().getLdapPort());
- adminConnect.bind(getApplicationConfig().getLdapUser(), getApplicationConfig().getLdapPassword());
-
- // search user in ldap
- String userDN = null;
- SearchResultEntry searchEntry = null;
- if (adminConnect.isConnected()) {
- // sn est le login interne à franciaflex
- String filter = String.format("(sAMAccountName=%s)", login);
- SearchResult searchResult = adminConnect.search(getApplicationConfig().getLdapBaseDn(), SearchScope.SUB, filter);
- if (!searchResult.getSearchEntries().isEmpty()) {
- searchEntry = searchResult.getSearchEntries().get(0);
- userDN = searchEntry.getDN();
- }
- }
-
- if (searchEntry != null) {
- // ouvre une connexion avec l'identification de l'utilisateur qui essaye de se connecter
- // à l'application (ca permet de vérifier l'authentification)
- LDAPConnection userConnect = new LDAPConnection();
- userConnect.connect(getApplicationConfig().getLdapHost(), getApplicationConfig().getLdapPort());
- userConnect.bind(userDN, password);
-
- if (userConnect.isConnected()) {
- // update in database
- result = updateUserFormLdap(adminConnect, searchEntry, login, null);
- getPersistenceContext().commit();
-
- userConnect.close();
- } else {
- throw new AuthenticationException("Not connected");
- }
- } else {
- throw new AuthenticationException("Utilisateur inconnu : " + login);
- }
- adminConnect.close();
-
- } catch (LDAPException ex) {
- if (log.isWarnEnabled()) {
- log.warn("Can't login to ldap", ex);
- }
- throw new AuthenticationException(ex.getResultCode().getName(), ex);
- }
- return result;
- }
-
- /**
- * Retreive user from principal and updated user database instance.
- *
- * This method doesn't require any password.
- *
- * @param login user principal (without domain)
- * @return user instance
- * @throws AuthenticationException is user can't be found in ldap
- */
- public FaxToMailUser getUserFromPrincipal(String login) throws AuthenticationException {
-
- FaxToMailUser result;
-
- login = login.toLowerCase();
-
- try {
- // first connexion to get full user login
- LDAPConnection adminConnect = new LDAPConnection();
- adminConnect.connect(getApplicationConfig().getLdapHost(), getApplicationConfig().getLdapPort());
- adminConnect.bind(getApplicationConfig().getLdapUser(), getApplicationConfig().getLdapPassword());
-
- // search user in ldap
- SearchResultEntry searchEntry = null;
- if (adminConnect.isConnected()) {
- // sAMAccountName est l'identifiant kerberos
- String filter = String.format("(sAMAccountName=%s)", login);
- SearchResult searchResult = adminConnect.search(getApplicationConfig().getLdapBaseDn(), SearchScope.SUB, filter);
- if (!searchResult.getSearchEntries().isEmpty()) {
- searchEntry = searchResult.getSearchEntries().get(0);
- }
-
- } else {
- throw new AuthenticationException("Utilisateur inconnu : " + login);
- }
-
- if( searchEntry != null ) {
- // update in database
- result = updateUserFormLdap(adminConnect, searchEntry, login, null);
- getPersistenceContext().commit();
- } else {
- throw new AuthenticationException("Utilisateur inconnu : " + login);
- }
-
- adminConnect.close();
- } catch (LDAPException ex) {
- if (log.isWarnEnabled()) {
- log.warn("Can't login to ldap", ex);
- }
- throw new AuthenticationException(ex.getResultCode().getName(), ex);
- }
- return result;
- }
-
- /**
- * Update user (or create) in database from ldap search result entry.
- *
- * @param adminConnect admin connection used to load groups content
- * @param searchEntry entry containing data
- * @param login login
- * @param groupCache group cache when mass update (can be null)
- * @return updated user
- * @throws LDAPException
- */
- protected FaxToMailUser updateUserFormLdap(LDAPConnection adminConnect, SearchResultEntry searchEntry, String login, Map<String, FaxToMailUserGroup> groupCache) throws LDAPException {
-
- FaxToMailUser user;
-
- // create or
- FaxToMailUserTopiaDao faxtomailUserDao = getPersistenceContext().getFaxToMailUserDao();
- FaxToMailUserGroupTopiaDao faxtomailUserGroupDao = getPersistenceContext().getFaxToMailUserGroupDao();
- user = faxtomailUserDao.forLoginEquals(login).findUniqueOrNull();
-
- if (user == null) {
- user = new FaxToMailUserImpl();
- user.setLogin(login);
- }
- user.setHidden(false);
-
- // update other ldap fields
- String fullName = searchEntry.getAttributeValue("name");
- if (fullName.indexOf(' ') != -1) {
- String lastName = fullName.substring(0, fullName.indexOf(' '));
- String firstName = fullName.substring(fullName.indexOf(' ') + 1);
- user.setFirstName(firstName);
- user.setLastName(lastName);
- } else {
- user.setFirstName("");
- user.setLastName(fullName);
- }
-
- String trigraph = searchEntry.getAttributeValue("sAMAccountName");
- user.setTrigraph(StringUtils.upperCase(trigraph));
-
- // manage user groups
- user.clearUserGroups();
- String[] groups = searchEntry.getAttributeValues("memberOf");
- if (ArrayUtils.isNotEmpty(groups)) {
- for (String group : groups) {
-
- // en mass-update, on a le cache
- if (groupCache != null) {
- FaxToMailUserGroup userGroup = groupCache.get(group);
- if (userGroup != null) {
- user.addUserGroups(userGroup);
- }
- } else {
- // parmis tous les groupes, on n'utilise que ceux qui sont de la catégories
- // CN=Group,CN=Schema,CN=Configuration,DC=mac-groupe,DC=net
- SearchResultEntry groupSearchEntry = adminConnect.getEntry(group);
- String objectCategory = groupSearchEntry.getAttributeValue("objectCategory");
- if ("CN=Group,CN=Schema,CN=Configuration,DC=mac-groupe,DC=net".equals(objectCategory)) {
- String groupPath = getGroupCompleteName(group);
- String groupName = StringUtils.substringAfterLast(groupPath, "/");
- FaxToMailUserGroup userGroup = faxtomailUserGroupDao.forNameEquals(groupName).findUniqueOrNull();
- if (userGroup == null) {
- userGroup = faxtomailUserGroupDao.create(
- FaxToMailUserGroup.PROPERTY_NAME, groupName,
- FaxToMailUserGroup.PROPERTY_COMPLETE_NAME, groupPath);
- }
- user.addUserGroups(userGroup);
- }
- }
- }
- }
-
- if (user.isPersisted()) {
- user = faxtomailUserDao.update(user);
- } else {
- user = faxtomailUserDao.create(user);
- }
-
- // force collection loading to force non lazy collections
- user.isAffectedFoldersEmpty();
- user.isUserGroupsEmpty();
-
- return user;
- }
-}
Added: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/LdapService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/LdapService.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/LdapService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,18 @@
+package com.franciaflex.faxtomail.services.service;
+
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+import com.franciaflex.faxtomail.services.FaxToMailService;
+import com.franciaflex.faxtomail.services.service.ldap.AuthenticationException;
+
+/**
+ * @author Kevin Morin (Code Lutin)
+ */
+public interface LdapService extends FaxToMailService {
+ void updateLdapData();
+
+ FaxToMailUser getUserBean(String userTopiaId);
+
+ FaxToMailUser authenticateUser(String login, String password) throws AuthenticationException;
+
+ FaxToMailUser getUserFromPrincipal(String login) throws AuthenticationException;
+}
Copied: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/LdapServiceImpl.java (from rev 468, trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/LdapService.java)
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/LdapServiceImpl.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/LdapServiceImpl.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,395 @@
+package com.franciaflex.faxtomail.services.service;
+
+/*
+ * #%L
+ * FaxToMail :: Service
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2014 Franciaflex, Code Lutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.util.beans.Binder;
+import org.nuiton.util.beans.BinderFactory;
+
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroup;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroupTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserImpl;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserTopiaDao;
+import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
+import com.franciaflex.faxtomail.services.service.ldap.AuthenticationException;
+import com.unboundid.ldap.sdk.LDAPConnection;
+import com.unboundid.ldap.sdk.LDAPException;
+import com.unboundid.ldap.sdk.SearchResult;
+import com.unboundid.ldap.sdk.SearchResultEntry;
+import com.unboundid.ldap.sdk.SearchScope;
+
+public class LdapServiceImpl extends FaxToMailServiceSupport implements LdapService {
+
+ private static final Log log = LogFactory.getLog(LdapServiceImpl.class);
+
+ /**
+ * Update all user and group from ldap.
+ */
+ @Override
+ public void updateLdapData() {
+
+ LDAPConnection connection = null;
+ try {
+ connection = new LDAPConnection(getApplicationConfig().getLdapHost(),
+ getApplicationConfig().getLdapPort(),
+ getApplicationConfig().getLdapUser(),
+ getApplicationConfig().getLdapPassword());
+ if (connection.isConnected()) {
+
+ FaxToMailUserTopiaDao faxtomailUserDao = getPersistenceContext().getFaxToMailUserDao();
+ FaxToMailUserGroupTopiaDao faxtomailUserGroupDao = getPersistenceContext().getFaxToMailUserGroupDao();
+
+ // cache group DN > faxtomail user group instance
+ Map<String, FaxToMailUserGroup> groupCache = new HashMap<>();
+ // cache user DN > faxtomail user instance
+ Map<String, FaxToMailUser> userCache = new HashMap<>();
+
+ // get all groups
+ String groupsBaseDN = "OU=Mac-Groupe,DC=mac-groupe,DC=net";
+ String groupsFilter = "(objectCategory=CN=Group,CN=Schema,CN=Configuration,DC=mac-groupe,DC=net)";
+ SearchResult groupsResult = connection.search(groupsBaseDN, SearchScope.SUB, groupsFilter);
+ List<SearchResultEntry> groupEntries = groupsResult.getSearchEntries();
+ for (SearchResultEntry groupEntry : groupEntries) {
+ String groupDN = groupEntry.getDN();
+ String groupPath = getGroupCompleteName(groupDN);
+ String groupName = StringUtils.substringAfterLast(groupPath, "/");
+ FaxToMailUserGroup userGroup = faxtomailUserGroupDao.forNameEquals(groupName).findUniqueOrNull();
+ if (userGroup == null) {
+ userGroup = faxtomailUserGroupDao.create(
+ FaxToMailUserGroup.PROPERTY_NAME, groupName,
+ FaxToMailUserGroup.PROPERTY_COMPLETE_NAME, groupPath);
+ }
+ groupCache.put(groupDN, userGroup);
+ }
+
+ // get all users (
+ String usersBaseDN = "OU=Mac-Groupe,DC=mac-groupe,DC=net";
+ String usersFilter = "(objectCategory=CN=Person,CN=Schema,CN=Configuration,DC=mac-groupe,DC=net)";
+ // on recupere d'abord les organisationUnit pour fractionner les requettes
+ // sinon au dela de 1000 resultats ca veux plus
+ SearchResult usersResult = connection.search(usersBaseDN, SearchScope.SUB, "(objectClass=organizationalUnit)");
+ List<SearchResultEntry> unitEntries = usersResult.getSearchEntries();
+ for (SearchResultEntry unitEntry : unitEntries) {
+ if (log.isDebugEnabled()) {
+ log.debug("Search for unit " + unitEntry.getDN());
+ }
+ SearchResult userResult = connection.search(unitEntry.getDN(), SearchScope.ONE, usersFilter);
+
+ List<SearchResultEntry> userEntries = userResult.getSearchEntries();
+ for (SearchResultEntry userEntry : userEntries) {
+
+ String login = userEntry.getAttributeValue("sAMAccountName");
+ String userDN = userEntry.getDN();
+ if (login == null) {
+ if (log.isWarnEnabled()) {
+ log.warn("Null sAMAccountName for DN " + userDN);
+ }
+ } else {
+ login = login.toLowerCase();
+ FaxToMailUser user = updateUserFormLdap(connection, userEntry, login, groupCache);
+ userCache.put(userDN, user);
+ }
+ }
+ }
+
+ // make remaining user and groups in database as 'hidden'
+ Collection<FaxToMailUser> usersToHide = faxtomailUserDao.forNotIn(userCache.values());
+ for (FaxToMailUser userToHide : usersToHide) {
+ userToHide.setHidden(true);
+ faxtomailUserDao.update(userToHide);
+ }
+ Collection<FaxToMailUserGroup> userGroupsToHide = faxtomailUserGroupDao.forNotIn(groupCache.values());
+ for (FaxToMailUserGroup userGroupToHide : userGroupsToHide) {
+ userGroupToHide.setHidden(true);
+ faxtomailUserGroupDao.update(userGroupToHide);
+ }
+ getPersistenceContext().commit();
+ }
+
+ } catch (LDAPException ex) {
+ throw new RuntimeException("Can't connect to ldap", ex);
+ } finally {
+ if (connection != null) {
+ connection.close();
+ }
+ }
+ }
+
+ /**
+ * Transform group CN to group path.
+ *
+ * Example:
+ * CN=Tout Franciaflex,OU=Listes de distribution,OU=Comptes Spéciaux,OU=Mac-Groupe,DC=mac-groupe,DC=net
+ * net/mac-groupe/Mac-Groupe/Comptes Spéciaux/Listes de distribution/Tout Franciaflex
+ *
+ * @param groupCN
+ * @return
+ */
+ protected String getGroupCompleteName(String groupCN) {
+ String[] parts = groupCN.split(",");
+ ArrayUtils.reverse(parts);
+
+ // join tab
+ String separator = "";
+ StringBuilder result = new StringBuilder();
+ for (String part : parts) {
+ result.append(separator);
+ result.append(StringUtils.substringAfter(part, "="));
+ separator = "/";
+ }
+ return result.toString();
+ }
+
+ /**
+ * Return user for given user id.
+ *
+ * @param userTopiaId userTopiaId
+ * @return user bean (without password)
+ */
+ @Override
+ public FaxToMailUser getUserBean(String userTopiaId) {
+ FaxToMailUser result = null;
+
+ FaxToMailUserTopiaDao faxtomailUserDao = getPersistenceContext().getFaxToMailUserDao();
+ FaxToMailUser user = faxtomailUserDao.forTopiaIdEquals(userTopiaId).findUniqueOrNull();
+ if (user != null) {
+ Binder<FaxToMailUser, FaxToMailUser> faxToMailUserBinder = BinderFactory.newBinder(FaxToMailUser.class);
+ result = new FaxToMailUserImpl();
+ faxToMailUserBinder.copyExcluding(user, result);
+ }
+ return result;
+ }
+
+ /**
+ * Authenticate and update ldap user.
+ *
+ * @param login login
+ * @param password password
+ * @return authenticated user
+ * @throws AuthenticationException if authentication fails
+ */
+ @Override
+ public FaxToMailUser authenticateUser(String login, String password) throws AuthenticationException {
+
+ FaxToMailUser result;
+
+ login = login.toLowerCase();
+ try {
+ // first connexion to get full user login
+ LDAPConnection adminConnect = new LDAPConnection();
+ adminConnect.connect(getApplicationConfig().getLdapHost(), getApplicationConfig().getLdapPort());
+ adminConnect.bind(getApplicationConfig().getLdapUser(), getApplicationConfig().getLdapPassword());
+
+ // search user in ldap
+ String userDN = null;
+ SearchResultEntry searchEntry = null;
+ if (adminConnect.isConnected()) {
+ // sn est le login interne à franciaflex
+ String filter = String.format("(sAMAccountName=%s)", login);
+ SearchResult searchResult = adminConnect.search(getApplicationConfig().getLdapBaseDn(), SearchScope.SUB, filter);
+ if (!searchResult.getSearchEntries().isEmpty()) {
+ searchEntry = searchResult.getSearchEntries().get(0);
+ userDN = searchEntry.getDN();
+ }
+ }
+
+ if (searchEntry != null) {
+ // ouvre une connexion avec l'identification de l'utilisateur qui essaye de se connecter
+ // à l'application (ca permet de vérifier l'authentification)
+ LDAPConnection userConnect = new LDAPConnection();
+ userConnect.connect(getApplicationConfig().getLdapHost(), getApplicationConfig().getLdapPort());
+ userConnect.bind(userDN, password);
+
+ if (userConnect.isConnected()) {
+ // update in database
+ result = updateUserFormLdap(adminConnect, searchEntry, login, null);
+ getPersistenceContext().commit();
+
+ userConnect.close();
+ } else {
+ throw new AuthenticationException("Not connected");
+ }
+ } else {
+ throw new AuthenticationException("Utilisateur inconnu : " + login);
+ }
+ adminConnect.close();
+
+ } catch (LDAPException ex) {
+ if (log.isWarnEnabled()) {
+ log.warn("Can't login to ldap", ex);
+ }
+ throw new AuthenticationException(ex.getResultCode().getName(), ex);
+ }
+ return result;
+ }
+
+ /**
+ * Retreive user from principal and updated user database instance.
+ *
+ * This method doesn't require any password.
+ *
+ * @param login user principal (without domain)
+ * @return user instance
+ * @throws AuthenticationException is user can't be found in ldap
+ */
+ @Override
+ public FaxToMailUser getUserFromPrincipal(String login) throws AuthenticationException {
+
+ FaxToMailUser result;
+
+ login = login.toLowerCase();
+
+ try {
+ // first connexion to get full user login
+ LDAPConnection adminConnect = new LDAPConnection();
+ adminConnect.connect(getApplicationConfig().getLdapHost(), getApplicationConfig().getLdapPort());
+ adminConnect.bind(getApplicationConfig().getLdapUser(), getApplicationConfig().getLdapPassword());
+
+ // search user in ldap
+ SearchResultEntry searchEntry = null;
+ if (adminConnect.isConnected()) {
+ // sAMAccountName est l'identifiant kerberos
+ String filter = String.format("(sAMAccountName=%s)", login);
+ SearchResult searchResult = adminConnect.search(getApplicationConfig().getLdapBaseDn(), SearchScope.SUB, filter);
+ if (!searchResult.getSearchEntries().isEmpty()) {
+ searchEntry = searchResult.getSearchEntries().get(0);
+ }
+
+ } else {
+ throw new AuthenticationException("Utilisateur inconnu : " + login);
+ }
+
+ if( searchEntry != null ) {
+ // update in database
+ result = updateUserFormLdap(adminConnect, searchEntry, login, null);
+ getPersistenceContext().commit();
+ } else {
+ throw new AuthenticationException("Utilisateur inconnu : " + login);
+ }
+
+ adminConnect.close();
+ } catch (LDAPException ex) {
+ if (log.isWarnEnabled()) {
+ log.warn("Can't login to ldap", ex);
+ }
+ throw new AuthenticationException(ex.getResultCode().getName(), ex);
+ }
+ return result;
+ }
+
+ /**
+ * Update user (or create) in database from ldap search result entry.
+ *
+ * @param adminConnect admin connection used to load groups content
+ * @param searchEntry entry containing data
+ * @param login login
+ * @param groupCache group cache when mass update (can be null)
+ * @return updated user
+ * @throws LDAPException
+ */
+ protected FaxToMailUser updateUserFormLdap(LDAPConnection adminConnect, SearchResultEntry searchEntry, String login, Map<String, FaxToMailUserGroup> groupCache) throws LDAPException {
+
+ FaxToMailUser user;
+
+ // create or
+ FaxToMailUserTopiaDao faxtomailUserDao = getPersistenceContext().getFaxToMailUserDao();
+ FaxToMailUserGroupTopiaDao faxtomailUserGroupDao = getPersistenceContext().getFaxToMailUserGroupDao();
+ user = faxtomailUserDao.forLoginEquals(login).findUniqueOrNull();
+
+ if (user == null) {
+ user = new FaxToMailUserImpl();
+ user.setLogin(login);
+ }
+ user.setHidden(false);
+
+ // update other ldap fields
+ String fullName = searchEntry.getAttributeValue("name");
+ if (fullName.indexOf(' ') != -1) {
+ String lastName = fullName.substring(0, fullName.indexOf(' '));
+ String firstName = fullName.substring(fullName.indexOf(' ') + 1);
+ user.setFirstName(firstName);
+ user.setLastName(lastName);
+ } else {
+ user.setFirstName("");
+ user.setLastName(fullName);
+ }
+
+ String trigraph = searchEntry.getAttributeValue("sAMAccountName");
+ user.setTrigraph(StringUtils.upperCase(trigraph));
+
+ // manage user groups
+ user.clearUserGroups();
+ String[] groups = searchEntry.getAttributeValues("memberOf");
+ if (ArrayUtils.isNotEmpty(groups)) {
+ for (String group : groups) {
+
+ // en mass-update, on a le cache
+ if (groupCache != null) {
+ FaxToMailUserGroup userGroup = groupCache.get(group);
+ if (userGroup != null) {
+ user.addUserGroups(userGroup);
+ }
+ } else {
+ // parmis tous les groupes, on n'utilise que ceux qui sont de la catégories
+ // CN=Group,CN=Schema,CN=Configuration,DC=mac-groupe,DC=net
+ SearchResultEntry groupSearchEntry = adminConnect.getEntry(group);
+ String objectCategory = groupSearchEntry.getAttributeValue("objectCategory");
+ if ("CN=Group,CN=Schema,CN=Configuration,DC=mac-groupe,DC=net".equals(objectCategory)) {
+ String groupPath = getGroupCompleteName(group);
+ String groupName = StringUtils.substringAfterLast(groupPath, "/");
+ FaxToMailUserGroup userGroup = faxtomailUserGroupDao.forNameEquals(groupName).findUniqueOrNull();
+ if (userGroup == null) {
+ userGroup = faxtomailUserGroupDao.create(
+ FaxToMailUserGroup.PROPERTY_NAME, groupName,
+ FaxToMailUserGroup.PROPERTY_COMPLETE_NAME, groupPath);
+ }
+ user.addUserGroups(userGroup);
+ }
+ }
+ }
+ }
+
+ if (user.isPersisted()) {
+ user = faxtomailUserDao.update(user);
+ } else {
+ user = faxtomailUserDao.create(user);
+ }
+
+ // force collection loading to force non lazy collections
+ user.isAffectedFoldersEmpty();
+ user.isUserGroupsEmpty();
+
+ return user;
+ }
+}
Property changes on: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/LdapServiceImpl.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Deleted: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/MailFolderService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/MailFolderService.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/MailFolderService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -1,214 +0,0 @@
-package com.franciaflex.faxtomail.services.service;
-
-/*
- * #%L
- * FaxToMail :: Service
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2014 Franciaflex, Code Lutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/gpl-3.0.html>.
- * #L%
- */
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
-
-import org.apache.commons.collections4.CollectionUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.util.pagination.PaginationParameter;
-
-import com.franciaflex.faxtomail.persistence.entities.EmailTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.EtatAttente;
-import com.franciaflex.faxtomail.persistence.entities.MailFilter;
-import com.franciaflex.faxtomail.persistence.entities.MailFilterTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.MailFolder;
-import com.franciaflex.faxtomail.persistence.entities.MailFolderTopiaDao;
-import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
-
-/**
- * @author kmorin - kmorin(a)codelutin.com
- */
-public class MailFolderService extends FaxToMailServiceSupport {
-
- private static final Log log = LogFactory.getLog(MailFolderService.class);
-
- public MailFolder getFolderForRecipient(String recipient) {
- MailFilterTopiaDao filterTopiaDao = getPersistenceContext().getMailFilterDao();
-
- PaginationParameter tpb = PaginationParameter.of(0, -1, MailFilter.PROPERTY_POSITION, false);
-
- String query = "FROM " + MailFilter.class.getCanonicalName() + " WHERE :recipient LIKE " + MailFilter.PROPERTY_EXPRESSION;
- Map<String, Object> params = new HashMap<>();
- params.put("recipient", recipient);
-
- Collection<MailFilter> filters = filterTopiaDao.find(query, params, tpb);
- MailFolder result;
- if (CollectionUtils.isNotEmpty(filters)) {
- result = filters.iterator().next().getMailFolder();
- } else {
- result = null;
- }
- return result;
- }
-
- public Collection<MailFilter> getFiltersForRecipient(String recipient) {
- MailFilterTopiaDao filterTopiaDao = getPersistenceContext().getMailFilterDao();
-
- PaginationParameter tpb = PaginationParameter.of(0, -1, MailFilter.PROPERTY_POSITION, false);
-
- String query = "FROM " + MailFilter.class.getCanonicalName() + " WHERE :recipient LIKE " + MailFilter.PROPERTY_EXPRESSION;
- Map<String, Object> params = new HashMap<>();
- params.put("recipient", recipient);
-
- Collection<MailFilter> filters = filterTopiaDao.find(query, params, tpb);
- return filters;
- }
-
- public List<MailFolder> getAllMailFolders() {
- MailFolderTopiaDao dao = getPersistenceContext().getMailFolderDao();
- return new ArrayList<MailFolder>(dao.findAll());
- }
-
- public List<MailFolder> getRootMailFolders() {
- MailFolderTopiaDao dao = getPersistenceContext().getMailFolderDao();
- List<MailFolder> result = dao.forParentEquals(null).findAll();
- return result;
- }
-
- public List<MailFolder> getRootMailFoldersWithReadingRights(FaxToMailUser user) {
- List<MailFolder> rootFolders = getRootMailFolders();
- List<MailFolder> result = new ArrayList<>();
-
- for (MailFolder folder : rootFolders) {
- findReadableFolders(folder, user, result);
- }
-
- return result;
- }
-
- protected void findReadableFolders(MailFolder folder, FaxToMailUser user, List<MailFolder> folders) {
- if (folder.containsReadRightUsers(user)
- || !CollectionUtils.intersection(folder.getReadRightGroups(), user.getUserGroups()).isEmpty()) {
- folders.add(folder);
-
- } else if (folder.isChildrenNotEmpty()) {
- for (MailFolder child : folder.getChildren()) {
- findReadableFolders(child, user, folders);
- }
- }
- }
-
- public List<MailFolder> getRootMailFoldersWithMoveRights(FaxToMailUser user) {
- List<MailFolder> rootFolders = getRootMailFolders();
- List<MailFolder> result = new ArrayList<>();
-
- for (MailFolder folder : rootFolders) {
- findMoveFolders(folder, user, result);
- }
-
- return result;
- }
-
- protected void findMoveFolders(MailFolder folder, FaxToMailUser user, List<MailFolder> folders) {
- if (folder.containsMoveRightUsers(user)
- || !CollectionUtils.intersection(folder.getMoveRightGroups(), user.getUserGroups()).isEmpty()) {
- folders.add(folder);
-
- } else if (folder.isChildrenNotEmpty()) {
- for (MailFolder child : folder.getChildren()) {
- findMoveFolders(child, user, folders);
- }
- }
- }
-
- public List<MailFolder> getMailFolders(Collection<String> ids) {
- MailFolderTopiaDao dao = getPersistenceContext().getMailFolderDao();
- return new ArrayList<MailFolder>(dao.forTopiaIdIn(ids).findAll());
- }
-
- public Collection<MailFolder> getFoldersWithEtatAttente(EtatAttente etatAttente) {
- Collection<MailFolder> result = new HashSet<>();
-
- MailFolderTopiaDao dao = getPersistenceContext().getMailFolderDao();
- List<MailFolder> roots = dao.forParentEquals(null).findAll();
-
- for (MailFolder root : roots) {
- result.addAll(getFoldersWithEtatAttente(root, new HashSet<EtatAttente>(), etatAttente));
- }
-
- return result;
- }
-
- protected Collection<MailFolder> getFoldersWithEtatAttente(MailFolder folder,
- Collection<EtatAttente> parentEtatAttente,
- EtatAttente etatAttente) {
- Collection<EtatAttente> etatAttentes = folder.getEtatAttentes();
- if (CollectionUtils.isEmpty(etatAttentes)) {
- etatAttentes = parentEtatAttente;
- } else {
- parentEtatAttente = etatAttentes;
- }
-
- Collection<MailFolder> result = new HashSet<>();
- Collection<MailFolder> children = folder.getChildren();
- if (children != null) {
- for (MailFolder child : children) {
- result.addAll(getFoldersWithEtatAttente(child, parentEtatAttente, etatAttente));
- }
- }
-
- if (etatAttentes.contains(etatAttente)) {
- result.add(folder);
- }
-
- return result;
-
- }
-
- /**
- * Retourne une map avec les identifiants des {@code mailFolder}s et le nombre de mails qu'ils
- * contiennent pour pouvoir empecher la suppression.
- * Seulement pour les dossiers qui ont au moins un email.
- *
- * @return le nombre de mail par dossier
- */
- public Map<String, Long> getMailFoldersUsage() {
- EmailTopiaDao dao = getPersistenceContext().getEmailDao();
- Map<String, Long> result = dao.getMailCountByFolder();
- return result;
- }
-
- public MailFolder getFolderForFaxToMailUser(FaxToMailUser customerResponsible) {
- MailFolderTopiaDao dao = getPersistenceContext().getMailFolderDao();
- MailFolder result = dao.forCustomerResponsiblesContains(customerResponsible).findAnyOrNull();
- return result;
- }
-
- public MailFolder getMailFolder(String topiaId) {
- MailFolderTopiaDao dao = getPersistenceContext().getMailFolderDao();
- MailFolder result = dao.forTopiaIdEquals(topiaId).findUnique();
- return result;
- }
-
-}
Added: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/MailFolderService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/MailFolderService.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/MailFolderService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,38 @@
+package com.franciaflex.faxtomail.services.service;
+
+import com.franciaflex.faxtomail.persistence.entities.EtatAttente;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+import com.franciaflex.faxtomail.persistence.entities.MailFilter;
+import com.franciaflex.faxtomail.persistence.entities.MailFolder;
+import com.franciaflex.faxtomail.services.FaxToMailService;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @author Kevin Morin (Code Lutin)
+ */
+public interface MailFolderService extends FaxToMailService {
+ MailFolder getFolderForRecipient(String recipient);
+
+ Collection<MailFilter> getFiltersForRecipient(String recipient);
+
+ List<MailFolder> getAllMailFolders();
+
+ List<MailFolder> getRootMailFolders();
+
+ List<MailFolder> getRootMailFoldersWithReadingRights(FaxToMailUser user);
+
+ List<MailFolder> getRootMailFoldersWithMoveRights(FaxToMailUser user);
+
+ List<MailFolder> getMailFolders(Collection<String> ids);
+
+ Collection<MailFolder> getFoldersWithEtatAttente(EtatAttente etatAttente);
+
+ Map<String, Long> getMailFoldersUsage();
+
+ MailFolder getFolderForFaxToMailUser(FaxToMailUser customerResponsible);
+
+ MailFolder getMailFolder(String topiaId);
+}
Copied: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/MailFolderServiceImpl.java (from rev 468, trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/MailFolderService.java)
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/MailFolderServiceImpl.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/MailFolderServiceImpl.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,225 @@
+package com.franciaflex.faxtomail.services.service;
+
+/*
+ * #%L
+ * FaxToMail :: Service
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2014 Franciaflex, Code Lutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.util.pagination.PaginationParameter;
+
+import com.franciaflex.faxtomail.persistence.entities.EmailTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.EtatAttente;
+import com.franciaflex.faxtomail.persistence.entities.MailFilter;
+import com.franciaflex.faxtomail.persistence.entities.MailFilterTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.MailFolder;
+import com.franciaflex.faxtomail.persistence.entities.MailFolderTopiaDao;
+import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
+
+/**
+ * @author kmorin - kmorin(a)codelutin.com
+ */
+public class MailFolderServiceImpl extends FaxToMailServiceSupport implements MailFolderService {
+
+ private static final Log log = LogFactory.getLog(MailFolderServiceImpl.class);
+
+ @Override
+ public MailFolder getFolderForRecipient(String recipient) {
+ MailFilterTopiaDao filterTopiaDao = getPersistenceContext().getMailFilterDao();
+
+ PaginationParameter tpb = PaginationParameter.of(0, -1, MailFilter.PROPERTY_POSITION, false);
+
+ String query = "FROM " + MailFilter.class.getCanonicalName() + " WHERE :recipient LIKE " + MailFilter.PROPERTY_EXPRESSION;
+ Map<String, Object> params = new HashMap<>();
+ params.put("recipient", recipient);
+
+ Collection<MailFilter> filters = filterTopiaDao.find(query, params, tpb);
+ MailFolder result;
+ if (CollectionUtils.isNotEmpty(filters)) {
+ result = filters.iterator().next().getMailFolder();
+ } else {
+ result = null;
+ }
+ return result;
+ }
+
+ @Override
+ public Collection<MailFilter> getFiltersForRecipient(String recipient) {
+ MailFilterTopiaDao filterTopiaDao = getPersistenceContext().getMailFilterDao();
+
+ PaginationParameter tpb = PaginationParameter.of(0, -1, MailFilter.PROPERTY_POSITION, false);
+
+ String query = "FROM " + MailFilter.class.getCanonicalName() + " WHERE :recipient LIKE " + MailFilter.PROPERTY_EXPRESSION;
+ Map<String, Object> params = new HashMap<>();
+ params.put("recipient", recipient);
+
+ Collection<MailFilter> filters = filterTopiaDao.find(query, params, tpb);
+ return filters;
+ }
+
+ @Override
+ public List<MailFolder> getAllMailFolders() {
+ MailFolderTopiaDao dao = getPersistenceContext().getMailFolderDao();
+ return new ArrayList<MailFolder>(dao.findAll());
+ }
+
+ @Override
+ public List<MailFolder> getRootMailFolders() {
+ MailFolderTopiaDao dao = getPersistenceContext().getMailFolderDao();
+ List<MailFolder> result = dao.forParentEquals(null).findAll();
+ return result;
+ }
+
+ @Override
+ public List<MailFolder> getRootMailFoldersWithReadingRights(FaxToMailUser user) {
+ List<MailFolder> rootFolders = getRootMailFolders();
+ List<MailFolder> result = new ArrayList<>();
+
+ for (MailFolder folder : rootFolders) {
+ findReadableFolders(folder, user, result);
+ }
+
+ return result;
+ }
+
+ protected void findReadableFolders(MailFolder folder, FaxToMailUser user, List<MailFolder> folders) {
+ if (folder.containsReadRightUsers(user)
+ || !CollectionUtils.intersection(folder.getReadRightGroups(), user.getUserGroups()).isEmpty()) {
+ folders.add(folder);
+
+ } else if (folder.isChildrenNotEmpty()) {
+ for (MailFolder child : folder.getChildren()) {
+ findReadableFolders(child, user, folders);
+ }
+ }
+ }
+
+ @Override
+ public List<MailFolder> getRootMailFoldersWithMoveRights(FaxToMailUser user) {
+ List<MailFolder> rootFolders = getRootMailFolders();
+ List<MailFolder> result = new ArrayList<>();
+
+ for (MailFolder folder : rootFolders) {
+ findMoveFolders(folder, user, result);
+ }
+
+ return result;
+ }
+
+ protected void findMoveFolders(MailFolder folder, FaxToMailUser user, List<MailFolder> folders) {
+ if (folder.containsMoveRightUsers(user)
+ || !CollectionUtils.intersection(folder.getMoveRightGroups(), user.getUserGroups()).isEmpty()) {
+ folders.add(folder);
+
+ } else if (folder.isChildrenNotEmpty()) {
+ for (MailFolder child : folder.getChildren()) {
+ findMoveFolders(child, user, folders);
+ }
+ }
+ }
+
+ @Override
+ public List<MailFolder> getMailFolders(Collection<String> ids) {
+ MailFolderTopiaDao dao = getPersistenceContext().getMailFolderDao();
+ return new ArrayList<MailFolder>(dao.forTopiaIdIn(ids).findAll());
+ }
+
+ @Override
+ public Collection<MailFolder> getFoldersWithEtatAttente(EtatAttente etatAttente) {
+ Collection<MailFolder> result = new HashSet<>();
+
+ MailFolderTopiaDao dao = getPersistenceContext().getMailFolderDao();
+ List<MailFolder> roots = dao.forParentEquals(null).findAll();
+
+ for (MailFolder root : roots) {
+ result.addAll(getFoldersWithEtatAttente(root, new HashSet<EtatAttente>(), etatAttente));
+ }
+
+ return result;
+ }
+
+ protected Collection<MailFolder> getFoldersWithEtatAttente(MailFolder folder,
+ Collection<EtatAttente> parentEtatAttente,
+ EtatAttente etatAttente) {
+ Collection<EtatAttente> etatAttentes = folder.getEtatAttentes();
+ if (CollectionUtils.isEmpty(etatAttentes)) {
+ etatAttentes = parentEtatAttente;
+ } else {
+ parentEtatAttente = etatAttentes;
+ }
+
+ Collection<MailFolder> result = new HashSet<>();
+ Collection<MailFolder> children = folder.getChildren();
+ if (children != null) {
+ for (MailFolder child : children) {
+ result.addAll(getFoldersWithEtatAttente(child, parentEtatAttente, etatAttente));
+ }
+ }
+
+ if (etatAttentes.contains(etatAttente)) {
+ result.add(folder);
+ }
+
+ return result;
+
+ }
+
+ /**
+ * Retourne une map avec les identifiants des {@code mailFolder}s et le nombre de mails qu'ils
+ * contiennent pour pouvoir empecher la suppression.
+ * Seulement pour les dossiers qui ont au moins un email.
+ *
+ * @return le nombre de mail par dossier
+ */
+ @Override
+ public Map<String, Long> getMailFoldersUsage() {
+ EmailTopiaDao dao = getPersistenceContext().getEmailDao();
+ Map<String, Long> result = dao.getMailCountByFolder();
+ return result;
+ }
+
+ @Override
+ public MailFolder getFolderForFaxToMailUser(FaxToMailUser customerResponsible) {
+ MailFolderTopiaDao dao = getPersistenceContext().getMailFolderDao();
+ MailFolder result = dao.forCustomerResponsiblesContains(customerResponsible).findAnyOrNull();
+ return result;
+ }
+
+ @Override
+ public MailFolder getMailFolder(String topiaId) {
+ MailFolderTopiaDao dao = getPersistenceContext().getMailFolderDao();
+ MailFolder result = dao.forTopiaIdEquals(topiaId).findUnique();
+ return result;
+ }
+
+}
Property changes on: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/MailFolderServiceImpl.java
___________________________________________________________________
Added: svn:eol-style
+ native
Added: svn:keywords
+ Author Date Id Revision HeadURL
Deleted: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ReferentielService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ReferentielService.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ReferentielService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -1,332 +0,0 @@
-package com.franciaflex.faxtomail.services.service;
-
-/*
- * #%L
- * FaxToMail :: Service
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2014 Franciaflex, Code Lutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/gpl-3.0.html>.
- * #L%
- */
-
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.io.IOUtils;
-import org.nuiton.csv.Import;
-import org.nuiton.csv.ImportRuntimeException;
-import org.nuiton.jaxx.application.ApplicationTechnicalException;
-import org.nuiton.util.beans.Binder;
-import org.nuiton.util.beans.BinderFactory;
-
-import com.franciaflex.faxtomail.persistence.entities.Client;
-import com.franciaflex.faxtomail.persistence.entities.ClientImpl;
-import com.franciaflex.faxtomail.persistence.entities.ClientTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.DemandType;
-import com.franciaflex.faxtomail.persistence.entities.DemandTypeTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.EmailAccount;
-import com.franciaflex.faxtomail.persistence.entities.EmailAccountTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.EtatAttente;
-import com.franciaflex.faxtomail.persistence.entities.EtatAttenteTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.MailFilter;
-import com.franciaflex.faxtomail.persistence.entities.MailFilterTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.MailFolder;
-import com.franciaflex.faxtomail.persistence.entities.Priority;
-import com.franciaflex.faxtomail.persistence.entities.PriorityTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.Range;
-import com.franciaflex.faxtomail.persistence.entities.RangeTopiaDao;
-import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
-import com.franciaflex.faxtomail.services.service.imports.ClientImportModel;
-import com.franciaflex.faxtomail.services.service.imports.DemandTypeImportModel;
-import com.franciaflex.faxtomail.services.service.imports.EmailAccountImportModel;
-import com.franciaflex.faxtomail.services.service.imports.EmailFilterImportModel;
-import com.franciaflex.faxtomail.services.service.imports.EtatAttenteImportModel;
-import com.franciaflex.faxtomail.services.service.imports.PriorityImportModel;
-import com.franciaflex.faxtomail.services.service.imports.RangeImportModel;
-
-/**
- * @author kmorin - kmorin(a)codelutin.com
- */
-public class ReferentielService extends FaxToMailServiceSupport {
-
- public List<DemandType> getAllDemandType() {
- DemandTypeTopiaDao dao = getPersistenceContext().getDemandTypeDao();
- return dao.findAll();
- }
-
- public List<Priority> getAllPriority() {
- PriorityTopiaDao dao = getPersistenceContext().getPriorityDao();
- return dao.findAll();
- }
-
- public List<Range> getAllRange() {
- RangeTopiaDao dao = getPersistenceContext().getRangeDao();
- return dao.findAll();
- }
-
- public List<EtatAttente> getAllEtatAttente() {
- EtatAttenteTopiaDao dao = getPersistenceContext().getEtatAttenteDao();
- return dao.findAll();
- }
-
- public Map<String, Long> getEtatAttentesUsage() {
- EtatAttenteTopiaDao dao = getPersistenceContext().getEtatAttenteDao();
- Map<String, Long> result = dao.getEtatAttenteCountByFolder();
- return result;
- }
-
- public List<Client> getAllClients() {
- ClientTopiaDao dao = getPersistenceContext().getClientDao();
- return dao.findAll();
- }
-
- public List<Client> importClients(InputStream inputStream) {
- List<Client> result = new ArrayList<>();
- ClientTopiaDao dao = getPersistenceContext().getClientDao();
-
- ClientImportModel clientImportModel = new ClientImportModel(';');
- Binder<Client, Client> clientBinder = BinderFactory.newBinder(Client.class);
- Import<Client> importer = null;
- try {
- importer = Import.newImport(clientImportModel, new InputStreamReader(inputStream, getApplicationConfig().getImportFileEncoding()));
- for (Client client : importer) {
-
- Client current = dao.forCodeEquals(client.getCode()).addEquals(Client.PROPERTY_BRAND, client.getBrand()).findAnyOrNull();
- if (current == null) {
- current = new ClientImpl();
- }
-
- clientBinder.copyExcluding(client, current,
- Client.PROPERTY_TOPIA_ID,
- Client.PROPERTY_TOPIA_CREATE_DATE,
- Client.PROPERTY_TOPIA_VERSION);
-
- if (client.isPersisted()) {
- current = dao.update(current);
- } else {
- current = dao.create(current);
- }
- result.add(current);
- }
- getPersistenceContext().commit();
-
- } catch (ImportRuntimeException|UnsupportedEncodingException e) {
- String message;
- if (e.getCause() != null) {
- message = e.getCause().getMessage();
- } else {
- message = e.getMessage();
- }
- throw new ApplicationTechnicalException(message, e);
- } finally {
- IOUtils.closeQuietly(importer);
- IOUtils.closeQuietly(inputStream);
- }
- return result;
- }
-
- public List<EmailAccount> importEmailAccounts(InputStream inputStream) {
- List<EmailAccount> result = new ArrayList<>();
- EmailAccountTopiaDao dao = getPersistenceContext().getEmailAccountDao();
-
- EmailAccountImportModel emailAccountImportModel = new EmailAccountImportModel(';');
- try (Import<EmailAccount> importer = Import.newImport(emailAccountImportModel, new InputStreamReader(inputStream, getApplicationConfig().getImportFileEncoding()))) {
- for (EmailAccount emailAccount : importer) {
- result.add(dao.create(emailAccount));
- }
- getPersistenceContext().commit();
- } catch (ImportRuntimeException|UnsupportedEncodingException e) {
- String message;
- if (e.getCause() != null) {
- message = e.getCause().getMessage();
- } else {
- message = e.getMessage();
- }
- throw new ApplicationTechnicalException(message, e);
-
- } finally {
- IOUtils.closeQuietly(inputStream);
- }
- return result;
- }
-
- public List<MailFilter> importEmailFilters(InputStream inputStream, Map<String, MailFolder> foldersByName) {
- List<MailFilter> result = new ArrayList<>();
- MailFilterTopiaDao dao = getPersistenceContext().getMailFilterDao();
-
- EmailFilterImportModel emailFilterImportModel = new EmailFilterImportModel(';', foldersByName);
- try (Import<MailFilter> importer = Import.newImport(emailFilterImportModel, new InputStreamReader(inputStream, getApplicationConfig().getImportFileEncoding()))) {
- for (MailFilter emailFilter : importer) {
- result.add(dao.create(emailFilter));
- }
- getPersistenceContext().commit();
-
- } catch (ImportRuntimeException|UnsupportedEncodingException e) {
- String message;
- if (e.getCause() != null) {
- message = e.getCause().getMessage();
- } else {
- message = e.getMessage();
- }
- throw new ApplicationTechnicalException(message, e);
-
- } finally {
- IOUtils.closeQuietly(inputStream);
- }
- return result;
- }
-
- public List<EtatAttente> importEtatAttentes(InputStream inputStream) {
-
- List<EtatAttente> result = new ArrayList<>();
- EtatAttenteTopiaDao etatAttenteTopiaDao = getPersistenceContext().getEtatAttenteDao();
-
- EtatAttenteImportModel importModel = new EtatAttenteImportModel(';');
- try (Import<EtatAttente> importer = Import.newImport(importModel, new InputStreamReader(inputStream, getApplicationConfig().getImportFileEncoding()))) {
- for (EtatAttente etatAttente : importer) {
-
- EtatAttente currentEtatAttente = etatAttenteTopiaDao.forLabelEquals(etatAttente.getLabel()).findAnyOrNull();
- if (currentEtatAttente == null) {
- currentEtatAttente = etatAttenteTopiaDao.create(etatAttente);
- }
- // else maybe update current ?
-
- result.add(currentEtatAttente);
- }
- getPersistenceContext().commit();
-
- } catch (ImportRuntimeException|UnsupportedEncodingException e) {
- String message;
- if (e.getCause() != null) {
- message = e.getCause().getMessage();
- } else {
- message = e.getMessage();
- }
- throw new ApplicationTechnicalException(message, e);
-
- } finally {
- IOUtils.closeQuietly(inputStream);
- }
-
- return result;
- }
-
- public List<Priority> importPriorities(InputStream inputStream) {
- List<Priority> result = new ArrayList<>();
- PriorityTopiaDao priorityTopiaDao = getPersistenceContext().getPriorityDao();
-
- PriorityImportModel importModel = new PriorityImportModel(';');
- try (Import<Priority> importer = Import.newImport(importModel, new InputStreamReader(inputStream, getApplicationConfig().getImportFileEncoding()))) {
- for (Priority priority : importer) {
-
- Priority currentPriority = priorityTopiaDao.forLabelEquals(priority.getLabel()).findAnyOrNull();
- if (currentPriority == null) {
- currentPriority = priorityTopiaDao.create(priority);
- }
- // else maybe update current ?
-
- result.add(currentPriority);
- }
- getPersistenceContext().commit();
-
- } catch (ImportRuntimeException|UnsupportedEncodingException e) {
- String message;
- if (e.getCause() != null) {
- message = e.getCause().getMessage();
- } else {
- message = e.getMessage();
- }
- throw new ApplicationTechnicalException(message, e);
-
- } finally {
- IOUtils.closeQuietly(inputStream);
- }
-
- return result;
- }
-
- public List<Range> importRanges(InputStream inputStream) {
- List<Range> result = new ArrayList<>();
- RangeTopiaDao rangeTopiaDao = getPersistenceContext().getRangeDao();
-
- RangeImportModel importModel = new RangeImportModel(';');
- try (Import<Range> importer = Import.newImport(importModel, new InputStreamReader(inputStream, getApplicationConfig().getImportFileEncoding()))) {
- for (Range range : importer) {
-
- Range currentRange = rangeTopiaDao.forLabelEquals(range.getLabel()).findAnyOrNull();
- if (currentRange == null) {
- currentRange = rangeTopiaDao.create(range);
- }
- // else maybe update current ?
-
- result.add(currentRange);
- }
- getPersistenceContext().commit();
-
- } catch (ImportRuntimeException|UnsupportedEncodingException e) {
- String message;
- if (e.getCause() != null) {
- message = e.getCause().getMessage();
- } else {
- message = e.getMessage();
- }
- throw new ApplicationTechnicalException(message, e);
-
- } finally {
- IOUtils.closeQuietly(inputStream);
- }
- return result;
- }
-
- public List<DemandType> importDemandTypes(InputStream inputStream) {
- List<DemandType> result = new ArrayList<>();
- DemandTypeTopiaDao demandTypeTopiaDao = getPersistenceContext().getDemandTypeDao();
-
- DemandTypeImportModel importModel = new DemandTypeImportModel(';');
- try (Import<DemandType> importer = Import.newImport(importModel, new InputStreamReader(inputStream, getApplicationConfig().getImportFileEncoding()))) {
- for (DemandType demandType : importer) {
-
- DemandType currentDemandType = demandTypeTopiaDao.forLabelEquals(demandType.getLabel()).findAnyOrNull();
- if (currentDemandType == null) {
- currentDemandType = demandTypeTopiaDao.create(demandType);
- }
- // else maybe update current ?
-
- result.add(currentDemandType);
- }
- getPersistenceContext().commit();
-
- } catch (ImportRuntimeException|UnsupportedEncodingException e) {
- String message;
- if (e.getCause() != null) {
- message = e.getCause().getMessage();
- } else {
- message = e.getMessage();
- }
- throw new ApplicationTechnicalException(message, e);
-
- } finally {
- IOUtils.closeQuietly(inputStream);
- }
- return result;
- }
-}
Added: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ReferentielService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ReferentielService.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ReferentielService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,46 @@
+package com.franciaflex.faxtomail.services.service;
+
+import com.franciaflex.faxtomail.persistence.entities.Client;
+import com.franciaflex.faxtomail.persistence.entities.DemandType;
+import com.franciaflex.faxtomail.persistence.entities.EmailAccount;
+import com.franciaflex.faxtomail.persistence.entities.EtatAttente;
+import com.franciaflex.faxtomail.persistence.entities.MailFilter;
+import com.franciaflex.faxtomail.persistence.entities.MailFolder;
+import com.franciaflex.faxtomail.persistence.entities.Priority;
+import com.franciaflex.faxtomail.persistence.entities.Range;
+import com.franciaflex.faxtomail.services.FaxToMailService;
+
+import java.io.InputStream;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @author Kevin Morin (Code Lutin)
+ */
+public interface ReferentielService extends FaxToMailService {
+ List<DemandType> getAllDemandType();
+
+ List<Priority> getAllPriority();
+
+ List<Range> getAllRange();
+
+ List<EtatAttente> getAllEtatAttente();
+
+ Map<String, Long> getEtatAttentesUsage();
+
+ List<Client> getAllClients();
+
+ List<Client> importClients(InputStream inputStream);
+
+ List<EmailAccount> importEmailAccounts(InputStream inputStream);
+
+ List<MailFilter> importEmailFilters(InputStream inputStream, Map<String, MailFolder> foldersByName);
+
+ List<EtatAttente> importEtatAttentes(InputStream inputStream);
+
+ List<Priority> importPriorities(InputStream inputStream);
+
+ List<Range> importRanges(InputStream inputStream);
+
+ List<DemandType> importDemandTypes(InputStream inputStream);
+}
Copied: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ReferentielServiceImpl.java (from rev 468, trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ReferentielService.java)
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ReferentielServiceImpl.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ReferentielServiceImpl.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,345 @@
+package com.franciaflex.faxtomail.services.service;
+
+/*
+ * #%L
+ * FaxToMail :: Service
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2014 Franciaflex, Code Lutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.io.IOUtils;
+import org.nuiton.csv.Import;
+import org.nuiton.csv.ImportRuntimeException;
+import org.nuiton.jaxx.application.ApplicationTechnicalException;
+import org.nuiton.util.beans.Binder;
+import org.nuiton.util.beans.BinderFactory;
+
+import com.franciaflex.faxtomail.persistence.entities.Client;
+import com.franciaflex.faxtomail.persistence.entities.ClientImpl;
+import com.franciaflex.faxtomail.persistence.entities.ClientTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.DemandType;
+import com.franciaflex.faxtomail.persistence.entities.DemandTypeTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.EmailAccount;
+import com.franciaflex.faxtomail.persistence.entities.EmailAccountTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.EtatAttente;
+import com.franciaflex.faxtomail.persistence.entities.EtatAttenteTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.MailFilter;
+import com.franciaflex.faxtomail.persistence.entities.MailFilterTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.MailFolder;
+import com.franciaflex.faxtomail.persistence.entities.Priority;
+import com.franciaflex.faxtomail.persistence.entities.PriorityTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.Range;
+import com.franciaflex.faxtomail.persistence.entities.RangeTopiaDao;
+import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
+import com.franciaflex.faxtomail.services.service.imports.ClientImportModel;
+import com.franciaflex.faxtomail.services.service.imports.DemandTypeImportModel;
+import com.franciaflex.faxtomail.services.service.imports.EmailAccountImportModel;
+import com.franciaflex.faxtomail.services.service.imports.EmailFilterImportModel;
+import com.franciaflex.faxtomail.services.service.imports.EtatAttenteImportModel;
+import com.franciaflex.faxtomail.services.service.imports.PriorityImportModel;
+import com.franciaflex.faxtomail.services.service.imports.RangeImportModel;
+
+/**
+ * @author kmorin - kmorin(a)codelutin.com
+ */
+public class ReferentielServiceImpl extends FaxToMailServiceSupport implements ReferentielService {
+
+ @Override
+ public List<DemandType> getAllDemandType() {
+ DemandTypeTopiaDao dao = getPersistenceContext().getDemandTypeDao();
+ return dao.findAll();
+ }
+
+ @Override
+ public List<Priority> getAllPriority() {
+ PriorityTopiaDao dao = getPersistenceContext().getPriorityDao();
+ return dao.findAll();
+ }
+
+ @Override
+ public List<Range> getAllRange() {
+ RangeTopiaDao dao = getPersistenceContext().getRangeDao();
+ return dao.findAll();
+ }
+
+ @Override
+ public List<EtatAttente> getAllEtatAttente() {
+ EtatAttenteTopiaDao dao = getPersistenceContext().getEtatAttenteDao();
+ return dao.findAll();
+ }
+
+ @Override
+ public Map<String, Long> getEtatAttentesUsage() {
+ EtatAttenteTopiaDao dao = getPersistenceContext().getEtatAttenteDao();
+ Map<String, Long> result = dao.getEtatAttenteCountByFolder();
+ return result;
+ }
+
+ @Override
+ public List<Client> getAllClients() {
+ ClientTopiaDao dao = getPersistenceContext().getClientDao();
+ return dao.findAll();
+ }
+
+ @Override
+ public List<Client> importClients(InputStream inputStream) {
+ List<Client> result = new ArrayList<>();
+ ClientTopiaDao dao = getPersistenceContext().getClientDao();
+
+ ClientImportModel clientImportModel = new ClientImportModel(';');
+ Binder<Client, Client> clientBinder = BinderFactory.newBinder(Client.class);
+ Import<Client> importer = null;
+ try {
+ importer = Import.newImport(clientImportModel, new InputStreamReader(inputStream, getApplicationConfig().getImportFileEncoding()));
+ for (Client client : importer) {
+
+ Client current = dao.forCodeEquals(client.getCode()).addEquals(Client.PROPERTY_BRAND, client.getBrand()).findAnyOrNull();
+ if (current == null) {
+ current = new ClientImpl();
+ }
+
+ clientBinder.copyExcluding(client, current,
+ Client.PROPERTY_TOPIA_ID,
+ Client.PROPERTY_TOPIA_CREATE_DATE,
+ Client.PROPERTY_TOPIA_VERSION);
+
+ if (client.isPersisted()) {
+ current = dao.update(current);
+ } else {
+ current = dao.create(current);
+ }
+ result.add(current);
+ }
+ getPersistenceContext().commit();
+
+ } catch (ImportRuntimeException|UnsupportedEncodingException e) {
+ String message;
+ if (e.getCause() != null) {
+ message = e.getCause().getMessage();
+ } else {
+ message = e.getMessage();
+ }
+ throw new ApplicationTechnicalException(message, e);
+ } finally {
+ IOUtils.closeQuietly(importer);
+ IOUtils.closeQuietly(inputStream);
+ }
+ return result;
+ }
+
+ @Override
+ public List<EmailAccount> importEmailAccounts(InputStream inputStream) {
+ List<EmailAccount> result = new ArrayList<>();
+ EmailAccountTopiaDao dao = getPersistenceContext().getEmailAccountDao();
+
+ EmailAccountImportModel emailAccountImportModel = new EmailAccountImportModel(';');
+ try (Import<EmailAccount> importer = Import.newImport(emailAccountImportModel, new InputStreamReader(inputStream, getApplicationConfig().getImportFileEncoding()))) {
+ for (EmailAccount emailAccount : importer) {
+ result.add(dao.create(emailAccount));
+ }
+ getPersistenceContext().commit();
+ } catch (ImportRuntimeException|UnsupportedEncodingException e) {
+ String message;
+ if (e.getCause() != null) {
+ message = e.getCause().getMessage();
+ } else {
+ message = e.getMessage();
+ }
+ throw new ApplicationTechnicalException(message, e);
+
+ } finally {
+ IOUtils.closeQuietly(inputStream);
+ }
+ return result;
+ }
+
+ @Override
+ public List<MailFilter> importEmailFilters(InputStream inputStream, Map<String, MailFolder> foldersByName) {
+ List<MailFilter> result = new ArrayList<>();
+ MailFilterTopiaDao dao = getPersistenceContext().getMailFilterDao();
+
+ EmailFilterImportModel emailFilterImportModel = new EmailFilterImportModel(';', foldersByName);
+ try (Import<MailFilter> importer = Import.newImport(emailFilterImportModel, new InputStreamReader(inputStream, getApplicationConfig().getImportFileEncoding()))) {
+ for (MailFilter emailFilter : importer) {
+ result.add(dao.create(emailFilter));
+ }
+ getPersistenceContext().commit();
+
+ } catch (ImportRuntimeException|UnsupportedEncodingException e) {
+ String message;
+ if (e.getCause() != null) {
+ message = e.getCause().getMessage();
+ } else {
+ message = e.getMessage();
+ }
+ throw new ApplicationTechnicalException(message, e);
+
+ } finally {
+ IOUtils.closeQuietly(inputStream);
+ }
+ return result;
+ }
+
+ @Override
+ public List<EtatAttente> importEtatAttentes(InputStream inputStream) {
+
+ List<EtatAttente> result = new ArrayList<>();
+ EtatAttenteTopiaDao etatAttenteTopiaDao = getPersistenceContext().getEtatAttenteDao();
+
+ EtatAttenteImportModel importModel = new EtatAttenteImportModel(';');
+ try (Import<EtatAttente> importer = Import.newImport(importModel, new InputStreamReader(inputStream, getApplicationConfig().getImportFileEncoding()))) {
+ for (EtatAttente etatAttente : importer) {
+
+ EtatAttente currentEtatAttente = etatAttenteTopiaDao.forLabelEquals(etatAttente.getLabel()).findAnyOrNull();
+ if (currentEtatAttente == null) {
+ currentEtatAttente = etatAttenteTopiaDao.create(etatAttente);
+ }
+ // else maybe update current ?
+
+ result.add(currentEtatAttente);
+ }
+ getPersistenceContext().commit();
+
+ } catch (ImportRuntimeException|UnsupportedEncodingException e) {
+ String message;
+ if (e.getCause() != null) {
+ message = e.getCause().getMessage();
+ } else {
+ message = e.getMessage();
+ }
+ throw new ApplicationTechnicalException(message, e);
+
+ } finally {
+ IOUtils.closeQuietly(inputStream);
+ }
+
+ return result;
+ }
+
+ @Override
+ public List<Priority> importPriorities(InputStream inputStream) {
+ List<Priority> result = new ArrayList<>();
+ PriorityTopiaDao priorityTopiaDao = getPersistenceContext().getPriorityDao();
+
+ PriorityImportModel importModel = new PriorityImportModel(';');
+ try (Import<Priority> importer = Import.newImport(importModel, new InputStreamReader(inputStream, getApplicationConfig().getImportFileEncoding()))) {
+ for (Priority priority : importer) {
+
+ Priority currentPriority = priorityTopiaDao.forLabelEquals(priority.getLabel()).findAnyOrNull();
+ if (currentPriority == null) {
+ currentPriority = priorityTopiaDao.create(priority);
+ }
+ // else maybe update current ?
+
+ result.add(currentPriority);
+ }
+ getPersistenceContext().commit();
+
+ } catch (ImportRuntimeException|UnsupportedEncodingException e) {
+ String message;
+ if (e.getCause() != null) {
+ message = e.getCause().getMessage();
+ } else {
+ message = e.getMessage();
+ }
+ throw new ApplicationTechnicalException(message, e);
+
+ } finally {
+ IOUtils.closeQuietly(inputStream);
+ }
+
+ return result;
+ }
+
+ @Override
+ public List<Range> importRanges(InputStream inputStream) {
+ List<Range> result = new ArrayList<>();
+ RangeTopiaDao rangeTopiaDao = getPersistenceContext().getRangeDao();
+
+ RangeImportModel importModel = new RangeImportModel(';');
+ try (Import<Range> importer = Import.newImport(importModel, new InputStreamReader(inputStream, getApplicationConfig().getImportFileEncoding()))) {
+ for (Range range : importer) {
+
+ Range currentRange = rangeTopiaDao.forLabelEquals(range.getLabel()).findAnyOrNull();
+ if (currentRange == null) {
+ currentRange = rangeTopiaDao.create(range);
+ }
+ // else maybe update current ?
+
+ result.add(currentRange);
+ }
+ getPersistenceContext().commit();
+
+ } catch (ImportRuntimeException|UnsupportedEncodingException e) {
+ String message;
+ if (e.getCause() != null) {
+ message = e.getCause().getMessage();
+ } else {
+ message = e.getMessage();
+ }
+ throw new ApplicationTechnicalException(message, e);
+
+ } finally {
+ IOUtils.closeQuietly(inputStream);
+ }
+ return result;
+ }
+
+ @Override
+ public List<DemandType> importDemandTypes(InputStream inputStream) {
+ List<DemandType> result = new ArrayList<>();
+ DemandTypeTopiaDao demandTypeTopiaDao = getPersistenceContext().getDemandTypeDao();
+
+ DemandTypeImportModel importModel = new DemandTypeImportModel(';');
+ try (Import<DemandType> importer = Import.newImport(importModel, new InputStreamReader(inputStream, getApplicationConfig().getImportFileEncoding()))) {
+ for (DemandType demandType : importer) {
+
+ DemandType currentDemandType = demandTypeTopiaDao.forLabelEquals(demandType.getLabel()).findAnyOrNull();
+ if (currentDemandType == null) {
+ currentDemandType = demandTypeTopiaDao.create(demandType);
+ }
+ // else maybe update current ?
+
+ result.add(currentDemandType);
+ }
+ getPersistenceContext().commit();
+
+ } catch (ImportRuntimeException|UnsupportedEncodingException e) {
+ String message;
+ if (e.getCause() != null) {
+ message = e.getCause().getMessage();
+ } else {
+ message = e.getMessage();
+ }
+ throw new ApplicationTechnicalException(message, e);
+
+ } finally {
+ IOUtils.closeQuietly(inputStream);
+ }
+ return result;
+ }
+}
Property changes on: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ReferentielServiceImpl.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Deleted: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/UserService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/UserService.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/UserService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -1,83 +0,0 @@
-package com.franciaflex.faxtomail.services.service;
-
-/*
- * #%L
- * FaxToMail :: Service
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2014 Franciaflex, Code Lutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/gpl-3.0.html>.
- * #L%
- */
-
-import java.util.List;
-
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroup;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroupTopiaDao;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserTopiaDao;
-import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
-
-/**
- * @author kmorin - kmorin(a)codelutin.com
- */
-public class UserService extends FaxToMailServiceSupport {
-
- /**
- * Retourne le nombre d'utilisateur en base.
- *
- * @return user count
- */
- public long getActiveUserCount() {
- FaxToMailUserTopiaDao faxtomailUserDao = getPersistenceContext().getFaxToMailUserDao();
- long result = faxtomailUserDao.forHiddenEquals(false).count();
- return result;
- }
-
- /**
- * Retourne le nombre de groupe en base.
- *
- * @return group count
- */
- public long getActiveGroupCount() {
- FaxToMailUserGroupTopiaDao faxtomailUserGroupDao = getPersistenceContext().getFaxToMailUserGroupDao();
- long result = faxtomailUserGroupDao.forHiddenEquals(false).count();
- return result;
- }
-
- public List<FaxToMailUser> getAllActiveUsers() {
- FaxToMailUserTopiaDao dao = getPersistenceContext().getFaxToMailUserDao();
- return dao.forHiddenEquals(false).setOrderByArguments(FaxToMailUser.PROPERTY_FIRST_NAME, FaxToMailUser.PROPERTY_LAST_NAME).findAll();
- }
-
- public FaxToMailUser getUserByLogin(String login) {
- FaxToMailUserTopiaDao dao = getPersistenceContext().getFaxToMailUserDao();
- FaxToMailUser user = dao.forLoginEquals(login).findUnique();
- return user;
- }
-
- public List<FaxToMailUserGroup> getAllActiveUserGroups() {
- FaxToMailUserGroupTopiaDao dao = getPersistenceContext().getFaxToMailUserGroupDao();
- return dao.forHiddenEquals(false).setOrderByArguments(FaxToMailUserGroup.PROPERTY_COMPLETE_NAME).findAll();
- }
-
- public FaxToMailUser getUser(String topiaId) {
- FaxToMailUserTopiaDao dao = getPersistenceContext().getFaxToMailUserDao();
- FaxToMailUser user = dao.forTopiaIdEquals(topiaId).findUnique();
- return user;
- }
-}
Added: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/UserService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/UserService.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/UserService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,24 @@
+package com.franciaflex.faxtomail.services.service;
+
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroup;
+import com.franciaflex.faxtomail.services.FaxToMailService;
+
+import java.util.List;
+
+/**
+ * @author Kevin Morin (Code Lutin)
+ */
+public interface UserService extends FaxToMailService {
+ long getActiveUserCount();
+
+ long getActiveGroupCount();
+
+ List<FaxToMailUser> getAllActiveUsers();
+
+ FaxToMailUser getUserByLogin(String login);
+
+ List<FaxToMailUserGroup> getAllActiveUserGroups();
+
+ FaxToMailUser getUser(String topiaId);
+}
Copied: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/UserServiceImpl.java (from rev 468, trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/UserService.java)
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/UserServiceImpl.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/UserServiceImpl.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,89 @@
+package com.franciaflex.faxtomail.services.service;
+
+/*
+ * #%L
+ * FaxToMail :: Service
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2014 Franciaflex, Code Lutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import java.util.List;
+
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroup;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroupTopiaDao;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserTopiaDao;
+import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
+
+/**
+ * @author kmorin - kmorin(a)codelutin.com
+ */
+public class UserServiceImpl extends FaxToMailServiceSupport implements UserService {
+
+ /**
+ * Retourne le nombre d'utilisateur en base.
+ *
+ * @return user count
+ */
+ @Override
+ public long getActiveUserCount() {
+ FaxToMailUserTopiaDao faxtomailUserDao = getPersistenceContext().getFaxToMailUserDao();
+ long result = faxtomailUserDao.forHiddenEquals(false).count();
+ return result;
+ }
+
+ /**
+ * Retourne le nombre de groupe en base.
+ *
+ * @return group count
+ */
+ @Override
+ public long getActiveGroupCount() {
+ FaxToMailUserGroupTopiaDao faxtomailUserGroupDao = getPersistenceContext().getFaxToMailUserGroupDao();
+ long result = faxtomailUserGroupDao.forHiddenEquals(false).count();
+ return result;
+ }
+
+ @Override
+ public List<FaxToMailUser> getAllActiveUsers() {
+ FaxToMailUserTopiaDao dao = getPersistenceContext().getFaxToMailUserDao();
+ return dao.forHiddenEquals(false).setOrderByArguments(FaxToMailUser.PROPERTY_FIRST_NAME, FaxToMailUser.PROPERTY_LAST_NAME).findAll();
+ }
+
+ @Override
+ public FaxToMailUser getUserByLogin(String login) {
+ FaxToMailUserTopiaDao dao = getPersistenceContext().getFaxToMailUserDao();
+ FaxToMailUser user = dao.forLoginEquals(login).findUnique();
+ return user;
+ }
+
+ @Override
+ public List<FaxToMailUserGroup> getAllActiveUserGroups() {
+ FaxToMailUserGroupTopiaDao dao = getPersistenceContext().getFaxToMailUserGroupDao();
+ return dao.forHiddenEquals(false).setOrderByArguments(FaxToMailUserGroup.PROPERTY_COMPLETE_NAME).findAll();
+ }
+
+ @Override
+ public FaxToMailUser getUser(String topiaId) {
+ FaxToMailUserTopiaDao dao = getPersistenceContext().getFaxToMailUserDao();
+ FaxToMailUser user = dao.forTopiaIdEquals(topiaId).findUnique();
+ return user;
+ }
+}
Property changes on: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/UserServiceImpl.java
___________________________________________________________________
Added: svn:eol-style
+ native
Added: svn:keywords
+ Author Date Id Revision HeadURL
Deleted: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ValidationService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ValidationService.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ValidationService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -1,47 +0,0 @@
-package com.franciaflex.faxtomail.services.service;
-
-/*
- * #%L
- * FaxToMail :: Service
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2014 Franciaflex, Code Lutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/gpl-3.0.html>.
- * #L%
- */
-
-import org.nuiton.validator.NuitonValidator;
-import org.nuiton.validator.NuitonValidatorFactory;
-import org.nuiton.validator.NuitonValidatorResult;
-
-import com.franciaflex.faxtomail.persistence.entities.Email;
-import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
-
-/**
- * To validate some incoming data using nuiton-validators.
- *
- * @author kmorin - morin(a)codelutin.com
- */
-public class ValidationService extends FaxToMailServiceSupport {
-
- public NuitonValidatorResult validateEmail(Email email) {
- NuitonValidator<Email> validator = NuitonValidatorFactory.newValidator(Email.class);
- NuitonValidatorResult result = validator.validate(email);
- return result;
- }
-
-}
Added: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ValidationService.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ValidationService.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ValidationService.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,12 @@
+package com.franciaflex.faxtomail.services.service;
+
+import com.franciaflex.faxtomail.persistence.entities.Email;
+import com.franciaflex.faxtomail.services.FaxToMailService;
+import org.nuiton.validator.NuitonValidatorResult;
+
+/**
+ * @author Kevin Morin (Code Lutin)
+ */
+public interface ValidationService extends FaxToMailService {
+ NuitonValidatorResult validateEmail(Email email);
+}
Copied: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ValidationServiceImpl.java (from rev 468, trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ValidationService.java)
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ValidationServiceImpl.java (rev 0)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ValidationServiceImpl.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -0,0 +1,48 @@
+package com.franciaflex.faxtomail.services.service;
+
+/*
+ * #%L
+ * FaxToMail :: Service
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2014 Franciaflex, Code Lutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/gpl-3.0.html>.
+ * #L%
+ */
+
+import org.nuiton.validator.NuitonValidator;
+import org.nuiton.validator.NuitonValidatorFactory;
+import org.nuiton.validator.NuitonValidatorResult;
+
+import com.franciaflex.faxtomail.persistence.entities.Email;
+import com.franciaflex.faxtomail.services.FaxToMailServiceSupport;
+
+/**
+ * To validate some incoming data using nuiton-validators.
+ *
+ * @author kmorin - morin(a)codelutin.com
+ */
+public class ValidationServiceImpl extends FaxToMailServiceSupport implements ValidationService {
+
+ @Override
+ public NuitonValidatorResult validateEmail(Email email) {
+ NuitonValidator<Email> validator = NuitonValidatorFactory.newValidator(Email.class);
+ NuitonValidatorResult result = validator.validate(email);
+ return result;
+ }
+
+}
Property changes on: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ValidationServiceImpl.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ldap/LdapServiceMock.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ldap/LdapServiceMock.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ldap/LdapServiceMock.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -26,6 +26,7 @@
import java.util.List;
+import com.franciaflex.faxtomail.services.service.LdapServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
@@ -34,14 +35,13 @@
import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserGroupTopiaDao;
import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserImpl;
import com.franciaflex.faxtomail.persistence.entities.FaxToMailUserTopiaDao;
-import com.franciaflex.faxtomail.services.service.LdapService;
/**
* Surcharge les methodes qui utilisent le serveur ldap pour pouvoir fonctionner sans serveur ldap.
*
* @author Eric Chatellier
*/
-public class LdapServiceMock extends LdapService {
+public class LdapServiceMock extends LdapServiceImpl {
protected FaxToMailUser fakeUser;
Modified: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/AbstractFaxToMailServiceTest.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -150,7 +150,7 @@
serviceContext.setPersistenceContext(persistenceContext);
- InitFaxToMailService initFaxToMailService = serviceContext.newService(InitFaxToMailService.class);
+ InitFaxToMailService initFaxToMailService = serviceContext.newService(InitFaxToMailServiceImpl.class);
initFaxToMailService.init();
Modified: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/ClientServiceTest.java
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/ClientServiceTest.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/ClientServiceTest.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -63,7 +63,7 @@
@Test
public void testAddNewClientInTmpTable() {
- ClientService clientService = newService(ClientService.class);
+ ClientService clientService = newService(ClientServiceImpl.class);
NewClientTopiaDao newClientDao = getServiceContext().getPersistenceContext().getNewClientDao();
ClientTopiaDao clientDao = getServiceContext().getPersistenceContext().getClientDao();
Modified: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/EmailServiceTest.java
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/EmailServiceTest.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/EmailServiceTest.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -53,9 +53,9 @@
@Before
public void setUp() throws IOException {
- service = newService(EmailService.class);
- referentielService = newService(ReferentielService.class);
- userService = newService(UserService.class);
+ service = newService(EmailServiceImpl.class);
+ referentielService = newService(ReferentielServiceImpl.class);
+ userService = newService(UserServiceImpl.class);
newService(InitTestData.class).initTestData();
}
Modified: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestData.java
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestData.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/InitTestData.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -83,7 +83,7 @@
if (log.isDebugEnabled()) {
log.debug("Init test data");
}
- ReferentielService referentielService = newService(ReferentielService.class);
+ ReferentielService referentielService = newService(ReferentielServiceImpl.class);
// import etat attentes
List<EtatAttente> etatAttentes = null;
Modified: trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/MailFolderServiceTest.java
===================================================================
--- trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/MailFolderServiceTest.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-service/src/test/java/com/franciaflex/faxtomail/services/service/MailFolderServiceTest.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -46,7 +46,7 @@
@Before
public void setUp() throws IOException {
- service = newService(MailFolderService.class);
+ service = newService(MailFolderServiceImpl.class);
newService(InitTestData.class).initTestData();
}
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -38,6 +38,7 @@
import javax.swing.JFrame;
import javax.swing.JOptionPane;
+import com.franciaflex.faxtomail.services.service.InitFaxToMailServiceImpl;
import jaxx.runtime.swing.editor.bean.BeanDoubleList;
import jaxx.runtime.swing.editor.bean.BeanFilterableComboBox;
import jaxx.runtime.swing.session.BeanDoubleListState;
@@ -68,21 +69,11 @@
import com.franciaflex.faxtomail.FaxToMailConfiguration;
import com.franciaflex.faxtomail.persistence.RessourceClassLoader;
-import com.franciaflex.faxtomail.persistence.entities.Configuration;
import com.franciaflex.faxtomail.persistence.entities.FaxToMailTopiaApplicationContext;
-import com.franciaflex.faxtomail.persistence.entities.FaxToMailTopiaPersistenceContext;
import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
import com.franciaflex.faxtomail.persistence.entities.MailFolder;
-import com.franciaflex.faxtomail.services.DecoratorService;
import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
-import com.franciaflex.faxtomail.services.service.ConfigurationService;
-import com.franciaflex.faxtomail.services.service.EmailService;
import com.franciaflex.faxtomail.services.service.InitFaxToMailService;
-import com.franciaflex.faxtomail.services.service.LdapService;
-import com.franciaflex.faxtomail.services.service.MailFolderService;
-import com.franciaflex.faxtomail.services.service.ReferentielService;
-import com.franciaflex.faxtomail.services.service.UserService;
-import com.franciaflex.faxtomail.services.service.ValidationService;
import com.franciaflex.faxtomail.services.service.ldap.AuthenticationException;
import com.franciaflex.faxtomail.ui.swing.content.MainUI;
import com.franciaflex.faxtomail.ui.swing.content.demande.DemandeUIModel;
@@ -225,7 +216,7 @@
FaxToMailServiceContext serviceContext = newServiceContext();
InitFaxToMailService initExtranetService =
- serviceContext.newService(InitFaxToMailService.class);
+ serviceContext.newService(InitFaxToMailServiceImpl.class);
initExtranetService.init();
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/FaxToMailApplicationContext.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/FaxToMailApplicationContext.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/FaxToMailApplicationContext.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -30,6 +30,7 @@
import javax.servlet.ServletContext;
+import com.franciaflex.faxtomail.services.service.InitFaxToMailServiceImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.LogManager;
@@ -153,7 +154,7 @@
FaxToMailServiceContext serviceContext = newServiceContext(persistenceContext);
InitFaxToMailService initExtranetService =
- serviceContext.newService(InitFaxToMailService.class);
+ serviceContext.newService(InitFaxToMailServiceImpl.class);
initExtranetService.init();
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/FaxToMailInterceptor.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/FaxToMailInterceptor.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/FaxToMailInterceptor.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -29,6 +29,7 @@
import java.util.Map;
import java.util.Set;
+import com.franciaflex.faxtomail.services.service.LdapServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
@@ -143,7 +144,7 @@
protected void populateUser(FaxToMailSession faxToMailSession, FaxToMailServiceContext serviceContext) {
if (StringUtils.isNotBlank(faxToMailSession.getAuthenticatedUserId())) {
- LdapService ldapService = serviceContext.newService(LdapService.class);
+ LdapService ldapService = serviceContext.newService(LdapServiceImpl.class);
// return can be null
FaxToMailUser user = ldapService.getUserBean(faxToMailSession.getAuthenticatedUserId());
faxToMailSession.setAuthenticatedFaxToMailUser(user);
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/action/admin/LdapAction.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/action/admin/LdapAction.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/action/admin/LdapAction.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -24,6 +24,7 @@
* #L%
*/
+import com.franciaflex.faxtomail.services.service.LdapServiceImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
@@ -102,7 +103,7 @@
try {
persistenceContext = applicationContext.newPersistenceContext();
FaxToMailServiceContext serviceContext = applicationContext.newServiceContext(persistenceContext);
- LdapService ldapService2 = serviceContext.newService(LdapService.class);
+ LdapService ldapService2 = serviceContext.newService(LdapServiceImpl.class);
ldapService2.updateLdapData();
} finally {
persistenceContext.close();
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/ClientUpdateJob.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/ClientUpdateJob.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/ClientUpdateJob.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -24,6 +24,7 @@
* #L%
*/
+import com.franciaflex.faxtomail.services.service.ClientServiceImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.DisallowConcurrentExecution;
@@ -59,7 +60,7 @@
log.debug("Running ClientUpdateJob at " + serviceContext.getNow());
}
- ClientService clientService = serviceContext.newService(ClientService.class);
+ ClientService clientService = serviceContext.newService(ClientServiceImpl.class);
clientService.updateNewClients();
if (log.isDebugEnabled()) {
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/EDIManagementJob.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/EDIManagementJob.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/EDIManagementJob.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -29,6 +29,7 @@
import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import com.franciaflex.faxtomail.services.service.EmailService;
+import com.franciaflex.faxtomail.services.service.EmailServiceImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.DisallowConcurrentExecution;
@@ -57,7 +58,7 @@
log.debug("Running EDIManagementJob at " + serviceContext.getNow());
}
- EmailService emailService = serviceContext.newService(EmailService.class);
+ EmailService emailService = serviceContext.newService(EmailServiceImpl.class);
emailService.transmitPendingDemandsToEdi();
if (log.isDebugEnabled()) {
Modified: trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/MailFilterJob.java
===================================================================
--- trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/MailFilterJob.java 2014-08-05 09:25:13 UTC (rev 468)
+++ trunk/faxtomail-ui-web/src/main/java/com/franciaflex/faxtomail/web/job/MailFilterJob.java 2014-08-05 12:11:22 UTC (rev 469)
@@ -25,6 +25,12 @@
*/
import static org.nuiton.i18n.I18n.t;
+
+import com.franciaflex.faxtomail.services.DecoratorServiceImpl;
+import com.franciaflex.faxtomail.services.service.ClientServiceImpl;
+import com.franciaflex.faxtomail.services.service.ConfigurationServiceImpl;
+import com.franciaflex.faxtomail.services.service.EmailServiceImpl;
+import com.franciaflex.faxtomail.services.service.MailFolderServiceImpl;
import gui.ava.html.Html2Image;
import java.io.ByteArrayOutputStream;
@@ -138,11 +144,11 @@
log.debug("Running MailFilterJob at " + serviceContext.getNow());
}
- emailService = serviceContext.newService(EmailService.class);
- mailFolderService = serviceContext.newService(MailFolderService.class);
- configurationService = serviceContext.newService(ConfigurationService.class);
- clientService = serviceContext.newService(ClientService.class);
- decoratorService = serviceContext.newService(DecoratorService.class);
+ emailService = serviceContext.newService(EmailServiceImpl.class);
+ mailFolderService = serviceContext.newService(MailFolderServiceImpl.class);
+ configurationService = serviceContext.newService(ConfigurationServiceImpl.class);
+ clientService = serviceContext.newService(ClientServiceImpl.class);
+ decoratorService = serviceContext.newService(DecoratorServiceImpl.class);
Collection<EmailAccount> emailAccounts = configurationService.getEmailAccounts();
1
0
05 Aug '14
Author: kmorin
Date: 2014-08-05 11:25:13 +0200 (Tue, 05 Aug 2014)
New Revision: 468
Url: http://forge.codelutin.com/projects/faxtomail/repository/revisions/468
Log:
test modif syst?\195?\168me transaction (ca build pas, c'est normal)
Added:
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/Command.java
Modified:
trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/LoadFolderEmailsAction.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandeListUIHandler.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandesUIHandler.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/search/SearchToGroupUIHandler.java
trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/AbstractFaxToMailUIHandler.java
Modified: trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java
===================================================================
--- trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java 2014-08-05 08:22:38 UTC (rev 467)
+++ trunk/faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/FaxToMailServiceContext.java 2014-08-05 09:25:13 UTC (rev 468)
@@ -24,10 +24,19 @@
* #L%
*/
+import java.io.Closeable;
+import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
+import com.franciaflex.faxtomail.persistence.entities.FaxToMailTopiaApplicationContext;
+import com.franciaflex.faxtomail.services.service.ConfigurationService;
+import com.franciaflex.faxtomail.services.service.EmailService;
+import com.franciaflex.faxtomail.services.service.MailFolderService;
+import com.franciaflex.faxtomail.services.service.ReferentielService;
+import com.franciaflex.faxtomail.services.service.UserService;
+import com.franciaflex.faxtomail.services.service.ValidationService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.jaxx.application.ApplicationTechnicalException;
@@ -37,26 +46,35 @@
import com.franciaflex.faxtomail.services.service.LdapService;
import com.franciaflex.faxtomail.services.service.ldap.LdapServiceMock;
-public class FaxToMailServiceContext {
+public class FaxToMailServiceContext implements Closeable {
private static final Log log = LogFactory.getLog(FaxToMailServiceContext.class);
protected FaxToMailConfiguration applicationConfig;
+ protected FaxToMailTopiaApplicationContext topiaApplicationContext;
+
protected FaxToMailTopiaPersistenceContext persistenceContext;
+ public FaxToMailServiceContext(FaxToMailTopiaApplicationContext topiaApplicationContext) {
+ this.topiaApplicationContext = topiaApplicationContext;
+ }
+
public FaxToMailConfiguration getApplicationConfig() {
return applicationConfig;
}
- public void setPersistenceContext(FaxToMailTopiaPersistenceContext persistenceContext) {
- this.persistenceContext = persistenceContext;
- }
-
public FaxToMailTopiaPersistenceContext getPersistenceContext() {
+ if (persistenceContext == null) {
+ persistenceContext = topiaApplicationContext.newPersistenceContext();
+ }
return persistenceContext;
}
+ public FaxToMailTopiaApplicationContext getTopiaApplicationContext() {
+ return topiaApplicationContext;
+ }
+
public void setApplicationConfig(FaxToMailConfiguration applicationConfig) {
this.applicationConfig = applicationConfig;
}
@@ -88,4 +106,43 @@
Date now = new Date();
return now;
}
+
+ public DecoratorService getDecoratorService() {
+ return newService(DecoratorService.class);
+ }
+
+ public ValidationService getValidationService() {
+ return newService(ValidationService.class);
+ }
+
+ public MailFolderService getMailFolderService() {
+ return newService(MailFolderService.class);
+ }
+
+ public UserService getUserService() {
+ return newService(UserService.class);
+ }
+
+ public LdapService getLdapService() {
+ return newService(LdapService.class);
+ }
+
+ public EmailService getEmailService() {
+ return newService(EmailService.class);
+ }
+
+ public ReferentielService getReferentielService() {
+ return newService(ReferentielService.class);
+ }
+
+ public ConfigurationService getConfigurationService() {
+ return newService(ConfigurationService.class);
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (persistenceContext != null) {
+ persistenceContext.close();
+ }
+ }
}
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java 2014-08-05 08:22:38 UTC (rev 467)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/FaxToMailUIContext.java 2014-08-05 09:25:13 UTC (rev 468)
@@ -45,6 +45,7 @@
import jaxx.runtime.swing.session.State;
import jaxx.runtime.swing.session.SwingSession;
+import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -133,11 +134,6 @@
protected FaxToMailTopiaApplicationContext topiaApplicationContext;
/**
- * Service context used by any service.
- */
- protected final FaxToMailServiceContext serviceContext;
-
- /**
* Swing session used to save ui states.
*/
protected final SwingSession swingSession;
@@ -225,12 +221,9 @@
protected FaxToMailUIContext(FaxToMailConfiguration config) {
this.config = config;
this.resourceLoader = new RessourceClassLoader(Thread.currentThread().getContextClassLoader());
- this.serviceContext = new FaxToMailServiceContext();
topiaApplicationContext = new FaxToMailTopiaApplicationContext(config.getTopiaProperties());
- FaxToMailTopiaPersistenceContext persistenceContext = topiaApplicationContext.newPersistenceContext();
- serviceContext.setPersistenceContext(persistenceContext);
- serviceContext.setApplicationConfig(config);
+ FaxToMailServiceContext serviceContext = newServiceContext();
InitFaxToMailService initExtranetService =
serviceContext.newService(InitFaxToMailService.class);
@@ -287,20 +280,6 @@
faxToMailActionEngine = new ApplicationActionEngine(faxToMailActionFactory);
}
- /**
- * Ferme la transaction actuelle et en ouvre une nouvelle pour casser le problème d'isolation
- * des données. Cela permet d'ouvrir une nouvelle transaction qui verra les modifications faites
- * par le serveur hors de la transaction précédente.
- */
- public void createNewTransaction() {
- // ne pas faire le close deux fois, ca lance une exception
- if (!serviceContext.getPersistenceContext().isClosed()) {
- serviceContext.getPersistenceContext().close();
- }
- FaxToMailTopiaPersistenceContext persistenceContext = topiaApplicationContext.newPersistenceContext();
- serviceContext.setPersistenceContext(persistenceContext);
- }
-
@Override
public ApplicationConfiguration getConfiguration() {
return config;
@@ -384,43 +363,50 @@
String principal = getLoggedInUsername();
// l'authentification par defaut se fait par trigramme
+ final FaxToMailServiceContext serviceContext = newServiceContext();
try {
- FaxToMailUser currentUser = getLdapService().getUserFromPrincipal(principal);
- if (log.isInfoEnabled()) {
- log.info("Connected as " + currentUser.getFirstName() + " " + currentUser.getLastName());
+ try {
+ FaxToMailUser currentUser = serviceContext.getLdapService().getUserFromPrincipal(principal);
+ if (log.isInfoEnabled()) {
+ log.info("Connected as " + currentUser.getFirstName() + " " + currentUser.getLastName());
+ }
+ setCurrentUser(currentUser);
+ } catch (AuthenticationException ex) {
+ if (log.isWarnEnabled()) {
+ log.warn("Can't anthenticate user", ex);
+ }
+
}
- setCurrentUser(currentUser);
- } catch (AuthenticationException ex) {
- if (log.isWarnEnabled()) {
- log.warn("Can't anthenticate user", ex);
- }
- }
- // si ca n'a pas fonctionné, on retente par login mot de passe
- while (getCurrentUser() == null) {
- JXLoginPane pane = new JXLoginPane();
- pane.setLoginService(new LoginService() {
- @Override
- public boolean authenticate(String name, char[] password, String server) throws Exception {
- boolean result = false;
- try {
- FaxToMailUser user = getLdapService().authenticateUser(name, String.valueOf(password));
- setCurrentUser(user);
- result = true;
- } catch (AuthenticationException ex) {
- if (log.isWarnEnabled()) {
- log.warn("Can't anthenticate user", ex);
+ // si ca n'a pas fonctionné, on retente par login mot de passe
+ while (getCurrentUser() == null) {
+ JXLoginPane pane = new JXLoginPane();
+ pane.setLoginService(new LoginService() {
+ @Override
+ public boolean authenticate(String name, char[] password, String server) throws Exception {
+ boolean result = false;
+ try {
+ FaxToMailUser user = serviceContext.getLdapService().authenticateUser(name, String.valueOf(password));
+ setCurrentUser(user);
+ result = true;
+ } catch (AuthenticationException ex) {
+ if (log.isWarnEnabled()) {
+ log.warn("Can't anthenticate user", ex);
+ }
}
+ return result;
}
- return result;
- }
- });
+ });
- // show login dialog
- Status loginStatus = JXLoginPane.showLoginDialog(null, pane);
- if (loginStatus == Status.CANCELLED) {
- throw new ApplicationTechnicalException("Authentication canceled");
+ // show login dialog
+ Status loginStatus = JXLoginPane.showLoginDialog(null, pane);
+ if (loginStatus == Status.CANCELLED) {
+ throw new ApplicationTechnicalException("Authentication canceled");
+ }
}
+
+ } finally {
+ IOUtils.closeQuietly(serviceContext);
}
}
@@ -494,38 +480,13 @@
//-- Service methods --//
//------------------------------------------------------------------------//
- public DecoratorService getDecoratorService() {
- return serviceContext.newService(DecoratorService.class);
+ public FaxToMailServiceContext newServiceContext() {
+ FaxToMailServiceContext serviceContext = new FaxToMailServiceContext();
+ serviceContext.setTopiaApplicationContext(topiaApplicationContext);
+ serviceContext.setApplicationConfig(config);
+ return serviceContext;
}
- public ValidationService getValidationService() {
- return serviceContext.newService(ValidationService.class);
- }
-
- public MailFolderService getMailFolderService() {
- return serviceContext.newService(MailFolderService.class);
- }
-
- public UserService getUserService() {
- return serviceContext.newService(UserService.class);
- }
-
- public LdapService getLdapService() {
- return serviceContext.newService(LdapService.class);
- }
-
- public EmailService getEmailService() {
- return serviceContext.newService(EmailService.class);
- }
-
- public ReferentielService getReferentielService() {
- return serviceContext.newService(ReferentielService.class);
- }
-
- public ConfigurationService getConfigurationService() {
- return serviceContext.newService(ConfigurationService.class);
- }
-
//------------------------------------------------------------------------//
//-- DataContext methods --//
//------------------------------------------------------------------------//
@@ -671,11 +632,6 @@
firePropertyChange(PROPERTY_LOCALE, null, locale);
}
- public Configuration getFaxToMailConfiguration() {
- // make sure configuration is loaded by current service context
- return getConfigurationService().getConfiguration();
- }
-
public FaxToMailUser getCurrentUser() {
return currentUser;
}
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/LoadFolderEmailsAction.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/LoadFolderEmailsAction.java 2014-08-05 08:22:38 UTC (rev 467)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/actions/LoadFolderEmailsAction.java 2014-08-05 09:25:13 UTC (rev 468)
@@ -127,4 +127,5 @@
super.postFailedAction(error);
getUI().getNavigationTree().setEnabled(true);
}
+
}
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandeListUIHandler.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandeListUIHandler.java 2014-08-05 08:22:38 UTC (rev 467)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandeListUIHandler.java 2014-08-05 09:25:13 UTC (rev 468)
@@ -268,9 +268,9 @@
navigationTree.setEnabled(false);
MailFolder folder = folderNode.getMailFolder();
- // open new transaction for current folder
- getContext().createNewTransaction();
- folder = getContext().getMailFolderService().getMailFolder(folder.getTopiaId()); // Fix lazy exception
+// // open new transaction for current folder
+// getContext().createNewTransaction();
+// folder = getContext().getMailFolderService().getMailFolder(folder.getTopiaId()); // Fix lazy exception
getModel().setSelectedFolder(folder);
getContext().setCurrentMailFolder(folder);
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandesUIHandler.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandesUIHandler.java 2014-08-05 08:22:38 UTC (rev 467)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/demande/DemandesUIHandler.java 2014-08-05 09:25:13 UTC (rev 468)
@@ -71,6 +71,7 @@
private static final Log log = LogFactory.getLog(DemandesUIHandler.class);
protected DelegateTabContainerHandler delegateTabHandler;
+ protected Configuration config;
@Override
public void beforeInit(DemandesUI ui) {
@@ -82,6 +83,8 @@
DemandesUIModel model = new DemandesUIModel();
+ config = getContext().newServiceContext().getConfigurationService().getConfiguration();
+
this.ui.setContextValue(model);
}
@@ -146,7 +149,6 @@
}
protected boolean isActionEnabled(DemandeUIModel model, MailAction action) {
- Configuration config = getContext().getFaxToMailConfiguration();
EtatAttente etatAttente = model.getEtatAttente();
boolean valid = model.isValid();
@@ -165,6 +167,7 @@
boolean editable = model.isEditable();
boolean archived = model.getArchiveDate() != null;
+
boolean transmitEnabled = editable && isActionEnabled(model, MailAction.TRANSMIT);
getModel().setTransmitEnabled(transmitEnabled);
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/search/SearchToGroupUIHandler.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/search/SearchToGroupUIHandler.java 2014-08-05 08:22:38 UTC (rev 467)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/content/search/SearchToGroupUIHandler.java 2014-08-05 09:25:13 UTC (rev 468)
@@ -28,6 +28,7 @@
import com.franciaflex.faxtomail.persistence.entities.EmailFilter;
import com.franciaflex.faxtomail.persistence.entities.FaxToMailUser;
import com.franciaflex.faxtomail.persistence.entities.MailField;
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
import com.franciaflex.faxtomail.services.service.ReferentielService;
import com.franciaflex.faxtomail.ui.swing.actions.GroupAction;
import com.franciaflex.faxtomail.ui.swing.actions.SearchAction;
@@ -36,6 +37,7 @@
import com.franciaflex.faxtomail.ui.swing.util.AbstractFaxToMailDemandListHandler;
import com.franciaflex.faxtomail.ui.swing.util.Cancelable;
+import com.franciaflex.faxtomail.ui.swing.util.Command;
import jaxx.runtime.validator.swing.SwingValidator;
import org.apache.commons.logging.Log;
@@ -111,128 +113,137 @@
public void afterInit(SearchToGroupUI ui) {
initUI(ui);
- ReferentielService referentielService = getContext().getReferentielService();
+ FaxToMailServiceContext serviceContext = getContext().newServiceContext();
+ Command command = new Command(serviceContext) {
+ @Override
+ protected void doAction() {
- List<FaxToMailUser> users = getContext().getUserService().getAllActiveUsers();
- SearchUIModel model = getModel();
- initBeanFilterableComboBox(ui.getTakenByComboBox(),
- users,
- model.getTakenBy());
- initBeanFilterableComboBox(ui.getModifiedByComboBox(),
- users,
- model.getModifiedBy());
- initBeanFilterableComboBox(ui.getArchivedByComboBox(),
- users,
- model.getArchivedBy());
- initBeanFilterableComboBox(ui.getTransferByComboBox(),
- users,
- model.getTransferBy());
- initBeanFilterableComboBox(ui.getPrintedByComboBox(),
- users,
- model.getPrintingBy());
- initBeanFilterableComboBox(ui.getRepliedByComboBox(),
- users,
- model.getReplyBy());
+ SearchToGroupUI ui = getUI();
+ ReferentielService referentielService = serviceContext.getReferentielService();
- initCheckBoxComboBox(ui.getDocTypeComboBox(),
- referentielService.getAllDemandType(),
- model.getDemandType(),
- EmailFilter.PROPERTY_DEMAND_TYPE,
- true);
- initCheckBoxComboBox(ui.getPriorityComboBox(),
- referentielService.getAllPriority(),
- model.getPriority(),
- EmailFilter.PROPERTY_PRIORITY,
- true);
- initCheckBoxComboBox(ui.getEtatAttenteComboBox(),
- referentielService.getAllEtatAttente(),
- model.getEtatAttente(),
- EmailFilter.PROPERTY_ETAT_ATTENTE,
- true);
- initCheckBoxComboBox(ui.getStatusComboBox(),
- Arrays.asList(DemandStatus.values()),
- model.getDemandStatus(),
- EmailFilter.PROPERTY_DEMAND_STATUS,
- false);
- initCheckBoxComboBox(ui.getGammeComboBox(),
- referentielService.getAllRange(),
- model.getGamme(),
- EmailFilter.PROPERTY_GAMME,
- false);
+ List<FaxToMailUser> users = serviceContext.getUserService().getAllActiveUsers();
+ SearchUIModel model = getModel();
+ initBeanFilterableComboBox(ui.getTakenByComboBox(),
+ users,
+ model.getTakenBy());
+ initBeanFilterableComboBox(ui.getModifiedByComboBox(),
+ users,
+ model.getModifiedBy());
+ initBeanFilterableComboBox(ui.getArchivedByComboBox(),
+ users,
+ model.getArchivedBy());
+ initBeanFilterableComboBox(ui.getTransferByComboBox(),
+ users,
+ model.getTransferBy());
+ initBeanFilterableComboBox(ui.getPrintedByComboBox(),
+ users,
+ model.getPrintingBy());
+ initBeanFilterableComboBox(ui.getRepliedByComboBox(),
+ users,
+ model.getReplyBy());
- final JXTable dataTable = getUI().getDataTable();
- dataTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ initCheckBoxComboBox(ui.getDocTypeComboBox(),
+ referentielService.getAllDemandType(),
+ model.getDemandType(),
+ EmailFilter.PROPERTY_DEMAND_TYPE,
+ true);
+ initCheckBoxComboBox(ui.getPriorityComboBox(),
+ referentielService.getAllPriority(),
+ model.getPriority(),
+ EmailFilter.PROPERTY_PRIORITY,
+ true);
+ initCheckBoxComboBox(ui.getEtatAttenteComboBox(),
+ referentielService.getAllEtatAttente(),
+ model.getEtatAttente(),
+ EmailFilter.PROPERTY_ETAT_ATTENTE,
+ true);
+ initCheckBoxComboBox(ui.getStatusComboBox(),
+ Arrays.asList(DemandStatus.values()),
+ model.getDemandStatus(),
+ EmailFilter.PROPERTY_DEMAND_STATUS,
+ false);
+ initCheckBoxComboBox(ui.getGammeComboBox(),
+ referentielService.getAllRange(),
+ model.getGamme(),
+ EmailFilter.PROPERTY_GAMME,
+ false);
- initDemandeTable(dataTable, true);
+ final JXTable dataTable = getUI().getDataTable();
+ dataTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
- model.addPropertyChangeListener(SearchUIModel.PROPERTY_RESULTS, new PropertyChangeListener() {
- @Override
- public void propertyChange(PropertyChangeEvent evt) {
- List<DemandeUIModel> emails = (List<DemandeUIModel>) evt.getNewValue();
- AbstractApplicationTableModel<DemandeUIModel> dataTableModel = (AbstractApplicationTableModel<DemandeUIModel>) dataTable.getModel();
- dataTableModel.setRows(emails);
- showInformationMessage(t("faxtomail.search.resultNb", emails.size()));
+ initDemandeTable(dataTable, true);
- DemandeUIModel currentEmail = getContext().getCurrentEmail();
- if (currentEmail != null) {
- int row = dataTableModel.getRowIndex(currentEmail);
- if (row > 0) {
- dataTable.setRowSelectionInterval(row, row);
+ model.addPropertyChangeListener(SearchUIModel.PROPERTY_RESULTS, new PropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+ List<DemandeUIModel> emails = (List<DemandeUIModel>) evt.getNewValue();
+ AbstractApplicationTableModel<DemandeUIModel> dataTableModel = (AbstractApplicationTableModel<DemandeUIModel>) dataTable.getModel();
+ dataTableModel.setRows(emails);
+ showInformationMessage(t("faxtomail.search.resultNb", emails.size()));
+
+ DemandeUIModel currentEmail = getContext().getCurrentEmail();
+ if (currentEmail != null) {
+ int row = dataTableModel.getRowIndex(currentEmail);
+ if (row > 0) {
+ dataTable.setRowSelectionInterval(row, row);
+ }
}
}
- }
- });
+ });
- if (getContext().getSearch() != null) {
- try {
- SearchToGroupAction searchAction = getContext().getActionFactory().createLogicAction(this, SearchToGroupAction.class);
- searchAction.doAction();
+ if (getContext().getSearch() != null) {
+ try {
+ SearchToGroupAction searchAction = getContext().getActionFactory().createLogicAction(SearchToGroupUIHandler.this, SearchToGroupAction.class);
+ searchAction.doAction();
- } catch (Exception e) {
- if (log.isErrorEnabled()) {
- log.error("error while searching", e);
+ } catch (Exception e) {
+ if (log.isErrorEnabled()) {
+ log.error("error while searching", e);
+ }
+ getContext().getErrorHelper().showErrorDialog(t("faxtomail.search.action.error"));
}
- getContext().getErrorHelper().showErrorDialog(t("faxtomail.search.action.error"));
}
- }
- dataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
- @Override
- public void valueChanged(ListSelectionEvent e) {
- if (!e.getValueIsAdjusting()) {
- ListSelectionModel selectionModel = (ListSelectionModel) e.getSource();
- SearchUIModel model = getModel();
- int selectedIndex = selectionModel.getLeadSelectionIndex();
+ dataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
+ @Override
+ public void valueChanged(ListSelectionEvent e) {
+ if (!e.getValueIsAdjusting()) {
+ ListSelectionModel selectionModel = (ListSelectionModel) e.getSource();
+ SearchUIModel model = getModel();
+ int selectedIndex = selectionModel.getLeadSelectionIndex();
+ AbstractApplicationTableModel<DemandeUIModel> dataTableModel = (AbstractApplicationTableModel<DemandeUIModel>) dataTable.getModel();
+ DemandeUIModel selectedModel = selectedIndex < 0 ? null : dataTableModel.getEntry(selectedIndex);
+ model.setGroupEnabled(!selectionModel.isSelectionEmpty() && isDemandSelectable(selectedModel));
+ }
+ }
+ });
+
+ HighlightPredicate rowAlreadyInGroupPredicate = new HighlightPredicate() {
+ @Override
+ public boolean isHighlighted(Component renderer, ComponentAdapter adapter) {
+ int viewRow = adapter.row;
+ int modelRow = adapter.convertRowIndexToModel(viewRow);
AbstractApplicationTableModel<DemandeUIModel> dataTableModel = (AbstractApplicationTableModel<DemandeUIModel>) dataTable.getModel();
- DemandeUIModel selectedModel = selectedIndex < 0 ? null : dataTableModel.getEntry(selectedIndex);
- model.setGroupEnabled(!selectionModel.isSelectionEmpty() && isDemandSelectable(selectedModel));
+ DemandeUIModel row = dataTableModel.getEntry(modelRow);
+ return !isDemandSelectable(row);
}
- }
- });
+ };
+ dataTable.addHighlighter(new ColorHighlighter(rowAlreadyInGroupPredicate, null, Color.GRAY, Color.GRAY, Color.WHITE));
- HighlightPredicate rowAlreadyInGroupPredicate = new HighlightPredicate() {
- @Override
- public boolean isHighlighted(Component renderer, ComponentAdapter adapter) {
- int viewRow = adapter.row;
- int modelRow = adapter.convertRowIndexToModel(viewRow);
- AbstractApplicationTableModel<DemandeUIModel> dataTableModel = (AbstractApplicationTableModel<DemandeUIModel>) dataTable.getModel();
- DemandeUIModel row = dataTableModel.getEntry(modelRow);
- return !isDemandSelectable(row);
+ // int combo box for result per page
+ ui.getResultPerPageCombo().setModel(new DefaultComboBoxModel<Integer>(new Integer[] {10, 20, 30, 40, 50}));
+ int resultPerPage = getConfig().getResultPerPage();
+ ui.getModel().setResultPerPage(resultPerPage);
+ ui.getResultPerPageCombo().setSelectedItem(resultPerPage);
+ ui.getResultPerPageCombo().addItemListener(new ItemListener() {
+ @Override
+ public void itemStateChanged(ItemEvent e) {
+ updateResultPerPage(e);
+ }
+ });
}
};
- dataTable.addHighlighter(new ColorHighlighter(rowAlreadyInGroupPredicate, null, Color.GRAY, Color.GRAY, Color.WHITE));
-
- // int combo box for result per page
- ui.getResultPerPageCombo().setModel(new DefaultComboBoxModel<Integer>(new Integer[] {10, 20, 30, 40, 50}));
- int resultPerPage = getConfig().getResultPerPage();
- ui.getModel().setResultPerPage(resultPerPage);
- ui.getResultPerPageCombo().setSelectedItem(resultPerPage);
- ui.getResultPerPageCombo().addItemListener(new ItemListener() {
- @Override
- public void itemStateChanged(ItemEvent e) {
- updateResultPerPage(e);
- }
- });
+ command.execute();
}
public void searchDemandes() {
Modified: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/AbstractFaxToMailUIHandler.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/AbstractFaxToMailUIHandler.java 2014-08-05 08:22:38 UTC (rev 467)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/AbstractFaxToMailUIHandler.java 2014-08-05 09:25:13 UTC (rev 468)
@@ -112,12 +112,7 @@
public Component getTopestUI() {
Component result;
ApplicationActionUI actionUI = getContext().getActionUI();
-// if (actionUI.isVisible()) {
- result = actionUI;
-// } else {
-// result = getContext().getMainUI();
-// }
- return result;
+ return actionUI;
}
public void clearValidators() {
@@ -130,8 +125,7 @@
@Override
public <O> Decorator<O> getDecorator(Class<O> type, String name) {
- DecoratorService decoratorService =
- getContext().getDecoratorService();
+ DecoratorService decoratorService = getContext().newServiceContext().getDecoratorService();
Preconditions.checkNotNull(type);
Added: trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/Command.java
===================================================================
--- trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/Command.java (rev 0)
+++ trunk/faxtomail-ui-swing/src/main/java/com/franciaflex/faxtomail/ui/swing/util/Command.java 2014-08-05 09:25:13 UTC (rev 468)
@@ -0,0 +1,29 @@
+package com.franciaflex.faxtomail.ui.swing.util;
+
+import com.franciaflex.faxtomail.services.FaxToMailServiceContext;
+import org.apache.commons.io.IOUtils;
+
+/**
+ * @author Kevin Morin (Code Lutin)
+ * @since x.x
+ */
+public abstract class Command {
+
+ protected FaxToMailServiceContext serviceContext;
+
+ protected Command(FaxToMailServiceContext serviceContext) {
+ this.serviceContext = serviceContext;
+ }
+
+ protected abstract void doAction();
+
+ public void execute() {
+ try {
+ doAction();
+
+ } finally {
+ IOUtils.closeQuietly(serviceContext);
+ }
+ }
+
+}
1
0