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

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

Changes function name (to english)
version changed to 0.13.1

File size: 9.4 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.om.Image;
15import fr.mael.jiwigo.transverse.enumeration.MethodsEnum;
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    /**
77     * Private singleton, to use a singleton
78     */
79    private ImageDao(SessionManager sessionManager) {
80        cache = new HashMap<Integer, List<Image>>();
81        this.sessionManager = sessionManager;
82    }
83
84    /**
85     * @return le singleton
86     */
87    public static ImageDao getInstance(SessionManager sessionManager) {
88        if (instance == null) {
89            instance = new ImageDao(sessionManager);
90        }
91        return instance;
92    }
93
94    /**
95     * Lists all images
96     * @return the list of images
97     * @throws IOException
98     */
99    public List<Image> list(boolean refresh) throws IOException {
100        return listByCategory(null, refresh);
101    }
102
103    /**
104     * Listing of the images for a category
105     * @param categoryId the id of the category
106     * @return the list of images
107     * @throws IOException
108     */
109    public List<Image> listByCategory(Integer categoryId, boolean refresh) throws IOException {
110        if (refresh || cache.get(categoryId) == null) {
111            Document doc = null;
112
113            if (categoryId != null) {
114                doc = sessionManager.executeReturnDocument(MethodsEnum.LISTER_IMAGES.getLabel(), "cat_id", String
115                        .valueOf(categoryId));
116            } else {
117                doc = sessionManager.executeReturnDocument(MethodsEnum.LISTER_IMAGES.getLabel());
118            }
119            Element element = doc.getRootElement().getChild("images");
120            List<Image> images = getImagesFromElement(element);
121            cache.remove(categoryId);
122            cache.put(categoryId, images);
123            if (firstCatInCache == null) {
124                firstCatInCache = categoryId;
125            }
126            return images;
127        } else {
128            return cache.get(categoryId);
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 image 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 reponses precedentes est negative
147    public boolean create(Image image, Double chunkSize) throws Exception {
148        //thumbnail converted to base64
149        BASE64Encoder base64 = new BASE64Encoder();
150
151        String thumbnailBase64 = base64.encode(Tools.getBytesFromFile(image.getThumbnail()));
152        //sends the thumbnail and gets the result
153        Document reponseThumb = (sessionManager.executeReturnDocument("pwg.images.addChunk", "data", thumbnailBase64,
154                "type", "thumb", "position", "1", "original_sum", Tools.getMD5Checksum(image.getOriginale()
155                        .getAbsolutePath())));
156
157        //begin feature:0001827
158        int chunk = chunkSize.intValue();
159        ArrayList<File> fichiersAEnvoyer = Tools.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(Tools.getBytesFromFile(fichierAEnvoyer));
164            Document reponseOriginale = (sessionManager.executeReturnDocument("pwg.images.addChunk", "data",
165                    originaleBase64, "type", "file", "position", String.valueOf(i), "original_sum", Tools
166                            .getMD5Checksum(image.getOriginale().getAbsolutePath())));
167            if (!Tools.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 = (sessionManager.executeReturnDocument("pwg.images.add", "file_sum", Tools
176                .getMD5Checksum(image.getOriginale().getAbsolutePath()), "thumbnail_sum", Tools.getMD5Checksum(image
177                .getThumbnail().getCanonicalPath()), "position", "1", "original_sum", Tools.getMD5Checksum(image
178                .getOriginale().getAbsolutePath()), "categories", String.valueOf(image.getIdCategory()), "name", image
179                .getName(), "author", sessionManager.getLogin(), "level", image.getPrivacyLevel()));
180        LOG.debug("Response add : " + Tools.documentToString(reponseAjout));
181        //      System.out.println(Main.sessionManager.executerReturnString("pwg.images.add", "file_sum", Outil
182        //              .getMD5Checksum(image.getOriginale().getAbsolutePath()), "thumbnail_sum", Outil.getMD5Checksum(image
183        //              .getThumbnail().getCanonicalPath()), "position", "1", "original_sum", Outil.getMD5Checksum(image
184        //              .getOriginale().getAbsolutePath()), "categories", String.valueOf(image.getIdCategory()), "name", image
185        //              .getName(), "author", Main.sessionManager.getLogin()));
186        //      Document reponsePrivacy = null;
187        //      if (Outil.checkOk(reponseAjout)) {
188        //          reponsePrivacy = Main.sessionManager.executerReturnDocument(MethodsEnum.SET_PRIVACY_LEVEL.getLabel());
189        //      }
190        boolean reussite = true;
191        if (!Tools.checkOk(reponseThumb) || echec || !Tools.checkOk(reponseAjout)) {
192            reussite = false;
193        }
194        deleteTempFiles();
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 = sessionManager.executeReturnDocument(MethodsEnum.SET_INFO.getLabel(), "image_id", String
207                .valueOf(imageId), "tag_ids", tagId);
208        return Tools.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.setThumbnailUrl(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.setSeen(Integer.valueOf(im.getAttributeValue("hit")));
228            myImage.setIdentifier(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 = sessionManager.executeReturnDocument(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 deleteTempFiles() {
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.