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.formengine.service.draft;
35  
36  import java.io.IOException;
37  import java.io.InputStream;
38  import java.util.ArrayList;
39  import java.util.Collection;
40  import java.util.Collections;
41  import java.util.List;
42  import java.util.Map;
43  import java.util.Map.Entry;
44  import java.util.Set;
45  
46  import javax.inject.Inject;
47  import javax.servlet.http.HttpServletRequest;
48  import javax.servlet.http.HttpSession;
49  
50  import net.sf.json.JSONArray;
51  import net.sf.json.JSONObject;
52  import net.sf.json.JSONSerializer;
53  
54  import org.apache.commons.fileupload.FileItem;
55  import org.apache.commons.io.IOUtils;
56  import org.apache.commons.lang.StringUtils;
57  import org.apache.log4j.Logger;
58  
59  import fr.paris.lutece.plugins.blobstore.service.BlobStoreFileItem;
60  import fr.paris.lutece.plugins.blobstore.service.IBlobStoreService;
61  import fr.paris.lutece.plugins.blobstore.service.NoSuchBlobException;
62  import fr.paris.lutece.plugins.crm.modules.formengine.service.ICRMParametersService;
63  import fr.paris.lutece.plugins.crm.modules.formengine.util.Constants;
64  import fr.paris.lutece.plugins.crmclient.service.ICRMClientService;
65  import fr.paris.lutece.plugins.crmclient.service.authenticator.IAuthenticatorService;
66  import fr.paris.lutece.plugins.crmclient.util.CRMException;
67  import fr.paris.lutece.plugins.crmclient.util.CrmClientConstants;
68  import fr.paris.lutece.plugins.formengine.business.jaxb.formdefinition.Field;
69  import fr.paris.lutece.plugins.formengine.service.FormsRegistrationService;
70  import fr.paris.lutece.plugins.formengine.service.draft.DraftBackupService;
71  import fr.paris.lutece.plugins.formengine.util.JSONUtils;
72  import fr.paris.lutece.plugins.formengine.web.Form;
73  import fr.paris.lutece.plugins.formengine.web.SharedConstants;
74  import fr.paris.lutece.plugins.formengine.web.SubForm;
75  import fr.paris.lutece.portal.service.i18n.I18nService;
76  import fr.paris.lutece.portal.service.message.SiteMessage;
77  import fr.paris.lutece.portal.service.message.SiteMessageException;
78  import fr.paris.lutece.portal.service.message.SiteMessageService;
79  import fr.paris.lutece.portal.service.security.LuteceUser;
80  import fr.paris.lutece.portal.service.security.SecurityService;
81  import fr.paris.lutece.portal.service.util.AppException;
82  
83  
84  /**
85   * CRM Draft Backup Service
86   */
87  public class CRMDraftBackupService implements DraftBackupService
88  {
89      private static Logger _logger = Logger.getLogger( "lutece.crm" );
90      private IBlobStoreService _blobStoreService;
91      @Inject
92      private ICRMParametersService _crmParametersService;
93      @Inject
94      private ICRMClientService _crmClientService;
95      @Inject
96      private IAuthenticatorService _authenticatorService;
97  
98      /**
99       * {@inheritDoc }
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             SiteMessageService.setMessage( request, Constants.PROPERTY_MESSAGE_STOP_ACCESS_DENIED,
115                     SiteMessage.TYPE_STOP );
116         }
117 
118         if ( draftAction( request ) )
119         {
120             return true;
121         }
122 
123         //update session attributes 
124         if ( !StringUtils.isEmpty( request.getParameter( Constants.PARAM_ID_DEMAND ) ) )
125         {
126             updateSessionAttributes( request, form );
127         }
128 
129         if ( !existsDraft( request, form ) )
130         {
131             create( request, form );
132         }
133 
134         restore( request, form );
135 
136         return false;
137     }
138 
139     /**
140      * {@inheritDoc }
141      */
142     @Override
143     public void saveDraft( HttpServletRequest request, Form form )
144     {
145         if ( _logger.isDebugEnabled( ) )
146         {
147             _logger.debug( "Saving Draft ..." );
148         }
149 
150         HttpSession session = request.getSession( true );
151 
152         String strData = (String) session.getAttribute( getSessionAttributeName( form,
153                 Constants.SESSION_ATTRIBUTE_DEMAND_DATA_PARAMS ) );
154         String strIdDemand = (String) session.getAttribute( getSessionAttributeName( form,
155                 Constants.SESSION_ATTRIBUTE_ID_DEMAND_PARAMS ) );
156         String strCrmWebAppCode = (String) session.getAttribute( getSessionAttributeName( form,
157                 Constants.SESSION_ATTRIBUTE_DEMAND_CRM_WEBB_APP_CODE_PARAMS ) );
158 
159         if ( StringUtils.isNotBlank( strData ) && StringUtils.isNotBlank( strIdDemand ) )
160         {
161             String strIdBlob = JSONUtils.getIdBlobFromJson( strData );
162 
163             if ( StringUtils.isNotBlank( strIdBlob ) )
164             {
165                 String strStatusText = I18nService.getLocalizedString( Constants.PROPERTY_CRM_STATUS_TEXT_MODIF,
166                         request.getLocale( ) );
167                 try
168                 {
169                     _crmClientService.sendUpdateDemand( strIdDemand, strStatusText, strCrmWebAppCode,
170                             Constants.CRM_STATUS_DRAFT, strData );
171                 }
172                 catch ( CRMException e )
173                 {
174                     _logger.error( "Error saving draft : " + e.getMessage( ), e );
175 
176                     // Add warning message to formengine
177                     String strWarningMessage = I18nService.getLocalizedString(
178                             Constants.PROPERTY_CRM_MESSAGE_ERROR_CALLING_WS, request.getLocale( ) );
179                     session.setAttribute( SharedConstants.SESSION_ATTRIBUTE_WARNING_ERROR_WS, strWarningMessage );
180 
181                 }
182                 for ( SubForm subForm : ( (Map<?, SubForm>) form.getSubForm( ) ).values( ) )
183                 {
184                     storeFiles( subForm, request );
185                 }
186 
187                 _blobStoreService.update( strIdBlob, form.getBlob( request ) );
188             }
189         }
190 
191     }
192 
193     /**
194      * {@inheritDoc}
195      */
196     @Override
197     public void validateDraft( HttpServletRequest request, Form form )
198     {
199         if ( _logger.isDebugEnabled( ) )
200         {
201             _logger.debug( "Validating Draft ..." );
202         }
203 
204         HttpSession session = request.getSession( true );
205 
206         String strData = (String) session.getAttribute( getSessionAttributeName( form,
207                 Constants.SESSION_ATTRIBUTE_DEMAND_DATA_PARAMS ) );
208         String strDemandId = (String) session.getAttribute( getSessionAttributeName( form,
209                 Constants.SESSION_ATTRIBUTE_ID_DEMAND_PARAMS ) );
210         String strCrmWebAppCode = (String) session.getAttribute( getSessionAttributeName( form,
211                 Constants.SESSION_ATTRIBUTE_DEMAND_CRM_WEBB_APP_CODE_PARAMS ) );
212 
213         try
214         {
215             if ( StringUtils.isNotBlank( strData ) && StringUtils.isNotBlank( strDemandId ) )
216             {
217                 String strIdBlob = JSONUtils.getIdBlobFromJson( strData );
218 
219                 if ( StringUtils.isNotBlank( strIdBlob ) )
220                 {
221                     String strStatusText = I18nService.getLocalizedString( Constants.PROPERTY_CRM_STATUS_TEXT_VALIDATE,
222                             request.getLocale( ) );
223                     _crmClientService.sendUpdateDemand( strDemandId, strStatusText, strCrmWebAppCode,
224                             CrmClientConstants.CRM_STATUS_VALIDATED, strData );
225 
226                     _blobStoreService.delete( strIdBlob );
227                 }
228             }
229         }
230         catch ( CRMException ex )
231         {
232             _logger.error( "Error validating draft : " + ex.getMessage( ), ex );
233         }
234     }
235 
236     /**
237      * Check if the draft exists
238      * @param request the HTTP request
239      * @param form the form
240      * @return true if the draft already exists, false otherwise
241      */
242     private boolean existsDraft( HttpServletRequest request, Form form )
243     {
244         HttpSession session = request.getSession( true );
245 
246         //test if exists Id Demand link to the form 
247         if ( session.getAttribute( getSessionAttributeName( form, Constants.SESSION_ATTRIBUTE_ID_DEMAND_PARAMS ) ) != null )
248         {
249             return true;
250         }
251         return false;
252     }
253 
254     /**
255      * Stores all file for the subform to BlobStore and replaces
256      * {@link FileItem} by {@link BlobStoreFileItem}
257      * @param subForm the subform
258      * @param request the request
259      */
260     private void storeFiles( SubForm subForm, HttpServletRequest request )
261     {
262         for ( Field field : subForm.getUploadFields( request ) )
263         {
264             List<FileItem> uploadedFiles = subForm.getFileItems( request, field.getName( ) );
265 
266             if ( uploadedFiles != null )
267             {
268                 List<FileItem> listBlobStoreFileItems = new ArrayList<FileItem>( );
269 
270                 for ( int nIndex = 0; nIndex < uploadedFiles.size( ); nIndex++ )
271                 {
272                     FileItem fileItem = uploadedFiles.get( nIndex );
273                     String strFileName = field.getFileNames( ).getFileName( ).get( nIndex ).getValue( );
274 
275                     if ( !( fileItem instanceof BlobStoreFileItem ) )
276                     {
277                         // file is not blobstored yet
278                         String strFileBlobId;
279                         InputStream is = null;
280 
281                         try
282                         {
283                             is = fileItem.getInputStream( );
284                             strFileBlobId = _blobStoreService.storeInputStream( is );
285                         }
286                         catch ( IOException e1 )
287                         {
288                             IOUtils.closeQuietly( is );
289                             _logger.error( e1.getMessage( ), e1 );
290                             throw new AppException( e1.getMessage( ), e1 );
291                         }
292 
293                         String strJSON = BlobStoreFileItem.buildFileMetadata( strFileName, fileItem.getSize( ),
294                                 strFileBlobId, fileItem.getContentType( ) );
295 
296                         if ( _logger.isDebugEnabled( ) )
297                         {
298                             _logger.debug( "Storing " + fileItem.getName( ) + " with : " + strJSON );
299                         }
300 
301                         String strFileMetadataBlobId = _blobStoreService.store( strJSON.getBytes( ) );
302 
303                         try
304                         {
305                             BlobStoreFileItem blobStoreFileItem = new BlobStoreFileItem( strFileMetadataBlobId,
306                                     _blobStoreService );
307                             listBlobStoreFileItems.add( blobStoreFileItem );
308                         }
309                         catch ( NoSuchBlobException nsbe )
310                         {
311                             // nothing to do, blob is deleted and draft is not up to date.
312                             if ( _logger.isDebugEnabled( ) )
313                             {
314                                 _logger.debug( nsbe.getMessage( ) );
315                             }
316                         }
317                         catch ( Exception e )
318                         {
319                             _logger.error( "Unable to create new BlobStoreFileItem " + e.getMessage( ), e );
320                             throw new AppException( e.getMessage( ), e );
321                         }
322                     }
323                     else
324                     {
325                         // nothing to do
326                         listBlobStoreFileItems.add( fileItem );
327                     }
328                 }
329 
330                 // replace current file list with the new one
331                 uploadedFiles.clear( );
332                 uploadedFiles.addAll( listBlobStoreFileItems );
333             }
334         }
335     }
336 
337     /**
338      * Removes all files stored in blobstore for the current subform and
339      * strJsonFields.
340      * @param subForm subform
341      * @param request the request
342      * @param strJsonFields json
343      */
344     private void deleteFiles( SubForm subForm, HttpServletRequest request, String strJsonFields )
345     {
346         for ( Field field : subForm.getUploadFields( request ) )
347         {
348             for ( String strBlobId : getFileMetadataBlobIdsFromJson( strJsonFields, field ) )
349             {
350                 FileItem fileItem;
351 
352                 try
353                 {
354                     fileItem = new BlobStoreFileItem( strBlobId, _blobStoreService );
355 
356                     if ( _logger.isDebugEnabled( ) )
357                     {
358                         _logger.debug( "Removing file " + fileItem.getName( ) );
359                     }
360 
361                     fileItem.delete( );
362                 }
363                 catch ( NoSuchBlobException nsbe )
364                 {
365                     // file might be deleted
366                     if ( _logger.isDebugEnabled( ) )
367                     {
368                         _logger.debug( nsbe.getMessage( ) );
369                     }
370                 }
371                 catch ( Exception e )
372                 {
373                     throw new AppException( "Unable to parse JSON file metadata for blob id " + strBlobId + " : "
374                             + e.getMessage( ), e );
375                 }
376             }
377         }
378     }
379 
380     /**
381      * Create a draft
382      * @param request the HTTP request
383      * @param form the form
384      */
385     private void create( HttpServletRequest request, Form form )
386     {
387         HttpSession session = request.getSession( true );
388 
389         String strDemandType = _crmParametersService.getIdTypeDemande( request, form );
390         String strCrmWebAppCode = _crmParametersService.getCrmWebAppCode( request, form );
391 
392         if ( StringUtils.isNotBlank( strDemandType ) )
393         {
394             // handle fileItems
395             for ( Entry<String, SubForm> entry : ( (Map<String, SubForm>) form.getSubForm( ) ).entrySet( ) )
396             {
397                 SubForm subForm = entry.getValue( );
398                 storeFiles( subForm, request );
399             }
400 
401             String strData = JSONUtils.buildJsonIdBlob( _blobStoreService.store( form.getBlob( request ) ) );
402 
403             try
404             {
405                 String strIdCRMUser = request.getParameter( Constants.PARAM_ID_CRM_USER );
406                 String strUserGuid = StringUtils.EMPTY;
407                 String strIdDemand = StringUtils.EMPTY;
408 
409                 if ( StringUtils.isBlank( strIdCRMUser ) && SecurityService.isAuthenticationEnable( ) )
410                 {
411                     LuteceUser user = SecurityService.getInstance( ).getRemoteUser( request );
412 
413                     if ( user != null )
414                     {
415                         strUserGuid = user.getName( );
416                     }
417                 }
418 
419                 String strStatusText = I18nService.getLocalizedString( Constants.PROPERTY_CRM_STATUS_TEXT_NEW,
420                         request.getLocale( ) );
421 
422                 if ( StringUtils.isNotBlank( strUserGuid ) )
423                 {
424                     strIdDemand = _crmClientService.sendCreateDemandByUserGuid( strDemandType, strUserGuid,
425                             CrmClientConstants.CRM_STATUS_DRAFT, strStatusText, strData, strCrmWebAppCode );
426                 }
427                 else if ( StringUtils.isNotBlank( strIdCRMUser ) )
428                 {
429                     strIdDemand = _crmClientService.sendCreateDemandByIdCRMUser( strDemandType, strIdCRMUser,
430                             CrmClientConstants.CRM_STATUS_DRAFT, strStatusText, strData, strCrmWebAppCode );
431                 }
432 
433                 if ( StringUtils.isNotBlank( strIdDemand ) && !Constants.INVALID_ID.equals( strIdDemand ) )
434                 {
435 
436                     try
437                     {
438                         strUserGuid = _crmClientService.getUserGuidFromIdDemand( strIdDemand, strCrmWebAppCode );
439                     }
440                     catch ( CRMException ex )
441                     {
442                         _logger.error( "Error calling WebService : " + ex.getMessage( ), ex );
443                     }
444 
445                     updateSessionAttributes( session, form, strIdDemand, strData, strUserGuid, strCrmWebAppCode );
446                 }
447                 else
448                 {
449                     throw new Exception( "Invalid ID demand" );
450                 }
451             }
452             catch ( Exception e )
453             {
454                 _logger.error( "Error calling WebService : " + e.getMessage( ), e );
455 
456                 // Remove the blob created previously
457                 String strIdBlob = JSONUtils.getIdBlobFromJson( strData );
458                 _blobStoreService.delete( strIdBlob );
459             }
460         }
461     }
462 
463     /**
464      * Restore a draft
465      * @param request the HTTP request
466      * @param form the form
467      */
468     private void restore( HttpServletRequest request, Form form )
469     {
470         if ( _logger.isDebugEnabled( ) )
471         {
472             _logger.debug( "Restoring Draft ..." );
473         }
474 
475         HttpSession session = request.getSession( true );
476         String strData = ( (String) session.getAttribute( getSessionAttributeName( form,
477                 Constants.SESSION_ATTRIBUTE_DEMAND_DATA_PARAMS ) ) );
478         String strIdBlob = JSONUtils.getIdBlobFromJson( strData );
479 
480         if ( StringUtils.isNotBlank( strIdBlob ) )
481         {
482             byte[] dataForm = _blobStoreService.getBlob( strIdBlob );
483 
484             if ( dataForm != null )
485             {
486                 String strDataForm = new String( dataForm );
487 
488                 if ( StringUtils.isNotBlank( strDataForm ) )
489                 {
490                     String strJSONForm = JSONUtils.getJsonValue( strDataForm, Constants.JSON_KEY_FORM );
491 
492                     String strJSONListSubForms = JSONUtils.getJsonValue( strJSONForm, Constants.JSON_KEY_SUBFORMS );
493                     Set<String> subforms = form.getSubForm( ).keySet( );
494 
495                     for ( String strSubForm : subforms )
496                     {
497                         SubForm subForm = form.getSubForm( strSubForm );
498                         String strJSONFields = JSONUtils.getJsonValuesFieldsBySubForm( strJSONListSubForms,
499                                 subForm.getName( ) );
500 
501                         for ( Field field : subForm.getFormElements( request ).getFields( ).getField( ) )
502                         {
503                             if ( SharedConstants.FIELD_TYPE_UPLOAD.equals( field.getType( ) ) )
504                             {
505                                 // if the list is not null, there is no need to get the files again
506                                 if ( ( field.getFileNames( ) == null )
507                                         || ( field.getFileNames( ).getFileName( ) == null ) )
508                                 {
509                                     for ( String strBlobId : getFileMetadataBlobIdsFromJson( strJSONFields, field ) )
510                                     {
511                                         FileItem fileItem;
512 
513                                         try
514                                         {
515                                             fileItem = new BlobStoreFileItem( strBlobId, _blobStoreService );
516                                             subForm.addFileItemToUploadedFiles( request, field, fileItem, null );
517                                         }
518                                         catch ( NoSuchBlobException nsbe )
519                                         {
520                                             // file might be deleted
521                                             _logger.debug( nsbe.getMessage( ) );
522                                         }
523                                         catch ( Exception e )
524                                         {
525                                             throw new AppException( "Unable to parse JSON file metadata for blob id "
526                                                     + strBlobId + " : " + e.getMessage( ), e );
527                                         }
528                                     }
529                                 }
530                             }
531                             else
532                             {
533                                 JSONUtils.doRestoreValuesFields( strJSONFields, field, request );
534                             }
535                         }
536                     }
537                 }
538             }
539         }
540         else
541         {
542             // Add warning message to formengine
543             String strWarningMessage = I18nService.getLocalizedString( Constants.PROPERTY_CRM_MESSAGE_ERROR_CALLING_WS,
544                     request.getLocale( ) );
545             session.setAttribute( SharedConstants.SESSION_ATTRIBUTE_WARNING_ERROR_WS, strWarningMessage );
546         }
547     }
548 
549     /**
550      * Gets blobs id for files metadata
551      * @param strJSONFields the strJSONFields
552      * @param field the field
553      * @return blob ids found, empty list otherwise.
554      */
555     private Collection<String> getFileMetadataBlobIdsFromJson( String strJSONFields, Field field )
556     {
557         if ( StringUtils.isNotBlank( strJSONFields ) )
558         {
559             JSONArray jsonList = (JSONArray) JSONSerializer.toJSON( strJSONFields );
560 
561             for ( Object o : jsonList )
562             {
563                 JSONObject json = (JSONObject) o;
564 
565                 if ( json.containsKey( field.getName( ) ) )
566                 {
567                     Object oMetadata = json.get( BlobStoreFileItem.JSON_KEY_FILE_METADATA_BLOB_ID );
568 
569                     if ( oMetadata == null )
570                     {
571                         return Collections.emptyList( );
572                     }
573 
574                     if ( oMetadata instanceof JSONArray )
575                     {
576                         return (Collection<String>) oMetadata;
577                     }
578                     else
579                     {
580                         return Collections.singletonList( oMetadata.toString( ) );
581                     }
582                 }
583             }
584         }
585 
586         return Collections.emptyList( );
587     }
588 
589     /**
590      * Delete a draft
591      * @param request the HTTP request
592      */
593     private void delete( HttpServletRequest request )
594     {
595         if ( _logger.isDebugEnabled( ) )
596         {
597             _logger.debug( "Deleting Draft ..." );
598         }
599 
600         HttpSession session = request.getSession( true );
601         boolean bHasError = false;
602 
603         String strIdDemand = request.getParameter( Constants.PARAM_ID_DEMAND );
604         String strData = request.getParameter( Constants.PARAM_DEMAND_DATA );
605         String strCrmWebAppCode = request.getParameter( Constants.PARAM_CRM_WEBB_APP_CODE );
606 
607         if ( StringUtils.isNotBlank( strIdDemand ) && StringUtils.isNumeric( strIdDemand )
608                 && StringUtils.isNotBlank( strData ) )
609         {
610             try
611             {
612                 // Delete the demand in CRM
613                 _crmClientService.sendDeleteDemand( strIdDemand, strCrmWebAppCode );
614 
615                 String strIdBlob = JSONUtils.getIdBlobFromJson( strData );
616 
617                 if ( StringUtils.isNotBlank( strIdBlob ) )
618                 {
619                     byte[] dataForm = _blobStoreService.getBlob( strIdBlob );
620 
621                     if ( dataForm != null )
622                     {
623                         // get the blob
624                         String strDataForm = new String( dataForm );
625 
626                         // get associated blobs (files...)
627                         if ( StringUtils.isNotBlank( strDataForm ) )
628                         {
629                             String strJSONForm = JSONUtils.getJsonValue( strDataForm, Constants.JSON_KEY_FORM );
630                             Form form = FormsRegistrationService
631                                     .getForm( JSONUtils.getJsonValue( strJSONForm, "name" ) );
632 
633                             if ( form != null )
634                             {
635                                 // handle fileItems
636                                 for ( Entry<String, SubForm> entry : ( (Map<String, SubForm>) form.getSubForm( ) )
637                                         .entrySet( ) )
638                                 {
639                                     String strJSONListSubForms = JSONUtils.getJsonValue( strJSONForm,
640                                             Constants.JSON_KEY_SUBFORMS );
641                                     SubForm subForm = entry.getValue( );
642                                     String strJsonFields = JSONUtils.getJsonValuesFieldsBySubForm( strJSONListSubForms,
643                                             subForm.getName( ) );
644                                     deleteFiles( subForm, request, strJsonFields );
645                                 }
646                             }
647                         }
648 
649                         _blobStoreService.delete( strIdBlob );
650                     }
651                 }
652             }
653             catch ( CRMException ex )
654             {
655                 _logger.error( "Error deleting draft : " + ex.getMessage( ), ex );
656                 bHasError = true;
657             }
658         }
659         else
660         {
661             bHasError = true;
662         }
663 
664         if ( bHasError )
665         {
666             // Add warning message to formengine
667             String strErrorMessage = I18nService.getLocalizedString( Constants.PROPERTY_CRM_MESSAGE_ERROR_CALLING_WS,
668                     request.getLocale( ) );
669             session.setAttribute( SharedConstants.SESSION_ATTRIBUTE_WARNING_ERROR_WS, strErrorMessage );
670         }
671     }
672 
673     /**
674      * Do draft action
675      * @param request the HTTP request
676      * @return true if there is an draft action, false otherwise
677      * @throws SiteMessageException message exception if remove draft
678      */
679     private boolean draftAction( HttpServletRequest request ) throws SiteMessageException
680     {
681         String strAction = request.getParameter( Constants.PARAMETER_ACTION_NAME );
682 
683         if ( StringUtils.isNotBlank( strAction ) )
684         {
685             if ( Constants.ACTION_DO_REMOVE_DRAFT.equals( strAction ) )
686             {
687                 doRemoveDraft( request );
688             }
689             else if ( Constants.ACTION_REMOVE_DRAFT.equals( strAction ) )
690             {
691                 removeDraft( request );
692             }
693 
694             return true;
695         }
696 
697         return false;
698     }
699 
700     /**
701      * Do remove a demand by calling the DraftBackUpService
702      * @param request The HTTP request
703      */
704     private void doRemoveDraft( HttpServletRequest request )
705     {
706         delete( request );
707     }
708 
709     /**
710      * Remove a draft and display a message saying the draft has or not been
711      * deleted
712      * @param request The HTTP request
713      * @throws SiteMessageException the message exception
714      */
715     private void removeDraft( HttpServletRequest request ) throws SiteMessageException
716     {
717         String strUrlReturn = request.getParameter( Constants.PARAMETER_URL_RETURN );
718 
719         if ( StringUtils.isNotBlank( strUrlReturn ) )
720         {
721             delete( request );
722 
723             if ( StringUtils.isNotBlank( (String) request.getSession( ).getAttribute(
724                     SharedConstants.SESSION_ATTRIBUTE_WARNING_ERROR_WS ) ) )
725             {
726                 request.getSession( ).removeAttribute( SharedConstants.SESSION_ATTRIBUTE_WARNING_ERROR_WS );
727                 SiteMessageService.setMessage( request, Constants.PROPERTY_MESSAGE_ERROR_CALLING_WS,
728                         SiteMessage.TYPE_ERROR, strUrlReturn );
729             }
730             else
731             {
732                 SiteMessageService.setMessage( request, Constants.PROPERTY_MESSAGE_INFO_REMOVE_DEMAND,
733                         SiteMessage.TYPE_INFO, strUrlReturn );
734             }
735         }
736     }
737 
738     /**
739      * return session attribute name with form prefix
740      * @param form Form
741      * @param strSessionAttributeName the session attribute name
742      * @return session attribute name with form prefix
743      */
744     private static String getSessionAttributeName( Form form, String strSessionAttributeName )
745     {
746 
747         StringBuilder strBuilder = new StringBuilder( );
748         strBuilder.append( getPrefixSession( form ) );
749         strBuilder.append( strSessionAttributeName );
750         return strBuilder.toString( );
751     }
752 
753     /**
754      * Get the prefix for the session
755      * @param form the form
756      * @return the prefix
757      */
758     private static String getPrefixSession( Form form )
759     {
760         String strPrefix = SharedConstants.SESSION_PREFIX + Constants.UNDERSCORE + form.getName( )
761                 + Constants.UNDERSCORE;
762         strPrefix = strPrefix.toUpperCase( );
763 
764         return strPrefix;
765     }
766 
767     /**
768      * Check if the request is authenticated
769      * @param request the HTTP request
770      * @return true if it is authenticated, false otherwise
771      */
772     private boolean isRequestAuthenticated( HttpServletRequest request, Form form )
773     {
774         boolean bIsAuthenticated = true;
775         String strDemandType = _crmParametersService.getIdTypeDemande( request, form );
776         String strCrmWebAppCode = _crmParametersService.getCrmWebAppCode( request, form );
777         String strDemand = request.getParameter( Constants.PARAM_ID_DEMAND );
778         String strAction = request.getParameter( Constants.PARAMETER_ACTION_NAME );
779         if ( StringUtils.isNotBlank( strAction ) && Constants.ACTION_DO_REMOVE_DRAFT.equals( strAction ) )
780         {
781 
782             bIsAuthenticated = _authenticatorService.getRequestAuthenticatorForWs( strCrmWebAppCode )
783                     .isRequestAuthenticated( request );
784         }
785         else if ( !_crmParametersService.isEnabledLocalCrmParameters( )
786                 && ( StringUtils.isNotBlank( strDemandType ) || StringUtils.isNotBlank( strDemand ) )
787                 || ( StringUtils.isNotBlank( strAction ) && Constants.ACTION_REMOVE_DRAFT.equals( strAction ) ) )
788         {
789             bIsAuthenticated = _authenticatorService.getRequestAuthenticatorForUrl( strCrmWebAppCode )
790                     .isRequestAuthenticated( request );
791         }
792 
793         return bIsAuthenticated;
794     }
795 
796     /**
797      * Update session attributes
798      * @param request the HTTP request
799      * @param form the form object
800      * 
801      */
802     private void updateSessionAttributes( HttpServletRequest request, Form form )
803     {
804         HttpSession session = request.getSession( true );
805         String strIdDemand = request.getParameter( Constants.PARAM_ID_DEMAND );
806         String strCrmWebAppCode = _crmParametersService.getCrmWebAppCode( request, form );
807         String strUserGuid = null;
808         try
809         {
810             strUserGuid = _crmClientService.getUserGuidFromIdDemand( strIdDemand, strCrmWebAppCode );
811         }
812         catch ( CRMException ex )
813         {
814             _logger.error( "Error calling WebService : " + ex.getMessage( ), ex );
815         }
816 
817         String strDemandData = request.getParameter( Constants.PARAM_DEMAND_DATA );
818         updateSessionAttributes( session, form, strIdDemand, strDemandData, strUserGuid, strCrmWebAppCode );
819     }
820 
821     /**
822      * Update session attributes
823      * @param session the Http session
824      * @param strIdDemand the demand id
825      * @param strDemandData the demad data
826      * @param strUserGuid the user guid
827      * @param strCrmWebAppCode the web app code
828      */
829     private void updateSessionAttributes( HttpSession session, Form form, String strIdDemand, String strDemandData,
830             String strUserGuid, String strCrmWebAppCode )
831     {
832         if ( !StringUtils.isEmpty( strIdDemand ) )
833         {
834             session.setAttribute( getSessionAttributeName( form, Constants.SESSION_ATTRIBUTE_ID_DEMAND_PARAMS ),
835                     strIdDemand );
836         }
837 
838         if ( !StringUtils.isEmpty( strDemandData ) )
839         {
840             session.setAttribute( getSessionAttributeName( form, Constants.SESSION_ATTRIBUTE_DEMAND_DATA_PARAMS ),
841                     strDemandData );
842         }
843         if ( !StringUtils.isEmpty( strUserGuid ) )
844         {
845             session.setAttribute( getSessionAttributeName( form, Constants.SESSION_ATTRIBUTE_USER_GUID_PARAMS ),
846                     strUserGuid );
847         }
848         if ( !StringUtils.isEmpty( strCrmWebAppCode ) )
849         {
850             session.setAttribute(
851                     getSessionAttributeName( form, Constants.SESSION_ATTRIBUTE_DEMAND_CRM_WEBB_APP_CODE_PARAMS ),
852                     strCrmWebAppCode );
853         }
854     }
855 
856 }