source: extensions/jiwigo-ws-api/src/main/java/fr/mael/jiwigo/dao/ImageDao.java @ 9394

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

Major bug fix :
The ImageService allowed the chunk size to be 0 which led to fill the temporary folder.
Now an exception is thrown if the value is 0

File size: 9.6 KB
Line 
1package fr.mael.jiwigo.dao;
2
3import java.io.File;
4import java.io.IOException;
5import java.util.ArrayList;
6import java.util.HashMap;
7import java.util.List;
8
9import org.jdom.Document;
10import org.jdom.Element;
11
12import sun.misc.BASE64Encoder;
13import fr.mael.jiwigo.om.Image;
14import fr.mael.jiwigo.transverse.enumeration.MethodsEnum;
15import fr.mael.jiwigo.transverse.exception.WrongChunkSizeException;
16import fr.mael.jiwigo.transverse.session.SessionManager;
17import fr.mael.jiwigo.transverse.util.Tools;
18
19/*
20Copyright (c) 2010, Mael
21All rights reserved.
22
23Redistribution and use in source and binary forms, with or without
24modification, are permitted provided that the following conditions are met:
25 * Redistributions of source code must retain the above copyright
26   notice, this list of conditions and the following disclaimer.
27 * Redistributions in binary form must reproduce the above copyright
28   notice, this list of conditions and the following disclaimer in the
29   documentation and/or other materials provided with the distribution.
30 * Neither the name of jiwigo nor the
31   names of its contributors may be used to endorse or promote products
32   derived from this software without specific prior written permission.
33
34THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
35ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
36WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
37DISCLAIMED. IN NO EVENT SHALL Mael BE LIABLE FOR ANY
38DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
39(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
40LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
41ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
42(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
43SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44*/
45/**
46
47 * Dao of the images
48 * @author mael
49 *
50 */
51public class ImageDao {
52
53    /**
54     * Logger
55     */
56    public static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory
57            .getLog(ImageDao.class);
58
59    /**
60     * Singleton
61     */
62    private static ImageDao instance;
63
64    /**
65     * cache to avoid downloading image for each access
66     */
67    private HashMap<Integer, List<Image>> cache;
68
69    /**
70     *
71     */
72    private Integer firstCatInCache;
73
74    private SessionManager sessionManager;
75
76    private ArrayList<File> filesToSend;
77
78    /**
79     * Private singleton, to use a singleton
80     */
81    private ImageDao(SessionManager sessionManager) {
82        cache = new HashMap<Integer, List<Image>>();
83        this.sessionManager = sessionManager;
84    }
85
86    /**
87     * @return le singleton
88     */
89    public static ImageDao getInstance(SessionManager sessionManager) {
90        if (instance == null) {
91            instance = new ImageDao(sessionManager);
92        }
93        return instance;
94    }
95
96    /**
97     * Lists all images
98     * @return the list of images
99     * @throws IOException
100     */
101    public List<Image> list(boolean refresh) throws IOException {
102        return listByCategory(null, refresh);
103    }
104
105    /**
106     * Listing of the images for a category
107     * @param categoryId the id of the category
108     * @return the list of images
109     * @throws IOException
110     */
111    public List<Image> listByCategory(Integer categoryId, boolean refresh) throws IOException {
112        if (refresh || cache.get(categoryId) == null) {
113            Document doc = null;
114
115            if (categoryId != null) {
116                doc = sessionManager.executeReturnDocument(MethodsEnum.LISTER_IMAGES.getLabel(), "cat_id", String
117                        .valueOf(categoryId));
118            } else {
119                doc = sessionManager.executeReturnDocument(MethodsEnum.LISTER_IMAGES.getLabel());
120            }
121            Element element = doc.getRootElement().getChild("images");
122            List<Image> images = getImagesFromElement(element);
123            cache.remove(categoryId);
124            cache.put(categoryId, images);
125            if (firstCatInCache == null) {
126                firstCatInCache = categoryId;
127            }
128            return images;
129        } else {
130            return cache.get(categoryId);
131        }
132    }
133
134    /**
135     * Creation of an image<br/>
136     * Sequence : <br/>
137     * <li>
138     * <ul>sending of the thumbnail in base64, thanks to the method addchunk.</ul>
139     * <ul>sending of the image in base64, thanks to the method addchunk</ul>
140     * <ul>using of the add method to add the image to the database<ul>
141     * </li>
142     * Finally, the response of the webservice is checked
143     *
144     * @param image the image to create
145     * @return true if the creation of the image was the successful
146     * @throws Exception
147     */
148    //TODO ne pas continuer si une des reponses precedentes est negative
149    public boolean create(Image image, Double chunkSize) throws Exception {
150        //thumbnail converted to base64
151        BASE64Encoder base64 = new BASE64Encoder();
152
153        String thumbnailBase64 = base64.encode(Tools.getBytesFromFile(image.getThumbnail()));
154        //sends the thumbnail and gets the result
155        Document reponseThumb = (sessionManager.executeReturnDocument("pwg.images.addChunk", "data", thumbnailBase64,
156                "type", "thumb", "position", "1", "original_sum", Tools.getMD5Checksum(image.getOriginale()
157                        .getAbsolutePath())));
158
159        //begin feature:0001827
160        int chunk = chunkSize.intValue();
161        if (chunk == 0) {
162            throw new WrongChunkSizeException("Error : the chunk size cannot be 0");
163        }
164        filesToSend = Tools.splitFile(image.getOriginale(), chunk);
165        boolean echec = false;
166        for (int i = 0; i < filesToSend.size(); i++) {
167            File fichierAEnvoyer = filesToSend.get(i);
168            String originaleBase64 = base64.encode(Tools.getBytesFromFile(fichierAEnvoyer));
169            Document reponseOriginale = (sessionManager.executeReturnDocument("pwg.images.addChunk", "data",
170                    originaleBase64, "type", "file", "position", String.valueOf(i), "original_sum", Tools
171                            .getMD5Checksum(image.getOriginale().getAbsolutePath())));
172            if (!Tools.checkOk(reponseOriginale)) {
173                echec = true;
174                break;
175            }
176        }
177        //end
178
179        //add the image in the database and get the result of the webservice
180        Document reponseAjout = (sessionManager.executeReturnDocument("pwg.images.add", "file_sum", Tools
181                .getMD5Checksum(image.getOriginale().getAbsolutePath()), "thumbnail_sum", Tools.getMD5Checksum(image
182                .getThumbnail().getCanonicalPath()), "position", "1", "original_sum", Tools.getMD5Checksum(image
183                .getOriginale().getAbsolutePath()), "categories", String.valueOf(image.getIdCategory()), "name", image
184                .getName(), "author", sessionManager.getLogin(), "level", image.getPrivacyLevel()));
185        LOG.debug("Response add : " + Tools.documentToString(reponseAjout));
186        //      System.out.println(Main.sessionManager.executerReturnString("pwg.images.add", "file_sum", Outil
187        //              .getMD5Checksum(image.getOriginale().getAbsolutePath()), "thumbnail_sum", Outil.getMD5Checksum(image
188        //              .getThumbnail().getCanonicalPath()), "position", "1", "original_sum", Outil.getMD5Checksum(image
189        //              .getOriginale().getAbsolutePath()), "categories", String.valueOf(image.getIdCategory()), "name", image
190        //              .getName(), "author", Main.sessionManager.getLogin()));
191        //      Document reponsePrivacy = null;
192        //      if (Outil.checkOk(reponseAjout)) {
193        //          reponsePrivacy = Main.sessionManager.executerReturnDocument(MethodsEnum.SET_PRIVACY_LEVEL.getLabel());
194        //      }
195        boolean reussite = true;
196        if (!Tools.checkOk(reponseThumb) || echec || !Tools.checkOk(reponseAjout)) {
197            reussite = false;
198        }
199        deleteTempFiles();
200        return reussite;
201
202    }
203
204    /**
205     * Add tags to an image
206     * @param imageId id of the image
207     * @param tagId ids of the tags
208     * @throws IOException
209     */
210    public boolean addTags(Integer imageId, String tagId) throws IOException {
211        Document doc = sessionManager.executeReturnDocument(MethodsEnum.SET_INFO.getLabel(), "image_id", String
212                .valueOf(imageId), "tag_ids", tagId);
213        return Tools.checkOk(doc);
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        ArrayList<Image> images = new ArrayList<Image>();
225        for (Element im : listElement) {
226            Image myImage = new Image();
227            myImage.setThumbnailUrl(im.getAttributeValue("tn_url"));
228            myImage.setUrl(im.getAttributeValue("element_url"));
229            myImage.setWidth(Integer.valueOf(im.getAttributeValue("width")));
230            myImage.setHeight(Integer.valueOf(im.getAttributeValue("height")));
231            myImage.setFile(im.getAttributeValue("file"));
232            myImage.setSeen(Integer.valueOf(im.getAttributeValue("hit")));
233            myImage.setIdentifier(Integer.valueOf(im.getAttributeValue("id")));
234            myImage.setName(im.getChildText("name"));
235            //      myImage.setIdCategory(Integer.valueOf(im.getChild("categories").getChild("category")
236            //              .getAttributeValue("id")));
237            if (myImage.getName() == null) {
238                myImage.setName(myImage.getFile());
239            }
240            images.add(myImage);
241        }
242        return images;
243    }
244
245    /**
246     * Search images
247     * @param searchString the string to search
248     * @return the list of images matching the string
249     * @throws IOException
250     */
251    public List<Image> search(String searchString) throws IOException {
252        Document doc = sessionManager.executeReturnDocument(MethodsEnum.SEARCH.getLabel(), "query", searchString);
253        LOG.debug(doc);
254        Element element = doc.getRootElement().getChild("images");
255        return getImagesFromElement(element);
256
257    }
258
259    private void deleteTempFiles() {
260        File file = new File(System.getProperty("java.io.tmpdir") + "/originale.jpg");
261        file.delete();
262        file = new File(System.getProperty("java.io.tmpdir") + "/thumb.jpg");
263        file.delete();
264        for (File tempCut : filesToSend) {
265            tempCut.delete();
266        }
267
268    }
269
270}
Note: See TracBrowser for help on using the repository browser.