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

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

Images can be sent from the file new file browser.

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