IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Spring Java Discussion :

Problème de cron avec Spring + Quartz


Sujet :

Spring Java

  1. #1
    Nouveau Candidat au Club
    Femme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2011
    Messages
    3
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2011
    Messages : 3
    Points : 1
    Points
    1
    Par défaut Problème de cron avec Spring + Quartz
    Bonjour,

    Je souhaite récupérer et traiter les mails via un cron Quartz lancé par Spring.

    J'arrive bien à me connecter, je fais
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Message[] messages = folder.getMessages();
    et dans mon tableau de message je retrouve bien le nombre de messages à récupérer mais je n'arrive pas à les "mapper" en mail.
    Le contenu des messages est null

    Si je lance ma méthode de récupération des mails via la méthode main(String[] args) et que j'instancie dans ce main ma classe de départ, je récupère bien les messages et je peux en traiter le contenu.

    Quelle peut être la raison de ce comportement différent?

    Merci pour les pistes qu'on pourrait me donner.

  2. #2
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 481
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 481
    Points : 48 806
    Points
    48 806
    Par défaut
    code svp

  3. #3
    Nouveau Candidat au Club
    Femme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2011
    Messages
    3
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2011
    Messages : 3
    Points : 1
    Points
    1
    Par défaut Problème de cron avec Spring + Quartz
    Bonjour tchize_,

    Merci pour votre réaction rapide.

    J'utilise Maven et Spring.

    Voici mon code :

    Extrait du fichier XML de configuration du cron Quartz (ticket.xml):
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
     
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
    <beans>
     
        <!-- Job récupération des mails du compte Pop3 -->
     
        <bean id="saveTicketsFromPop3Job" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
            <property name="targetObject" ref="ticketControllerService"/>
            <property name="targetMethod" value="saveTicketsFromPop3"/>
        </bean>
     
        <bean id="saveTicketsFromPop3Trigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
            <property name="jobDetail" ref="saveTicketsFromPop3Job" />
            <property name="cronExpression">
                <value>${job.updateTicketsFromPop3.cron}</value>
            </property>
        </bean>
     
        <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
            <property name="triggers">
                <list>
                    <ref bean="saveTicketsFromPop3Trigger" />
                </list>
            </property>
        </bean>      
     
    </beans>
    Extrait de la classe (interface service) TicketControllerService dont la méthode est appelée par Quartz:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    package com.t4hr.isiweb.controller.service.ticket;
     
    import java.util.Collection;
    import java.util.Locale;
     
    import javax.faces.model.SelectItem;
     
    import org.apache.commons.mail.EmailException;
     
    import com.t4hr.isiweb.controller.search.AdvancedSearchable;
    import com.t4hr.isiweb.controller.service.SearchableControllerService;
    import com.t4hr.isiweb.model.PartialList;
    import com.t4hr.isiweb.model.bo.ticket.Note;
    import com.t4hr.isiweb.model.bo.ticket.Ticket;
    import com.t4hr.isiweb.model.bo.ticket.TicketableEnum;
    import com.t4hr.isiweb.model.search.ticket.TicketSearchField;
    import com.t4hr.isiweb.model.search.ticket.TicketSortField;
    import com.t4hr.isiweb.model.service.texttemplate.TextTemplateConversionException;
    import com.t4hr.isiweb.model.service.texttemplate.TextTemplateToTextService.ContextualObjectsIdsHolder;
    import com.t4hr.isiweb.view.ticket.NoteView;
    import com.t4hr.isiweb.view.ticket.TicketDashboardView;
    import com.t4hr.isiweb.view.ticket.TicketResumeView;
    import com.t4hr.isiweb.view.ticket.TicketSummaryView;
    import com.t4hr.isiweb.view.ticket.TicketView;
     
    public interface TicketControllerService
            extends
            SearchableControllerService<TicketSearchField, TicketSortField, TicketView, TicketSummaryView, AdvancedSearchable<TicketSearchField>, Ticket> {
        ......
        public void saveTicketsFromPop3();
        ......
     
        public class OwnerInfo {
     
            // -- Properties -----------------------------------------------------
     
            Long id;
     
            String title;
     
            // -- Constructor(s) -------------------------------------------------
     
            public OwnerInfo() {
                super();
            }
     
            public OwnerInfo(Long id, String title) {
                this();
                this.id = id;
                this.title = title;
            }
     
            // -- Getter(s) / Setter(s) ------------------------------------------
     
            public Long getId() {
                return id;
            }
     
            public void setId(Long id) {
                this.id = id;
            }
     
            public String getTitle() {
                return title;
            }
     
            public void setTitle(String title) {
                this.title = title;
            }
     
        }
     
        public TicketResumeView loadResume(Long id, Locale locale);
     
    }
    Extrait de la classe (TicketControllerServiceImpl) dont la méthode est appelée par l'interface TicketControllerService:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    package com.t4hr.isiweb.controller.impl.service.ticket;
     
    import java.io.File;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.text.DateFormat;
    import java.text.MessageFormat;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.Date;
    import java.util.List;
    import java.util.Locale;
    import java.util.ResourceBundle;
    import java.util.Set;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
     
    import javax.faces.model.SelectItem;
    import javax.mail.Folder;
    import javax.mail.MessagingException;
     
    import org.apache.commons.io.FileUtils;
    import org.apache.commons.io.FilenameUtils;
    import org.apache.commons.lang.StringUtils;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.apache.commons.mail.EmailAttachment;
    import org.apache.commons.mail.EmailException;
    import org.apache.commons.mail.HtmlEmail;
    import org.apache.commons.mail.MultiPartEmail;
     
    import com.t4hr.commons.email.Email;
    import com.t4hr.commons.email.impl.Pop3EmailReceiver;
    import com.t4hr.commons.email.impl.Pop3FolderTools;
    import com.t4hr.isiweb.controller.impl.service.SearchableControllerServiceImpl;
    import com.t4hr.isiweb.controller.search.AdvancedSearchable;
    import com.t4hr.isiweb.controller.service.auth.UserControllerService;
    import com.t4hr.isiweb.controller.service.common.DocumentControllerService;
    import com.t4hr.isiweb.controller.service.ticket.NoteControllerService;
    import com.t4hr.isiweb.controller.service.ticket.TicketControllerService;
    import com.t4hr.isiweb.controller.service.ticketEvent.TicketEventControllerService;
    import com.t4hr.isiweb.controller.util.EnumToSelectItemCollectionCreator;
    import com.t4hr.isiweb.impl.service.outlookplugin.OutlookPluginServiceImpl;
    import com.t4hr.isiweb.model.PartialArrayList;
    import com.t4hr.isiweb.model.PartialList;
    import com.t4hr.isiweb.model.bo.EntityKey;
    import com.t4hr.isiweb.model.bo.auth.Account;
    import com.t4hr.isiweb.model.bo.auth.Role;
    import com.t4hr.isiweb.model.bo.auth.RoleVisitor;
    import com.t4hr.isiweb.model.bo.common.Document;
    import com.t4hr.isiweb.model.bo.company.AbstractCompany;
    import com.t4hr.isiweb.model.bo.company.Company;
    import com.t4hr.isiweb.model.bo.company.Holding;
    import com.t4hr.isiweb.model.bo.company.Site;
    import com.t4hr.isiweb.model.bo.config.TicketConfiguration;
    import com.t4hr.isiweb.model.bo.conflict.Conflict;
    import com.t4hr.isiweb.model.bo.conflict.Conflictable;
    import com.t4hr.isiweb.model.bo.conflict.ConflictableType;
    import com.t4hr.isiweb.model.bo.conflict.ConflictableTypeGetter;
    import com.t4hr.isiweb.model.bo.convention.Convention;
    import com.t4hr.isiweb.model.bo.mission.Mission;
    import com.t4hr.isiweb.model.bo.person.Agent;
    import com.t4hr.isiweb.model.bo.person.Customer;
    import com.t4hr.isiweb.model.bo.person.Person;
    import com.t4hr.isiweb.model.bo.person.Worker;
    import com.t4hr.isiweb.model.bo.position.BasicPosition;
    import com.t4hr.isiweb.model.bo.texttemplate.EmailTemplate;
    import com.t4hr.isiweb.model.bo.ticket.Note;
    import com.t4hr.isiweb.model.bo.ticket.Ticket;
    import com.t4hr.isiweb.model.bo.ticket.TicketTypeVisitor;
    import com.t4hr.isiweb.model.bo.ticket.TicketVisitor;
    import com.t4hr.isiweb.model.bo.ticket.Ticketable;
    import com.t4hr.isiweb.model.bo.ticket.TicketableEnum;
    import com.t4hr.isiweb.model.bo.workflow.automaticRecruitment.AutomaticRecruitment;
    import com.t4hr.isiweb.model.bo.workflow.mc.MarketingCampaign;
    import com.t4hr.isiweb.model.bo.workflow.opportunity.Opportunity;
    import com.t4hr.isiweb.model.bo.workflow.recruitment.Recruitment;
    import com.t4hr.isiweb.model.bo.workflow.target.AffectedCompanyTarget;
    import com.t4hr.isiweb.model.bo.workflow.target.CompanyTarget;
    import com.t4hr.isiweb.model.bo.workflow.task.BasicTask;
    import com.t4hr.isiweb.model.bo.workflow.task.TargetedTask;
    import com.t4hr.isiweb.model.bo.workflow.task.TargetedTaskGenerator;
    import com.t4hr.isiweb.model.bo.workflow.task.Task;
    import com.t4hr.isiweb.model.search.ticket.TicketSearchField;
    import com.t4hr.isiweb.model.search.ticket.TicketSortField;
    import com.t4hr.isiweb.model.service.SearchableService;
    import com.t4hr.isiweb.model.service.TranslatableService;
    import com.t4hr.isiweb.model.service.auth.AccountService;
    import com.t4hr.isiweb.model.service.common.DocumentService;
    import com.t4hr.isiweb.model.service.company.AbstractCompanyService;
    import com.t4hr.isiweb.model.service.config.TicketConfigurationService;
    import com.t4hr.isiweb.model.service.conflict.ConflictableService;
    import com.t4hr.isiweb.model.service.person.AgentService;
    import com.t4hr.isiweb.model.service.person.CustomerService;
    import com.t4hr.isiweb.model.service.person.WorkerService;
    import com.t4hr.isiweb.model.service.texttemplate.EmailTemplateService;
    import com.t4hr.isiweb.model.service.texttemplate.TextTemplateConversionException;
    import com.t4hr.isiweb.model.service.texttemplate.TextTemplateToTextService;
    import com.t4hr.isiweb.model.service.texttemplate.TextTemplateToTextService.ContextualObjectsIdsHolder;
    import com.t4hr.isiweb.model.service.ticket.TicketService;
    import com.t4hr.isiweb.model.service.ticket.TicketTypeService;
    import com.t4hr.isiweb.model.service.ticket.TicketableService;
    import com.t4hr.isiweb.model.service.ticketEvent.TicketEventService;
    import com.t4hr.isiweb.model.service.workflow.mc.MarketingCampaignService;
    import com.t4hr.isiweb.model.service.workflow.opportunity.OpportunityService;
    import com.t4hr.isiweb.model.service.workflow.recruitment.RecruitmentService;
    import com.t4hr.isiweb.service.EmailSender;
    import com.t4hr.isiweb.service.HtmlParserService;
    import com.t4hr.isiweb.service.export.rtftemplate.RtfDocumentCreatorService;
    import com.t4hr.isiweb.service.mailing.Rtf2Html;
    import com.t4hr.isiweb.service.outlookplugin.OutlookPluginService;
    import com.t4hr.isiweb.view.auth.AccountOwnerInfoView;
    import com.t4hr.isiweb.view.auth.UserView;
    import com.t4hr.isiweb.view.common.DocumentView;
    import com.t4hr.isiweb.view.ticket.NoteView;
    import com.t4hr.isiweb.view.ticket.TicketDashboardView;
    import com.t4hr.isiweb.view.ticket.TicketResumeView;
    import com.t4hr.isiweb.view.ticket.TicketSummaryView;
    import com.t4hr.isiweb.view.ticket.TicketView;
    import com.t4hr.util.jBundles.InheritedBundleManager;
     
    public class TicketControllerServiceImpl
            extends
            SearchableControllerServiceImpl<TicketSearchField, TicketSortField, TicketView, TicketSummaryView, AdvancedSearchable<TicketSearchField>, Ticket>
            implements TicketControllerService {
     
        // -- Constant(s) --------------------------------------------------------
     
        private static final String CONFLICT_BUNDLE = "com.t4hr.isiweb.translation.conflict.conflict";
     
        private static final String TICKETMAIL_BUNDLE = "com.t4hr.isiweb.controller.translation.ticketmail";
     
        private static final String RESOURCEBUNDLE_ENTITYKEY = "com.t4hr.isiweb.translation.entitykey";
     
        // ---- Logger
     
        private static final Log LOG = LogFactory.getLog(TicketControllerServiceImpl.class);
     
        // -- Properties ---------------------------------------------------------
     
        .........
        private String fromAddress;
     
        private EmailSender emailSender;
     
        private String pop3Server;
     
        private String pop3Login;
     
        private String pop3Password;
     
        private String backupMailOnError;
     
        private EmailTemplateService emailTemplateService;
     
        private TextTemplateToTextService textTemplateToTextService;
     
        private DocumentControllerService documentControllerService;
     
        private DocumentService documentService;
     
        private OutlookPluginService outlookPluginService;
     
        private Boolean documentAsAttachment = Boolean.TRUE;
     
        private TicketConfigurationService ticketConfigurationService;
     
        private Rtf2Html rtf2Html;
     
        private RtfDocumentCreatorService rtfDocumentCreatorService;
     
        private MarketingCampaignService marketingCampaignService;
        ......
     
        // -- Constructor(s) -----------------------------------------------------
     
        public TicketControllerServiceImpl() {
            super();
        }
     
        // -- Public method(s) ---------------------------------------------------
     
        .........
        public void saveTicketsFromPop3() {
            LOG.info("Reading new notes from Pop3 inbox...");
            Pop3EmailReceiver pop3EmailReceiver = new Pop3EmailReceiver(pop3Server, pop3Login, pop3Password, new File(
                    "d:\\temppop3File"), false, null);
     
            Set<Email> emails = pop3EmailReceiver.receive();  // ***** NOUS APPROCHONS DU PROBLÈME
     
            LOG.info(emails.size() + " emails found in pop3 box " + pop3Login + " on server " + pop3Server);
     
            for (Email email : emails) {
                try {
                    Boolean threaten = false;
                    if (email.getSubject().trim().compareToIgnoreCase("OUTLOOK_ISIWEB_PLUGIN_REQUEST") == 0) {
                        LOG.info("Found Email that need to be threaten with outlook plugin: " + email.getSubject());
                        OutlookPluginServiceImpl outlookPluginService = new OutlookPluginServiceImpl();
                        threaten = outlookPluginService.processEmail(email);
                    } else if (Ticket.extractEmailKey(email.getSubject()) != null) {
                        LOG.info("Found Email that need to be threaten as a ticket note: " + email.getSubject());
                        createNoteFromEmail(email);
                        threaten = true;
                    } else {
                        LOG.info("Found Email that will not be threaten: " + email.getSubject());
                        throw new IllegalArgumentException("Subject is not a threaten pattern");
                    }
     
                    if (!threaten) {
                        throw new IllegalArgumentException("Illegal Email content or processing Exception");
                    }
                } catch (Exception e) {
                    // try {
                    LOG.error(e);
                    /*
                     * org.apache.commons.mail.Email backupEmail = new org.apache.commons.mail.SimpleEmail();
                     * backupEmail.setSubject("Email Isiweb error: " + email.getSubject()); backupEmail.setMsg("Cause:\n" +
                     * StackTraceUtils.getStackTrace(e) + "\n" + email.getMessage());
                     * 
                     * backupEmail.setFrom(fromAddress); backupEmail.addTo(backupMailOnError);
                     * emailSender.send(backupEmail);
                     */
                    /*
                     * } catch (EmailException e1) { throw new RuntimeException(e1); }
                     */
                }
                LOG.info("Done!");
            }
            try {
                Pop3FolderTools.deleteAllEmails(Pop3FolderTools.openFolder(pop3Server, pop3Login, pop3Password,
                        Folder.READ_WRITE));
            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
        }
        ......
    }
    Extrait de la classe (Pop3EmailReceiver) dont la méthode receive() est appelée par TicketControllerServiceImpl:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
     
    package com.t4hr.isiweb.impl.service.email.impl;
     
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.StringWriter;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Iterator;
    import java.util.LinkedHashSet;
    import java.util.Locale;
    import java.util.Properties;
    import java.util.Set;
     
    import javax.mail.Address;
    import javax.mail.FetchProfile;
    import javax.mail.Flags;
    import javax.mail.Folder;
    import javax.mail.Message;
    import javax.mail.Message.RecipientType;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    import javax.mail.Part;
    import javax.mail.Session;
    import javax.mail.Store;
    import javax.mail.UIDFolder;
    import javax.mail.internet.InternetAddress;
     
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
     
    import com.sun.mail.pop3.POP3Folder;
    import com.sun.mail.pop3.POP3Message; // PHH New <> 1.06
    import com.t4hr.isiweb.impl.service.email.Email;
    import com.t4hr.isiweb.impl.service.email.EmailAddress;
    import com.t4hr.isiweb.impl.service.email.EmailException;
    import com.t4hr.isiweb.impl.service.email.EmailReceiver;
    import com.t4hr.isiweb.impl.service.email.impl.uid.UidStore;
     
    /**
     * 
     * The POP3 implementation of the MailReceiver interface.
     * 
     */
    public class Pop3EmailReceiver implements EmailReceiver {
     
        private static final Log LOG = LogFactory.getLog(Pop3EmailReceiver.class);
     
        // ---------------------------- Constants -----------------------------
     
        private static final String SUB_LEVEL1 = "MMMMM.yyyy";
     
        private static final String SUB_LEVEL2 = "dd.MMMMM.yyyy";
     
        private static final String SUB_LEVEL3 = "HH'h'mm'm'ss's'.SS";
     
        private static final Locale LOCALE = Locale.FRANCE;
     
        private static final String POP3 = "pop3";
     
        private static final String INBOX = "INBOX"; // POP3-> Only 1 folder :
     
        // "INBOX"
        private static final String RFC822_EXTENSION = ".eml";
     
        private static final String DATA_EXTENSION = ".dat";
     
        private static final String TEXT_EXTENSION = ".txt";
     
        private static final String HTML_EXTENSION = ".html";
     
        private static final String NO_FILENAME_TEXT = "(text)";
     
        private static final String NO_FILENAME_HTML = "(html)";
     
        private static final String NO_FILENAME_APPLICATION = "(application)";
     
        private static final String NO_FILENAME_VIDEO = "(video)";
     
        private static final String NO_FILENAME_AUDIO = "(audio)";
     
        private static final String NO_FILENAME_IMAGE = "(image)";
     
        private static final String NO_FILENAME_MESSAGE = "(message)";
     
        // ---------------------------- Properties ----------------------------
     
        /**
         * Server used to receive mails
         */
        private String pop3Server;
     
        /**
         * User name.
         */
        private String userName;
     
        /**
         * User password.
         */
        private String password;
     
        /**
         * Local folder for incoming mails
         */
        private File repository;
     
        /**
         * Serialize the messages?
         */
        private boolean autoSerialization;
     
        /**
         * Enable the retrieval determined by the server uids. Used to retrieve
         * mails that were not retrieved.
         */
        private UidStore uidStore;
     
        /**
         * Delete the mails that were successfully received
         */
        private boolean autoDelete;
     
        /**
         * Debug infos in console..
         */
        private boolean debug;
     
        // ---------------------------- Constructors --------------------------
     
        public Pop3EmailReceiver() {
            this(null, null, null, null);
        }
     
        /**
         * Creates a new POP3MailReceiver with the given POP3 server, the
         * username/password informations and the repository where to detach the
         * mails attachments. By default : * RFC822 auto-serialization of the
         * messages to the local folder is enabled * No UID store used * Messages
         * auto-delete on the server is disabled * Debug informations are hidden
         * 
         * @param pop3Server
         *            String
         * @param userName
         *            String
         * @param password
         *            String
         * @param repository
         *            File
         */
        public Pop3EmailReceiver(String pop3Server, String userName, String password, File repository) {
            this(pop3Server, userName, password, repository, true, null);
        }
     
        public Pop3EmailReceiver(String pop3Server, String userName, String password, File repository,
                boolean autoSerialization) {
            this(pop3Server, userName, password, repository, autoSerialization, null);
        }
     
        public Pop3EmailReceiver(String pop3Server, String userName, String password, File repository,
                boolean autoSerialization, UidStore uidStore) {
            this(pop3Server, userName, password, repository, autoSerialization, uidStore, false);
        }
     
        public Pop3EmailReceiver(String pop3Server, String userName, String password, File repository,
                boolean autoSerialization, UidStore uidStore, boolean autoDelete) {
            this(pop3Server, userName, password, repository, autoSerialization, uidStore, autoDelete, false);
        }
     
        public Pop3EmailReceiver(String pop3Server, String userName, String password, File repository,
                boolean autoSerialization, UidStore uidStore, boolean autoDelete, boolean debug) {
     
            this.pop3Server = pop3Server;
            this.userName = userName;
            this.password = password;
            this.repository = repository;
            this.autoSerialization = autoSerialization;
            this.uidStore = uidStore;
            this.autoDelete = autoDelete;
            this.debug = debug;
        }
     
        // /////////////////////////////METHODS//////////////////////////////////////
     
        // ------------- Public
     
        /**
         * Receives the emails contained in the "INBOX" folder.
         * 
         * @return Set
         */
        public Set<Email> receive() {
     
            Set<Email> emails = null;
            Store store = null;
            POP3Folder inbox = null;
            boolean expungeDeletedMails = false;
     
            try {
     
                // Create the Session
                Properties props = System.getProperties();
                Session session = Session.getInstance(props, null);
                session.setDebug(this.debug);
     
                // Connection on the server
                store = session.getStore(POP3);
                store.connect(this.pop3Server, this.userName, this.password);
     
                // Check the "Inbox"
                inbox = (POP3Folder) store.getFolder(INBOX);
                inbox.open(Folder.READ_WRITE);
     
     
     
                 // >>>>>>>>>>>>>>>> ***** Nous y sommes *****
                POP3Message[] messages = (POP3Message[]) inbox.getMessages(); // ***** Nous y sommes *****
                // >>>>>>>>>>>>>>>>
                /*
                 * If UID store is enabled -> UIDs for all messages in the folder
                 * are fetched using the POP3 UIDL command
                 */
                if (this.uidStore != null) {
     
                    FetchProfile profile = new FetchProfile();
                    profile.add(UIDFolder.FetchProfileItem.UID);
                    inbox.fetch(messages, profile);
                }
     
                // Mail
                if ((messages != null) && (messages.length > 0)) {
     
                    for (POP3Message message : messages) {
     
                        // If the UID based checking is enabled
                        String uid = null;
                        if (this.uidStore != null) {
                            uid = inbox.getUID(message).trim();
                        }
     
                        if ((this.uidStore == null) || ((this.uidStore != null) && (!this.uidStore.contains(uid)))) {
     
                            // Process the message
                            Email email = this.map(message);
     
                            if (email != null) {
     
                                if (emails == null) {
                                    emails = new LinkedHashSet<Email>();
                                }
                                emails.add(email);
                            }
     
                            // Store the new uid
                            if (this.uidStore != null) {
                                this.uidStore.store(uid);
                            }
     
                        } else {
     
                            // If the message is not new -> skip..
                            LOG.debug("Old mail skipped - UID : " + uid);
                        }
     
                        // Flag to "deleted"
                        if (this.autoDelete) {
                            message.setFlag(Flags.Flag.DELETED, true);
                        }
                    }
                }
     
                // Everything is ok until now -> allow delete
                expungeDeletedMails = true;
     
            } catch (Throwable throwable) {
                StringBuilder msg = new StringBuilder();
                msg.append("Cannot receive the mails ");
                msg.append("[POP3: ");
                msg.append(this.pop3Server);
                msg.append("; UserName: ");
                msg.append(this.userName);
                msg.append("]");
                throw new EmailException(msg.toString(), throwable);
            } finally {
                try {
                    if (inbox != null) {
                        // Close the "Inbox" and remove retreived mails
                        // (Flag.DELETED)
                        inbox.close(expungeDeletedMails);
                    }
                    if (store != null) {
                        store.close();
                    }
                } catch (Throwable throwable) {
                    throw new EmailException(throwable);
                }
            }
     
            if (emails == null) {
                return new LinkedHashSet<Email>();
            }
            return emails;
        }
     
        // ------------- Private
     
        /**
         * Maps a Message to an Email.
         * 
         * @param message
         *            Message
         * @return Email
         * @throws IOException
         * @throws MessagingException
         */
        private Email map(POP3Message message) throws IOException, MessagingException {
     
            Email email = null;
     
            /*
             * Current date/time is used to build local subfolders
             * message.getReceivedDate() returns null sometimes..
             */
            Date receivedDate = new Date();
     
            // Serialize to localfolder
            if (this.autoSerialization) {
                this.serialize(message, receivedDate);
            }
     
            // Recipients
            Set<EmailAddress> fromAdresses = this.map(message.getFrom());
            EmailAddress from = null;
            if (fromAdresses != null) {
                if (fromAdresses.size() > 0) {
                    LOG.error("More than one email address found in \"from\"");
                }
                Iterator<EmailAddress> iterator = fromAdresses.iterator();
                from = iterator.next();
            }
            Set<EmailAddress> to = this.map(message.getRecipients(RecipientType.TO));
            Set<EmailAddress> cc = this.map(message.getRecipients(RecipientType.CC));
            Set<EmailAddress> bcc = this.map(message.getRecipients(RecipientType.BCC));
            // Subject
            String subject = message.getSubject();
     
            email = new Email();
            email.setFrom(from);
            email.setTo(to);
            email.setSubject(subject);
            email.setCc(cc);
            email.setBcc(bcc);
            email.setReceivedDate(receivedDate);
            email.setSentDate(message.getSentDate());
            this.processPart(message, email, receivedDate);
     
            return email;
        }
        .....
        Getters et Setters
    }
    La classe Pop3Folder est celle de Sun (import com.sun.mail.pop3.POP3Folder)

    Le problème est le suivant:

    Quand on appelle la méthode saveTicketsFromPop3() au départ d'un Main en instanciant la classe TicketControllerServiceImpl, lors du inbox.getMessages(), les messages sont récupérés correctement.
    Quand on fait tourner le cron, lors du inbox.getMessages(), les messages sont récupérés mais à null.

    Je me doute qu'il s'agit d'un problème de l'intervention (ou plutôt de la non intervention) de Spring lorsque c'est le cron qui appelle la méthode mais je ne vois pas ce qui cloche.

    Merci.

  4. #4
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 481
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 481
    Points : 48 806
    Points
    48 806
    Par défaut
    vous voulez dire que POP3Message[] messages = (POP3Message[]) inbox.getMessages(); renvoie un tableau de nulls?

  5. #5
    Nouveau Candidat au Club
    Femme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2011
    Messages
    3
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2011
    Messages : 3
    Points : 1
    Points
    1
    Par défaut
    Non, le tableau n'est pas null car il contient le bon nombre de messages téléchargés depuis la boîte via Pop3Folder ("INBOX") mais les messages sont à null et, évidemment, ne peuvent être convertis en e-mail (Email).

    Par exemple, dans la méthode map(), tous les gets renvoient null.
    En debug, la taille de toutes les occurrences de message=messages[n] est à 0 !

    Je vous reprends ci-dessous la méthode map() de Pop3EmailReceiver.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    // ***** methode map() de Pop3EmailReceiver
       /**
         * Maps a Message to an Email.
         * 
         * @param message
         *            Message
         * @return Email
         * @throws IOException
         * @throws MessagingException
         */
        private Email map(POP3Message message) throws IOException, MessagingException {
     
            Email email = null;
     
            /*
             * Current date/time is used to build local subfolders
             * message.getReceivedDate() returns null sometimes..
             */
            Date receivedDate = new Date();
     
            // Serialize to localfolder
            if (this.autoSerialization) {
                this.serialize(message, receivedDate);
            }
     
            // Recipients
            Set<EmailAddress> fromAdresses = this.map(message.getFrom());
            EmailAddress from = null;
            if (fromAdresses != null) {
                if (fromAdresses.size() > 1) {
                    LOG.error("More than one email address found in \"from\"");
                }
                Iterator<EmailAddress> iterator = fromAdresses.iterator();
                from = iterator.next();
            }
            Set<EmailAddress> to = this.map(message.getRecipients(RecipientType.TO));
            Set<EmailAddress> cc = this.map(message.getRecipients(RecipientType.CC));
            Set<EmailAddress> bcc = this.map(message.getRecipients(RecipientType.BCC));
            // Subject
            String subject = message.getSubject();
     
            email = new Email();
            email.setFrom(from);
            email.setTo(to);
            email.setSubject(subject);
            email.setCc(cc);
            email.setBcc(bcc);
            email.setReceivedDate(receivedDate);
            email.setSentDate(message.getSentDate());
            this.processPart(message, email, receivedDate);
     
            return email;
        }
    Merci

  6. #6
    Membre du Club
    Profil pro
    Inscrit en
    Juin 2006
    Messages
    67
    Détails du profil
    Informations personnelles :
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations forums :
    Inscription : Juin 2006
    Messages : 67
    Points : 67
    Points
    67
    Par défaut
    Bonjour,

    Par exemple, dans la méthode map(), tous les gets renvoient null.
    En debug, la taille de toutes les occurrences de message=messages[n] est à 0 !

    Je vous reprends ci-dessous la méthode map() de Pop3EmailReceiver.
    :!!

    Bon il me semble que tu utilises les getters de javax.mail.Message et ton objet est un POP3Message, mais ton POP3Message hérite de javax.mail.Message
    extended by javax.mail.internet.MimeMessage!!
    donc il doit bien récupérer ce qu'il y a dans message !!!
    Est ce que tes sur de ne rien oublier coté Spring!! puis je veux plus de détails sur le debug et comment tu fais pour avoir ton message dans l'autre cas

Discussions similaires

  1. [Débutant] Problème handling JSP avec Spring
    Par toufik135 dans le forum Spring
    Réponses: 0
    Dernier message: 21/12/2013, 03h56
  2. Problème de datasource avec Spring+Hibernate
    Par _MattU_ dans le forum Spring
    Réponses: 1
    Dernier message: 04/10/2013, 22h30
  3. [MVC] Problème d'exécution avec Spring MVC
    Par noumery dans le forum Spring Web
    Réponses: 5
    Dernier message: 20/09/2012, 17h41
  4. [GateIn] Problème de contexte avec spring MVC
    Par FunkyBreizh dans le forum Portails
    Réponses: 0
    Dernier message: 07/08/2010, 13h22
  5. [Data] Problème test Dao avec Spring et iBatis
    Par fiatlux dans le forum Spring
    Réponses: 3
    Dernier message: 23/12/2007, 09h55

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo