source: extensions/jiwigo/trunk/src/main/java/fr/mael/jiwigo/transverse/util/Outil.java @ 6821

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

Premier commit. Actuellement, l'application gère :
-Listing des catégories
-Affichage des miniatures
-Ajout de commentaires
-gestion d'un cache pour ne pas télécharger les images plusieurs fois
-gestion d'un zoom dans le navigateur d'images
-navigateur d'images complètement refait, je viens de tester sur un grand écran, à priori, c'est beaucoup mieux
-meilleure gestion des exceptions, avec affichage de messages d'erreurs
-ajout d'un "logger" qui enregistre toutes les exceptions dans un fichier de log
-possibilité de ne pas mettre le "http://" dans l'écran de connexion
-gestion de transformations d'images dans le navigateur d'images : "flip" horizontal et vertical, rotations
-menu dans le navigateur d'images, qui permet d'effectuer toutes les actions, avec en plus, la possibilité d'imprimer une image

en cours d'implémentation : gestion des préférences de l'utilisateur. Actuellement, le fichier xml permettant d'écrire les préférences est géré,
il reste à faire un écran de gestion des préférences, avec un maximum d'options, afin que l'appli soit configurable.

File size: 6.6 KB
Line 
1package fr.mael.jiwigo.transverse.util;
2
3import java.io.BufferedInputStream;
4import java.io.DataInputStream;
5import java.io.File;
6import java.io.FileInputStream;
7import java.io.IOException;
8import java.io.InputStream;
9import java.io.PrintWriter;
10import java.io.StringReader;
11import java.io.StringWriter;
12import java.io.Writer;
13import java.net.URL;
14import java.net.URLClassLoader;
15import java.security.MessageDigest;
16
17import org.jdom.Document;
18import org.jdom.JDOMException;
19import org.jdom.input.SAXBuilder;
20import org.jdom.output.XMLOutputter;
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 
49 * @author mael
50 *
51 */
52public class Outil {
53    /**
54     * Logger
55     */
56    public static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(Outil.class);
57
58    /**
59     * Transformation d'un inputstream en string.<br/>
60     * Util pour lire la réponse du webservice
61     * @param input le stream
62     * @return la string
63     * @throws IOException
64     */
65    public static String readInputStreamAsString(InputStream input) throws IOException {
66        DataInputStream dis = new DataInputStream(new BufferedInputStream(input));
67
68        String temp;
69        StringBuffer buffer = new StringBuffer();
70        while ((temp = dis.readLine()) != null) {
71            buffer.append(temp);
72        }
73        return buffer.toString();
74    }
75
76    /**
77     * Transformation d'une string en document
78     * @param string la string
79     * @return le document correspondant
80     * @throws JDOMException
81     * @throws IOException
82     */
83    public static Document stringToDocument(String string) throws JDOMException, IOException {
84        SAXBuilder sb = new SAXBuilder();
85        Document doc = sb.build(new StringReader(string));
86        return doc;
87
88    }
89
90    /**
91     * Transformation d'un inputstream en document
92     * @param input l'inputstream
93     * @return le document
94     * @throws JDOMException
95     * @throws IOException
96     */
97    public static Document readInputStreamAsDocument(InputStream input) throws JDOMException, IOException {
98        return stringToDocument(readInputStreamAsString(input));
99    }
100
101    /**
102     * Transformation d'un document en string
103     * @param doc le document à transformer
104     * @return la string
105     */
106    public static String documentToString(Document doc) {
107        return new XMLOutputter().outputString(doc);
108
109    }
110
111    /**
112     * Fonction qui retour l'url d'un fichier donné.
113     * Utile pour récupérer le chemin des images à l'intérieur du jar
114     * @param fileName le chemin du fichier
115     * @return l'url
116     */
117    public static URL getURL(String fileName) {
118        URLClassLoader urlLoader = (URLClassLoader) Outil.class.getClassLoader();
119        URL fileLocation = urlLoader.findResource(fileName);
120        return fileLocation;
121    }
122
123    /**
124     * Fonction qui retourne la somme de controle MD5 d'un fichier donné
125     * @param filename le chemin du fichier
126     * @return la somme de controle
127     * @throws Exception
128     */
129    public static String getMD5Checksum(String filename) throws Exception {
130        byte[] b = createChecksum(filename);
131        String result = "";
132        for (int i = 0; i < b.length; i++) {
133            result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
134        }
135        return result;
136    }
137
138    /**
139     * Creation de la somme de controle d'un fichier
140     * @param filename le chemin du fichier
141     * @return la somme de controle sous forme de byte[]
142     * @throws Exception
143     */
144    private static byte[] createChecksum(String filename) throws Exception {
145        InputStream fis = new FileInputStream(filename);
146
147        byte[] buffer = new byte[1024];
148        MessageDigest complete = MessageDigest.getInstance("MD5");
149        int numRead;
150        do {
151            numRead = fis.read(buffer);
152            if (numRead > 0) {
153                complete.update(buffer, 0, numRead);
154            }
155        } while (numRead != -1);
156        fis.close();
157        return complete.digest();
158    }
159
160    /**
161     * Fonction qui transforme un fichier en tableau de bytes
162     * @param file le fichier
163     * @return le tableau de bytes
164     * @throws IOException
165     */
166    public static byte[] getBytesFromFile(File file) throws IOException {
167        InputStream is = new FileInputStream(file);
168        long length = file.length();
169
170        byte[] bytes = new byte[(int) length];
171        int offset = 0;
172        int numRead = 0;
173        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
174            offset += numRead;
175        }
176
177        if (offset < bytes.length) {
178            throw new IOException("Could not completely read file " + file.getName());
179        }
180        is.close();
181        return bytes;
182    }
183
184    /**
185     * Fonction qui vérifie que si la réponse du webservice est positive
186     * @param doc le document que retourne le webservice
187     * @return true si c'est ok
188     */
189    public static boolean checkOk(Document doc) {
190        if (doc.getRootElement().getAttributeValue("stat").equals("ok")) {
191            return true;
192        } else {
193            LOG.error("Resultat : " + doc.getRootElement().getAttributeValue("stat") + "\nDocument retourné : \n"
194                    + Outil.documentToString(doc));
195            return false;
196        }
197
198    }
199
200    /**
201     * Exception to string
202     * @param aThrowable exception
203     * @return l'exception en string
204     */
205    public static String getStackTrace(Throwable aThrowable) {
206        final Writer result = new StringWriter();
207        final PrintWriter printWriter = new PrintWriter(result);
208        aThrowable.printStackTrace(printWriter);
209        return result.toString();
210    }
211}
Note: See TracBrowser for help on using the repository browser.