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

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

Bug correction :
bug:0001837 : there is now a default translation file (in english), so the application won't crash when a translation is not found
bug:0001833 : the accents are manage when creating a new category
bug:0001832 : on a right click on the categories list, the selection is now visible
bug:0001830 : there is no bug on refreshing the categories tree

Features :
feature:001828 : exif and iptc tags are kept after resizing an image
feature:001827 : pwg.images.addChunk is now fully used : images are split into chunks before being sent

Other features :

  • The user can manage his preferences :

-The web images size
-The chunks size

  • The user can save the login informations (url, login, password) /!\ in a plain text file !
File size: 8.0 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
64     */
65    private HashMap<Integer, ArrayList<Image>> cache;
66
67    /**
68     *
69     */
70    private Integer firstCatInCache;
71
72    /**
73     * Constructeur privé, pour n'avoir accès qu'au singleton
74     */
75    private ImageDao() {
76        cache = new HashMap<Integer, ArrayList<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     * Lister toutes les images
91     * @return la liste des images
92     * @throws IOException
93     */
94    public List<Image> lister(boolean rafraichir) throws IOException {
95        return listerParCategory(null, rafraichir);
96    }
97
98    /**
99     * Listing des images d'une catégorie
100     * @param categoryId l'id de la catégorie
101     * @return la liste des 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<Element> listElement = (List<Element>) element.getChildren("image");
115            ArrayList<Image> images = new ArrayList<Image>();
116            for (Element im : listElement) {
117                Image myImage = new Image();
118                myImage.setMiniature(im.getAttributeValue("tn_url"));
119                myImage.setUrl(im.getAttributeValue("element_url"));
120                myImage.setWidth(Integer.valueOf(im.getAttributeValue("width")));
121                myImage.setHeight(Integer.valueOf(im.getAttributeValue("height")));
122                myImage.setFile(im.getAttributeValue("file"));
123                myImage.setVue(Integer.valueOf(im.getAttributeValue("hit")));
124                myImage.setIdentifiant(Integer.valueOf(im.getAttributeValue("id")));
125                myImage.setName(im.getChildText("name"));
126                if (myImage.getName() == null) {
127                    myImage.setName(myImage.getFile());
128                }
129                images.add(myImage);
130
131            }
132            cache.remove(categoryId);
133            cache.put(categoryId, images);
134            if (firstCatInCache == null) {
135                firstCatInCache = categoryId;
136            }
137            return images;
138        } else {
139            return cache.get(categoryId);
140        }
141    }
142
143    /**
144     * Creation d'une image.<br/>
145     * Dans l'ordre : <br/>
146     * <li>
147     * <ul>envoi de la miniature en base64, grace à la méthode addchunk.</ul>
148     * <ul>envoi de l'image originale en base64, grace à la méthode addchunk</ul>
149     * <ul>utilisation de la methode add pour ajouter l'image dans la base<ul>
150     * </li>
151     * Pour finir, on vérifie les réponses du webservice.
152     *
153     * @param image l'image à créer
154     * @return true si l'insertiopn de l'image s'est bien passée
155     * @throws Exception
156     */
157    //TODO ne pas continuer si une des réponses précédentes est négative
158    public boolean creer(Image image) throws Exception {
159        //on convertit la miniature en string base64
160        BASE64Encoder base64 = new BASE64Encoder();
161
162        String thumbnailBase64 = base64.encode(Outil.getBytesFromFile(image.getThumbnail()));
163        //on envoie la miniature et on recupere la reponse
164        Document reponseThumb = (Main.sessionManager.executerReturnDocument("pwg.images.addChunk", "data",
165                thumbnailBase64, "type", "thumb", "position", "1", "original_sum", Outil.getMD5Checksum(image
166                        .getOriginale().getAbsolutePath())));
167
168        //begin feature:0001827
169        Double doubleChunk = Double.parseDouble(PreferencesManagement.getValue(PreferencesEnum.CHUNK_SIZE.getLabel())) * 1000 * 1024;
170        int chunk = doubleChunk.intValue();
171        ArrayList<File> fichiersAEnvoyer = Outil.splitFile(image.getOriginale(), chunk);
172        boolean echec = false;
173        for (int i = 0; i < fichiersAEnvoyer.size(); i++) {
174            File fichierAEnvoyer = fichiersAEnvoyer.get(i);
175            String originaleBase64 = base64.encode(Outil.getBytesFromFile(fichierAEnvoyer));
176            Document reponseOriginale = (Main.sessionManager.executerReturnDocument("pwg.images.addChunk", "data",
177                    originaleBase64, "type", "file", "position", String.valueOf(i), "original_sum", Outil
178                            .getMD5Checksum(image.getOriginale().getAbsolutePath())));
179            if (!Outil.checkOk(reponseOriginale)) {
180                echec = true;
181                break;
182            }
183        }
184        //end
185
186        //on ajoute l'image en base et on recupere la reponse
187        Document reponseAjout = (Main.sessionManager.executerReturnDocument("pwg.images.add", "file_sum", Outil
188                .getMD5Checksum(image.getOriginale().getAbsolutePath()), "thumbnail_sum", Outil.getMD5Checksum(image
189                .getThumbnail().getCanonicalPath()), "position", "1", "original_sum", Outil.getMD5Checksum(image
190                .getOriginale().getAbsolutePath()), "categories", String.valueOf(image.getIdCategory()), "name", image
191                .getName(), "author", Main.sessionManager.getLogin()));
192        //      System.out.println(Main.sessionManager.executerReturnString("pwg.images.add", "file_sum", Outil
193        //              .getMD5Checksum(image.getOriginale().getAbsolutePath()), "thumbnail_sum", Outil.getMD5Checksum(image
194        //              .getThumbnail().getCanonicalPath()), "position", "1", "original_sum", Outil.getMD5Checksum(image
195        //              .getOriginale().getAbsolutePath()), "categories", String.valueOf(image.getIdCategory()), "name", image
196        //              .getName(), "author", Main.sessionManager.getLogin()));
197        boolean reussite = true;
198        if (!Outil.checkOk(reponseThumb) || echec || !Outil.checkOk(reponseAjout)) {
199            reussite = false;
200        }
201        suppressionFichierTemporaires();
202        return reussite;
203
204    }
205
206    private void suppressionFichierTemporaires() {
207        File file = new File(System.getProperty("java.io.tmpdir") + "/originale.jpg");
208        file.delete();
209        file = new File(System.getProperty("java.io.tmpdir") + "/thumb.jpg");
210        file.delete();
211
212    }
213
214}
Note: See TracBrowser for help on using the repository browser.