View Javadoc
1   package fr.paris.lutece.plugins.crm.modules.form.util;
2   
3   
4   import java.util.ArrayList;
5   import java.util.Collection;
6   import java.util.Collections;
7   import java.util.HashMap;
8   import java.util.List;
9   import java.util.Locale;
10  import java.util.Map;
11  
12  import javax.servlet.http.HttpSession;
13  
14  import fr.paris.lutece.plugins.form.service.upload.FormAsynchronousUploadHandler;
15  import fr.paris.lutece.plugins.genericattributes.business.GenericAttributeError;
16  import fr.paris.lutece.plugins.genericattributes.business.Entry;
17  import fr.paris.lutece.plugins.genericattributes.business.EntryHome;
18  import fr.paris.lutece.plugins.genericattributes.business.Response;
19  import fr.paris.lutece.plugins.genericattributes.business.Field;
20  import fr.paris.lutece.plugins.genericattributes.business.FieldHome;
21  import fr.paris.lutece.plugins.genericattributes.service.entrytype.IEntryTypeService;
22  import fr.paris.lutece.plugins.genericattributes.util.GenericAttributesUtils;
23  import fr.paris.lutece.plugins.genericattributes.service.entrytype.EntryTypeServiceManager;
24  import fr.paris.lutece.plugins.blobstore.service.BlobStoreFileItem;
25  import fr.paris.lutece.portal.service.util.AppLogService;
26  import net.sf.json.JSON;
27  import net.sf.json.JSONArray;
28  import net.sf.json.JSONException;
29  import net.sf.json.JSONObject;
30  
31  import org.apache.commons.fileupload.FileItem;
32  import org.apache.commons.io.FilenameUtils;
33  import org.apache.commons.lang.StringUtils;
34  
35  import fr.paris.lutece.portal.business.file.File;
36  
37  public final class JSONUtils {
38  	
39  	public static final String JSON_KEY_RESPONSE = "response";
40  	public static final String JSON_KEY_ID_FORM = "id_form";
41  	public static final String JSON_KEY_ID_ENTRY = "id_entry";
42      public static final String JSON_KEY_ID_RESPONSE = "id_response";
43      public static final String JSON_KEY_ID_FIELD = "id_field";
44      public static final String JSON_KEY_VALUE_RESPONSE = "value_response";
45      public static final String JSON_KEY_FILE_NAME = "file_name";
46      public static final String JSON_KEY_FILE_EXTENSION = "file_extension";
47      public static final String JSON_KEY_ERROR_MESSAGE = "error_message";
48      public static final String JSON_KEY_MANDATORY_ERROR = "mandatory_error";
49      public static final String JSON_KEY_TITLE_QUESTION = "title_question";
50      public static final String JSON_KEY_FORM_ERROR = "form_error";
51      public static final String JSON_KEY_MIME_TYPE = "mime_type";
52     
53     
54   
55  	
56  	/**
57       * Empty constructor
58       */
59      private JSONUtils( )
60      {
61          // nothing
62      }
63      /**
64       * Builds the json string for the response map
65       * @param mapResponse the response map
66       * @param nIdForm the id form
67       * @param session the session
68       * @return the json string
69       */
70      public static String buildJson( Map<Integer, List<Response>> mapResponse, int nIdForm, HttpSession session )
71      {
72          JSONObject jsonResponses = new JSONObject( );
73  
74          for ( List<Response> listResponse : mapResponse.values( ) )
75          {
76              for ( Response response : listResponse )
77              {
78                  jsonResponses.accumulate( JSON_KEY_RESPONSE, buildJson( response, session ));
79              }
80          }
81  
82          jsonResponses.element( JSON_KEY_ID_FORM, nIdForm );
83  
84          return jsonResponses.toString( );
85      }
86      
87      /**
88       * Builds the json string for the {@link Response}
89       * @param response the response
90       * @param session the session
91       * @return the json string
92       */
93      public static JSONObject buildJson( Response response, HttpSession session )
94      {
95          JSONObject jsonResponse = new JSONObject( );
96          jsonResponse.element( JSON_KEY_ID_ENTRY, response.getEntry( ).getIdEntry( ) );
97          jsonResponse.element( JSON_KEY_ID_RESPONSE, response.getIdResponse( ) );
98  
99          if ( response.getField( ) != null )
100         {
101             jsonResponse.element( JSON_KEY_ID_FIELD, response.getField( ).getIdField( ) );
102         }
103 
104         if ( ( response.getResponseValue( ) != null ) && ( response.getFile( ) != null ) )
105         {
106             jsonResponse.element( JSON_KEY_VALUE_RESPONSE, response.getResponseValue( ) );
107         }
108         else
109         {
110             // file specific data
111             if ( ( response.getFile( ) != null ) && StringUtils.isNotBlank( response.getFile( ).getTitle( ) ) )
112             {
113                 jsonResponse.element( JSON_KEY_FILE_NAME, response.getFile( ).getTitle( ) );
114                 jsonResponse.element( JSON_KEY_FILE_EXTENSION,
115                         FilenameUtils.getExtension( response.getFile( ).getTitle( ) ) );
116                 jsonResponse.element( JSON_KEY_MIME_TYPE, response.getFile( ).getMimeType( ) );
117 
118                 List<FileItem> listFileItems = FormAsynchronousUploadHandler.getHandler( ).getListUploadedFiles(
119                 		IEntryTypeService.PREFIX_ATTRIBUTE +Integer.toString( response.getEntry( ).getIdEntry( ) ), session );
120 
121                 if ( ( listFileItems != null ) && !listFileItems.isEmpty( ) )
122                 {
123                     for ( FileItem fileItem : listFileItems )
124                     {
125                         if ( fileItem instanceof BlobStoreFileItem
126                                 && fileItem.getName( ).equals( response.getFile( ).getTitle( ) ) )
127                         {
128                             jsonResponse.accumulate( BlobStoreFileItem.JSON_KEY_FILE_METADATA_BLOB_ID,
129                                     ( (BlobStoreFileItem) fileItem ).getBlobId( ) );
130 
131                             break;
132                         }
133                     }
134                 }
135             }
136         }
137 
138         // form error
139         if ( response.getEntry( ).getError( ) != null )
140         {
141             jsonResponse.element( JSON_KEY_FORM_ERROR, buildJson( response.getEntry( ).getError( ) ) );
142         }
143 
144         return jsonResponse;
145     }
146     /**
147      * Builds json form {@link GenericAttributeError}
148      * @param formError {@link GenericAttributeError}
149      * @return json string
150      */
151     public static String buildJson( GenericAttributeError formError )
152     {
153         JSONObject jsonError = new JSONObject( );
154 
155         jsonError.element( JSON_KEY_ERROR_MESSAGE,
156                 StringUtils.isNotBlank( formError.getErrorMessage( ) ) ? formError.getErrorMessage( )
157                         : StringUtils.EMPTY );
158         jsonError.element( JSON_KEY_MANDATORY_ERROR, formError.isMandatoryError( ) );
159         jsonError.element( JSON_KEY_TITLE_QUESTION, formError.getTitleQuestion( ) );
160 
161         return jsonError.toString( );
162     }
163     
164     /**
165      * Get the list of blob id from a JSON string
166      * @param strJSON The JSON to get blob id from
167      * @param nIdEntry The id of the entry to get blob id from, or
168      *            {@link FormUtils#CONSTANT_ID_NULL} to get blob id from any
169      *            entry
170      * @return The list of blob id, or an empty list if no blob id was found
171      *         in the JSON string
172      */
173     public static List<String> getBlobIds( String strJSON, int nIdEntry )
174     {
175         List<String> listBlobIds = new ArrayList<String>( );
176         JSONObject jsonObject = JSONObject.fromObject( strJSON );
177 
178         try
179         {
180             JSON jsonResponses = (JSON) jsonObject.get( JSON_KEY_RESPONSE );
181 
182             if ( ( jsonResponses != null ) && !jsonResponses.isEmpty( ) )
183             {
184                 if ( jsonResponses.isArray( ) )
185                 {
186                     // array
187                     for ( JSONObject jsonResponse : ( (Collection<JSONObject>) ( (JSONArray) jsonResponses ) ) )
188                     {
189                         if ( ( ( nIdEntry == GenericAttributesUtils.CONSTANT_ID_NULL ) || ( nIdEntry == jsonResponse
190                                 .getInt( JSON_KEY_ID_ENTRY ) ) )
191                                 && jsonResponse.containsKey( BlobStoreFileItem.JSON_KEY_FILE_METADATA_BLOB_ID ) )
192                         {
193                             listBlobIds.addAll( getFileMetadataBlobIdsFromJson( jsonResponse ) );
194                         }
195                     }
196                 }
197                 else
198                 {
199                     // only one response ?
200                     JSONObject jsonResponse = (JSONObject) jsonResponses;
201 
202                     if ( ( ( nIdEntry == jsonResponse.getInt( JSON_KEY_ID_ENTRY ) ) || ( nIdEntry == GenericAttributesUtils.CONSTANT_ID_NULL ) )
203                             && jsonResponse.containsKey( BlobStoreFileItem.JSON_KEY_FILE_METADATA_BLOB_ID ) )
204                     {
205                         listBlobIds.addAll( getFileMetadataBlobIdsFromJson( jsonResponse ) );
206                     }
207                 }
208             }
209         }
210         catch ( JSONException jsonEx )
211         {
212             // nothing to do - response might no be present
213         }
214 
215         return listBlobIds;
216     }
217     
218     /**
219      * Get the list of blob id from a JSON string
220      * @param strJSON The JSON to get blob id from
221      * @return The list of blob id, or an empty list if no blob id was found
222      *         in the JSON string
223      */
224     public static List<String> getBlobIds( String strJSON )
225     {
226         return getBlobIds( strJSON, GenericAttributesUtils.CONSTANT_ID_NULL );
227     }
228 
229    
230     /**
231      * Gets blobs id for files metadata
232      * @param strJSONFields the strJSONFields
233      * @param field the field
234      * @return blob ids found, empty list otherwise.
235      */
236     private static Collection<String> getFileMetadataBlobIdsFromJson( JSONObject json )
237     {
238         Object oMetadata = json.get( BlobStoreFileItem.JSON_KEY_FILE_METADATA_BLOB_ID );
239 
240         if ( oMetadata == null )
241         {
242             return Collections.emptyList( );
243         }
244 
245         if ( oMetadata instanceof JSONArray )
246         {
247             return (Collection<String>) oMetadata;
248         }
249 
250         return Collections.singletonList( oMetadata.toString( ) );
251     }
252     
253     /**
254      * Builds {@link GenericAttributeError} from json string
255      * @param strJson json string
256      * @return the {@link GenericAttributeError}
257      */
258     public static GenericAttributeError buildFormError( String strJson )
259     {
260         JSONObject jsonObject = JSONObject.fromObject( strJson );
261         GenericAttributeError formError = new GenericAttributeError( );
262         formError.setErrorMessage( jsonObject.getString( JSON_KEY_ERROR_MESSAGE ) );
263         formError.setMandatoryError( jsonObject.getBoolean( JSON_KEY_MANDATORY_ERROR ) );
264         formError.setTitleQuestion( jsonObject.getString( JSON_KEY_TITLE_QUESTION ) );
265 
266         return formError;
267     }
268     /**
269      * Builds the response
270      * @param json the json
271      * @param locale the locale
272      * @param session the session
273      * @return response the response
274      */
275     private static Response buildResponse( JSONObject json, Locale locale, HttpSession session )
276     {
277         Response response = new Response( );
278         response.setIdResponse( json.getInt( JSON_KEY_ID_RESPONSE ) );
279 
280         Entry entry = EntryHome.findByPrimaryKey( json.getInt( JSON_KEY_ID_ENTRY ) );
281         response.setEntry( entry );
282 
283         if ( json.containsKey( JSON_KEY_FORM_ERROR ) )
284         {
285             response.getEntry( ).setError( buildFormError( json.getString( JSON_KEY_FORM_ERROR ) ) );
286         }
287 
288         if ( json.containsKey( JSON_KEY_VALUE_RESPONSE ) && !json.containsKey( JSON_KEY_FILE_NAME ) )
289         {
290             response.setResponseValue( json.getString( JSON_KEY_VALUE_RESPONSE ) );
291         }
292 
293         if ( json.containsKey( JSON_KEY_ID_FIELD ) )
294         {
295             Field field = FieldHome.findByPrimaryKey( json.getInt( JSON_KEY_ID_FIELD ) );
296             response.setField( field );
297         }
298 
299         // file specific
300         boolean bIsFile = false;
301 
302         if ( json.containsKey( JSON_KEY_FILE_NAME ) )
303         {
304             File file = null;
305 
306             try
307             {
308                 file = new File( );
309                 file.setTitle( json.getString( JSON_KEY_FILE_NAME ) );
310                 file.setMimeType( json.getString( JSON_KEY_MIME_TYPE ) );
311             }
312             catch ( JSONException e )
313             {
314                 AppLogService.error( e.getMessage( ), e );
315             }
316 
317             response.setFile( file );
318             bIsFile = true;
319         }
320 
321         if ( !bIsFile && ( response.getResponseValue( ) != null ) )
322         {
323             // if the entry is not a file, we can set the string value
324             // data entry as specific behavior
325             EntryTypeServiceManager.getEntryTypeService( entry ).setResponseToStringValue( entry, response, locale );
326         }
327 
328         return response;
329     }
330 
331     
332     /**
333      * Builds the responses list - null if {@link #JSON_KEY_RESPONSE} is
334      * missing.
335      * @param strJSON the json
336      * @param locale the locale
337      * @param session the session
338      * @return the responses list - null if {@link #JSON_KEY_RESPONSE} is
339      *         missing
340      */
341     @SuppressWarnings( "unchecked" )
342     public static Map<Integer, List<Response>> buildListResponses( String strJSON, Locale locale, HttpSession session )
343     {
344         Map<Integer, List<Response>> mapResponses;
345         JSONObject jsonObject = JSONObject.fromObject( strJSON );
346 
347         try
348         {
349             JSON jsonResponses = (JSON) jsonObject.get( JSON_KEY_RESPONSE );
350 
351             if ( ( jsonResponses != null ) && !jsonResponses.isEmpty( ) )
352             {
353                 // there is at least one result
354                 mapResponses = new HashMap<Integer, List<Response>>( );
355 
356                 if ( jsonResponses.isArray( ) )
357                 {
358                     // array
359                     for ( JSONObject jsonResponse : ( (Collection<JSONObject>) ( (JSONArray) jsonResponses ) ) )
360                     {
361                         Response response = buildResponse( jsonResponse, locale, session );
362                         List<Response> listResponses = mapResponses.get( response.getEntry( ).getIdEntry( ) );
363 
364                         if ( listResponses == null )
365                         {
366                             listResponses = new ArrayList<Response>( );
367                             mapResponses.put( response.getEntry( ).getIdEntry( ), listResponses );
368                         }
369 
370                         listResponses.add( response );
371                     }
372                 }
373                 else
374                 {
375                     // only one response ?
376                     JSONObject jsonResponse = (JSONObject) jsonResponses;
377 
378                     Response response = buildResponse( jsonResponse, locale, session );
379 
380                     List<Response> listResponses = new ArrayList<Response>( );
381                     listResponses.add( response );
382                     mapResponses.put( response.getEntry( ).getIdEntry( ), listResponses );
383                 }
384             }
385             else
386             {
387                 // nothing to do - no response found
388                 mapResponses = null;
389             }
390         }
391         catch ( JSONException jsonEx )
392         {
393             // nothing to do - response might no be present
394             mapResponses = null;
395         }
396 
397         return mapResponses;
398     }
399     
400    
401 
402 }