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

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

implements feature : the number of thumbnails in the thumbnails viewer is adapted to the size of the frame
not perfect but better
feature:0001838

File size: 9.3 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;
8import org.jdom.Document;
9import org.jdom.Element;
10import sun.misc.BASE64Encoder;
11import fr.mael.jiwigo.Main;
12import fr.mael.jiwigo.om.Image;
13import fr.mael.jiwigo.transverse.ImagesManagement;
14import fr.mael.jiwigo.transverse.enumeration.MethodsEnum;
15import fr.mael.jiwigo.transverse.enumeration.PreferencesEnum;
16import fr.mael.jiwigo.transverse.util.Outil;
17import fr.mael.jiwigo.transverse.util.preferences.PreferencesManagement;
18
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        /**
53         * Logger
54         */
55        public static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.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        /**
74         * Private singleton, to use a singleton
75         */
76        private ImageDao() {
77                cache = new HashMap<Integer, List<Image>>();
78        }
79
80
81        /**
82         * @return le singleton
83         */
84        public static ImageDao getInstance() {
85                if (instance == null) {
86                        instance = new ImageDao();
87                }
88                return instance;
89        }
90
91
92        /**
93         * Lists all images
94         * @return the list of images
95         * @throws IOException
96         */
97        public List<Image> lister(boolean rafraichir) throws IOException {
98                return listerParCategory(null, rafraichir);
99        }
100
101
102        /**
103         * Listing of the images for a category
104         * @param categoryId the id of the category
105         * @return the list of images
106         * @throws IOException
107         */
108        public List<Image> listerParCategory(Integer categoryId, boolean rafraichir) throws IOException {
109                if (rafraichir || cache.get(categoryId) == null) {
110                        Document doc = null;
111
112                        if (categoryId != null) {
113                                doc = Main.sessionManager.executerReturnDocument(MethodsEnum.LISTER_IMAGES.getLabel(), "cat_id",
114                                                String.valueOf(categoryId));
115                        } else {
116                                doc = Main.sessionManager.executerReturnDocument(MethodsEnum.LISTER_IMAGES.getLabel());
117                        }
118                        Element element = doc.getRootElement().getChild("images");
119                        List<Image> images = getImagesFromElement(element);
120                        cache.remove(categoryId);
121                        cache.put(categoryId, images);
122                        if (firstCatInCache == null) {
123                                firstCatInCache = categoryId;
124                        }
125                        return images;
126                } else {
127                        return cache.get(categoryId);
128                }
129        }
130
131
132        /**
133         * Creation of an image<br/>
134         * Sequence : <br/>
135         * <li>
136         * <ul>sending of the thumbnail in base64, thanks to the method addchunk.</ul>
137         * <ul>sending of the image in base64, thanks to the method addchunk</ul>
138         * <ul>using of the add method to add the image to the database<ul>
139         * </li>
140         * Finally, the response of the webservice is checked
141         *
142         * @param the image to create
143         * @return true if the creation of the image was the successful
144         * @throws Exception
145         */
146        //TODO ne pas continuer si une des réponses précédentes est négative
147        public boolean creer(Image image) throws Exception {
148                //thumbnail converted to base64
149                BASE64Encoder base64 = new BASE64Encoder();
150
151                String thumbnailBase64 = base64.encode(Outil.getBytesFromFile(image.getThumbnail()));
152                //sends the thumbnail and gets the result
153                Document reponseThumb = (Main.sessionManager.executerReturnDocument("pwg.images.addChunk", "data", thumbnailBase64,
154                                "type", "thumb", "position", "1", "original_sum", Outil.getMD5Checksum(image.getOriginale().getAbsolutePath())));
155
156                //begin feature:0001827
157                Double doubleChunk = Double.parseDouble(PreferencesManagement.getValue(PreferencesEnum.CHUNK_SIZE.getLabel())) * 1000 * 1024;
158                int chunk = doubleChunk.intValue();
159                ArrayList<File> fichiersAEnvoyer = Outil.splitFile(image.getOriginale(), chunk);
160                boolean echec = false;
161                for (int i = 0; i < fichiersAEnvoyer.size(); i++) {
162                        File fichierAEnvoyer = fichiersAEnvoyer.get(i);
163                        String originaleBase64 = base64.encode(Outil.getBytesFromFile(fichierAEnvoyer));
164                        Document reponseOriginale = (Main.sessionManager.executerReturnDocument("pwg.images.addChunk", "data",
165                                        originaleBase64, "type", "file", "position", String.valueOf(i), "original_sum",
166                                        Outil.getMD5Checksum(image.getOriginale().getAbsolutePath())));
167                        if (!Outil.checkOk(reponseOriginale)) {
168                                echec = true;
169                                break;
170                        }
171                }
172                //end
173
174                //add the image in the database and get the result of the webservice
175                Document reponseAjout = (Main.sessionManager.executerReturnDocument("pwg.images.add", "file_sum",
176                                Outil.getMD5Checksum(image.getOriginale().getAbsolutePath()), "thumbnail_sum",
177                                Outil.getMD5Checksum(image.getThumbnail().getCanonicalPath()), "position", "1", "original_sum",
178                                Outil.getMD5Checksum(image.getOriginale().getAbsolutePath()), "categories",
179                                String.valueOf(image.getIdCategory()), "name", image.getName(), "author", Main.sessionManager.getLogin(),
180                                "level", String.valueOf(ImagesManagement.privacyLevel)));
181                LOG.debug("Response add : " + Outil.documentToString(reponseAjout));
182                //      System.out.println(Main.sessionManager.executerReturnString("pwg.images.add", "file_sum", Outil
183                //              .getMD5Checksum(image.getOriginale().getAbsolutePath()), "thumbnail_sum", Outil.getMD5Checksum(image
184                //              .getThumbnail().getCanonicalPath()), "position", "1", "original_sum", Outil.getMD5Checksum(image
185                //              .getOriginale().getAbsolutePath()), "categories", String.valueOf(image.getIdCategory()), "name", image
186                //              .getName(), "author", Main.sessionManager.getLogin()));
187                //      Document reponsePrivacy = null;
188                //      if (Outil.checkOk(reponseAjout)) {
189                //          reponsePrivacy = Main.sessionManager.executerReturnDocument(MethodsEnum.SET_PRIVACY_LEVEL.getLabel());
190                //      }
191                boolean reussite = true;
192                if (!Outil.checkOk(reponseThumb) || echec || !Outil.checkOk(reponseAjout)) {
193                        reussite = false;
194                }
195                suppressionFichierTemporaires();
196                return reussite;
197
198        }
199
200
201        /**
202         * Add tags to an image
203         * @param imageId id of the image
204         * @param tagId ids of the tags
205         * @throws IOException
206         */
207        public boolean addTags(Integer imageId, String tagId) throws IOException {
208                Document doc = Main.sessionManager.executerReturnDocument(MethodsEnum.SET_INFO.getLabel(), "image_id",
209                                String.valueOf(imageId), "tag_ids", tagId);
210                return Outil.checkOk(doc);
211
212        }
213
214
215        /**
216         * parse an element to find images
217         * @param element the element to parse
218         * @return the list of images
219         */
220        private List<Image> getImagesFromElement(Element element) {
221                List<Element> listElement = (List<Element>) element.getChildren("image");
222                ArrayList<Image> images = new ArrayList<Image>();
223                for (Element im : listElement) {
224                        Image myImage = new Image();
225                        myImage.setMiniature(im.getAttributeValue("tn_url"));
226                        myImage.setUrl(im.getAttributeValue("element_url"));
227                        myImage.setWidth(Integer.valueOf(im.getAttributeValue("width")));
228                        myImage.setHeight(Integer.valueOf(im.getAttributeValue("height")));
229                        myImage.setFile(im.getAttributeValue("file"));
230                        myImage.setVue(Integer.valueOf(im.getAttributeValue("hit")));
231                        myImage.setIdentifiant(Integer.valueOf(im.getAttributeValue("id")));
232                        myImage.setName(im.getChildText("name"));
233                        if (myImage.getName() == null) {
234                                myImage.setName(myImage.getFile());
235                        }
236                        images.add(myImage);
237
238                }
239                return images;
240        }
241
242
243        /**
244         * Search images
245         * @param searchString the string to search
246         * @return the list of images matching the string
247         * @throws IOException
248         */
249        public List<Image> search(String searchString) throws IOException {
250                Document doc = Main.sessionManager.executerReturnDocument(MethodsEnum.SEARCH.getLabel(), "query", searchString);
251                LOG.debug(doc);
252                Element element = doc.getRootElement().getChild("images");
253                return getImagesFromElement(element);
254
255        }
256
257
258        private void suppressionFichierTemporaires() {
259                File file = new File(System.getProperty("java.io.tmpdir") + "/originale.jpg");
260                file.delete();
261                file = new File(System.getProperty("java.io.tmpdir") + "/thumb.jpg");
262                file.delete();
263
264        }
265
266}
Note: See TracBrowser for help on using the repository browser.