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

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

Two minor improvements :

  • I now get the responses of piwigo's webservices as stream, and not as string any more.
  • The information panel now displays which file is being processed.
File size: 10.0 KB
Line 
1package fr.mael.jiwigo.transverse.util;
2
3import java.io.BufferedReader;
4import java.io.ByteArrayInputStream;
5import java.io.ByteArrayOutputStream;
6import java.io.File;
7import java.io.FileInputStream;
8import java.io.FileOutputStream;
9import java.io.IOException;
10import java.io.InputStream;
11import java.io.InputStreamReader;
12import java.io.PrintWriter;
13import java.io.StringReader;
14import java.io.StringWriter;
15import java.io.Writer;
16import java.net.URL;
17import java.net.URLClassLoader;
18import java.security.MessageDigest;
19import java.util.ArrayList;
20
21import org.apache.sanselan.Sanselan;
22import org.apache.sanselan.common.IImageMetadata;
23import org.apache.sanselan.formats.jpeg.JpegImageMetadata;
24import org.apache.sanselan.formats.jpeg.JpegPhotoshopMetadata;
25import org.apache.sanselan.formats.jpeg.exifRewrite.ExifRewriter;
26import org.apache.sanselan.formats.jpeg.iptc.JpegIptcRewriter;
27import org.apache.sanselan.formats.jpeg.iptc.PhotoshopApp13Data;
28import org.apache.sanselan.formats.tiff.write.TiffOutputSet;
29import org.jdom.Document;
30import org.jdom.JDOMException;
31import org.jdom.input.SAXBuilder;
32import org.jdom.output.XMLOutputter;
33
34/**
35   Copyright (c) 2010, Mael
36   All rights reserved.
37
38   Redistribution and use in source and binary forms, with or without
39   modification, are permitted provided that the following conditions are met:
40    * Redistributions of source code must retain the above copyright
41      notice, this list of conditions and the following disclaimer.
42    * Redistributions in binary form must reproduce the above copyright
43      notice, this list of conditions and the following disclaimer in the
44      documentation and/or other materials provided with the distribution.
45    * Neither the name of jiwigo nor the
46      names of its contributors may be used to endorse or promote products
47      derived from this software without specific prior written permission.
48
49   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
50   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
51   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
52   DISCLAIMED. IN NO EVENT SHALL Mael BE LIABLE FOR ANY
53   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
54   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
55   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
56   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
57   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
58   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
59   
60 
61 * @author mael
62 *
63 */
64public class Outil {
65    /**
66     * Logger
67     */
68    public static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(Outil.class);
69
70    /**
71     * Transformation d'un inputstream en string.<br/>
72     * Util pour lire la réponse du webservice
73     * @param input le stream
74     * @return la string
75     * @throws IOException
76     */
77    public static String readInputStreamAsString(InputStream input) throws IOException {
78        //      DataInputStream dis = new DataInputStream(new BufferedInputStream(input));
79        //
80        //      String temp;
81        //      StringBuffer buffer = new StringBuffer();
82        //      while ((temp = dis.readLine()) != null) {
83        //          buffer.append(temp);
84        //      }
85        //      return buffer.toString();
86        StringWriter writer = new StringWriter();
87        InputStreamReader streamReader = new InputStreamReader(input);
88        //le buffer permet le readline
89        BufferedReader buffer = new BufferedReader(streamReader);
90        String line = "";
91        while (null != (line = buffer.readLine())) {
92            writer.write(line);
93        }
94        // Sortie finale dans le String
95        return writer.toString();
96    }
97
98    /**
99     * Transformation d'une string en document
100     * @param string la string
101     * @return le document correspondant
102     * @throws JDOMException
103     * @throws IOException
104     */
105    public static Document stringToDocument(String string) throws JDOMException, IOException {
106        SAXBuilder sb = new SAXBuilder();
107        Document doc = sb.build(new StringReader(string));
108        return doc;
109
110    }
111
112    /**
113     * Transformation d'un inputstream en document
114     * @param input l'inputstream
115     * @return le document
116     * @throws JDOMException
117     * @throws IOException
118     */
119    public static Document readInputStreamAsDocument(InputStream input) throws JDOMException, IOException {
120        return stringToDocument(readInputStreamAsString(input));
121    }
122
123    /**
124     * Transformation d'un document en string
125     * @param doc le document à transformer
126     * @return la string
127     */
128    public static String documentToString(Document doc) {
129        return new XMLOutputter().outputString(doc);
130
131    }
132
133    /**
134     * Fonction qui retour l'url d'un fichier donné.
135     * Utile pour récupérer le chemin des images à l'intérieur du jar
136     * @param fileName le chemin du fichier
137     * @return l'url
138     */
139    public static URL getURL(String fileName) {
140        URLClassLoader urlLoader = (URLClassLoader) Outil.class.getClassLoader();
141        URL fileLocation = urlLoader.findResource(fileName);
142        return fileLocation;
143    }
144
145    /**
146     * Fonction qui retourne la somme de controle MD5 d'un fichier donné
147     * @param filename le chemin du fichier
148     * @return la somme de controle
149     * @throws Exception
150     */
151    public static String getMD5Checksum(String filename) throws Exception {
152        byte[] b = createChecksum(filename);
153        String result = "";
154        for (int i = 0; i < b.length; i++) {
155            result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
156        }
157        return result;
158    }
159
160    /**
161     * Creation de la somme de controle d'un fichier
162     * @param filename le chemin du fichier
163     * @return la somme de controle sous forme de byte[]
164     * @throws Exception
165     */
166    private static byte[] createChecksum(String filename) throws Exception {
167        InputStream fis = new FileInputStream(filename);
168
169        byte[] buffer = new byte[1024];
170        MessageDigest complete = MessageDigest.getInstance("MD5");
171        int numRead;
172        do {
173            numRead = fis.read(buffer);
174            if (numRead > 0) {
175                complete.update(buffer, 0, numRead);
176            }
177        } while (numRead != -1);
178        fis.close();
179        return complete.digest();
180    }
181
182    /**
183     * Fonction qui transforme un fichier en tableau de bytes
184     * @param file le fichier
185     * @return le tableau de bytes
186     * @throws IOException
187     */
188    public static byte[] getBytesFromFile(File file) throws IOException {
189        InputStream is = new FileInputStream(file);
190        long length = file.length();
191
192        byte[] bytes = new byte[(int) length];
193        int offset = 0;
194        int numRead = 0;
195        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
196            offset += numRead;
197        }
198
199        if (offset < bytes.length) {
200            throw new IOException("Could not completely read file " + file.getName());
201        }
202        is.close();
203        return bytes;
204    }
205
206    /**
207     * Fonction qui vérifie que si la réponse du webservice est positive
208     * @param doc le document que retourne le webservice
209     * @return true si c'est ok
210     */
211    public static boolean checkOk(Document doc) {
212        if (doc.getRootElement().getAttributeValue("stat").equals("ok")) {
213            return true;
214        } else {
215            LOG.error("Resultat : " + doc.getRootElement().getAttributeValue("stat") + "\nDocument retourné : \n"
216                    + Outil.documentToString(doc));
217            return false;
218        }
219
220    }
221
222    /**
223     * Exception to string
224     * @param aThrowable exception
225     * @return l'exception en string
226     */
227    public static String getStackTrace(Throwable aThrowable) {
228        final Writer result = new StringWriter();
229        final PrintWriter printWriter = new PrintWriter(result);
230        aThrowable.printStackTrace(printWriter);
231        return result.toString();
232    }
233
234    /**
235     * Function that splits a file
236     * @param fichier the file to split
237     * @param size the size of the resulting chunks
238     * @return the list of files
239     * @throws IOException
240     */
241    //feature:0001827
242    public static ArrayList<File> splitFile(File fichier, int size) throws IOException {
243        FileInputStream fis = new FileInputStream(fichier);
244        byte buffer[] = new byte[size];
245        ArrayList<File> listFichiers = new ArrayList<File>();
246        int count = 0;
247        while (true) {
248            int i = fis.read(buffer, 0, size);
249            if (i == -1)
250                break;
251            File file = new File(System.getProperty("java.io.tmpdir") + "/tempcut" + count);
252            listFichiers.add(file);
253            FileOutputStream fos = new FileOutputStream(file);
254            fos.write(buffer, 0, i);
255            fos.flush();
256            fos.close();
257
258            ++count;
259        }
260        return listFichiers;
261    }
262
263    /**
264     * Function used to put the exif and iptc metadata from one image to another
265     * @param enriched original image where the metadata comes from
266     * @param naked image where to put metadata
267     * @return enriched image
268     * @throws Exception
269     */
270    public static byte[] enrich(byte[] enriched, byte[] naked) throws Exception {
271
272        // read IPTC metadata from the original enriched image
273        IImageMetadata metadata = Sanselan.getMetadata(enriched);
274        JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
275        JpegPhotoshopMetadata photoshopMetadata = jpegMetadata.getPhotoshop();
276        if (photoshopMetadata == null) {
277            return naked;
278        }
279
280        PhotoshopApp13Data data = photoshopMetadata.photoshopApp13Data;
281
282        // read the EXIF metadata from the parsed JPEG metadata
283        TiffOutputSet outputSet = jpegMetadata.getExif().getOutputSet();
284
285        // enrich the naked byte[] with EXIF metadata
286        ExifRewriter writer = new ExifRewriter();
287        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
288        writer.updateExifMetadataLossless(naked, outputStream, outputSet);
289
290        // enrich the partially clothed byte[] with IPTC metadata
291        InputStream src = new ByteArrayInputStream(outputStream.toByteArray());
292        ByteArrayOutputStream dest = new ByteArrayOutputStream();
293        new JpegIptcRewriter().writeIPTC(src, dest, data);
294
295        // return the fully clothed image as a byte[]
296        return dest.toByteArray();
297    }
298
299    public static void byteToFile(String fichier, byte[] bytes) throws IOException {
300        FileOutputStream fos = new FileOutputStream(fichier);
301        fos.write(bytes);
302        fos.flush();
303        fos.close();
304
305    }
306}
Note: See TracBrowser for help on using the repository browser.