View Javadoc
1   /*
2    * Copyright (c) 2002-2017, 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.directory.utils;
35  
36  import fr.paris.lutece.plugins.directory.service.upload.DirectoryAsynchronousUploadHandler;
37  
38  import net.sf.json.JSONArray;
39  import net.sf.json.JSONObject;
40  import net.sf.json.JSONSerializer;
41  
42  import org.apache.commons.fileupload.FileItem;
43  import org.apache.commons.lang.StringUtils;
44  
45  import java.util.HashMap;
46  import java.util.List;
47  import java.util.Map;
48  
49  /**
50   *
51   * JSONUtils
52   *
53   */
54  public final class JSONUtils
55  {
56      // JSON
57      private static final String JSON_KEY_FORM_ERROR = "directory_error";
58      private static final String JSON_KEY_SUCCESS = "success";
59      private static final String JSON_KEY_FIELD_NAME = "field_name";
60      private static final String JSON_KEY_UPLOADED_FILES = "uploadedFiles";
61      private static final String JSON_KEY_UPLOADED_FILES_SIZE = "uploadedFilesSize";
62      private static final String JSON_KEY_FILE_COUNT = "fileCount";
63      private static final String KEY_USER_ATTRIBUTES = "user-attributes";
64  
65      /**
66       * Private constructor
67       */
68      private JSONUtils( )
69      {
70      }
71  
72      /**
73       * Builds a json object with the error message.
74       * 
75       * @param strMessage
76       *            the error message
77       * @return the json object.
78       */
79      public static JSONObject buildJsonError( String strMessage )
80      {
81          JSONObject json = new JSONObject( );
82          buildJsonError( json, strMessage );
83  
84          return json;
85      }
86  
87      /**
88       * Builds a json object with the error message.
89       * 
90       * @param json
91       *            the JSON
92       * @param strMessage
93       *            the error message
94       */
95      public static void buildJsonError( JSONObject json, String strMessage )
96      {
97          if ( json != null )
98          {
99              json.accumulate( JSON_KEY_FORM_ERROR, strMessage );
100         }
101     }
102 
103     /**
104      * Build the json form success removing file
105      * 
106      * @param strIdEntry
107      *            the id entry
108      * @param strSessionId
109      *            the session id
110      * @return the json object
111      */
112     public static JSONObject buildJsonSuccess( String strIdEntry, String strSessionId )
113     {
114         JSONObject json = new JSONObject( );
115         json.accumulateAll( getUploadedFileJSON( DirectoryAsynchronousUploadHandler.getHandler( ).getFileItems( strIdEntry, strSessionId ) ) );
116         buildJsonSuccess( DirectoryAsynchronousUploadHandler.getHandler( ).buildFieldName( strIdEntry ), json );
117 
118         return json;
119     }
120 
121     /**
122      * Build the json form success removing file
123      * 
124      * @param strFieldName
125      *            the field name (WARNING : it is not the id entry, it is 'directory_' + id_entry, ex: directory_11)
126      * @param json
127      *            the JSON object
128      */
129     public static void buildJsonSuccess( String strFieldName, JSONObject json )
130     {
131         if ( json != null )
132         {
133             // operation successful
134             json.element( JSON_KEY_SUCCESS, JSONUtils.JSON_KEY_SUCCESS );
135             json.element( JSON_KEY_FIELD_NAME, strFieldName );
136         }
137     }
138 
139     /**
140      * Builds a json object for the file item list. Key is {@link #JSON_KEY_UPLOADED_FILES}, value is the array of uploaded file.
141      * 
142      * @param listFileItem
143      *            the fileItem list
144      * @return the json
145      */
146     public static JSONObject getUploadedFileJSON( List<FileItem> listFileItem )
147     {
148         JSONObject json = new JSONObject( );
149 
150         if ( listFileItem != null )
151         {
152             for ( FileItem fileItem : listFileItem )
153             {
154                 json.accumulate( JSON_KEY_UPLOADED_FILES, fileItem.getName( ) );
155                 json.accumulate( JSON_KEY_UPLOADED_FILES_SIZE, fileItem.getSize( ) );
156             }
157 
158             json.element( JSON_KEY_FILE_COUNT, listFileItem.size( ) );
159         }
160         else
161         {
162             // no file
163             json.element( JSON_KEY_FILE_COUNT, 0 );
164         }
165 
166         return json;
167     }
168 
169     /**
170      * Get the user infos. <br>
171      * The json must be written with the following format : <br>
172      * <code>
173      * <br>{ "user-attributes": [
174      * <br>{ "user-attribute-key": "user.name.family", "user-attribute-value": "FAMILYNAME" },
175      * <br>{ "user-attribute-key": "user.home-info.online.email", "user-attribute-value": "EMAIL@EMAIL.EMAIL"}
176      * <br>] }
177      * </code>
178      * 
179      * @param strJSON
180      *            the json
181      * @return the user attributes
182      */
183     public static Map<String, String> getUserInfos( String strJSON )
184     {
185         Map<String, String> userInfos = new HashMap<String, String>( );
186 
187         if ( StringUtils.isNotBlank( strJSON ) )
188         {
189             // Get object "user-attributes"
190             JSONObject json = (JSONObject) JSONSerializer.toJSON( strJSON );
191 
192             if ( json != null )
193             {
194                 // Get sub-objects of "user-attributes"
195                 JSONArray arrayUserAttributes = json.getJSONArray( KEY_USER_ATTRIBUTES );
196 
197                 if ( arrayUserAttributes != null )
198                 {
199                     // Browse each user attribute
200                     for ( int i = 0; i < arrayUserAttributes.size( ); i++ )
201                     {
202                         put( userInfos, arrayUserAttributes.getJSONObject( i ) );
203                     }
204                 }
205             }
206         }
207 
208         return userInfos;
209     }
210 
211     /**
212      * Insert user attribute to the map
213      * 
214      * @param userInfos
215      *            the map
216      * @param userAttribute
217      *            the user attribute
218      */
219     private static void put( Map<String, String> userInfos, JSONObject userAttribute )
220     {
221         if ( userAttribute != null )
222         {
223             JSONArray listCodes = userAttribute.names( );
224 
225             for ( int i = 0; i < listCodes.size( ); i++ )
226             {
227                 String strCode = listCodes.getString( i );
228                 String strValue = userAttribute.getString( strCode );
229                 userInfos.put( strCode, strValue );
230             }
231         }
232     }
233 }