View Javadoc
1   /*
2    * Copyright (c) 2002-2014, Mairie de Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.plugins.crm.modules.form.service.draft;
35  
36  import java.io.IOException;
37  import java.io.InputStream;
38  import java.util.ArrayList;
39  import java.util.HashMap;
40  import java.util.List;
41  import java.util.Map;
42  import java.util.Map.Entry;
43  
44  import javax.inject.Inject;
45  import javax.servlet.http.HttpServletRequest;
46  import javax.servlet.http.HttpSession;
47  
48  import net.sf.json.JSONObject;
49  
50  import org.apache.commons.fileupload.FileItem;
51  import org.apache.commons.io.IOUtils;
52  import org.apache.commons.lang.StringUtils;
53  import org.apache.log4j.Logger;
54  
55  import fr.paris.lutece.plugins.blobstore.service.BlobStoreFileItem;
56  import fr.paris.lutece.plugins.blobstore.service.IBlobStoreService;
57  import fr.paris.lutece.plugins.blobstore.service.NoSuchBlobException;
58  import fr.paris.lutece.plugins.crm.modules.form.service.CRMParametersService;
59  import fr.paris.lutece.plugins.crm.modules.form.service.ICRMParametersService;
60  import fr.paris.lutece.plugins.crm.modules.form.util.Constants;
61  import fr.paris.lutece.plugins.crm.modules.form.util.JSONUtils;
62  import fr.paris.lutece.plugins.crmclient.service.ICRMClientService;
63  import fr.paris.lutece.plugins.crmclient.service.authenticator.IAuthenticatorService;
64  import fr.paris.lutece.plugins.crmclient.util.CRMException;
65  import fr.paris.lutece.plugins.crmclient.util.CrmClientConstants;
66  import fr.paris.lutece.plugins.form.business.Form;
67  import fr.paris.lutece.plugins.form.business.FormSubmit;
68  import fr.paris.lutece.plugins.form.service.draft.DraftBackupService;
69  import fr.paris.lutece.plugins.form.service.upload.FormAsynchronousUploadHandler;
70  import fr.paris.lutece.plugins.form.utils.FormUtils;
71  import fr.paris.lutece.plugins.genericattributes.business.Response;
72  import fr.paris.lutece.plugins.genericattributes.service.entrytype.IEntryTypeService;
73  import fr.paris.lutece.portal.service.i18n.I18nService;
74  import fr.paris.lutece.portal.service.message.SiteMessage;
75  import fr.paris.lutece.portal.service.message.SiteMessageException;
76  import fr.paris.lutece.portal.service.message.SiteMessageService;
77  import fr.paris.lutece.portal.service.security.LuteceUser;
78  import fr.paris.lutece.portal.service.security.SecurityService;
79  import fr.paris.lutece.portal.service.util.AppException;
80  import fr.paris.lutece.portal.service.util.AppLogService;
81  
82  
83  /**
84   * CRM Draft Backup Service
85   */
86  public class CRMDraftBackupService implements DraftBackupService
87  {
88      private static Logger _logger = Logger.getLogger( "lutece.crm" );
89      private IBlobStoreService _blobStoreService;
90      @Inject
91      private ICRMParametersService _crmParametersService;
92      @Inject
93      private ICRMClientService _crmClientService;
94      @Inject
95      private IAuthenticatorService _authenticatorService;
96  
97      /**
98       * Set the blobstore service of this draft backup service
99       * @param blobStoreService The blobstore service
100      */
101     public void setBlobStoreService( IBlobStoreService blobStoreService )
102     {
103         _blobStoreService = blobStoreService;
104     }
105 
106     /**
107      * {@inheritDoc}
108      */
109     @Override
110     public boolean preProcessRequest( HttpServletRequest request, Form form ) throws SiteMessageException
111     {
112         if ( !isRequestAuthenticated( request, form ) )
113         {
114 
115             SiteMessageService.setMessage( request, Constants.PROPERTY_MESSAGE_STOP_ACCESS_DENIED,
116                     SiteMessage.TYPE_STOP );
117 
118         }
119 
120         // handle delete actions
121         if ( draftAction( request ) )
122         {
123             return true;
124         }
125 
126         //update session attributes 
127         if ( !StringUtils.isEmpty( request.getParameter( Constants.PARAM_ID_DEMAND ) ) )
128         {
129             updateSessionAttributes( request, form );
130         }
131 
132         // create if the draft does not exist
133         else if ( !existsDraft( request, form ) )
134         {
135             create( request, form );
136         }
137 
138         restore( request );
139 
140         return false;
141     }
142 
143     /**
144      * {@inheritDoc}
145      */
146     @Override
147     public void saveDraft( HttpServletRequest request, Form form ) throws SiteMessageException
148     {
149         if ( _logger.isDebugEnabled( ) )
150         {
151             _logger.debug( "Saving Draft ..." );
152         }
153 
154         HttpSession session = request.getSession( true );
155 
156         saveResponses( FormUtils.getResponses( session ), form.getIdForm( ), session );
157 
158         updateCRMStatus( request );
159     }
160 
161     /**
162      * Updates the CRM status to "in progress".
163      * @param request the request
164      */
165     private void updateCRMStatus( HttpServletRequest request )
166     {
167         HttpSession session = request.getSession( );
168 
169         // get draft blob id
170         String strKey = (String) session.getAttribute( Constants.SESSION_ATTRIBUTE_DEMAND_DATA_PARAMS );
171         String strIdDemand = (String) session.getAttribute( Constants.SESSION_ATTRIBUTE_ID_DEMAND_PARAMS );
172         String strCrmWebAppCode = (String) session
173                 .getAttribute( Constants.SESSION_ATTRIBUTE_DEMAND_CRM_WEBB_APP_CODE_PARAMS );
174         String strStatusText = I18nService.getLocalizedString( Constants.PROPERTY_CRM_STATUS_TEXT_MODIF,
175                 request.getLocale( ) );
176 
177         if ( StringUtils.isNotBlank( strKey ) )
178         {
179             try
180             {
181                 _crmClientService.sendUpdateDemand( strIdDemand, strStatusText, strCrmWebAppCode,
182                         CrmClientConstants.CRM_STATUS_DRAFT, strKey );
183 
184             }
185             catch ( CRMException e )
186             {
187                 AppLogService.error( e );
188             }
189         }
190         else
191         {
192             _logger.error( "No draft found" );
193         }
194     }
195 
196     /**
197      * Saves the responses
198      * @param mapResponses map response
199      * @param nIdForm the id form
200      * @param session the session
201      */
202     public void saveResponses( Map<Integer, List<Response>> mapResponses, int nIdForm, HttpSession session )
203     {
204         // get draft blob id
205         String strKey = (String) session.getAttribute( Constants.SESSION_ATTRIBUTE_DEMAND_DATA_PARAMS );
206 
207         if ( StringUtils.isNotBlank( strKey ) )
208         {
209             storeFiles( mapResponses, session );
210 
211             String strJsonResponse = JSONUtils.buildJson( mapResponses, nIdForm, session );
212             _blobStoreService.update( strKey, strJsonResponse.getBytes( ) );
213         }
214     }
215 
216     /**
217      * {@inheritDoc}
218      */
219     @Override
220     public void saveDraft( HttpServletRequest request, FormSubmit formSubmit )
221     {
222         if ( _logger.isDebugEnabled( ) )
223         {
224             _logger.debug( "Saving formsubmit ..." );
225         }
226 
227         HttpSession session = request.getSession( true );
228 
229         // build the map response
230         Map<Integer, List<Response>> mapResponses = new HashMap<Integer, List<Response>>( );
231 
232         for ( Response response : formSubmit.getListResponse( ) )
233         {
234             int nIdEntry = response.getEntry( ).getIdEntry( );
235             List<Response> listResponseEntry = mapResponses.get( nIdEntry );
236 
237             if ( listResponseEntry == null )
238             {
239                 listResponseEntry = new ArrayList<Response>( );
240                 mapResponses.put( nIdEntry, listResponseEntry );
241             }
242 
243             listResponseEntry.add( response );
244         }
245 
246         saveResponses( mapResponses, formSubmit.getForm( ).getIdForm( ), session );
247 
248         updateCRMStatus( request );
249     }
250 
251     /**
252      * {@inheritDoc}
253      */
254     @Override
255     public void validateDraft( HttpServletRequest request, Form form )
256     {
257         if ( _logger.isDebugEnabled( ) )
258         {
259             _logger.debug( "Validating Draft ..." );
260         }
261 
262         HttpSession session = request.getSession( true );
263 
264         String strKey = (String) session.getAttribute( Constants.SESSION_ATTRIBUTE_DEMAND_DATA_PARAMS );
265         String strDemandId = (String) session.getAttribute( Constants.SESSION_ATTRIBUTE_ID_DEMAND_PARAMS );
266         String strCrmWebAppCode = (String) session
267                 .getAttribute( Constants.SESSION_ATTRIBUTE_DEMAND_CRM_WEBB_APP_CODE_PARAMS );
268 
269         if ( StringUtils.isNotBlank( strKey ) )
270         {
271             String strStatusText = I18nService.getLocalizedString( Constants.PROPERTY_CRM_STATUS_TEXT_VALIDATE,
272                     request.getLocale( ) );
273 
274             try
275             {
276                 _crmClientService.sendUpdateDemand( strDemandId, strStatusText, strCrmWebAppCode,
277                         CrmClientConstants.CRM_STATUS_VALIDATED, strKey );
278 
279             }
280             catch ( CRMException e )
281             {
282                 AppLogService.error( e );
283             }
284             byte[] dataForm = _blobStoreService.getBlob( strKey );
285 
286             if ( dataForm != null )
287             {
288                 String strDataForm = new String( dataForm );
289                 deleteFiles( strDataForm );
290             }
291 
292             _blobStoreService.delete( strKey );
293 
294             // Remove session attributes
295             removeSessionAttributes( session );
296 
297         }
298     }
299 
300     /**
301      * Check if the draft exists
302      * @param request the HTTP request
303      * @param form The form
304      * @return true if the draft already exists, false otherwise
305      */
306     private boolean existsDraft( HttpServletRequest request, Form form )
307     {
308 
309         if ( request.getParameter( Constants.PARAM_DEMAND_DATA ) != null )
310         {
311             return true;
312         }
313 
314         return false;
315 
316     }
317 
318     /**
319      * Stores all file for the subform to BlobStore and replaces
320      * {@link FileItem} by {@link BlobStoreFileItem}
321      * @param mapResponses the map of <id_entry,Responses>
322      * @param session the session
323      */
324     private void storeFiles( Map<Integer, List<Response>> mapResponses, HttpSession session )
325     {
326         for ( Entry<Integer, List<Response>> entryMap : mapResponses.entrySet( ) )
327         {
328             int nIdEntry = entryMap.getKey( );
329             String strIdEntry = Integer.toString( nIdEntry );
330             List<FileItem> uploadedFiles = FormAsynchronousUploadHandler.getHandler( ).getListUploadedFiles( IEntryTypeService.PREFIX_ATTRIBUTE + strIdEntry,
331                     session);
332 
333             if ( uploadedFiles != null )
334             {
335                 List<FileItem> listBlobStoreFileItems = new ArrayList<FileItem>( );
336 
337                 for ( int nIndex = 0; nIndex < uploadedFiles.size( ); nIndex++ )
338                 {
339                     FileItem fileItem = uploadedFiles.get( nIndex );
340                     String strFileName = fileItem.getName( );
341 
342                     if ( !( fileItem instanceof BlobStoreFileItem ) )
343                     {
344                         // file is not blobstored yet
345                         String strFileBlobId;
346                         InputStream is = null;
347 
348                         try
349                         {
350                             is = fileItem.getInputStream( );
351                             strFileBlobId = _blobStoreService.storeInputStream( is );
352                         }
353                         catch ( IOException e1 )
354                         {
355                             IOUtils.closeQuietly( is );
356                             _logger.error( e1.getMessage( ), e1 );
357                             throw new AppException( e1.getMessage( ), e1 );
358                         }
359 
360                         String strJSON = BlobStoreFileItem.buildFileMetadata( strFileName, fileItem.getSize( ),
361                                 strFileBlobId, fileItem.getContentType( ) );
362 
363                         if ( _logger.isDebugEnabled( ) )
364                         {
365                             _logger.debug( "Storing " + fileItem.getName( ) + " with : " + strJSON );
366                         }
367 
368                         String strFileMetadataBlobId = _blobStoreService.store( strJSON.getBytes( ) );
369 
370                         try
371                         {
372                             BlobStoreFileItem blobStoreFileItem = new BlobStoreFileItem( strFileMetadataBlobId,
373                                     _blobStoreService );
374                             listBlobStoreFileItems.add( blobStoreFileItem );
375                         }
376                         catch ( NoSuchBlobException nsbe )
377                         {
378                             // nothing to do, blob is deleted and draft is not up to date.
379                             if ( _logger.isDebugEnabled( ) )
380                             {
381                                 _logger.debug( nsbe.getMessage( ) );
382                             }
383                         }
384                         catch ( Exception e )
385                         {
386                             _logger.error( "Unable to create new BlobStoreFileItem " + e.getMessage( ), e );
387                             throw new AppException( e.getMessage( ), e );
388                         }
389                     }
390                     else
391                     {
392                         // nothing to do
393                         listBlobStoreFileItems.add( fileItem );
394                     }
395                 }
396 
397                 // replace current file list with the new one
398                 uploadedFiles.clear( );
399                 uploadedFiles.addAll( listBlobStoreFileItems );
400             }
401         }
402     }
403 
404     /**
405      * Create a draft
406      * @param request the HTTP request
407      * @param form the form
408      */
409     private void create( HttpServletRequest request, Form form )
410     {
411         HttpSession session = request.getSession( true );
412 
413         String strDemandType = _crmParametersService.getIdTypeDemande( request, form );
414         String strCrmWebAppCode = _crmParametersService.getCrmWebAppCode( request, form );
415 
416         if ( StringUtils.isNotBlank( strDemandType ) )
417         {
418             JSONObject json = new JSONObject( );
419             json.element( JSONUtils.JSON_KEY_ID_FORM, form.getIdForm( ) );
420 
421             // the data is only the key - no need to store any other data
422             String strData = _blobStoreService.store( json.toString( ).getBytes( ) );
423 
424             try
425             {
426                 // save user info and demand to CRM
427                 String strIdCRMUser = request.getParameter( Constants.PARAM_ID_CRM_USER );
428                 String strUserGuid = StringUtils.EMPTY;
429                 String strIdDemand = StringUtils.EMPTY;
430 
431                 if ( StringUtils.isBlank( strIdCRMUser ) && SecurityService.isAuthenticationEnable( ) )
432                 {
433                     LuteceUser user = SecurityService.getInstance( ).getRemoteUser( request );
434 
435                     if ( user != null )
436                     {
437                         strUserGuid = user.getName( );
438                     }
439                 }
440 
441                 String strStatusText = I18nService.getLocalizedString( Constants.PROPERTY_CRM_STATUS_TEXT_NEW,
442                         request.getLocale( ) );
443 
444                 if ( StringUtils.isNotBlank( strUserGuid ) )
445                 {
446                     strIdDemand = _crmClientService.sendCreateDemandByUserGuid( strDemandType, strUserGuid,
447                             CrmClientConstants.CRM_STATUS_DRAFT, strStatusText, strData, strCrmWebAppCode );
448 
449                 }
450                 else if ( StringUtils.isNotBlank( strIdCRMUser ) )
451                 {
452                     strIdDemand = _crmClientService.sendCreateDemandByIdCRMUser( strDemandType, strIdCRMUser,
453                             CrmClientConstants.CRM_STATUS_DRAFT, strStatusText, strData, strCrmWebAppCode );
454                 }
455 
456                 if ( StringUtils.isNotBlank( strIdDemand ) && !Constants.INVALID_ID.equals( strIdDemand ) )
457                 {
458 
459                     try
460                     {
461                         strUserGuid = _crmClientService.getUserGuidFromIdDemand( strIdDemand, strCrmWebAppCode );
462                     }
463                     catch ( CRMException ex )
464                     {
465                         _logger.error( "Error calling WebService : " + ex.getMessage( ), ex );
466                     }
467                     updateSessionAttributes( session, strIdDemand, strData, strUserGuid, strCrmWebAppCode );
468                 }
469                 else
470                 {
471                     throw new Exception( "Invalid ID demand" );
472                 }
473             }
474             catch ( Exception e )
475             {
476                 _logger.error( "Error calling WebService : " + e.getMessage( ), e );
477 
478                 // Remove the blob created previously
479                 _blobStoreService.delete( strData );
480             }
481         }
482     }
483 
484     /**
485      * Restore a draft
486      * @param request the HTTP request
487      */
488     private void restore( HttpServletRequest request )
489     {
490         if ( _logger.isDebugEnabled( ) )
491         {
492             _logger.debug( "Restoring Draft ..." );
493         }
494 
495         HttpSession session = request.getSession( true );
496 
497         String strData = ( (String) session.getAttribute( Constants.SESSION_ATTRIBUTE_DEMAND_DATA_PARAMS ) );
498 
499         if ( StringUtils.isNotBlank( strData ) )
500         {
501             byte[] dataForm = _blobStoreService.getBlob( strData );
502 
503             if ( dataForm != null )
504             {
505                 String strDataForm = new String( dataForm );
506 
507                 if ( StringUtils.isNotBlank( strDataForm ) )
508                 {
509                     // bind responses to session if jsonresponse has content - use default otherwise.
510                     Map<Integer, List<Response>> mapResponses = JSONUtils.buildListResponses( strDataForm,
511                             request.getLocale( ), session );
512 
513                     if ( mapResponses != null )
514                     {
515                         if ( _logger.isDebugEnabled( ) )
516                         {
517                             _logger.debug( "Found reponses - restoring form" );
518                         }
519 
520                         FormUtils.restoreResponses( session, mapResponses );
521 
522                         for ( Entry<Integer, List<Response>> entryMap : mapResponses.entrySet( ) )
523                         {
524                             int nIdEntry = entryMap.getKey( );
525                             List<String> listBlobIds = JSONUtils.getBlobIds( strDataForm, nIdEntry );
526 
527                             if ( ( listBlobIds != null ) && !listBlobIds.isEmpty( ) )
528                             {
529                                 for ( String strBlobId : listBlobIds )
530                                 {
531                                     FileItem fileItem;
532 
533                                     try
534                                     {
535                                         fileItem = new BlobStoreFileItem( strBlobId, _blobStoreService );
536                                         
537                                         FormAsynchronousUploadHandler.getHandler(  )
538                                         .addFileItemToUploadedFilesList( fileItem,
539                                         		IEntryTypeService.PREFIX_ATTRIBUTE + Integer.toString( nIdEntry ), request );
540                                        
541                                     }
542                                     catch ( NoSuchBlobException nsbe )
543                                     {
544                                         // file might be deleted
545                                         _logger.debug( nsbe.getMessage( ) );
546                                     }
547                                     catch ( Exception e )
548                                     {
549                                         throw new AppException( "Unable to parse JSON file metadata for blob id "
550                                                 + strBlobId + " : " + e.getMessage( ), e );
551                                     }
552                                 }
553                             }
554                         }
555                     }
556                 }
557             }
558         }
559         else
560         {
561             AppLogService.error( "No blob id found for the current session" );
562         }
563     }
564 
565     /**
566      * Delete a draft
567      * @param request the HTTP request
568      * @return <code>true</code> if an error occurs, <code>false</code>
569      *         otherwise
570      */
571     private boolean delete( HttpServletRequest request )
572     {
573         if ( _logger.isDebugEnabled( ) )
574         {
575             _logger.debug( "Deleting Draft ..." );
576         }
577 
578         boolean bHasError = false;
579 
580         String strIdDemand = request.getParameter( Constants.PARAM_ID_DEMAND );
581         String strData = request.getParameter( Constants.PARAM_DEMAND_DATA );
582         String strCrmWebAppCode = request.getParameter( Constants.PARAM_CRM_WEBB_APP_CODE );
583 
584         if ( StringUtils.isNotBlank( strIdDemand ) && StringUtils.isNumeric( strIdDemand )
585                 && StringUtils.isNotBlank( strData ) )
586         {
587             try
588             {
589                 // Delete the demand in CRM
590                 _crmClientService.sendDeleteDemand( strIdDemand, strCrmWebAppCode );
591 
592                 byte[] dataForm = _blobStoreService.getBlob( strData );
593 
594                 if ( dataForm != null )
595                 {
596                     String strDataForm = new String( dataForm );
597                     deleteFiles( strDataForm );
598                 }
599 
600                 // Delete the demand in Blobstore
601                 _blobStoreService.delete( strData );
602             }
603             catch ( CRMException ex )
604             {
605                 _logger.error( "Error deleting draft : " + ex.getMessage( ), ex );
606                 bHasError = true;
607             }
608         }
609         else
610         {
611             bHasError = true;
612         }
613 
614         return bHasError;
615     }
616 
617     /**
618      * Removes all files stored in blobstore for the current subform and
619      * strJsonFields.
620      * @param strDataForm the data form
621      */
622     private void deleteFiles( String strDataForm )
623     {
624         List<String> listBlobIds = JSONUtils.getBlobIds( strDataForm );
625 
626         if ( ( listBlobIds != null ) && !listBlobIds.isEmpty( ) )
627         {
628             for ( String strBlobId : listBlobIds )
629             {
630                 FileItem fileItem;
631 
632                 try
633                 {
634                     fileItem = new BlobStoreFileItem( strBlobId, _blobStoreService );
635 
636                     if ( _logger.isDebugEnabled( ) )
637                     {
638                         _logger.debug( "Removing file " + fileItem.getName( ) );
639                     }
640 
641                     fileItem.delete( );
642                 }
643                 catch ( NoSuchBlobException nsbe )
644                 {
645                     // file might be deleted
646                     if ( _logger.isDebugEnabled( ) )
647                     {
648                         _logger.debug( nsbe.getMessage( ) );
649                     }
650                 }
651                 catch ( Exception e )
652                 {
653                     throw new AppException( "Unable to parse JSON file metadata for blob id " + strBlobId + " : "
654                             + e.getMessage( ), e );
655                 }
656             }
657         }
658     }
659 
660     /**
661      * Do draft action
662      * @param request the HTTP request
663      * @return true if there is an draft action, false otherwise
664      * @throws SiteMessageException message exception if remove draft
665      */
666     private boolean draftAction( HttpServletRequest request ) throws SiteMessageException
667     {
668         String strAction = request.getParameter( Constants.PARAMETER_ACTION_NAME );
669 
670         if ( StringUtils.isNotBlank( strAction ) )
671         {
672             if ( Constants.ACTION_DO_REMOVE_DRAFT.equals( strAction ) )
673             {
674                 doRemoveDraft( request );
675             }
676             else if ( Constants.ACTION_REMOVE_DRAFT.equals( strAction ) )
677             {
678                 removeDraft( request );
679             }
680 
681             return true;
682         }
683 
684         return false;
685     }
686 
687     /**
688      * Do remove a demand by calling the DraftBackUpService
689      * @param request The HTTP request
690      */
691     private void doRemoveDraft( HttpServletRequest request )
692     {
693         delete( request );
694     }
695 
696     /**
697      * Remove a draft and display a message saying the draft has or not been
698      * deleted
699      * @param request The HTTP request
700      * @throws SiteMessageException the message exception
701      */
702     private void removeDraft( HttpServletRequest request ) throws SiteMessageException
703     {
704         String strUrlReturn = request.getParameter( Constants.PARAMETER_URL_RETURN );
705 
706         if ( StringUtils.isNotBlank( strUrlReturn ) )
707         {
708             if ( delete( request ) )
709             {
710                 SiteMessageService.setMessage( request, Constants.PROPERTY_MESSAGE_ERROR_CALLING_WS,
711                         SiteMessage.TYPE_ERROR, strUrlReturn );
712             }
713             else
714             {
715                 SiteMessageService.setMessage( request, Constants.PROPERTY_MESSAGE_INFO_REMOVE_DEMAND,
716                         SiteMessage.TYPE_INFO, strUrlReturn );
717             }
718         }
719     }
720 
721     /**
722      * Check if the request is authenticated
723      * @param request the HTTP request
724      * @return true if it is authenticated, false otherwise
725      */
726     private boolean isRequestAuthenticated( HttpServletRequest request, Form form )
727     {
728         boolean bIsAuthenticated = true;
729         String strDemandType = _crmParametersService.getIdTypeDemande( request, form );
730         String strCrmWebAppCode = _crmParametersService.getCrmWebAppCode( request, form );
731         String strDemand = request.getParameter( Constants.PARAM_ID_DEMAND );
732         String strAction = request.getParameter( Constants.PARAMETER_ACTION_NAME );
733         if ( StringUtils.isNotBlank( strAction ) && Constants.ACTION_DO_REMOVE_DRAFT.equals( strAction ) )
734         {
735 
736             bIsAuthenticated = _authenticatorService.getRequestAuthenticatorForWs( strCrmWebAppCode )
737                     .isRequestAuthenticated( request );
738         }
739         else if ( !_crmParametersService.isEnabledLocalCrmParameters( )
740                 && ( StringUtils.isNotBlank( strDemandType ) || StringUtils.isNotBlank( strDemand ) )
741                 || ( StringUtils.isNotBlank( strAction ) && Constants.ACTION_REMOVE_DRAFT.equals( strAction ) ) )
742         {
743             bIsAuthenticated = _authenticatorService.getRequestAuthenticatorForUrl( strCrmWebAppCode )
744                     .isRequestAuthenticated( request );
745         }
746 
747         return bIsAuthenticated;
748     }
749 
750     /**
751      * Update session attributes
752      * @param request the HTTP request
753      * @param form the form object
754      * 
755      */
756     private void updateSessionAttributes( HttpServletRequest request, Form form )
757     {
758         HttpSession session = request.getSession( true );
759         String strIdDemand = request.getParameter( Constants.PARAM_ID_DEMAND );
760         String strCrmWebAppCode = _crmParametersService.getCrmWebAppCode( request, form );
761         String strUserGuid = null;
762         try
763         {
764             strUserGuid = _crmClientService.getUserGuidFromIdDemand( strIdDemand, strCrmWebAppCode );
765         }
766         catch ( CRMException ex )
767         {
768             _logger.error( "Error calling WebService : " + ex.getMessage( ), ex );
769         }
770 
771         String strDemandData = request.getParameter( Constants.PARAM_DEMAND_DATA );
772         updateSessionAttributes( session, strIdDemand, strDemandData, strUserGuid, strCrmWebAppCode );
773     }
774 
775     /**
776      * Update session attributes
777      * @param session the Http session
778      * @param strIdDemand the demand id
779      * @param strDemandData the demad data
780      * @param strUserGuid the user guid
781      * @param strCrmWebAppCode the web app code
782      */
783     private void updateSessionAttributes( HttpSession session, String strIdDemand, String strDemandData,
784             String strUserGuid, String strCrmWebAppCode )
785     {
786         if ( !StringUtils.isEmpty( strIdDemand ) )
787         {
788             session.setAttribute( Constants.SESSION_ATTRIBUTE_ID_DEMAND_PARAMS, strIdDemand );
789         }
790         if ( !StringUtils.isEmpty( strDemandData ) )
791         {
792             session.setAttribute( Constants.SESSION_ATTRIBUTE_DEMAND_DATA_PARAMS, strDemandData );
793         }
794         if ( !StringUtils.isEmpty( strUserGuid ) )
795         {
796             session.setAttribute( Constants.SESSION_ATTRIBUTE_USER_GUID_PARAMS, strUserGuid );
797         }
798         if ( !StringUtils.isEmpty( strCrmWebAppCode ) )
799         {
800             session.setAttribute( Constants.SESSION_ATTRIBUTE_DEMAND_CRM_WEBB_APP_CODE_PARAMS, strCrmWebAppCode );
801         }
802     }
803 
804     /**
805      * Remove the session attributes
806      * @param session the session
807      */
808     private void removeSessionAttributes( HttpSession session )
809     {
810         session.removeAttribute( Constants.SESSION_ATTRIBUTE_ID_DEMAND_PARAMS );
811         session.removeAttribute( Constants.SESSION_ATTRIBUTE_DEMAND_DATA_PARAMS );
812         session.removeAttribute( Constants.SESSION_ATTRIBUTE_DEMAND_CRM_WEBB_APP_CODE_PARAMS );
813         session.removeAttribute( Constants.SESSION_ATTRIBUTE_USER_GUID_PARAMS );
814     }
815 
816     /**
817      * set _crmParametersService
818      * @param _crmParametersService _crmParametersService
819      */
820     public void setCrmParametersService( CRMParametersService crmParametersService )
821     {
822         this._crmParametersService = crmParametersService;
823     }
824 
825 }