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.formengine.util;
35  
36  import java.util.List;
37  import java.util.Set;
38  
39  import javax.servlet.http.HttpServletRequest;
40  
41  import net.sf.json.JSONArray;
42  import net.sf.json.JSONObject;
43  import net.sf.json.JSONSerializer;
44  
45  import org.apache.commons.fileupload.FileItem;
46  import org.apache.commons.lang.StringUtils;
47  
48  import fr.paris.lutece.plugins.blobstore.service.BlobStoreFileItem;
49  import fr.paris.lutece.plugins.formengine.business.jaxb.formdefinition.Field;
50  import fr.paris.lutece.plugins.formengine.web.Form;
51  import fr.paris.lutece.plugins.formengine.web.SharedConstants;
52  import fr.paris.lutece.plugins.formengine.web.SubForm;
53  import fr.paris.lutece.portal.service.util.AppLogService;
54  
55  
56  /**
57   * JSONUtils
58   */
59  public final class JSONUtils
60  {
61      public static final String TAG_ID_BLOB = "id_blob";
62      public static final String MESSAGE_DATA_NOT_FOUND = "id_blob not found";
63  
64      //JSON KEY
65      private static final String JSON_KEY_FORM = "form";
66      private static final String JSON_KEY_SUBFORMS = "subforms";
67      private static final String JSON_KEY_NAME = "name";
68      private static final String JSON_KEY_FIELDS = "fields";
69      public static final String JSON_KEY_UPLOADED_FILES = "uploadedFiles";
70      public static final String JSON_KEY_FIELD = "field";
71      public static final String JSON_KEY_ERROR = "error";
72      public static final String JSON_KEY_ERROR_MESSAGES = "errorMessages";
73      public static final String JSON_KEY_SUCCESS = "success";
74      public static final String JSON_KEY_FILE_COUNT = "fileCount";
75  
76      /** private constructor */
77      private JSONUtils( )
78      {
79      }
80  
81      /**
82       * Build a JSON flow from a form object that contains fields data
83       * @param form The Form object
84       * @param request The HTTP request
85       * @return The JSON flow
86       */
87      public static String buildJson( Form form, HttpServletRequest request )
88      {
89          JSONObject json = new JSONObject( );
90          JSONObject jsonForm = new JSONObject( );
91          JSONArray jsonSubForms = new JSONArray( );
92  
93          Set<String> subforms = form.getSubForm( ).keySet( );
94  
95          for ( String strSubForm : subforms )
96          {
97              JSONObject jsonSubForm = new JSONObject( );
98              JSONArray jsonFields = new JSONArray( );
99  
100             SubForm subForm = form.getSubForm( strSubForm );
101 
102             for ( Field field : subForm.getFormElements( request ).getFields( ).getField( ) )
103             {
104                 JSONObject jsonField = new JSONObject( );
105                 jsonField.accumulate( field.getName( ), field.getValue( ) );
106 
107                 if ( SharedConstants.FIELD_TYPE_UPLOAD.equals( field.getType( ) ) )
108                 {
109                     // upload file --> add fileItems metadata
110                     List<FileItem> listFileItem = subForm.getFileItems( request, field.getName( ) );
111 
112                     if ( listFileItem != null )
113                     {
114                         for ( FileItem fileItem : listFileItem )
115                         {
116                             if ( fileItem instanceof BlobStoreFileItem )
117                             {
118                                 jsonField.accumulate( BlobStoreFileItem.JSON_KEY_FILE_METADATA_BLOB_ID,
119                                         ( (BlobStoreFileItem) fileItem ).getBlobId( ) );
120                             }
121                         }
122                     }
123                 }
124 
125                 jsonFields.add( jsonField );
126             }
127 
128             jsonSubForm.accumulate( JSON_KEY_NAME, subForm.getName( ) );
129             jsonSubForm.accumulate( JSON_KEY_FIELDS, jsonFields );
130 
131             jsonSubForms.add( jsonSubForm );
132         }
133 
134         jsonForm.accumulate( JSON_KEY_NAME, form.getName( ) );
135         jsonForm.accumulate( JSON_KEY_SUBFORMS, jsonSubForms );
136         json.accumulate( JSON_KEY_FORM, jsonForm );
137 
138         return json.toString( );
139     }
140 
141     /**
142      * Get Blob Id in JSON Format
143      * @param strIdBlob the id blob
144      * @return the string of the blob id in JSON format
145      */
146     public static String buildJsonIdBlob( String strIdBlob )
147     {
148         String strJSON = StringUtils.EMPTY;
149 
150         if ( StringUtils.isNotBlank( strIdBlob ) )
151         {
152             JSONObject json = new JSONObject( );
153             json.accumulate( TAG_ID_BLOB, strIdBlob );
154             strJSON = json.toString( );
155         }
156         else
157         {
158             AppLogService.error( MESSAGE_DATA_NOT_FOUND );
159         }
160 
161         return strJSON;
162     }
163 
164     /**
165      * Get value by given key in JSON Object
166      * @param strData data in JSON
167      * @param strKey the specific key
168      * @return value
169      */
170     public static String getJsonValue( String strData, String strKey )
171     {
172         String strValue = StringUtils.EMPTY;
173 
174         if ( StringUtils.isNotBlank( strData ) && StringUtils.isNotBlank( strKey ) )
175         {
176             JSONObject json = (JSONObject) JSONSerializer.toJSON( strData );
177 
178             strValue = json.getString( strKey );
179         }
180 
181         return strValue;
182     }
183 
184     /**
185      * This method allows to get fields by the name of subform
186      * @param strData data in JSON
187      * @param strKey the specific key
188      * @return value
189      */
190     public static String getJsonValuesFieldsBySubForm( String strData, String strKey )
191     {
192         if ( StringUtils.isNotBlank( strData ) && StringUtils.isNotBlank( strKey ) )
193         {
194             JSONArray jsonList = (JSONArray) JSONSerializer.toJSON( strData );
195 
196             for ( Object o : jsonList )
197             {
198                 String strValue = StringUtils.EMPTY;
199                 JSONObject json = (JSONObject) o;
200                 strValue = json.getString( JSON_KEY_NAME );
201 
202                 if ( strValue.equals( strKey ) )
203                 {
204                     return json.getString( JSON_KEY_FIELDS );
205                 }
206             }
207         }
208 
209         return null;
210     }
211 
212     /**
213      * This method restore the values in the field
214      * @param strJSONFields fields in JSON format
215      * @param field field
216      * @param request the request
217      */
218     public static void doRestoreValuesFields( String strJSONFields, Field field, HttpServletRequest request )
219     {
220         if ( StringUtils.isNotBlank( strJSONFields ) )
221         {
222             JSONArray jsonList = (JSONArray) JSONSerializer.toJSON( strJSONFields );
223 
224             for ( Object o : jsonList )
225             {
226                 JSONObject json = (JSONObject) o;
227 
228                 if ( json.containsKey( field.getName( ) ) )
229                 {
230                     // regular field
231                     field.setValue( json.getString( field.getName( ) ) );
232                 }
233             }
234         }
235     }
236 
237     /**
238      * Get the id blob from the json
239      * @param strData the json
240      * @return the id blob
241      */
242     public static String getIdBlobFromJson( String strData )
243     {
244         return getJsonValue( strData, TAG_ID_BLOB );
245     }
246 
247     /**
248      * Builds a json object for the file item list.
249      * Key is {@link #JSON_UPLOADED_FILES}, value is the array of uploaded file.
250      * @param listFileItem the fileItem list
251      * @return the json
252      */
253     public static JSONObject getUploadedFileJSON( List<FileItem> listFileItem )
254     {
255         JSONObject json = new JSONObject( );
256 
257         if ( listFileItem != null )
258         {
259             for ( FileItem fileItem : listFileItem )
260             {
261                 json.accumulate( JSON_KEY_UPLOADED_FILES, fileItem.getName( ) );
262             }
263 
264             json.element( JSON_KEY_FILE_COUNT, listFileItem.size( ) );
265         }
266         else
267         {
268             // no file
269             json.element( JSON_KEY_FILE_COUNT, 0 );
270         }
271 
272         return json;
273     }
274 }