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

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

Translation of the comments
French -> English

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