View Javadoc
1   /*
2    * DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway
3    * Copyright (C) 2010  Mickael Guessant
4    *
5    * This program is free software; you can redistribute it and/or
6    * modify it under the terms of the GNU General Public License
7    * as published by the Free Software Foundation; either version 2
8    * of the License, or (at your option) any later version.
9    *
10   * This program is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with this program; if not, write to the Free Software
17   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18   */
19  package davmail.util;
20  
21  import org.apache.commons.codec.binary.Base64;
22  import org.codehaus.jettison.json.JSONException;
23  import org.codehaus.jettison.json.JSONObject;
24  
25  import javax.imageio.ImageIO;
26  import javax.mail.MessagingException;
27  import javax.mail.internet.MimeMessage;
28  import java.awt.*;
29  import java.awt.image.BufferedImage;
30  import java.io.*;
31  import java.nio.charset.StandardCharsets;
32  
33  /**
34   * Input output functions.
35   */
36  public final class IOUtil {
37      private IOUtil() {
38      }
39  
40      /**
41       * Write all input stream content to output stream.
42       *
43       * @param inputStream  input stream
44       * @param outputStream output stream
45       * @throws IOException on error
46       */
47      public static void write(InputStream inputStream, OutputStream outputStream) throws IOException {
48          byte[] bytes = new byte[8192];
49          int length;
50          while ((length = inputStream.read(bytes)) > 0) {
51              outputStream.write(bytes, 0, length);
52          }
53      }
54  
55  
56      /**
57       * Decode base64 input string, return byte array.
58       *
59       * @param encoded Base64 encoded string
60       * @return decoded content as byte array
61       */
62      public static byte[] decodeBase64(String encoded) {
63          return Base64.decodeBase64(encoded.getBytes(StandardCharsets.US_ASCII));
64      }
65  
66      /**
67       * Decode base64 input string, return content as UTF-8 String.
68       *
69       * @param encoded Base64 encoded string
70       * @return decoded content as byte array
71       */
72      public static String decodeBase64AsString(String encoded) {
73          return new String(decodeBase64(encoded), StandardCharsets.UTF_8);
74      }
75  
76      /**
77       * Base64 encode value.
78       *
79       * @param value input value
80       * @return base64  value
81       */
82      public static String encodeBase64AsString(String value) {
83          return new String(Base64.encodeBase64(value.getBytes(StandardCharsets.UTF_8)), StandardCharsets.US_ASCII);
84      }
85  
86      /**
87       * Base64 encode value.
88       *
89       * @param value input value
90       * @return base64  value
91       */
92      public static String encodeBase64AsString(byte[] value) {
93          return new String(Base64.encodeBase64(value), StandardCharsets.US_ASCII);
94      }
95  
96      /**
97       * Base64 encode value.
98       *
99       * @param value input value
100      * @return base64  value
101      */
102     public static byte[] encodeBase64(String value) {
103         return Base64.encodeBase64(value.getBytes(StandardCharsets.UTF_8));
104     }
105 
106     /**
107      * Base64 encode value.
108      *
109      * @param value input value
110      * @return base64  value
111      */
112     public static byte[] encodeBase64(byte[] value) {
113         return Base64.encodeBase64(value);
114     }
115 
116     /**
117      * Encodes the content of the provided MimeMessage into a Base64-encoded byte array.
118      *
119      * @param mimeMessage the MimeMessage object whose content is to be encoded
120      * @return a byte array containing the Base64-encoded content of the MimeMessage
121      * @throws IOException if an I/O error occurs during encoding or if a MessagingException occurs
122      */
123     public static byte[] encodeBase64(MimeMessage mimeMessage) throws IOException {
124         byte[] mimeContent;
125         try (
126                 ByteArrayOutputStream baos = new ByteArrayOutputStream()
127         ) {
128             mimeMessage.writeTo(baos);
129             mimeContent = IOUtil.encodeBase64(baos.toByteArray());
130         } catch (MessagingException e) {
131             throw new IOException(e.getMessage(), e);
132         }
133         return mimeContent;
134     }
135 
136     /**
137      * Resize image bytes to a max width or height image size.
138      *
139      * @param inputBytes input image bytes
140      * @param max        max size
141      * @return scaled image bytes
142      * @throws IOException on error
143      */
144     public static byte[] resizeImage(byte[] inputBytes, int max) throws IOException {
145         BufferedImage inputImage = ImageIO.read(new ByteArrayInputStream(inputBytes));
146         if (inputImage == null) {
147             throw new IOException("Unable to decode image data");
148         }
149         BufferedImage outputImage = resizeImage(inputImage, max);
150         ByteArrayOutputStream baos = new ByteArrayOutputStream();
151         ImageIO.write(outputImage, "jpg", baos);
152         return baos.toByteArray();
153     }
154 
155     /**
156      * Resize image to a max width or height image size.
157      *
158      * @param inputImage input image
159      * @param max        max size
160      * @return scaled image
161      */
162     public static BufferedImage resizeImage(BufferedImage inputImage, int max) {
163         int width = inputImage.getWidth();
164         int height = inputImage.getHeight();
165         int targetWidth;
166         int targetHeight;
167         if (width <= max && height <= max) {
168             return inputImage;
169         } else if (width > height) {
170             targetWidth = max;
171             targetHeight = targetWidth * height / width;
172         } else {
173             targetHeight = max;
174             targetWidth = targetHeight * width / height;
175         }
176         Image scaledImage = inputImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
177         BufferedImage targetImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
178         targetImage.getGraphics().drawImage(scaledImage, 0, 0, null);
179         return targetImage;
180     }
181 
182     /**
183      * Read all inputStream content to a byte array.
184      *
185      * @param inputStream input stream
186      * @return content as byte array
187      * @throws IOException on error
188      */
189     public static byte[] readFully(InputStream inputStream) throws IOException {
190         ByteArrayOutputStream baos = new ByteArrayOutputStream();
191         write(inputStream, baos);
192         return baos.toByteArray();
193     }
194 
195     public static byte[] convertToBytes(JSONObject jsonObject) throws IOException {
196         if (jsonObject == null) {
197             return new byte[0];
198         }
199         byte[] result;
200         try (
201                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
202                 OutputStreamWriter writer = new java.io.OutputStreamWriter(baos, StandardCharsets.UTF_8);
203         ) {
204             jsonObject.write(writer);
205             writer.flush();
206             result = baos.toByteArray();
207         } catch (JSONException e) {
208             throw new IOException(e.getMessage(), e);
209         }
210         return result;
211 
212     }
213 
214 }