1 | package fr.mael.jiwigo.dao.impl; |
---|
2 | |
---|
3 | import java.io.BufferedReader; |
---|
4 | import java.io.File; |
---|
5 | import java.io.IOException; |
---|
6 | import java.io.InputStreamReader; |
---|
7 | import java.io.UnsupportedEncodingException; |
---|
8 | import java.net.HttpURLConnection; |
---|
9 | import java.security.NoSuchAlgorithmException; |
---|
10 | import java.util.ArrayList; |
---|
11 | import java.util.HashMap; |
---|
12 | import java.util.List; |
---|
13 | |
---|
14 | import org.apache.http.HttpEntity; |
---|
15 | import org.apache.http.HttpResponse; |
---|
16 | import org.apache.http.client.ClientProtocolException; |
---|
17 | import org.apache.http.client.methods.HttpPost; |
---|
18 | import org.apache.http.entity.BufferedHttpEntity; |
---|
19 | import org.apache.http.entity.mime.MultipartEntity; |
---|
20 | import org.apache.http.entity.mime.content.FileBody; |
---|
21 | import org.apache.http.entity.mime.content.StringBody; |
---|
22 | import org.slf4j.Logger; |
---|
23 | import org.slf4j.LoggerFactory; |
---|
24 | import org.w3c.dom.Document; |
---|
25 | import org.w3c.dom.Element; |
---|
26 | import org.w3c.dom.Node; |
---|
27 | import org.w3c.dom.NodeList; |
---|
28 | |
---|
29 | import sun.misc.BASE64Encoder; |
---|
30 | import fr.mael.jiwigo.dao.ImageDao; |
---|
31 | import fr.mael.jiwigo.om.Image; |
---|
32 | import fr.mael.jiwigo.transverse.enumeration.MethodsEnum; |
---|
33 | import fr.mael.jiwigo.transverse.exception.FileAlreadyExistsException; |
---|
34 | import fr.mael.jiwigo.transverse.exception.JiwigoException; |
---|
35 | import fr.mael.jiwigo.transverse.exception.ProxyAuthenticationException; |
---|
36 | import fr.mael.jiwigo.transverse.exception.WrongChunkSizeException; |
---|
37 | import fr.mael.jiwigo.transverse.session.SessionManager; |
---|
38 | import fr.mael.jiwigo.transverse.session.impl.SessionManagerImpl; |
---|
39 | import fr.mael.jiwigo.transverse.util.Tools; |
---|
40 | |
---|
41 | /* |
---|
42 | * jiwigo-ws-api Piwigo webservice access Api |
---|
43 | * Copyright (c) 2010-2011 Mael mael@le-guevel.com |
---|
44 | * All Rights Reserved |
---|
45 | * |
---|
46 | * This library is free software. It comes without any warranty, to |
---|
47 | * the extent permitted by applicable law. You can redistribute it |
---|
48 | * and/or modify it under the terms of the Do What The Fuck You Want |
---|
49 | * To Public License, Version 2, as published by Sam Hocevar. See |
---|
50 | * http://sam.zoy.org/wtfpl/COPYING for more details. |
---|
51 | */ |
---|
52 | /** |
---|
53 | |
---|
54 | * Dao of the images |
---|
55 | * @author mael |
---|
56 | * |
---|
57 | */ |
---|
58 | public class ImageDaoImpl implements ImageDao { |
---|
59 | |
---|
60 | /** |
---|
61 | * Logger |
---|
62 | */ |
---|
63 | private final Logger LOG = LoggerFactory.getLogger(ImageDaoImpl.class); |
---|
64 | |
---|
65 | /** |
---|
66 | * cache to avoid downloading image for each access |
---|
67 | */ |
---|
68 | private HashMap<Integer, List<Image>> cache; |
---|
69 | |
---|
70 | /** |
---|
71 | * |
---|
72 | */ |
---|
73 | private Integer firstCatInCache; |
---|
74 | |
---|
75 | private SessionManager sessionManager; |
---|
76 | |
---|
77 | private ArrayList<File> filesToSend; |
---|
78 | |
---|
79 | public ImageDaoImpl() { |
---|
80 | cache = new HashMap<Integer, List<Image>>(); |
---|
81 | } |
---|
82 | |
---|
83 | /** |
---|
84 | * Lists all images |
---|
85 | * @return the list of images |
---|
86 | * @throws IOException |
---|
87 | * @throws ProxyAuthenticationException |
---|
88 | */ |
---|
89 | public List<Image> list(boolean refresh) throws JiwigoException { |
---|
90 | return listByCategory(null, refresh); |
---|
91 | } |
---|
92 | |
---|
93 | /** |
---|
94 | * Listing of the images for a category |
---|
95 | * @param categoryId the id of the category |
---|
96 | * @return the list of images |
---|
97 | * @throws IOException |
---|
98 | * @throws ProxyAuthenticationException |
---|
99 | */ |
---|
100 | public List<Image> listByCategory(Integer categoryId, boolean refresh) throws JiwigoException { |
---|
101 | if (refresh || cache.get(categoryId) == null) { |
---|
102 | Document doc = null; |
---|
103 | if (categoryId != null) { |
---|
104 | doc = sessionManager.executeReturnDocument(MethodsEnum.LISTER_IMAGES.getLabel(), "cat_id", |
---|
105 | String.valueOf(categoryId)); |
---|
106 | } else { |
---|
107 | doc = sessionManager.executeReturnDocument(MethodsEnum.LISTER_IMAGES.getLabel()); |
---|
108 | } |
---|
109 | Element element = (Element) doc.getDocumentElement().getElementsByTagName("images").item(0); |
---|
110 | List<Image> images = getImagesFromElement(element); |
---|
111 | cache.remove(categoryId); |
---|
112 | cache.put(categoryId, images); |
---|
113 | if (firstCatInCache == null) { |
---|
114 | firstCatInCache = categoryId; |
---|
115 | } |
---|
116 | return images; |
---|
117 | } else { |
---|
118 | return cache.get(categoryId); |
---|
119 | } |
---|
120 | } |
---|
121 | |
---|
122 | /** |
---|
123 | * Creation of an image<br/> |
---|
124 | * Sequence : <br/> |
---|
125 | * <li> |
---|
126 | * <ul>sending of the thumbnail in base64, thanks to the method addchunk.</ul> |
---|
127 | * <ul>sending of the image in base64, thanks to the method addchunk</ul> |
---|
128 | * <ul>using of the add method to add the image to the database<ul> |
---|
129 | * </li> |
---|
130 | * Finally, the response of the webservice is checked |
---|
131 | * |
---|
132 | * @param image the image to create |
---|
133 | * @return true if the creation of the image was the successful |
---|
134 | * @throws IOException |
---|
135 | * @throws NoSuchAlgorithmException |
---|
136 | * @throws WrongChunkSizeException |
---|
137 | * @throws JiwigoException |
---|
138 | * @throws Exception |
---|
139 | */ |
---|
140 | //TODO ne pas continuer si une des reponses precedentes est negative |
---|
141 | public boolean create(Image image, Double chunkSize) throws FileAlreadyExistsException, IOException, |
---|
142 | ProxyAuthenticationException, NoSuchAlgorithmException, WrongChunkSizeException, JiwigoException { |
---|
143 | //thumbnail converted to base64 |
---|
144 | BASE64Encoder base64 = new BASE64Encoder(); |
---|
145 | |
---|
146 | String thumbnailBase64 = base64.encode(Tools.getBytesFromFile(image.getThumbnail())); |
---|
147 | //sends the thumbnail and gets the result |
---|
148 | Document reponseThumb = (sessionManager.executeReturnDocument("pwg.images.addChunk", "data", thumbnailBase64, |
---|
149 | "type", "thumb", "position", "1", "original_sum", |
---|
150 | Tools.getMD5Checksum(image.getOriginale().getAbsolutePath()))); |
---|
151 | |
---|
152 | //begin feature:0001827 |
---|
153 | int chunk = chunkSize.intValue(); |
---|
154 | if (chunk == 0) { |
---|
155 | throw new WrongChunkSizeException("Error : the chunk size cannot be 0"); |
---|
156 | } |
---|
157 | filesToSend = Tools.splitFile(image.getOriginale(), chunk); |
---|
158 | boolean echec = false; |
---|
159 | for (int i = 0; i < filesToSend.size(); i++) { |
---|
160 | File fichierAEnvoyer = filesToSend.get(i); |
---|
161 | String originaleBase64 = base64.encode(Tools.getBytesFromFile(fichierAEnvoyer)); |
---|
162 | Document reponseOriginale = (sessionManager.executeReturnDocument("pwg.images.addChunk", "data", |
---|
163 | originaleBase64, "type", "file", "position", String.valueOf(i), "original_sum", |
---|
164 | Tools.getMD5Checksum(image.getOriginale().getAbsolutePath()))); |
---|
165 | if (!Tools.checkOk(reponseOriginale)) { |
---|
166 | echec = true; |
---|
167 | break; |
---|
168 | } |
---|
169 | } |
---|
170 | //end |
---|
171 | |
---|
172 | //add the image in the database and get the result of the webservice |
---|
173 | Document reponseAjout = (sessionManager.executeReturnDocument("pwg.images.add", "file_sum", |
---|
174 | Tools.getMD5Checksum(image.getOriginale().getAbsolutePath()), "thumbnail_sum", |
---|
175 | Tools.getMD5Checksum(image.getThumbnail().getCanonicalPath()), "position", "1", "original_sum", |
---|
176 | Tools.getMD5Checksum(image.getOriginale().getAbsolutePath()), "categories", |
---|
177 | String.valueOf(image.getIdCategory()), "name", image.getName(), "author", sessionManager.getLogin(), |
---|
178 | "level", image.getPrivacyLevel())); |
---|
179 | LOG.debug("Response add : " + Tools.documentToString(reponseAjout)); |
---|
180 | // System.out.println(Main.sessionManager.executerReturnString("pwg.images.add", "file_sum", Outil |
---|
181 | // .getMD5Checksum(image.getOriginale().getAbsolutePath()), "thumbnail_sum", Outil.getMD5Checksum(image |
---|
182 | // .getThumbnail().getCanonicalPath()), "position", "1", "original_sum", Outil.getMD5Checksum(image |
---|
183 | // .getOriginale().getAbsolutePath()), "categories", String.valueOf(image.getIdCategory()), "name", image |
---|
184 | // .getName(), "author", Main.sessionManager.getLogin())); |
---|
185 | // Document reponsePrivacy = null; |
---|
186 | // if (Outil.checkOk(reponseAjout)) { |
---|
187 | // reponsePrivacy = Main.sessionManager.executerReturnDocument(MethodsEnum.SET_PRIVACY_LEVEL.getLabel()); |
---|
188 | // } |
---|
189 | boolean reussite = true; |
---|
190 | if (!Tools.checkOk(reponseThumb) || echec || !Tools.checkOk(reponseAjout)) { |
---|
191 | reussite = false; |
---|
192 | } |
---|
193 | deleteTempFiles(); |
---|
194 | return reussite; |
---|
195 | |
---|
196 | } |
---|
197 | |
---|
198 | /** |
---|
199 | * Add tags to an image |
---|
200 | * @param imageId id of the image |
---|
201 | * @param tagId ids of the tags |
---|
202 | * @throws IOException |
---|
203 | * @throws ProxyAuthenticationException |
---|
204 | */ |
---|
205 | public boolean addTags(Integer imageId, String tagId) throws JiwigoException { |
---|
206 | Document doc = sessionManager.executeReturnDocument(MethodsEnum.SET_INFO.getLabel(), "image_id", |
---|
207 | String.valueOf(imageId), "tag_ids", tagId); |
---|
208 | try { |
---|
209 | return Tools.checkOk(doc); |
---|
210 | } catch (FileAlreadyExistsException e) { |
---|
211 | LOG.error(Tools.getStackTrace(e)); |
---|
212 | return false; |
---|
213 | } |
---|
214 | |
---|
215 | } |
---|
216 | |
---|
217 | /** |
---|
218 | * parse an element to find images |
---|
219 | * @param element the element to parse |
---|
220 | * @return the list of images |
---|
221 | */ |
---|
222 | private List<Image> getImagesFromElement(Element element) { |
---|
223 | // List<Element> listElement = (List<Element>) element.getChildren("image"); |
---|
224 | NodeList listImages = element.getElementsByTagName("image"); |
---|
225 | ArrayList<Image> images = new ArrayList<Image>(); |
---|
226 | for (int i = 0; i < listImages.getLength(); i++) { |
---|
227 | Node nodeImage = listImages.item(i); |
---|
228 | if (nodeImage.getNodeType() == Node.ELEMENT_NODE) { |
---|
229 | Element im = (Element) nodeImage; |
---|
230 | Image myImage = new Image(); |
---|
231 | myImage.setThumbnailUrl(im.getAttribute("tn_url")); |
---|
232 | myImage.setUrl(im.getAttribute("element_url")); |
---|
233 | myImage.setWidth(Integer.valueOf(im.getAttribute("width"))); |
---|
234 | myImage.setHeight(Integer.valueOf(im.getAttribute("height"))); |
---|
235 | myImage.setFile(im.getAttribute("file")); |
---|
236 | myImage.setSeen(Integer.valueOf(im.getAttribute("hit"))); |
---|
237 | myImage.setIdentifier(Integer.valueOf(im.getAttribute("id"))); |
---|
238 | myImage.setName(Tools.getStringValueDom(im, "name")); |
---|
239 | Element elementCategories = (Element) im.getElementsByTagName("categories").item(0); |
---|
240 | Element elementCategory = (Element) elementCategories.getElementsByTagName("category").item(0); |
---|
241 | myImage.setIdCategory(Integer.valueOf(elementCategory.getAttribute("id"))); |
---|
242 | if (myImage.getName() == null) { |
---|
243 | myImage.setName(myImage.getFile()); |
---|
244 | } |
---|
245 | images.add(myImage); |
---|
246 | } |
---|
247 | } |
---|
248 | return images; |
---|
249 | } |
---|
250 | |
---|
251 | /** |
---|
252 | * Search images |
---|
253 | * @param searchString the string to search |
---|
254 | * @return the list of images matching the string |
---|
255 | * @throws IOException |
---|
256 | * @throws ProxyAuthenticationException |
---|
257 | */ |
---|
258 | public List<Image> search(String searchString) throws JiwigoException { |
---|
259 | Document doc = sessionManager.executeReturnDocument(MethodsEnum.SEARCH.getLabel(), "query", searchString); |
---|
260 | LOG.debug(Tools.documentToString(doc)); |
---|
261 | Element element = (Element) doc.getDocumentElement().getElementsByTagName("images").item(0); |
---|
262 | return getImagesFromElement(element); |
---|
263 | |
---|
264 | } |
---|
265 | |
---|
266 | private void deleteTempFiles() { |
---|
267 | File file = new File(System.getProperty("java.io.tmpdir") + "/originale.jpg"); |
---|
268 | file.delete(); |
---|
269 | file = new File(System.getProperty("java.io.tmpdir") + "/thumb.jpg"); |
---|
270 | file.delete(); |
---|
271 | for (File tempCut : filesToSend) { |
---|
272 | tempCut.delete(); |
---|
273 | } |
---|
274 | |
---|
275 | } |
---|
276 | |
---|
277 | public void addSimple(File file, Integer category, String title) throws JiwigoException { |
---|
278 | HttpPost httpMethod = new HttpPost(((SessionManagerImpl) sessionManager).getUrl()); |
---|
279 | |
---|
280 | // nameValuePairs.add(new BasicNameValuePair("method", "pwg.images.addSimple")); |
---|
281 | // for (int i = 0; i < parametres.length; i += 2) { |
---|
282 | // nameValuePairs.add(new BasicNameValuePair(parametres[i], parametres[i + 1])); |
---|
283 | // } |
---|
284 | // method.setEntity(new UrlEncodedFormEntity(nameValuePairs)); |
---|
285 | |
---|
286 | if (file != null) { |
---|
287 | MultipartEntity multipartEntity = new MultipartEntity(); |
---|
288 | |
---|
289 | // String string = nameValuePairs.toString(); |
---|
290 | // dirty fix to remove the enclosing entity{} |
---|
291 | // String substring = string.substring(string.indexOf("{"), |
---|
292 | // string.lastIndexOf("}") + 1); |
---|
293 | try { |
---|
294 | multipartEntity.addPart("method", new StringBody("pwg.images.addSimple")); |
---|
295 | multipartEntity.addPart("category", new StringBody(category.toString())); |
---|
296 | multipartEntity.addPart("name", new StringBody(title)); |
---|
297 | } catch (UnsupportedEncodingException e) { |
---|
298 | throw new JiwigoException(e); |
---|
299 | } |
---|
300 | |
---|
301 | // StringBody contentBody = new StringBody(substring, |
---|
302 | // Charset.forName("UTF-8")); |
---|
303 | // multipartEntity.addPart("entity", contentBody); |
---|
304 | FileBody fileBody = new FileBody(file); |
---|
305 | multipartEntity.addPart("image", fileBody); |
---|
306 | ((HttpPost) httpMethod).setEntity(multipartEntity); |
---|
307 | } |
---|
308 | |
---|
309 | HttpResponse response; |
---|
310 | StringBuilder sb = new StringBuilder(); |
---|
311 | try { |
---|
312 | response = ((SessionManagerImpl) sessionManager).getClient().execute(httpMethod); |
---|
313 | |
---|
314 | int responseStatusCode = response.getStatusLine().getStatusCode(); |
---|
315 | |
---|
316 | switch (responseStatusCode) { |
---|
317 | case HttpURLConnection.HTTP_CREATED: |
---|
318 | break; |
---|
319 | case HttpURLConnection.HTTP_OK: |
---|
320 | break; |
---|
321 | case HttpURLConnection.HTTP_BAD_REQUEST: |
---|
322 | throw new JiwigoException("status code was : " + responseStatusCode); |
---|
323 | case HttpURLConnection.HTTP_FORBIDDEN: |
---|
324 | throw new JiwigoException("status code was : " + responseStatusCode); |
---|
325 | case HttpURLConnection.HTTP_NOT_FOUND: |
---|
326 | throw new JiwigoException("status code was : " + responseStatusCode); |
---|
327 | default: |
---|
328 | throw new JiwigoException("status code was : " + responseStatusCode); |
---|
329 | } |
---|
330 | |
---|
331 | HttpEntity resultEntity = response.getEntity(); |
---|
332 | BufferedHttpEntity responseEntity = new BufferedHttpEntity(resultEntity); |
---|
333 | |
---|
334 | BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent())); |
---|
335 | String line; |
---|
336 | |
---|
337 | try { |
---|
338 | while ((line = reader.readLine()) != null) { |
---|
339 | sb.append(line); |
---|
340 | sb.append("\n"); |
---|
341 | } |
---|
342 | } finally { |
---|
343 | reader.close(); |
---|
344 | } |
---|
345 | } catch (ClientProtocolException e) { |
---|
346 | throw new JiwigoException(e); |
---|
347 | } catch (IOException e) { |
---|
348 | throw new JiwigoException(e); |
---|
349 | } |
---|
350 | String stringResult = sb.toString(); |
---|
351 | |
---|
352 | } |
---|
353 | |
---|
354 | public SessionManager getSessionManager() { |
---|
355 | return sessionManager; |
---|
356 | } |
---|
357 | |
---|
358 | public void setSessionManager(SessionManager sessionManager) { |
---|
359 | this.sessionManager = sessionManager; |
---|
360 | } |
---|
361 | } |
---|