1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package fr.paris.lutece.plugins.asynchronousupload.util;
35
36 import java.util.List;
37
38 import javax.servlet.http.HttpServletRequest;
39 import javax.xml.bind.DatatypeConverter;
40
41 import org.apache.commons.fileupload.FileItem;
42 import org.apache.commons.lang3.StringUtils;
43
44 import fr.paris.lutece.portal.service.i18n.I18nService;
45 import fr.paris.lutece.util.file.FileUtil;
46 import net.sf.json.JSONObject;
47
48
49
50
51
52 public final class JSONUtils
53 {
54
55
56
57 public static final String JSON_KEY_FIELD_NAME = "field_name";
58
59
60
61
62 public static final String JSON_KEY_SUCCESS = "success";
63 private static final String JSON_KEY_FILE_NAME = "name";
64 private static final String JSON_KEY_FILE_SIZE = "size";
65 private static final String JSON_KEY_FILE_PREVIEW = "preview";
66 private static final String JSON_KEY_FORM_ERROR = "form_error";
67 private static final String JSON_KEY_UPLOADED_FILES = "files";
68 private static final String JSON_KEY_FILE_COUNT = "fileCount";
69
70
71 private static final String PROPERTY_MESSAGE_ERROR_REMOVING_FILE = "form.message.error.removingFile";
72
73
74
75
76 private JSONUtils( )
77 {
78
79 }
80
81
82
83
84
85
86
87
88 public static JSONObject getUploadedFileJSON( List<FileItem> listFileItem )
89 {
90 JSONObject json = new JSONObject( );
91
92 if ( listFileItem != null )
93 {
94 for ( FileItem fileItem : listFileItem )
95 {
96 JSONObject jsonObject = new JSONObject( );
97 jsonObject.element( JSON_KEY_FILE_NAME, fileItem.getName( ) );
98 jsonObject.element( JSON_KEY_FILE_PREVIEW, getPreviewImage( fileItem ) );
99 jsonObject.element( JSON_KEY_FILE_SIZE, fileItem.getSize( ) );
100 json.accumulate( JSON_KEY_UPLOADED_FILES, jsonObject );
101 }
102
103 json.element( JSON_KEY_FILE_COUNT, listFileItem.size( ) );
104 }
105 else
106 {
107
108 json.element( JSON_KEY_FILE_COUNT, 0 );
109 }
110
111 return json;
112 }
113
114
115
116
117
118
119
120
121 public static JSONObject buildJsonErrorRemovingFile( HttpServletRequest request )
122 {
123 JSONObject json = new JSONObject( );
124
125 json.element( JSON_KEY_FORM_ERROR, I18nService.getLocalizedString( PROPERTY_MESSAGE_ERROR_REMOVING_FILE, request.getLocale( ) ) );
126
127 return json;
128 }
129
130
131
132
133
134
135
136
137
138 public static void buildJsonError( JSONObject json, String strMessage )
139 {
140 if ( json != null )
141 {
142 json.accumulate( JSON_KEY_FORM_ERROR, strMessage );
143 }
144 }
145
146 private static String getPreviewImage( FileItem fileItem )
147 {
148
149 if ( FileUtil.hasImageExtension( fileItem.getName( ) ) )
150 {
151
152 return "data:image/png;base64," + DatatypeConverter.printBase64Binary( fileItem.get( ) );
153 }
154
155 return StringUtils.EMPTY;
156 }
157 }