source: extensions/jiwigo-ws-api/src/main/java/fr/mael/jiwigo/dao/impl/ImageDaoImpl.java @ 10704

Last change on this file since 10704 was 10704, checked in by mlg, 13 years ago

Delete useless println

File size: 13.1 KB
Line 
1package fr.mael.jiwigo.dao.impl;
2
3import java.io.BufferedReader;
4import java.io.File;
5import java.io.IOException;
6import java.io.InputStreamReader;
7import java.io.UnsupportedEncodingException;
8import java.net.HttpURLConnection;
9import java.security.NoSuchAlgorithmException;
10import java.util.ArrayList;
11import java.util.HashMap;
12import java.util.List;
13
14import org.apache.http.HttpEntity;
15import org.apache.http.HttpResponse;
16import org.apache.http.client.ClientProtocolException;
17import org.apache.http.client.methods.HttpPost;
18import org.apache.http.entity.BufferedHttpEntity;
19import org.apache.http.entity.mime.MultipartEntity;
20import org.apache.http.entity.mime.content.FileBody;
21import org.apache.http.entity.mime.content.StringBody;
22import org.slf4j.Logger;
23import org.slf4j.LoggerFactory;
24import org.w3c.dom.Document;
25import org.w3c.dom.Element;
26import org.w3c.dom.Node;
27import org.w3c.dom.NodeList;
28
29import sun.misc.BASE64Encoder;
30import fr.mael.jiwigo.dao.ImageDao;
31import fr.mael.jiwigo.om.Image;
32import fr.mael.jiwigo.transverse.enumeration.MethodsEnum;
33import fr.mael.jiwigo.transverse.exception.FileAlreadyExistsException;
34import fr.mael.jiwigo.transverse.exception.JiwigoException;
35import fr.mael.jiwigo.transverse.exception.ProxyAuthenticationException;
36import fr.mael.jiwigo.transverse.exception.WrongChunkSizeException;
37import fr.mael.jiwigo.transverse.session.SessionManager;
38import fr.mael.jiwigo.transverse.session.impl.SessionManagerImpl;
39import 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 */
58public 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                if (elementCategories != null) {
241                    Element elementCategory = (Element) elementCategories.getElementsByTagName("category").item(0);
242                    myImage.setIdCategory(Integer.valueOf(elementCategory.getAttribute("id")));
243                    if (myImage.getName() == null) {
244                        myImage.setName(myImage.getFile());
245                    }
246                }
247                images.add(myImage);
248            }
249        }
250        return images;
251    }
252
253    /**
254     * Search images
255     * @param searchString the string to search
256     * @return the list of images matching the string
257     * @throws IOException
258     * @throws ProxyAuthenticationException
259     */
260    public List<Image> search(String searchString) throws JiwigoException {
261        Document doc = sessionManager.executeReturnDocument(MethodsEnum.SEARCH.getLabel(), "query", searchString);
262        LOG.debug(Tools.documentToString(doc));
263        Element element = (Element) doc.getDocumentElement().getElementsByTagName("images").item(0);
264        return getImagesFromElement(element);
265
266    }
267
268    private void deleteTempFiles() {
269        File file = new File(System.getProperty("java.io.tmpdir") + "/originale.jpg");
270        file.delete();
271        file = new File(System.getProperty("java.io.tmpdir") + "/thumb.jpg");
272        file.delete();
273        for (File tempCut : filesToSend) {
274            tempCut.delete();
275        }
276
277    }
278
279    public void addSimple(File file, Integer category, String title) throws JiwigoException {
280        HttpPost httpMethod = new HttpPost(((SessionManagerImpl) sessionManager).getUrl());
281
282        //      nameValuePairs.add(new BasicNameValuePair("method", "pwg.images.addSimple"));
283        //      for (int i = 0; i < parametres.length; i += 2) {
284        //          nameValuePairs.add(new BasicNameValuePair(parametres[i], parametres[i + 1]));
285        //      }
286        //      method.setEntity(new UrlEncodedFormEntity(nameValuePairs));
287
288        if (file != null) {
289            MultipartEntity multipartEntity = new MultipartEntity();
290
291            //          String string = nameValuePairs.toString();
292            // dirty fix to remove the enclosing entity{}
293            //          String substring = string.substring(string.indexOf("{"),
294            //                          string.lastIndexOf("}") + 1);
295            try {
296                multipartEntity.addPart("method", new StringBody("pwg.images.addSimple"));
297                multipartEntity.addPart("category", new StringBody(category.toString()));
298                multipartEntity.addPart("name", new StringBody(title));
299            } catch (UnsupportedEncodingException e) {
300                throw new JiwigoException(e);
301            }
302
303            //          StringBody contentBody = new StringBody(substring,
304            //                          Charset.forName("UTF-8"));
305            //          multipartEntity.addPart("entity", contentBody);
306            FileBody fileBody = new FileBody(file);
307            multipartEntity.addPart("image", fileBody);
308            ((HttpPost) httpMethod).setEntity(multipartEntity);
309        }
310
311        HttpResponse response;
312        StringBuilder sb = new StringBuilder();
313        try {
314            response = ((SessionManagerImpl) sessionManager).getClient().execute(httpMethod);
315
316            int responseStatusCode = response.getStatusLine().getStatusCode();
317
318            switch (responseStatusCode) {
319            case HttpURLConnection.HTTP_CREATED:
320                break;
321            case HttpURLConnection.HTTP_OK:
322                break;
323            case HttpURLConnection.HTTP_BAD_REQUEST:
324                throw new JiwigoException("status code was : " + responseStatusCode);
325            case HttpURLConnection.HTTP_FORBIDDEN:
326                throw new JiwigoException("status code was : " + responseStatusCode);
327            case HttpURLConnection.HTTP_NOT_FOUND:
328                throw new JiwigoException("status code was : " + responseStatusCode);
329            default:
330                throw new JiwigoException("status code was : " + responseStatusCode);
331            }
332
333            HttpEntity resultEntity = response.getEntity();
334            BufferedHttpEntity responseEntity = new BufferedHttpEntity(resultEntity);
335
336            BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
337            String line;
338
339            try {
340                while ((line = reader.readLine()) != null) {
341                    sb.append(line);
342                    sb.append("\n");
343                }
344            } finally {
345                reader.close();
346            }
347        } catch (ClientProtocolException e) {
348            throw new JiwigoException(e);
349        } catch (IOException e) {
350            throw new JiwigoException(e);
351        }
352        String stringResult = sb.toString();
353
354    }
355
356    public SessionManager getSessionManager() {
357        return sessionManager;
358    }
359
360    public void setSessionManager(SessionManager sessionManager) {
361        this.sessionManager = sessionManager;
362    }
363}
Note: See TracBrowser for help on using the repository browser.