r469 - in trunk: faxtomail-service/src/main/java/com/franciaflex/faxtomail/services faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service faxtomail-service/src/main/java/com/franciaflex/faxtomail/services/service/ldap 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/faxtom
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@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@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@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@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@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@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@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@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@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@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@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@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@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@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@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@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();
participants (1)
-
kmorin@users.forge.codelutin.com