source: extensions/jiwigo-ws-api/src/main/java/fr/mael/jiwigo/transverse/util/Outil.java @ 9387

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

First commit for jiwigo-ws-api

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