source: extensions/jiwigo/trunk/src/main/java/fr/mael/jiwigo/dao/ImageDao.java @ 7070

Last change on this file since 7070 was 7070, checked in by mlg, 14 years ago

New feature : management of the privacy level ;
feature:0001888
Moved ImagesManagement from ui to transverse

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