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

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

Changed the licence
to a funniest one.

File size: 8.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 *  jiwigo-ws-api Piwigo webservice access Api
36 *  Copyright (c) 2010-2011 Mael mael@le-guevel.com
37 *                All Rights Reserved
38 *
39 *  This library is free software. It comes without any warranty, to
40 *  the extent permitted by applicable law. You can redistribute it
41 *  and/or modify it under the terms of the Do What The Fuck You Want
42 *  To Public License, Version 2, as published by Sam Hocevar. See
43 *  http://sam.zoy.org/wtfpl/COPYING for more details.
44 */
45/**
46
47 * @author mael
48 *
49 */
50public class Tools {
51    /**
52     * Logger
53     */
54    public static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(Tools.class);
55
56    /**
57     * Transformation of an inpustream into string.<br/>
58     * useful to read the result of the webservice
59     * @param input the stream
60     * @return the string
61     * @throws IOException
62     */
63    public static String readInputStreamAsString(InputStream input) throws IOException {
64        StringWriter writer = new StringWriter();
65        InputStreamReader streamReader = new InputStreamReader(input);
66        BufferedReader buffer = new BufferedReader(streamReader);
67        String line = "";
68        while (null != (line = buffer.readLine())) {
69            writer.write(line);
70        }
71        return writer.toString();
72    }
73
74    /**
75     * String to document
76     * @param string the string
77     * @return the corresponding document
78     * @throws JDOMException
79     * @throws IOException
80     */
81    public static Document stringToDocument(String string) throws JDOMException, IOException {
82        SAXBuilder sb = new SAXBuilder();
83        Document doc = sb.build(new StringReader(string));
84        return doc;
85
86    }
87
88    /**
89     * Inputstream to document
90     * @param input the inputStream
91     * @return the document
92     * @throws JDOMException
93     * @throws IOException
94     */
95    public static Document readInputStreamAsDocument(InputStream input) throws JDOMException, IOException {
96        return stringToDocument(readInputStreamAsString(input));
97    }
98
99    /**
100     * Document to string
101     * @param doc the document to transform
102     * @return the string
103     */
104    public static String documentToString(Document doc) {
105        return new XMLOutputter().outputString(doc);
106
107    }
108
109    /**
110     * Function that gets the url of a file
111     * Useful to get the images that are in the jar
112     * @param fileName the path of the file
113     * @return the url of the file
114     */
115    public static URL getURL(String fileName) {
116        URLClassLoader urlLoader = (URLClassLoader) Tools.class.getClassLoader();
117        URL fileLocation = urlLoader.findResource(fileName);
118        return fileLocation;
119    }
120
121    /**
122     * gets the md5 sum of a file
123     * @param filename the path of the file
124     * @return the checksum
125     * @throws Exception
126     */
127    public static String getMD5Checksum(String filename) throws Exception {
128        byte[] b = createChecksum(filename);
129        String result = "";
130        for (int i = 0; i < b.length; i++) {
131            result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
132        }
133        return result;
134    }
135
136    /**
137     * Creation of the checksum of a file
138     * @param filename the path of the file
139     * @return the checksum as array byte
140     * @throws Exception
141     */
142    private static byte[] createChecksum(String filename) throws Exception {
143        InputStream fis = new FileInputStream(filename);
144
145        byte[] buffer = new byte[1024];
146        MessageDigest complete = MessageDigest.getInstance("MD5");
147        int numRead;
148        do {
149            numRead = fis.read(buffer);
150            if (numRead > 0) {
151                complete.update(buffer, 0, numRead);
152            }
153        } while (numRead != -1);
154        fis.close();
155        return complete.digest();
156    }
157
158    /**
159     * File to array bytes
160     * @param file the file
161     * @return the array bytes
162     * @throws IOException
163     */
164    public static byte[] getBytesFromFile(File file) throws IOException {
165        InputStream is = new FileInputStream(file);
166        long length = file.length();
167
168        byte[] bytes = new byte[(int) length];
169        int offset = 0;
170        int numRead = 0;
171        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
172            offset += numRead;
173        }
174
175        if (offset < bytes.length) {
176            throw new IOException("Could not completely read file " + file.getName());
177        }
178        is.close();
179        return bytes;
180    }
181
182    /**
183     * Function that checks if the webservice response is ok
184     * @param doc the document from the webservice
185     * @return true if ok
186     */
187    public static boolean checkOk(Document doc) {
188        if (doc.getRootElement().getAttributeValue("stat").equals("ok")) {
189            return true;
190        } else {
191            LOG.error("Resultat : " + doc.getRootElement().getAttributeValue("stat") + "\nDocument retourné : \n"
192                    + Tools.documentToString(doc));
193            return false;
194        }
195
196    }
197
198    /**
199     * Exception to string
200     * @param aThrowable exception
201     * @return l'exception en string
202     */
203    public static String getStackTrace(Throwable aThrowable) {
204        final Writer result = new StringWriter();
205        final PrintWriter printWriter = new PrintWriter(result);
206        aThrowable.printStackTrace(printWriter);
207        return result.toString();
208    }
209
210    /**
211     * Function that splits a file
212     * @param fichier the file to split
213     * @param size the size of the resulting chunks
214     * @return the list of files
215     * @throws IOException
216     */
217    //feature:0001827
218    public static ArrayList<File> splitFile(File fichier, int size) throws IOException {
219        FileInputStream fis = new FileInputStream(fichier);
220        byte buffer[] = new byte[size];
221        ArrayList<File> listFichiers = new ArrayList<File>();
222        int count = 0;
223        while (true) {
224            int i = fis.read(buffer, 0, size);
225            if (i == -1)
226                break;
227            File file = new File(System.getProperty("java.io.tmpdir") + "/tempcut" + count);
228            listFichiers.add(file);
229            FileOutputStream fos = new FileOutputStream(file);
230            fos.write(buffer, 0, i);
231            fos.flush();
232            fos.close();
233
234            ++count;
235        }
236        return listFichiers;
237    }
238
239    /**
240     * Function used to put the exif and iptc metadata from one image to another
241     * @param enriched original image where the metadata comes from
242     * @param naked image where to put metadata
243     * @return enriched image
244     * @throws Exception
245     */
246    public static byte[] enrich(byte[] enriched, byte[] naked) throws Exception {
247
248        // read IPTC metadata from the original enriched image
249        IImageMetadata metadata = Sanselan.getMetadata(enriched);
250        JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
251        JpegPhotoshopMetadata photoshopMetadata = jpegMetadata.getPhotoshop();
252        if (photoshopMetadata == null) {
253            return naked;
254        }
255
256        PhotoshopApp13Data data = photoshopMetadata.photoshopApp13Data;
257
258        // read the EXIF metadata from the parsed JPEG metadata
259        TiffOutputSet outputSet = jpegMetadata.getExif().getOutputSet();
260
261        // enrich the naked byte[] with EXIF metadata
262        ExifRewriter writer = new ExifRewriter();
263        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
264        writer.updateExifMetadataLossless(naked, outputStream, outputSet);
265
266        // enrich the partially clothed byte[] with IPTC metadata
267        InputStream src = new ByteArrayInputStream(outputStream.toByteArray());
268        ByteArrayOutputStream dest = new ByteArrayOutputStream();
269        new JpegIptcRewriter().writeIPTC(src, dest, data);
270
271        // return the fully clothed image as a byte[]
272        return dest.toByteArray();
273    }
274
275    /**
276     * Bytes to file
277     * @param fichier the file path
278     * @param bytes the array bytes
279     * @throws IOException
280     */
281    public static void byteToFile(String fichier, byte[] bytes) throws IOException {
282        FileOutputStream fos = new FileOutputStream(fichier);
283        fos.write(bytes);
284        fos.flush();
285        fos.close();
286
287    }
288}
Note: See TracBrowser for help on using the repository browser.