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

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

Translation of the comments
French -> English

File size: 9.6 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 of an inpustream into string.<br/>
72     * useful to read the result of the webservice
73     * @param input the stream
74     * @return the string
75     * @throws IOException
76     */
77    public static String readInputStreamAsString(InputStream input) throws IOException {
78        StringWriter writer = new StringWriter();
79        InputStreamReader streamReader = new InputStreamReader(input);
80        BufferedReader buffer = new BufferedReader(streamReader);
81        String line = "";
82        while (null != (line = buffer.readLine())) {
83            writer.write(line);
84        }
85        return writer.toString();
86    }
87
88    /**
89     * String to document
90     * @param string the string
91     * @return the corresponding document
92     * @throws JDOMException
93     * @throws IOException
94     */
95    public static Document stringToDocument(String string) throws JDOMException, IOException {
96        SAXBuilder sb = new SAXBuilder();
97        Document doc = sb.build(new StringReader(string));
98        return doc;
99
100    }
101
102    /**
103     * Inputstream to document
104     * @param input the inputStream
105     * @return the document
106     * @throws JDOMException
107     * @throws IOException
108     */
109    public static Document readInputStreamAsDocument(InputStream input) throws JDOMException, IOException {
110        return stringToDocument(readInputStreamAsString(input));
111    }
112
113    /**
114     * Document to string
115     * @param doc the document to transform
116     * @return the string
117     */
118    public static String documentToString(Document doc) {
119        return new XMLOutputter().outputString(doc);
120
121    }
122
123    /**
124     * Function that gets the url of a file
125     * Useful to get the images that are in the jar
126     * @param fileName the path of the file
127     * @return the url of the file
128     */
129    public static URL getURL(String fileName) {
130        URLClassLoader urlLoader = (URLClassLoader) Outil.class.getClassLoader();
131        URL fileLocation = urlLoader.findResource(fileName);
132        return fileLocation;
133    }
134
135    /**
136     * gets the md5 sum of a file
137     * @param filename the path of the file
138     * @return the checksum
139     * @throws Exception
140     */
141    public static String getMD5Checksum(String filename) throws Exception {
142        byte[] b = createChecksum(filename);
143        String result = "";
144        for (int i = 0; i < b.length; i++) {
145            result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
146        }
147        return result;
148    }
149
150    /**
151     * Creation of the checksum of a file
152     * @param filename the path of the file
153     * @return the checksum as array byte
154     * @throws Exception
155     */
156    private static byte[] createChecksum(String filename) throws Exception {
157        InputStream fis = new FileInputStream(filename);
158
159        byte[] buffer = new byte[1024];
160        MessageDigest complete = MessageDigest.getInstance("MD5");
161        int numRead;
162        do {
163            numRead = fis.read(buffer);
164            if (numRead > 0) {
165                complete.update(buffer, 0, numRead);
166            }
167        } while (numRead != -1);
168        fis.close();
169        return complete.digest();
170    }
171
172    /**
173     * File to array bytes
174     * @param file the file
175     * @return the array bytes
176     * @throws IOException
177     */
178    public static byte[] getBytesFromFile(File file) throws IOException {
179        InputStream is = new FileInputStream(file);
180        long length = file.length();
181
182        byte[] bytes = new byte[(int) length];
183        int offset = 0;
184        int numRead = 0;
185        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
186            offset += numRead;
187        }
188
189        if (offset < bytes.length) {
190            throw new IOException("Could not completely read file " + file.getName());
191        }
192        is.close();
193        return bytes;
194    }
195
196    /**
197     * Function that checks if the webservice response is ok
198     * @param doc the document from the webservice
199     * @return true if ok
200     */
201    public static boolean checkOk(Document doc) {
202        if (doc.getRootElement().getAttributeValue("stat").equals("ok")) {
203            return true;
204        } else {
205            LOG.error("Resultat : " + doc.getRootElement().getAttributeValue("stat") + "\nDocument retourné : \n"
206                    + Outil.documentToString(doc));
207            return false;
208        }
209
210    }
211
212    /**
213     * Exception to string
214     * @param aThrowable exception
215     * @return l'exception en string
216     */
217    public static String getStackTrace(Throwable aThrowable) {
218        final Writer result = new StringWriter();
219        final PrintWriter printWriter = new PrintWriter(result);
220        aThrowable.printStackTrace(printWriter);
221        return result.toString();
222    }
223
224    /**
225     * Function that splits a file
226     * @param fichier the file to split
227     * @param size the size of the resulting chunks
228     * @return the list of files
229     * @throws IOException
230     */
231    //feature:0001827
232    public static ArrayList<File> splitFile(File fichier, int size) throws IOException {
233        FileInputStream fis = new FileInputStream(fichier);
234        byte buffer[] = new byte[size];
235        ArrayList<File> listFichiers = new ArrayList<File>();
236        int count = 0;
237        while (true) {
238            int i = fis.read(buffer, 0, size);
239            if (i == -1)
240                break;
241            File file = new File(System.getProperty("java.io.tmpdir") + "/tempcut" + count);
242            listFichiers.add(file);
243            FileOutputStream fos = new FileOutputStream(file);
244            fos.write(buffer, 0, i);
245            fos.flush();
246            fos.close();
247
248            ++count;
249        }
250        return listFichiers;
251    }
252
253    /**
254     * Function used to put the exif and iptc metadata from one image to another
255     * @param enriched original image where the metadata comes from
256     * @param naked image where to put metadata
257     * @return enriched image
258     * @throws Exception
259     */
260    public static byte[] enrich(byte[] enriched, byte[] naked) throws Exception {
261
262        // read IPTC metadata from the original enriched image
263        IImageMetadata metadata = Sanselan.getMetadata(enriched);
264        JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
265        JpegPhotoshopMetadata photoshopMetadata = jpegMetadata.getPhotoshop();
266        if (photoshopMetadata == null) {
267            return naked;
268        }
269
270        PhotoshopApp13Data data = photoshopMetadata.photoshopApp13Data;
271
272        // read the EXIF metadata from the parsed JPEG metadata
273        TiffOutputSet outputSet = jpegMetadata.getExif().getOutputSet();
274
275        // enrich the naked byte[] with EXIF metadata
276        ExifRewriter writer = new ExifRewriter();
277        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
278        writer.updateExifMetadataLossless(naked, outputStream, outputSet);
279
280        // enrich the partially clothed byte[] with IPTC metadata
281        InputStream src = new ByteArrayInputStream(outputStream.toByteArray());
282        ByteArrayOutputStream dest = new ByteArrayOutputStream();
283        new JpegIptcRewriter().writeIPTC(src, dest, data);
284
285        // return the fully clothed image as a byte[]
286        return dest.toByteArray();
287    }
288
289    /**
290     * Bytes to file
291     * @param fichier the file path
292     * @param bytes the array bytes
293     * @throws IOException
294     */
295    public static void byteToFile(String fichier, byte[] bytes) throws IOException {
296        FileOutputStream fos = new FileOutputStream(fichier);
297        fos.write(bytes);
298        fos.flush();
299        fos.close();
300
301    }
302}
Note: See TracBrowser for help on using the repository browser.