PageRenderTime 52ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/java/com/chebanca/proposta/config/mailsender/Attachments.java

https://gitlab.com/g5863/che-banca-proposta
Java | 403 lines | 163 code | 35 blank | 205 comment | 13 complexity | 9b144788e7ccd8d235474e77969c9979 MD5 | raw file
  1. package com.chebanca.proposta.config.mailsender;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.io.Serializable;
  6. import java.nio.file.Files;
  7. import java.util.ArrayList;
  8. import java.util.Arrays;
  9. import java.util.List;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. import net.lingala.zip4j.exception.ZipException;
  13. import net.lingala.zip4j.io.ZipOutputStream;
  14. import net.lingala.zip4j.model.ZipParameters;
  15. import net.lingala.zip4j.util.Zip4jConstants;
  16. /**
  17. * It is used to build the attachments of an email. <br>
  18. * Attachments are not saved on the disk but are managed by the JVM.
  19. *
  20. * <br>
  21. * <br>
  22. * <b>Upload a file attached by a path</b> <br>
  23. * {@link Attachments}.{@link #getInstance(String)}
  24. *
  25. * <br>
  26. * <br>
  27. * <b>Upload and rename a file attached by a path</b> <br>
  28. * {@link Attachments}.{@link #getInstance(String, String)}
  29. *
  30. * <br>
  31. * <br>
  32. * <b>Create an attachment from a byte[]</b> <br>
  33. * {@link Attachments}.{@link #getInstance(String, byte[])} <br>
  34. * You can use {@link Bytes} to transform your data structure into byte[].
  35. *
  36. * <br>
  37. * <br>
  38. * <b>Create a zip attachment from a list of attachments</b> <br>
  39. * {@link Attachments}.{@link #getInstance(String, Attachment...)}
  40. *
  41. * <br>
  42. * <br>
  43. * <b>Create a cripted zip attachment from a list of attachments</b> <br>
  44. * {@link Attachments}.{@link #getInstance(String, String, Attachment...)}
  45. *
  46. */
  47. public class Attachments implements Serializable {
  48. private static final long serialVersionUID = -1073247700591697315L;
  49. private static final Logger LOGGER = LoggerFactory.getLogger(Attachments.class);
  50. /**
  51. * Upload a file attached by a path. <br>
  52. * Path must contains file name.
  53. *
  54. * @param path
  55. * @return
  56. * @throws IOException
  57. */
  58. public static Attachment getInstance(String path) throws IOException {
  59. LOGGER.debug("Entering getInstance [path: {}]", path);
  60. File attachment = new File(path);
  61. return new Attachment().path(path).content(Files.readAllBytes(attachment.toPath())).name(attachment.getName());
  62. }
  63. /**
  64. * Upload and rename a file attached by a path. <br>
  65. * Path must contains file name.<br>
  66. * The original attachment is not modified.
  67. *
  68. * @param path
  69. * @param newName
  70. * @return
  71. * @throws IOException
  72. */
  73. public static Attachment getInstance(String newName, String path) throws IOException {
  74. return getInstance(path).name(newName);
  75. }
  76. /**
  77. * Create an attachment from a byte[].<br>
  78. * Attachment will be called <b>filename</b><br>
  79. * You can use {@link Bytes} to transform your data structure into a byte[].<br>
  80. *
  81. * @param filename
  82. * @param content
  83. * @return
  84. */
  85. public static Attachment getInstance(String filename, byte[] content) {
  86. return new Attachment(content, filename);
  87. }
  88. /**
  89. * Create a zip attachment from a list of attachments.<br>
  90. * Zip attachments are not saved on the disk but are managed by the JVM.
  91. *
  92. * @param zipFilename
  93. * @param attachments
  94. * @return
  95. * @throws ZipException
  96. * @throws IOException
  97. */
  98. public static Attachment getInstance(String zipFilename, Attachment... attachments) throws ZipException, IOException {
  99. Attachment zipAttachment = createZip(zipFilename, null, attachments);
  100. zipAttachment.isZip(true);
  101. return zipAttachment;
  102. }
  103. /**
  104. * Create a cripted zip attachment from a list of attachments.<br>
  105. * Zip attachments are not saved on the disk but are managed by the JVM.
  106. *
  107. * @param zipFilename
  108. * @param zipPassword
  109. * @param attachments
  110. * @return
  111. * @throws ZipException
  112. * @throws IOException
  113. */
  114. public static Attachment getInstance(String zipFilename, String zipPassword, Attachment... attachments) throws ZipException, IOException {
  115. Attachment zipAttachment = createZip(zipFilename, zipPassword, attachments);
  116. zipAttachment.isZip(true);
  117. return zipAttachment;
  118. }
  119. /**
  120. * Create a zip attachment from a list of attachments. <br>
  121. * Password is optional. <br>
  122. * If password is not null it will create a zip attachment with password.
  123. *
  124. * @param zipName
  125. * @param password
  126. * @param attachments
  127. * @return
  128. * @throws ZipException
  129. * @throws IOException
  130. */
  131. private static Attachment createZip(String zipName, String password, Attachment... attachments) throws ZipException, IOException {
  132. return Attachments.getInstance(zipName, getZipContent(password, attachments));
  133. }
  134. /**
  135. * Create a unique zip attachment from a list of attachments.
  136. *
  137. * @param attachments
  138. * @param password
  139. * @return
  140. */
  141. private static byte[] getZipContent(String password, Attachment... attachments) {
  142. ZipParameters parameters = getZipParameters(password);
  143. ByteArrayOutputStream baos = null;
  144. ZipOutputStream zout = null;
  145. try {
  146. baos = new ByteArrayOutputStream();
  147. zout = new ZipOutputStream(baos);
  148. for (Attachment zb : attachments) {
  149. byte file[] = zb.getContent();
  150. if (file == null || file.length == 0)
  151. continue;
  152. String fileName = zb.getName();
  153. parameters.setFileNameInZip(fileName);
  154. zout.putNextEntry(null, parameters);
  155. zout.write(file);
  156. zout.closeEntry();
  157. }
  158. zout.finish();
  159. return baos.toByteArray();
  160. } catch (IOException e) {
  161. e.printStackTrace();
  162. } catch (ZipException e) {
  163. e.printStackTrace();
  164. } finally {
  165. if (baos != null) {
  166. try {
  167. baos.close();
  168. } catch (IOException e) {
  169. e.printStackTrace();
  170. }
  171. }
  172. if (zout != null) {
  173. try {
  174. zout.close();
  175. } catch (IOException e) {
  176. e.printStackTrace();
  177. }
  178. }
  179. }
  180. return null;
  181. }
  182. /**
  183. * Create an object of ZipParameters with an optional password.
  184. *
  185. * @param password
  186. * @return
  187. */
  188. private static ZipParameters getZipParameters(String password) {
  189. ZipParameters parameters = new ZipParameters();
  190. parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
  191. parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
  192. if (password != null && !password.isEmpty()) {
  193. parameters.setEncryptFiles(true);
  194. parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
  195. parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
  196. parameters.setPassword(password);
  197. }
  198. parameters.setSourceExternalStream(true);
  199. return parameters;
  200. }
  201. /**
  202. * <b>Immutable class</b> representing the attachment. <br>
  203. * The information on the attachment are the follow:<br>
  204. * - <b>path</b>, which is the path of attachment;<br>
  205. * - <b>name</b>, which is the name of attachment; <br>
  206. * - <b>content</b>, which is the content of attachment.<br>
  207. * <br>
  208. * {@link #path} excludes {@link #name}. If you specifiy {@link #path} there is
  209. * no need to specify {@link #name}.<br>
  210. * Specify {@link #path} only to upload a file saved on the disk. <br>
  211. * Specify {@link #name} only to load content of object managed in JVM.
  212. */
  213. public static class Attachment implements Serializable {
  214. private static final long serialVersionUID = -4775419089660556376L;
  215. /**
  216. * Represent path of file to upload. <br>
  217. * Path must contain file name.
  218. */
  219. private String path;
  220. /**
  221. * Represent attachment name. <br>
  222. * Name must contain extension.
  223. */
  224. private String name;
  225. /**
  226. * Represent attachment content.
  227. */
  228. protected byte[] content;
  229. /**
  230. * Is this a zip attachment?
  231. */
  232. private boolean isZip = false;
  233. /**
  234. * List of zip attachments.
  235. */
  236. private List<Attachment> zipAttachments = new ArrayList<Attachment>();
  237. /**
  238. * Creates a new attachment from an indicated path
  239. * @param path
  240. */
  241. public Attachment(String path) {
  242. this.path = path;
  243. }
  244. /**
  245. * Creates a new attachment with a path and a name
  246. * <br>
  247. * The name must contain a valid extension
  248. * <br>
  249. * @param path
  250. * @param name
  251. */
  252. public Attachment(String path, String name) {
  253. this.path = path;
  254. this.name = name;
  255. }
  256. /**
  257. * Creates a new byte stream attachment
  258. * <br>
  259. * The name must contain a valid extension
  260. * <br>
  261. * @param content The byte stream you want to send into the email
  262. * @param name A valid file name, including the extension
  263. */
  264. public Attachment(byte[] content, String name) {
  265. this.name = name;
  266. this.content = content;
  267. }
  268. public Attachment() {
  269. }
  270. /**
  271. * Return attachment path.
  272. *
  273. * @return
  274. */
  275. public String getPath() {
  276. return path;
  277. }
  278. /**
  279. * Set attachment path.
  280. *
  281. * @param path
  282. * @return
  283. */
  284. private Attachment path(String path) {
  285. this.path = path;
  286. return this;
  287. }
  288. /**
  289. * Return attachment name.
  290. *
  291. * @return
  292. */
  293. public String getName() {
  294. return name;
  295. }
  296. /**
  297. * Set attachment name.
  298. *
  299. * @param name
  300. * @return
  301. */
  302. private Attachment name(String name) {
  303. this.name = name;
  304. return this;
  305. }
  306. /**
  307. * Return attachment content.
  308. *
  309. * @return
  310. */
  311. public byte[] getContent() {
  312. return content;
  313. }
  314. /**
  315. * Set attachment content.
  316. *
  317. * @param content
  318. * @return
  319. */
  320. private Attachment content(byte[] content) {
  321. this.content = content;
  322. return this;
  323. }
  324. /**
  325. * Is this a zip attachment?
  326. *
  327. * @return
  328. */
  329. public boolean isZip() {
  330. return isZip;
  331. }
  332. /**
  333. * Specify if this is a zip attachment.
  334. *
  335. * @param isZip
  336. * @return
  337. */
  338. public Attachment isZip(boolean isZip) {
  339. this.isZip = isZip;
  340. return this;
  341. }
  342. /**
  343. * Return list of zip attachments.<br>
  344. * The method only works in case of zip-type attachment returns an
  345. * {@link IllegalStateException}.<br>
  346. * See {@link #isZip()}.<br
  347. *
  348. * @return
  349. */
  350. public List<Attachment> getZipAttachments() {
  351. if (isZip)
  352. return zipAttachments;
  353. throw new IllegalStateException("Current attachment is not a zip, it hasn't a list of attachments.");
  354. }
  355. @Override
  356. public String toString() {
  357. StringBuilder builder = new StringBuilder();
  358. builder.append("Attachment [path=");
  359. builder.append(path);
  360. builder.append(", name=");
  361. builder.append(name);
  362. builder.append(", content=");
  363. builder.append(Arrays.toString(content));
  364. builder.append("]");
  365. return builder.toString();
  366. }
  367. }
  368. }