KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencrx > mail > servlet > MailImporterServlet


1   /*
2    * ====================================================================
3    * Project: opencrx, http://www.opencrx.org/
4    * Name: $Id: MailImporterServlet.java,v 1.21 2006/04/02 00:34:26 wfro Exp $
5    * Description: openCRX MailImporterServlet
6    * Revision: $Revision: 1.21 $
7    * Owner: CRIXP AG, Switzerland, http://www.crixp.com
8    * Date: $Date: 2006/04/02 00:34:26 $
9    * ====================================================================
10    *
11    * This software is published under the BSD license
12    * as listed below.
13    *
14    * Copyright (c) 2004-2006, CRIXP Corp., Switzerland
15    * All rights reserved.
16    *
17    * Redistribution and use in source and binary forms, with or without
18    * modification, are permitted provided that the following conditions
19    * are met:
20    *
21    * * Redistributions of source code must retain the above copyright
22    * notice, this list of conditions and the following disclaimer.
23    *
24    * * Redistributions in binary form must reproduce the above copyright
25    * notice, this list of conditions and the following disclaimer in
26    * the documentation and/or other materials provided with the
27    * distribution.
28    *
29    * * Neither the name of CRIXP Corp. nor the names of the contributors
30    * to openCRX may be used to endorse or promote products derived
31    * from this software without specific prior written permission
32    *
33    *
34    * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
35    * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
36    * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
37    * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38    * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
39    * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
40    * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
41    * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42    * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
43    * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44    * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
45    * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
46    * POSSIBILITY OF SUCH DAMAGE.
47    *
48    * ------------------
49    *
50    * This product includes software developed by the Apache Software
51    * Foundation (http://www.apache.org/).
52    *
53    * This product includes software developed by contributors to
54    * openMDX (http://www.openmdx.org/)
55    */

56 package org.opencrx.mail.servlet;
57
58 import java.io.IOException JavaDoc;
59 import java.util.ArrayList JavaDoc;
60 import java.util.Date JavaDoc;
61 import java.util.Iterator JavaDoc;
62 import java.util.List JavaDoc;
63
64 import javax.activation.MimeType JavaDoc;
65 import javax.activation.MimeTypeParseException JavaDoc;
66 import javax.jmi.reflect.RefException;
67 import javax.mail.Message JavaDoc;
68 import javax.naming.Context JavaDoc;
69 import javax.naming.InitialContext JavaDoc;
70 import javax.naming.NamingException JavaDoc;
71 import javax.servlet.ServletConfig JavaDoc;
72 import javax.servlet.ServletException JavaDoc;
73 import javax.servlet.http.HttpServlet JavaDoc;
74 import javax.servlet.http.HttpServletRequest JavaDoc;
75 import javax.servlet.http.HttpServletResponse JavaDoc;
76
77 import org.opencrx.kernel.account1.cci.EMailAddress;
78 import org.opencrx.kernel.account1.cci.EMailAddressFilter;
79 import org.opencrx.kernel.account1.cci.account1Package;
80 import org.opencrx.kernel.activity1.cci.ActivityCreator;
81 import org.opencrx.kernel.activity1.cci.ActivityCreatorFilter;
82 import org.opencrx.kernel.activity1.cci.ActivityProcess;
83 import org.opencrx.kernel.activity1.cci.ActivityProcessState;
84 import org.opencrx.kernel.activity1.cci.ActivityProcessTransition;
85 import org.opencrx.kernel.activity1.cci.ActivityTracker;
86 import org.opencrx.kernel.activity1.cci.ActivityType;
87 import org.opencrx.kernel.activity1.cci.EMail;
88 import org.opencrx.kernel.activity1.cci.EMailFilter;
89 import org.opencrx.kernel.activity1.cci.EMailRecipient;
90 import org.opencrx.kernel.activity1.cci.NewActivityParams;
91 import org.opencrx.kernel.activity1.cci.NewActivityResult;
92 import org.opencrx.kernel.activity1.cci.SetActualEndAction;
93 import org.opencrx.kernel.activity1.cci.SetActualStartAction;
94 import org.opencrx.kernel.activity1.cci.SetAssignedToAction;
95 import org.opencrx.kernel.activity1.cci.WfAction;
96 import org.opencrx.kernel.activity1.cci.activity1Package;
97 import org.opencrx.kernel.generic.SecurityKeys;
98 import org.opencrx.kernel.generic.cci.Media;
99 import org.opencrx.kernel.generic.cci.Note;
100 import org.opencrx.kernel.generic.cci.genericPackage;
101 import org.opencrx.kernel.workflow.servlet.WorkflowControllerServlet;
102 import org.opencrx.kernel.workflow1.cci.WfProcess;
103 import org.openmdx.application.log.AppLog;
104 import org.openmdx.base.accessor.generic.view.Manager_1;
105 import org.openmdx.base.accessor.jmi.cci.JmiServiceException;
106 import org.openmdx.base.accessor.jmi.cci.RefPackage_1_0;
107 import org.openmdx.base.accessor.jmi.spi.RefRootPackage_1;
108 import org.openmdx.base.exception.ServiceException;
109 import org.openmdx.compatibility.application.dataprovider.transport.ejb.cci.Dataprovider_1ConnectionFactoryImpl;
110 import org.openmdx.compatibility.base.dataprovider.cci.QualityOfService;
111 import org.openmdx.compatibility.base.dataprovider.cci.RequestCollection;
112 import org.openmdx.compatibility.base.dataprovider.cci.ServiceHeader;
113 import org.openmdx.compatibility.base.dataprovider.transport.adapter.Provider_1;
114 import org.openmdx.compatibility.base.dataprovider.transport.cci.Dataprovider_1_1Connection;
115 import org.openmdx.compatibility.base.dataprovider.transport.cci.Provider_1_0;
116 import org.openmdx.compatibility.base.dataprovider.transport.delegation.Connection_1;
117 import org.openmdx.compatibility.base.naming.Path;
118 import org.openmdx.compatibility.base.query.FilterOperators;
119 import org.openmdx.kernel.exception.BasicException;
120 import org.openmdx.kernel.id.UUIDs;
121 import org.openmdx.kernel.id.cci.UUIDGenerator;
122 import org.openmdx.model1.accessor.basic.spi.Model_1;
123
124 /**
125  * The EMailImporterServlet imports E-Mails from a configured Mail server
126  * and folder as openCRX EMail activities. Activities are created either
127  * with a default EMail activity creator or by the activity creator defined
128  * by the EMail subject.
129  */

