Rev 37477 | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed
package com.spice.profitmandi.common.util;import com.google.gson.Gson;import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;import com.spice.profitmandi.common.web.client.RestClient;import org.apache.commons.io.FileUtils;import org.apache.commons.lang3.StringEscapeUtils;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.springframework.core.io.InputStreamSource;import com.spice.profitmandi.common.mail.MailQueue;import com.spice.profitmandi.common.mail.MailQueueHolder;import com.spice.profitmandi.common.mail.MailRequest;import org.springframework.core.io.FileSystemResource;import java.io.File;import java.io.Serializable;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import javax.mail.Multipart;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import java.io.*;import java.time.*;import java.util.*;import java.util.concurrent.ConcurrentHashMap;import java.util.function.Function;import java.util.function.Predicate;import java.util.regex.Matcher;import java.util.regex.Pattern;public class Utils {public static final float FLOAT_EPSILON = 0.001f;public static final double DOUBLE_EPSILON = 0.001d;public static String[] getAlphaNumericParts(String alphaNumericString) {String[] parts = alphaNumericString.split("(?<=\\D)(?=\\d)");return parts;}private static final Logger logger = LogManager.getLogger(Utils.class);public static final String EXPORT_ENTITIES_PATH = getExportPath();public static final String PRODUCT_PROPERTIES_SNIPPET = "ProductPropertiesSnippet.html";public static final String DOCUMENT_STORE = "/profitmandi/documents/";private Gson gson = new Gson();private static final Map<Integer, String> helpMap = new HashMap<>(6);private static final Map<Integer, String> dthIdAliasMap = new HashMap<>(7);private static Map<Long, String> mobileProvidersMap;private static Map<Long, String> dthProvidersMap;private static Map<Long, String> allProviders;public static final String SYSTEM_PARTNER = "testpxps@gmail.com";public static final int SYSTEM_PARTNER_ID = 175120474;private static final RestClient rc = new RestClient();private static final String regex = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$";public static final LocalTime MAX_TIME = LocalTime.of(23, 59, 59);// Compile regular expression to get the patternprivate static final Pattern pattern = Pattern.compile(regex);public static boolean validateEmail(String email) {if (email == null) {return false;}Matcher matcher = pattern.matcher(email);return matcher.matches();}@SuppressWarnings("serial")public static final Map<String, String> MIME_TYPE = Collections.unmodifiableMap(new HashMap<String, String>() {{put("image/png", "png");put("image/jpeg", "jpeg");put("image/pjpeg", "jpeg");put("application/pdf", "pdf");put("application/msword", "doc");put("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx");put("application/vnd.ms-excel", "xls");put("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx");}});private static String getExportPath() {String exportPath = "/var/lib/tomcat7/webapps/export/html/entities/";/** String exportPath = null;** try { ConfigClient client = ConfigClient.getClient(); exportPath =* client.get("export_entities_path"); } catch (Exception ce) {* logger.error("Unable to read export path from the config client: ", ce);* logger.warn("Setting the default export path"); exportPath =* "/var/lib/tomcat7/webapps/export/html/entities/"; }*/return exportPath;}public static LocalDateTime toLocalDateTime(long epochTimeInMillis) {return LocalDateTime.ofInstant(Instant.ofEpochMilli(epochTimeInMillis), ZoneId.systemDefault());}public static boolean copyDocument(String documentPath) {File source = new File(documentPath);File dest = new File(DOCUMENT_STORE + source.getName());try {FileUtils.copyFile(source, dest);} catch (IOException e) {e.printStackTrace();return false;}return true;}public static Map<Long, String> getMobileProvidersMap() {return mobileProvidersMap;}public static Map<Long, String> getDthProvidersMap() {return dthProvidersMap;}public static Map<Long, String> getAllProviders() {return allProviders;}public static String getProvider(long operatorId) {return allProviders.get(operatorId);}public static void sendSms(String text, String mobileNumber) throws Exception {Map<String, String> paramsMap = new HashMap<>();paramsMap.put("username", "SmartDukaanT");paramsMap.put("password", "Smart@91");paramsMap.put("senderID", "SMTDKN");paramsMap.put("message", text);paramsMap.put("mobile", mobileNumber);paramsMap.put("messageType", "Text");// rc.getResponse(SMS_GATEWAY, paramsMap, null);}/** Mail helpers. These no longer send anything themselves.** Each used to build its own MimeMessage, hardcode From: noreply@smartdukaan.com,* and push it straight down whichever JavaMailSender the caller passed. That From* is precisely why mail was being refused — an authenticated Workspace session may* send only as the account it logged in as, and noreply@ is a different identity.* A failed send also took the calling job down with it, which is how one expired* credential came to mark ten report jobs FAILED.** They now hand the mail to the outbox, which owns retry, de-duplication and the* choice of transport. The JavaMailSender parameter is ignored and kept only so the* 27 existing call sites continue to compile; new code should inject* {@link com.spice.profitmandi.common.mail.MailQueue} and build a MailRequest.*/@Deprecatedpublic static void sendMailWithAttachments(JavaMailSender mailSender, String emailTo, String[] cc, String subject,String body, List<File> attachments) {queue(MailRequest.to(emailTo).cc(cc).subject(subject).body(body).attach(fromFiles(attachments)));}@Deprecatedpublic static void sendMailWithAttachment(JavaMailSender mailSender, String[] emailTo, String[] cc, String subject,String body, String fileName, InputStreamSource inputStreamSource) {queue(MailRequest.to(emailTo).cc(cc).subject(subject).body(body).attach(new Attachment(fileName, inputStreamSource)));}@Deprecatedpublic static void sendMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc, String[] bcc,String subject, String body, Attachment... attachments) {sendMailWithAttachments(mailSender, emailTo, cc, bcc, subject, body, false, attachments);}@Deprecatedpublic static void sendMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc, String[] bcc,String subject, String body, boolean html, Attachment... attachments) {MailRequest request = MailRequest.to(emailTo).cc(cc).bcc(bcc).subject(subject).attach(attachments);queue(html ? request.html(body) : request.body(body));}@Deprecatedpublic static void sendHtmlMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc,String subject, String body, Attachment... attachments) {queue(MailRequest.to(emailTo).cc(cc).subject(subject).html(body).attach(attachments));}/*** Inline images become ordinary attachments: the outbox stores attachments, not* CID-referenced parts. The mail still carries its images rather than being lost.*/@Deprecatedpublic static void sendEmbeddedHtmlMail(JavaMailSender mailSender, String[] emailTo, String[] cc, String subject,String body, Map<? extends Serializable, File> inlineImages) {List<Attachment> images = new ArrayList<>();if (inlineImages != null) {for (Map.Entry<? extends Serializable, File> entry : inlineImages.entrySet()) {File file = entry.getValue();if (file != null) {images.add(new Attachment(file.getName(), new FileSystemResource(file)));}}}queue(MailRequest.to(emailTo).cc(cc).subject(subject).html(body).attach(images.toArray(new Attachment[0])));}@Deprecatedpublic static void sendMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc, String subject,String body, List<File> attachments) {queue(MailRequest.to(emailTo).cc(cc).subject(subject).body(body).attach(fromFiles(attachments)));}private static void queue(MailRequest request) {MailQueue queue = MailQueueHolder.get();if (queue != null) {queue.queue(request.source("Utils"));}}private static Attachment[] fromFiles(List<File> files) {if (files == null || files.isEmpty()) {return null;}List<Attachment> converted = new ArrayList<>(files.size());for (File file : files) {if (file != null) {converted.add(new Attachment(file.getName(), new FileSystemResource(file)));}}return converted.toArray(new Attachment[0]);}public static String getIconUrl(int entityId, String host, int port, String webapp) {return "";}// Velocity-only helpers: the sole callers are .vm templates via $vmUtils// (AppConfig binds new Utils()), so no Java call site references them.public String html(String string) {return org.apache.commons.lang.StringEscapeUtils.escapeHtml(String.valueOf(string));}public String htmlJson(Object object) {return StringEscapeUtils.escapeHtml4(gson.toJson(object));}public static String getHyphenatedString(String s) {s = s.trim().replaceAll("\\s+", " ");s = s.replaceAll("\\s", "-");return s.toLowerCase();}public static void main(String[] args) throws Exception {Utils.sendSms("Hello", "9990381569");}public static class Attachment {public Attachment(String fileName, InputStreamSource inputStreamSource) {this.fileName = fileName;this.inputStreamSource = inputStreamSource;}private String fileName;private InputStreamSource inputStreamSource;public String getFileName() {return fileName;}public void setFileName(String fileName) {this.fileName = fileName;}public InputStreamSource getInputStreamSource() {return inputStreamSource;}public void setInputStreamSource(InputStreamSource inputStreamSource) {this.inputStreamSource = inputStreamSource;}@Overridepublic String toString() {return "Attachment [fileName=" + fileName + ", inputStreamSource=" + inputStreamSource + "]";}}public static int compareFloat(float f1, float f2) {if (Math.abs(f1 - f2) < DOUBLE_EPSILON) {return 0;}return Float.compare(f1, f2);}public static int compareDouble(double d1, double d2) {if (Math.abs(d1 - d2) < DOUBLE_EPSILON) {return 0;}return Double.compare(d1, d2);}public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {Set<Object> seen = ConcurrentHashMap.newKeySet();return t -> seen.add(keyExtractor.apply(t));}public static <T> Predicate<T> smallestByKey(Function<? super T, ?> keyExtractor) {Set<Object> seen = ConcurrentHashMap.newKeySet();return t -> seen.add(keyExtractor.apply(t));}public static LocalDate convertToLocalDate(Date dateToConvert) {return Instant.ofEpochMilli(dateToConvert.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();}public static LocalDateTime convertToLocalDateTime(Date dateToConvert) {return Instant.ofEpochMilli(dateToConvert.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();}/*** Saves the given InputStream to the specified File.* Automatically creates parent directories if they don't exist.** @param inputStream the source InputStream* @param file the destination file* @throws IOException if an I/O error occurs*/public static void saveStreamToFile(InputStream inputStream, File file) throws IOException {// Ensure parent directories existif (file.getParentFile() != null && !file.getParentFile().exists()) {file.getParentFile().mkdirs();}try (InputStream in = inputStream;OutputStream out = new FileOutputStream(file)) {byte[] buffer = new byte[8192]; // 8 KB bufferint bytesRead;while ((bytesRead = in.read(buffer)) != -1) {out.write(buffer, bytesRead == 0 ? 0 : 0, bytesRead);}}}/*** Saves a Spring InputStreamSource to the specified file.* Works on all OS (Windows, macOS, Linux) and Java 8+.*//*** Saves a Spring InputStreamSource to a file inside the user's home directory.* Works on Java 8+ and all operating systems.** @param source the InputStreamSource (e.g., MultipartFile, ByteArrayResource)* @param fileName the file name (without path)* @return the created File reference* @throws IOException if an error occurs during write*/public static File saveInputStreamSourceToHome(InputStreamSource source, String fileName) throws IOException {// Get user home directoryString userHome = System.getProperty("user.home");// Build the file path (home + filename)File targetFile = new File(userHome, fileName);// Ensure parent directories exist (in case filename contains subfolders)if (targetFile.getParentFile() != null && !targetFile.getParentFile().exists()) {targetFile.getParentFile().mkdirs();}// Copy the stream contentstry (InputStream in = source.getInputStream();OutputStream out = new FileOutputStream(targetFile)) {byte[] buffer = new byte[8192];int bytesRead;while ((bytesRead = in.read(buffer)) != -1) {out.write(buffer, 0, bytesRead);}}logger.info("Saving InputStreamSource to home directory: {}", targetFile.getAbsolutePath());return targetFile;}}