130 public class MailImporterServlet
131     extends HttpServlet JavaDoc {
132
133     //-----------------------------------------------------------------------
134
/* (non-Javadoc)
135      * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
136      */

137     public void init(
138         ServletConfig JavaDoc config
139     ) throws ServletException JavaDoc {
140
141         super.init(config);
142         
143         // initialize model repository
144
int i = 0;
145         List JavaDoc modelPackages = new ArrayList JavaDoc();
146         while(getInitParameter("modelPackage[" + i + "]") != null) {
147             modelPackages.add(
148               getInitParameter("modelPackage[" + i + "]")
149             );
150             i++;
151         }
152         try {
153             new Model_1().addModels(modelPackages);
154         }
155         catch(Exception JavaDoc e) {
156             AppLog.warning("Can not initialize model repository", e);
157         }
158
159         Context JavaDoc initialContext;
160         try {
161             initialContext = new InitialContext JavaDoc();
162         }
163         catch (NamingException JavaDoc e) {
164             throw new ServletException JavaDoc("can not get the initial context", e);
165         }
166         // data connection
167
try {
168             this.connectionData = Dataprovider_1ConnectionFactoryImpl.createGenericConnection(
169                 initialContext.lookup("java:comp/env/ejb/data")
170             );
171         }
172         catch(Exception JavaDoc e) {
173             throw new ServletException JavaDoc("can not get connection to data provider", e);
174         }
175     }
176
177     //-------------------------------------------------------------------------
178
/**
179      * Returns a reference to the root package using the given ServiceHeader
180      * and the Dataprovider connection established during the initialization
181      * of the MailImporters.
182      *
183      * @param header The ServiceHeader to use for this request.
184      * @return The RefPackage_1_0 instance
185      * @throws ServiceException
186      */

187     private RefPackage_1_0 createDataPkg(
188         ServiceHeader header
189     ) throws ServiceException {
190         Provider_1_0 provider = new Provider_1(
191             new RequestCollection(
192                 header,
193                 this.connectionData
194             ),
195             false
196         );
197         Manager_1 manager = new Manager_1(
198             new Connection_1(
199                 provider,
200                 false
201             )
202         );
203         RefPackage_1_0 rootPkg = new RefRootPackage_1(manager);
204         return rootPkg;
205     }
206
207     //-----------------------------------------------------------------------
208
/**
209      * @return Returns the activityPkg.
210      */

211     protected static org.opencrx.kernel.activity1.cci.activity1Package getActivityPkg(
212         RefPackage_1_0 rootPkg
213     ) {
214         return (org.opencrx.kernel.activity1.cci.activity1Package)rootPkg.refPackage(
215             org.opencrx.kernel.activity1.cci.activity1Package.class.getName()
216         );
217     }
218
219     //-----------------------------------------------------------------------
220
/**
221      * @return Returns the activitySegment.
222      */

223     protected static org.opencrx.kernel.activity1.cci.Segment getActivitySegment(
224         RefPackage_1_0 rootPkg,
225         String JavaDoc providerName,
226         String JavaDoc segmentName
227     ) {
228         return (org.opencrx.kernel.activity1.cci.Segment) rootPkg.refObject(
229             "xri:@openmdx:org.opencrx.kernel.activity1/provider/"
230             + providerName + "/segment/" + segmentName
231         );
232     }
233
234     //-----------------------------------------------------------------------
235
/**
236      * @return Returns the accountPkg.
237      */

238     protected static account1Package getAccountPkg(
239         RefPackage_1_0 rootPkg
240     ) {
241         return (account1Package) rootPkg.refPackage(
242             account1Package.class.getName()
243         );
244     }
245
246     //-----------------------------------------------------------------------
247
/**
248      * @return Returns the accountSegment.
249      */

250     protected static org.opencrx.kernel.account1.cci.Segment getAccountSegment(
251         RefPackage_1_0 rootPkg,
252         String JavaDoc providerName,
253         String JavaDoc segmentName
254     ) {
255         return (org.opencrx.kernel.account1.cci.Segment) rootPkg.refObject(
256             "xri:@openmdx:org.opencrx.kernel.account1/provider/"
257             + providerName + "/segment/" + segmentName
258         );
259     }
260
261     //-----------------------------------------------------------------------
262
protected static genericPackage getGenericPkg(
263         RefPackage_1_0 rootPkg
264     ) {
265         return (org.opencrx.kernel.generic.cci.genericPackage) rootPkg.refPackage(
266             org.opencrx.kernel.generic.cci.genericPackage.class.getName()
267         );
268     }
269
270     //-----------------------------------------------------------------------
271
protected void initEMailCreator(
272         RefPackage_1_0 rootPkg,
273         String JavaDoc providerName,
274         String JavaDoc segmentName
275     ) {
276         org.opencrx.kernel.activity1.cci.activity1Package activityPkg = getActivityPkg(
277             rootPkg
278         );
279         org.opencrx.kernel.activity1.cci.Segment activitySegment = getActivitySegment(
280             rootPkg,
281             providerName,
282             segmentName
283         );
284         // Create EMail creators
285
ActivityCreator emailCreator = null;
286         try {
287             emailCreator = activitySegment.getActivityCreator(DEFAULT_EMAIL_CREATOR_ID);
288         }
289         catch(JmiServiceException e) {
290             // Create default inbound email creator
291
if(e.getExceptionCode() != BasicException.Code.NOT_FOUND) {
292                 throw e;
293             }
294             try {
295                 // EMailCreator
296
rootPkg.refBegin();
297                 emailCreator = activityPkg.getActivityCreatorClass().createActivityCreator();
298                 emailCreator.setName("Default E-Mail Creator");
299                 emailCreator.setPriority((short)0);
300                 emailCreator.getOwningGroup().addAll(
301                     activitySegment.getOwningGroup()
302                 );
303                 activitySegment.addActivityCreator(
304                     DEFAULT_EMAIL_CREATOR_ID,
305                     emailCreator
306                 );
307                 rootPkg.refCommit();
308                 
309                 // Create email process
310
rootPkg.refBegin();
311                 ActivityProcess emailProcess = activityPkg.getActivityProcessClass().createActivityProcess();
312                 emailProcess.setName("E-Mail Process");
313                 emailProcess.getOwningGroup().addAll(
314                     activitySegment.getOwningGroup()
315                 );
316                 activitySegment.addActivityProcess(
317                     emailProcess
318                 );
319                 // State New
320
ActivityProcessState newState = activityPkg.getActivityProcessStateClass().createActivityProcessState();
321                 newState.setName("New");
322                 newState.getOwningGroup().addAll(
323                     activitySegment.getOwningGroup()
324                 );
325                 emailProcess.addState(newState);
326                 // State Open
327
ActivityProcessState openState = activityPkg.getActivityProcessStateClass().createActivityProcessState();
328                 openState.setName("Open");
329                 openState.getOwningGroup().addAll(
330                     activitySegment.getOwningGroup()
331                 );
332                 emailProcess.addState(openState);
333                 // State Closed
334
ActivityProcessState closedState = activityPkg.getActivityProcessStateClass().createActivityProcessState();
335                 closedState.setName("Closed");
336                 closedState.getOwningGroup().addAll(
337                     activitySegment.getOwningGroup()
338                 );
339                 emailProcess.addState(closedState);
340                 rootPkg.refCommit();
341                 // Initial State
342
rootPkg.refBegin();
343                 emailProcess.setStartState(newState);
344                 // Transition Assign: New->Open
345
ActivityProcessTransition processTransition = activityPkg.getActivityProcessTransitionClass().createActivityProcessTransition();
346                 processTransition.setName("Assign");
347                 processTransition.setPrevState(newState);
348                 processTransition.setNextState(openState);
349                 processTransition.setNewActivityState((short)10);
350                 processTransition.setNewPercentComplete(new Short JavaDoc((short)20));
351                 processTransition.getOwningGroup().addAll(
352                     activitySegment.getOwningGroup()
353                 );
354                 emailProcess.addTransition(processTransition);
355                 // Create SetAssignedToAction
356
SetAssignedToAction setAssignedToAction = activityPkg.getSetAssignedToActionClass().createSetAssignedToAction();
357                 setAssignedToAction.setName("Set assignedTo");
358                 setAssignedToAction.setDescription("Set assignedTo to current user");
359                 setAssignedToAction.getOwningGroup().addAll(
360                     activitySegment.getOwningGroup()
361                 );
362                 processTransition.addAction(setAssignedToAction);
363                 // Create SetActualStartAction
364
SetActualStartAction setActualStartAction = activityPkg.getSetActualStartActionClass().createSetActualStartAction();
365                 setActualStartAction.setName("Set actual start");
366                 setActualStartAction.setDescription("Set actual start on activity assignment");
367                 setActualStartAction.getOwningGroup().addAll(
368                     activitySegment.getOwningGroup()
369                 );
370                 processTransition.addAction(setActualStartAction);
371                 // Transition Add Note: Open->Open
372
processTransition = activityPkg.getActivityProcessTransitionClass().createActivityProcessTransition();
373                 processTransition.setName("Add Note");
374                 processTransition.setPrevState(openState);
375                 processTransition.setNextState(openState);
376                 processTransition.setNewActivityState((short)10);
377                 processTransition.setNewPercentComplete(new Short JavaDoc((short)50));
378                 processTransition.getOwningGroup().addAll(
379                     activitySegment.getOwningGroup()
380                 );
381                 emailProcess.addTransition(processTransition);
382                 // Transition Export: Open->Open
383
processTransition = activityPkg.getActivityProcessTransitionClass().createActivityProcessTransition();
384                 processTransition.setName("Export as mail attachment");
385                 processTransition.setPrevState(openState);
386                 processTransition.setNextState(openState);
387                 processTransition.setNewActivityState((short)10);
388                 processTransition.setNewPercentComplete(new Short JavaDoc((short)50));
389                 processTransition.getOwningGroup().addAll(
390                     activitySegment.getOwningGroup()
391                 );
392                 emailProcess.addTransition(processTransition);
393                 // Create WorkflowAction for ExportMail
394
WfAction wfAction = activityPkg.getWfActionClass().createWfAction();
395                 wfAction.setName("Export Mail");
396                 wfAction.setName("Export Mail as attachment to current user");
397                 wfAction.setWfProcess(
398                     (WfProcess)rootPkg.refObject(
399                         new Path("xri:@openmdx:org.opencrx.kernel.workflow1/provider/" + providerName + "/segment/" + segmentName + "/wfProcess/" + WorkflowControllerServlet.WORKFLOW_EXPORT_MAIL).toXri()
400                     )
401                 );
402                 wfAction.getOwningGroup().addAll(
403                     activitySegment.getOwningGroup()
404                 );
405                 processTransition.addAction(wfAction);
406                 // Transition Send: Open->Open
407
processTransition = activityPkg.getActivityProcessTransitionClass().createActivityProcessTransition();
408                 processTransition.setName("Send as mail");
409                 processTransition.setPrevState(openState);
410                 processTransition.setNextState(openState);
411                 processTransition.setNewActivityState((short)10);
412                 processTransition.setNewPercentComplete(new Short JavaDoc((short)50));
413                 processTransition.getOwningGroup().addAll(
414                     activitySegment.getOwningGroup()
415                 );
416                 emailProcess.addTransition(processTransition);
417                 // Create WorkflowAction for SendMail
418
wfAction = activityPkg.getWfActionClass().createWfAction();
419                 wfAction.setName("Send Mail");
420                 wfAction.setName("Send as mail");
421                 wfAction.setWfProcess(
422                     (WfProcess)rootPkg.refObject(
423                         new Path("xri:@openmdx:org.opencrx.kernel.workflow1/provider/" + providerName + "/segment/" + segmentName + "/wfProcess/" + WorkflowControllerServlet.WORKFLOW_SEND_MAIL).toXri()
424                     )
425                 );
426                 wfAction.getOwningGroup().addAll(
427                     activitySegment.getOwningGroup()
428                 );
429                 processTransition.addAction(wfAction);
430                 // Transition Close: Open->Closed
431
processTransition = activityPkg.getActivityProcessTransitionClass().createActivityProcessTransition();
432                 processTransition.setName("Close");
433                 processTransition.setPrevState(openState);
434                 processTransition.setNextState(closedState);
435                 processTransition.setNewActivityState((short)20);
436                 processTransition.setNewPercentComplete(new Short JavaDoc((short)100));
437                 processTransition.getOwningGroup().addAll(
438                     activitySegment.getOwningGroup()
439                 );
440                 emailProcess.addTransition(processTransition);
441                 // Create SetActualEndAction
442
SetActualEndAction setActualEndAction = activityPkg.getSetActualEndActionClass().createSetActualEndAction();
443                 setActualEndAction.setName("Set actual end");
444                 setActualEndAction.setName("Set actual end to current dateTime");
445                 setActualEndAction.getOwningGroup().addAll(
446                     activitySegment.getOwningGroup()
447                 );
448                 processTransition.addAction(setActualEndAction);
449                 // Commit
450
rootPkg.refCommit();
451                 
452                 // Create activity type
453
rootPkg.refBegin();
454                 ActivityType emailActivityType = activityPkg.getActivityTypeClass().createActivityType();
455                 emailActivityType.setName("E-Mails");
456                 emailActivityType.setActivityClass(ACTIVITY_CLASS_EMAIL);
457                 emailActivityType.setControlledBy(emailProcess);
458                 emailActivityType.getOwningGroup().addAll(
459                     activitySegment.getOwningGroup()
460                 );
461                 activitySegment.addActivityType(emailActivityType);
462                 rootPkg.refCommit();
463                 
464                 // Create activity group
465
rootPkg.refBegin();
466                 ActivityTracker emailGroup = activityPkg.getActivityTrackerClass().createActivityTracker();
467                 emailGroup.setName("E-Mails");
468                 emailGroup.getOwningGroup().addAll(
469                     activitySegment.getOwningGroup()
470                 );
471                 activitySegment.addActivityTracker(emailGroup);
472                 rootPkg.refCommit();
473                 
474                 // Complete activity creator
475
rootPkg.refBegin();
476                 emailCreator.getActivityGroup().add(emailGroup);
477                 emailCreator.setActivityType(emailActivityType);
478                 rootPkg.refCommit();
479                 
480             }
481             catch(JmiServiceException e0) {
482                 AppLog.info("Can not create default configuration", e0.getMessage());
483                 throw e0;
484             }
485         }
486     }
487     
488     //-----------------------------------------------------------------------
489
/**
490      * Search accounts containing the given email address.
491      *
492      * @param rootPkg The root package to be used for this request
493      * @param providerName The name of the current provider
494      * @param segmentName The name of the current segment
495      * @param emailAddress The email address
496      * @return A List of accounts containing the email address
497      */

498     private List JavaDoc lookupEMailAddress(
499         RefPackage_1_0 rootPkg,
500         String JavaDoc providerName,
501         String JavaDoc segmentName,
502         String JavaDoc emailAddress
503     ) {
504         EMailAddressFilter filter = getAccountPkg(rootPkg).createEMailAddressFilter();
505         org.opencrx.kernel.account1.cci.Segment accountSegment =
506             getAccountSegment(
507                 rootPkg,
508                 providerName,
509                 segmentName
510             );
511         filter.thereExistsIdentity(
512             FilterOperators.IS_LIKE,
513             new String JavaDoc[]{
514                 accountSegment.refMofId() + "/account/:*/address/:*"
515             }
516         );
517         filter.thereExistsEmailAddress(
518             FilterOperators.IS_IN,
519             new String JavaDoc[]{emailAddress}
520         );
521         return accountSegment.getExtent(filter);
522     }
523     
524     //-----------------------------------------------------------------------
525
/**
526      * Search email activity with the given external link, i.e. the given
527      * message id.
528      *
529      * @param rootPkg The root package to be used for this request
530      * @param providerName The name of the current provider
531      * @param segmentName The name of the current segment
532      * @param externalLink The message id
533      * @return A List of activities containing the message id
534      */

535     private List JavaDoc lookupEMailActivity(
536         RefPackage_1_0 rootPkg,
537         String JavaDoc providerName,
538         String JavaDoc segmentName,
539         String JavaDoc externalLink
540     ) {
541         EMailFilter filter = getActivityPkg(rootPkg).createEMailFilter();
542         org.opencrx.kernel.activity1.cci.Segment activitySegment =
543             getActivitySegment(
544                 rootPkg,
545                 providerName,
546                 segmentName
547             );
548         filter.thereExistsExternalLink(
549             FilterOperators.IS_IN,
550             new String JavaDoc[]{
551                 externalLink
552             }
553         );
554         return activitySegment.getActivity(filter);
555     }
556     
557     //-----------------------------------------------------------------------
558
/**
559      * @param mimeMsg The email to be imported as openCRX EMailActivity
560      * @param rootPkg The root package to be used for this request
561      * @param emailActivity The openCRX EMailActivity currently in process
562      */

563     private void addMedia(
564         SimpleMimeMessage mimeMsg,
565         RefPackage_1_0 rootPkg,
566         EMail emailActivity
567     ) {
568         // add attachments to email
569
// if the email already contains attachments as media, only
570
// those attachments not already contained in the email
571
// are imported. This check is done by comparing the name
572
// of the attachment with the contentNames of the media.
573
if(mimeMsg.containsAttachments()) {
574             Iterator JavaDoc contentsIter = mimeMsg.getContents().iterator();
575             boolean emailContainsMedia = emailActivity.getMedia().size() > 0;
576             while (contentsIter.hasNext()) {
577                 MessageContent content = (MessageContent)contentsIter.next();
578                 if (emailContainsMedia) {
579                     Iterator JavaDoc attachments = emailActivity.getMedia().iterator();
580                     while (attachments.hasNext()) {
581                         Media attachment = (Media)attachments.next();
582                         if(content.getId() != null && content.getId().equals(attachment.getContentName())) {
583                             AppLog.trace("Attachment already linked, '"
584                                 + mimeMsg.getSubject() + "', "
585                                 + mimeMsg.getMessageID() + "', "
586                                 + content.getId());
587                         }
588                         else {
589                             // add the attachment
590
addMedia(rootPkg,emailActivity,content);
591                         }
592                     }
593                 }
594                 else {
595                     // add the attachment
596
this.addMedia(
597                         rootPkg,
598                         emailActivity,
599                         content
600                     );
601                 }
602             }
603   
604         }
605     }
606
607     // -----------------------------------------------------------------------
608
/**
609      * Imports an inbound MimeMessage as an EMail activity.
610      *
611      * @param providerName The name of the current provider
612      * @param segmentName The name of the current segment
613      * @param mimeMsg The email to be imported as openCRX EMailActivity
614      * @throws ServiceException
615      */

616     private void importSimpleMimeMessage(
617         RefPackage_1_0 rootPkg,
618         String JavaDoc providerName,
619         String JavaDoc segmentName,
620         String JavaDoc creatorCriteria,
621         SimpleMimeMessage mimeMsg
622     ) throws ServiceException {
623
624         try {
625             List JavaDoc activities = this.lookupEMailActivity(
626                 rootPkg,
627                 providerName,
628                 segmentName,
629                 mimeMsg.getMessageID()
630             );
631             if (activities.size() == 0) {
632                 AppLog.trace("create a new EMailActivity");
633       
634                 ActivityCreator emailCreator = this.getEMailCreator(
635                     rootPkg,
636                     providerName,
637                     segmentName,
638                     creatorCriteria
639                 );
640                 
641                 rootPkg.refBegin();
642                 
643                 activity1Package activityPkg = getActivityPkg(rootPkg);
644                 NewActivityParams newActParam = activityPkg.createNewActivityParams(
645                     null,
646                     null,
647                     null, // dueBy
648
mimeMsg.getSubject(),
649                     mimeMsg.getPriority(),
650                     null, // reportingContract
651
null, // scheduledEnd
652
null // scheduledStart
653
);
654                 NewActivityResult newActivityResult = emailCreator.newActivity(
655                     newActParam
656                 );
657                 rootPkg.refCommit();
658       
659                 // Update EMail activity
660
EMail emailActivity = (EMail)activityPkg.refObject(newActivityResult.getActivity().refMofId());
661                 rootPkg.refBegin();
662                 emailActivity.setMessageSubject(mimeMsg.getSubject());
663                 emailActivity.setMessageBody(mimeMsg.getBody());
664                 emailActivity.getExternalLink().clear();
665                 emailActivity.getExternalLink().add(mimeMsg.getMessageID());
666                 emailActivity.setSendDate(mimeMsg.getDate());
667                 rootPkg.refCommit();
668       
669                 // Add FROM as sender
670
String JavaDoc fromAddress = mimeMsg.getFrom()[0];
671                 List JavaDoc addresses = this.lookupEMailAddress(
672                     rootPkg,
673                     providerName,
674                     segmentName,
675                     fromAddress
676                 );
677                 EMailAddress from = null;
678                 if (addresses.size() == 1) {
679                     from = (EMailAddress) addresses.iterator().next();
680                     rootPkg.refBegin();
681                     emailActivity.setSender(from);
682                     rootPkg.refCommit();
683                 } else {
684                     AppLog.trace("lookup " + fromAddress + " finds "
685                         + addresses.size() + " addresses");
686                 }
687                 // Handle recipients
688
this.addRecipientToEMailActivity(
689                     rootPkg,
690                     providerName,
691                     segmentName,
692                     emailActivity,
693                     mimeMsg.getRecipients(),
694                     Message.RecipientType.TO
695                 );
696                 this.addRecipientToEMailActivity(
697                     rootPkg,
698                     providerName,
699                     segmentName,
700                     emailActivity,
701                     mimeMsg.getRecipients(Message.RecipientType.CC),
702                     Message.RecipientType.CC
703                 );
704                 // add originator and recipients to a note
705
this.addNote(
706                     rootPkg,
707                     emailActivity,
708                     "Recipients",
709                     this.addRecipientsAsNote(
710                         rootPkg,
711                         providerName,
712                         segmentName,
713                         mimeMsg
714                     )
715                 );
716       
717                 // add EMail headers as Note
718
this.addNote(
719                     rootPkg,
720                     emailActivity,
721                     "Message-Header",
722                     mimeMsg.getAllHeaderLinesAsString()
723                 );
724                 // Add attachments if some exist
725
this.addMedia(
726                     mimeMsg,
727                     rootPkg,
728                     emailActivity
729                 );
730             }
731             else if (activities.size() == 1) {
732               AppLog.warning(
733                   "Import of email message skipped, an email with this message id exists already, "
734                   + mimeMsg.getMessageID() + ", " + mimeMsg.getSubject());
735             }
736             else {
737                 AppLog.warning(
738                     "Import of email message skipped, found "
739                     + activities.size() + " email with this message id, "
740                     + mimeMsg.getMessageID() + ", " + mimeMsg.getSubject());
741             }
742         }
743         catch (RefException e) {
744             AppLog.info("Can not create email activity", e.getMessage());
745             throw new ServiceException(e);
746         }
747     }
748
749     //-----------------------------------------------------------------------
750
/**
751      * Adds an email recipient to the currently processed email activity if
752      * the email message contains an email address which is contained in an
753      * openCRX account. Email addresses for which no account can be found, are
754      * recorded via a note attached to the email activity.
755      *
756      * @param rootPkg The root package to be used for this request
757      * @param providerName The name of the current provider
758      * @param segmentName The name of the current segment
759      * @param emailActivity The openCRX EMailActivity currently in process
760      * @param addresses A list of addresses
761      * @param type The address type (TO, CC, BCC)
762      */

763     private void addRecipientToEMailActivity(
764         RefPackage_1_0 rootPkg,
765         String JavaDoc providerName,
766         String JavaDoc segmentName,
767         EMail emailActivity,
768         String JavaDoc[] addresses,
769         Message.RecipientType JavaDoc type
770     ) {
771         if (addresses == null || addresses.length == 0) {
772             AppLog.trace("Message does not contain any recipient of type '" + type.toString() + "'");
773         }
774         for (int i = 0; i < addresses.length; i++) {
775             String JavaDoc address = addresses[i];
776             List JavaDoc emailAddresses = this.lookupEMailAddress(
777                 rootPkg,
778                 providerName,
779                 segmentName,
780                 address
781             );
782             if(emailAddresses.size() > 0) {
783                 this.addEMailRecipient(
784                     rootPkg,
785                     emailActivity,
786                     (EMailAddress)emailAddresses.iterator().next(),
787                     type
788                 );
789             }
790         }
791     }
792     
793     //-----------------------------------------------------------------------
794
/**
795      * Formats a text containing all the addresses of the different types
796      * (i.e., TO, CC, BCC) to be attached to the email activity by a note
797      * indicating whether an account containing the email address could be
798      * found.
799      *
800      * @param rootPkg The root package to be used for this request
801      * @param providerName The name of the current provider
802      * @param segmentName The name of the current segment
803      * @param mimeMsg The email to be imported as openCRX EMailActivity
804      * @return The formatted content for the 'Recipients' note
805      */

806     private String JavaDoc addRecipientsAsNote(
807         RefPackage_1_0 rootPkg,
808         String JavaDoc providerName,
809         String JavaDoc segmentName,
810         SimpleMimeMessage mimeMsg
811     ) {
812         StringBuffer JavaDoc text = new StringBuffer JavaDoc();
813
814         // add 'FROM's to the note
815
String JavaDoc addresses[] = mimeMsg.getFrom();
816         for (int i = 0; i < addresses.length; i++) {
817             List JavaDoc emailAddresses = lookupEMailAddress(
818                 rootPkg,
819                 providerName,
820                 segmentName,
821                 addresses[i]
822             );
823             text.append("FROM: " + addresses[i] + " ["
824                 + ((emailAddresses == null || emailAddresses.size() == 0) ? "UNMATCHED" : "MATCHED") + "]\n");
825         }
826   
827         // add 'TO's to the note
828
addresses = mimeMsg.getRecipients(Message.RecipientType.TO);
829         for (int i = 0; i < addresses.length; i++) {
830             List JavaDoc emailAddresses = lookupEMailAddress(
831                 rootPkg,
832                 providerName,
833                 segmentName,
834                 addresses[i]
835             );
836             text.append("TO: " + addresses[i] + " ["
837                 + ((emailAddresses == null || emailAddresses.size() == 0) ? "UNMATCHED" : "MATCHED") + "]\n");
838         }
839   
840         // add 'CC's to the note
841
addresses = mimeMsg.getRecipients(Message.RecipientType.CC);
842         for (int i = 0; i < addresses.length; i++) {
843             List JavaDoc emailAddresses = lookupEMailAddress(
844                 rootPkg,
845                 providerName,
846                 segmentName,
847                 addresses[i]
848             );
849             text.append("CC: " + addresses[i] + " ["
850                 + ((emailAddresses == null || emailAddresses.size() == 0) ? "UNMATCHED" : "MATCHED") + "]\n");
851         }
852   
853         // add 'BCC's to the note
854
addresses = mimeMsg.getRecipients(Message.RecipientType.CC);
855         for (int i = 0; i < addresses.length; i++) {
856             List JavaDoc emailAddresses = lookupEMailAddress(
857                 rootPkg,
858                 providerName,
859                 segmentName,
860                 addresses[i]
861             );
862             text.append("BCC: " + addresses[i] + " ["
863                 + ((emailAddresses == null || emailAddresses.size() == 0) ? "UNMATCHED" : "MATCHED") + "]\n");
864         }
865         return text.toString();
866     }
867
868     //-----------------------------------------------------------------------
869
/**
870      * Adds a note to the currently processed email activity.
871      *
872      * @param rootPkg The root package to be used for this request
873      * @param emailActivity The openCRX EMailActivity currently in process
874      * @param title The note's title
875      * @param content The note's content
876      */

877     private void addNote(
878         RefPackage_1_0 rootPkg,
879         EMail emailActivity,
880         String JavaDoc title,
881         String JavaDoc content
882     ) {
883         rootPkg.refBegin();
884         Note note = getGenericPkg(rootPkg).getNoteClass().createNote();
885         emailActivity.addNote(uuidGenerator.next().toString(), note);
886         note.setTitle(title);
887         note.setText(content);
888         // 'copy' the email's owning groups
889
note.getOwningGroup().addAll(
890             emailActivity.getOwningGroup()
891         );
892         rootPkg.refCommit();
893     }
894
895     //-----------------------------------------------------------------------
896
/**
897      * Adds a Media object to the currently processed email activity with the
898      * given content. This is how attachments of email messages can be imported.
899      *
900      * @param rootPkg The root package to be used for this request
901      * @param emailActivity The openCRX EMailActivity currently in process
902      * @param content The content of the media object, e.g. an
903      * attachment
904      */

905     private void addMedia(
906         RefPackage_1_0 rootPkg,
907         EMail emailActivity,
908         MessageContent content
909     ) {
910         rootPkg.refBegin();
911         Media media = getGenericPkg(rootPkg).getMediaClass().createMedia();
912         emailActivity.addMedia(uuidGenerator.next().toString(), media);
913         String JavaDoc contentType = content.getContentType();
914         if(contentType != null && contentType.length() > 50) {
915             MimeType JavaDoc mt = null;
916             try {
917                 mt = new MimeType JavaDoc(contentType);
918                 contentType = mt.getBaseType();
919                 AppLog.trace("MimeType: " + mt.toString());
920             }
921             catch (MimeTypeParseException JavaDoc e) {
922                 // if it cannot be parsed it is likely no valid mime type, just
923
// cut off after 50 chars since otherwise the object cannot be
924
// written to the database
925
contentType = contentType.substring(0,49);
926             }
927         }
928         media.setContentName(content.getId());
929         media.setContent(content.getInputStream());
930         media.setContentMimeType(contentType);
931         if(AppLog.isTraceOn()) {
932             AppLog.trace("Media to add: " + content.toString());
933         }
934         // 'copy' the email's owning groups
935
media.getOwningGroup().addAll(
936             emailActivity.getOwningGroup()
937         );
938         rootPkg.refCommit();
939     }
940
941     //-----------------------------------------------------------------------
942
/**
943      * Creates and adds an email recipient to the currently processed email
944      * activity.
945      *
946      * @param rootPkg The root package to be used for this request
947      * @param emailActivity The openCRX EMailActivity currently in process
948      * @param address The email address object
949      * @param type The address type (TO, CC, BCC)
950      */

951     private void addEMailRecipient(
952         RefPackage_1_0 rootPkg,
953         EMail emailActivity,
954         EMailAddress address,
955         Message.RecipientType JavaDoc type
956     ) {
957         activity1Package activityPkg = getActivityPkg(rootPkg);
958         activityPkg.refBegin();
959         EMailRecipient recipient = activityPkg.getEMailRecipientClass().createEMailRecipient();
960         emailActivity.addEmailRecipient(
961             uuidGenerator.next().toString(),
962             recipient
963         );
964         recipient.setParty(address);
965         if(Message.RecipientType.TO.toString().equalsIgnoreCase(type.toString())) {
966             recipient.setPartyType(PARTY_TYPE_EMAIL_TO);
967         }
968         else if(Message.RecipientType.CC.toString().equalsIgnoreCase(type.toString())) {
969             recipient.setPartyType(PARTY_TYPE_EMAIL_CC);
970         }
971         else if(Message.RecipientType.BCC.toString().equalsIgnoreCase(type.toString())) {
972             recipient.setPartyType(PARTY_TYPE_EMAIL_BCC);
973         }
974         // 'copy' the email's owning groups
975
recipient.getOwningGroup().addAll(
976             emailActivity.getOwningGroup()
977         );
978         activityPkg.refCommit();
979     }
980
981     //-----------------------------------------------------------------------
982
/**
983      * Search the appropriate ActivityCreator according to the email message.
984      * Currently only the default inbound email creator is active. If no
985      * creator can be found a new default one is created.
986      *
987      * @param rootPkg The root package to be used for this request
988      * @param providerName The name of the current provider
989      * @param segmentName The name of the current segment
990      * @param message The email to be imported as openCRX EMailActivity
991      */

992     private ActivityCreator getEMailCreator(
993         RefPackage_1_0 rootPkg,
994         String JavaDoc providerName,
995         String JavaDoc segmentName,
996         String JavaDoc criteria
997     ) {
998         try {
999             org.opencrx.kernel.activity1.cci.activity1Package activityPkg = getActivityPkg(
1000                rootPkg
1001            );
1002            org.opencrx.kernel.activity1.cci.Segment activitySegment = getActivitySegment(
1003                rootPkg,
1004                providerName,
1005                segmentName
1006            );
1007            
1008            ActivityCreator emailCreator = null;
1009            // Try to get activity creator which's name matches the message subject
1010
ActivityCreatorFilter filter = activityPkg.createActivityCreatorFilter();
1011            filter.thereExistsName(
1012                FilterOperators.IS_LIKE,
1013                new String JavaDoc[]{criteria}
1014            );
1015            for(Iterator JavaDoc i = activitySegment.getActivityCreator(filter).iterator(); i.hasNext(); ) {
1016                ActivityCreator creator = (ActivityCreator)i.next();
1017                if((creator.getActivityType() != null) && (creator.getActivityType().getActivityClass() == ACTIVITY_CLASS_EMAIL)) {
1018                    emailCreator = creator;
1019                    break;
1020                }
1021            }
1022            // If not found get default creator for inbound email activities.
1023
if(emailCreator == null) {
1024                emailCreator = activitySegment.getActivityCreator(DEFAULT_EMAIL_CREATOR_ID);
1025            }
1026            return emailCreator;
1027        }
1028        catch(Exception JavaDoc e) {
1029            AppLog.info("Can not retrieve config from external task configuration", e.getMessage());
1030        }
1031        return null;
1032    }
1033    
1034    //-----------------------------------------------------------------------
1035
/**
1036     * Import the EMails attached / embedded to message
1037     *
1038     * @param providerName The name of the current provider
1039     * @param segmentName The name of the current segment
1040     * @param message The email to be imported as openCRX EMailActivity
1041     * @throws ServiceException
1042     */

1043    private void importNestedMessages(
1044        RefPackage_1_0 rootPkg,
1045        String JavaDoc providerName,
1046        String JavaDoc segmentName,
1047        SimpleMimeMessage message
1048    ) {
1049        AppLog.trace("Importing Message (" + providerName + "/" + segmentName + "): " + message.toString());
1050        try {
1051            // attachments not of type SimpleMimeMessage are ignored
1052
AppLog.trace("Import email activities based on the mail attachments");
1053            if (message.containsNestedMessage()) {
1054                AppLog.trace("Create new EMail activities for nested email messages");
1055                for(Iterator JavaDoc i = message.getBinaryContents().iterator(); i.hasNext(); ) {
1056                    MessageContent content = (MessageContent)i.next();
1057                    if(content.getContent() instanceof SimpleMimeMessage) {
1058                        this.importSimpleMimeMessage(
1059                            rootPkg,
1060                            providerName,
1061                            segmentName,
1062                            message.getSubject(),
1063                            (SimpleMimeMessage)content.getContent()
1064                        );
1065                    }
1066                }
1067            }
1068            else {
1069                AppLog.trace("Email does not contain any nested email message, ignore it");
1070            }
1071        }
1072        catch (ServiceException e) {
1073            AppLog.warning("Error importing EmailActivity", e);
1074        }
1075    }
1076
1077    //-----------------------------------------------------------------------
1078
/**
1079     * Import the emails by using the appropriate ActivityCreator according to
1080     * the email messages.
1081     *
1082     * @param providerName The name of the current provider
1083     * @param segmentName The name of the current segment
1084     * @throws IOException
1085     */

1086    protected void importMessages(
1087        String JavaDoc providerName,
1088        String JavaDoc segmentName
1089    ) throws IOException JavaDoc {
1090        try {
1091            RefPackage_1_0 rootPkg = this.createDataPkg(
1092                new ServiceHeader(SecurityKeys.ADMIN_PRINCIPAL + SecurityKeys.ID_SEPARATOR + segmentName, null, false, new QualityOfService())
1093            );
1094            WorkflowControllerServlet.initWorkflows(
1095                rootPkg,
1096                providerName,
1097                segmentName
1098            );
1099            this.initEMailCreator(
1100                rootPkg,
1101                providerName,
1102                segmentName
1103            );
1104            MailServerConfig config = new MailServerConfig(
1105                rootPkg,
1106                providerName,
1107                segmentName,
1108                this.getServletContext()
1109            );
1110            MailStore mailStore = new MailStore(config);
1111            mailStore.openStore();
1112            mailStore.openFolder(
1113                config.getMailbox()
1114            );
1115            SimpleMimeMessage[] messages = mailStore.getMessages();
1116            for (int i = 0; i < messages.length; i++) {
1117               this.importNestedMessages(
1118                   rootPkg,
1119                   providerName,
1120                   segmentName,
1121                   messages[i]
1122               );
1123               if(config.deleteImportedMessages()) {
1124                   messages[i].markAsDeleted();
1125               }
1126            }
1127            mailStore.closeFolder();
1128            mailStore.closeStore();
1129        }
1130        catch (ServiceException e) {
1131            AppLog.warning(new Date JavaDoc() + ": openCRX/EMailImporter: " + providerName + "/" + segmentName + ": exception occured " + e.getMessage() + ". Continuing");
1132            new ServiceException(e).log();
1133        }
1134    }
1135
1136    //-----------------------------------------------------------------------
1137
/**
1138     * Process an email import request.
1139     *
1140     * @param req The servlet request
1141     * @param res The servlet response
1142     * @throws ServletException
1143     * @throws IOException
1144     */

1145    protected void handleRequest(
1146        HttpServletRequest JavaDoc req,
1147        HttpServletResponse JavaDoc res
1148    ) throws ServletException JavaDoc, IOException JavaDoc {
1149        String JavaDoc segmentName = req.getParameter("segment");
1150        String JavaDoc providerName = req.getParameter("provider");
1151        String JavaDoc id = providerName + "/" + segmentName;
1152        // run
1153
if(
1154            COMMAND_EXECUTE.equals(req.getPathInfo()) &&
1155            !this.runningSegments.contains(id)
1156        ) {
1157            try {
1158                this.runningSegments.add(id);
1159                this.importMessages(
1160                    providerName,
1161                    segmentName
1162                );
1163            }
1164            catch(Exception JavaDoc e) {
1165                new ServiceException(e).log();
1166            }
1167            finally {
1168                this.runningSegments.remove(id);
1169            }
1170        }
1171    }
1172
1173    //-----------------------------------------------------------------------
1174
/* (non-Javadoc)
1175     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
1176     */

1177    protected void doGet(
1178        HttpServletRequest JavaDoc req,
1179        HttpServletResponse JavaDoc res
1180    ) throws ServletException JavaDoc, IOException JavaDoc {
1181        res.setStatus(HttpServletResponse.SC_OK);
1182        res.flushBuffer();
1183        this.handleRequest(
1184            req,
1185            res
1186        );
1187    }
1188        
1189    //-----------------------------------------------------------------------
1190
/* (non-Javadoc)
1191     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
1192     */

1193    protected void doPost(
1194        HttpServletRequest JavaDoc req,
1195        HttpServletResponse JavaDoc res
1196    ) throws ServletException JavaDoc, IOException JavaDoc {
1197        res.setStatus(HttpServletResponse.SC_OK);
1198        res.flushBuffer();
1199        this.handleRequest(
1200            req,
1201            res
1202        );
1203    }
1204
1205    //-----------------------------------------------------------------------
1206
// Members
1207
//-----------------------------------------------------------------------
1208
private static final long serialVersionUID = -7260829387268368633L;
1209    
1210    private static final short PARTY_TYPE_EMAIL_TO = 220;
1211    private static final short PARTY_TYPE_EMAIL_CC = 230;
1212    private static final short PARTY_TYPE_EMAIL_BCC = 240;
1213    
1214    private static final short ACTIVITY_CLASS_EMAIL = 0;
1215    
1216    private static final String JavaDoc COMMAND_EXECUTE = "/execute";
1217    private static final String JavaDoc DEFAULT_EMAIL_CREATOR_ID = "EMailCreator";
1218    
1219    private static final UUIDGenerator uuidGenerator = UUIDs.getGenerator();
1220
1221    private Dataprovider_1_1Connection connectionData = null;
1222
1223    private final List JavaDoc runningSegments = new ArrayList JavaDoc();
1224
1225}
1226
1227// --- End of File -----------------------------------------------------------
1228
Popular Tags