Subversion Repositories SmartDukaan

Rev

Rev 35204 | 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 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 pattern
    private 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);
    }

    public static void sendMailWithAttachments(JavaMailSender mailSender, String emailTo, String[] cc, String subject,
                                               String body, List<File> attachments) throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setSubject(subject);
        helper.setText(body);
        if (cc != null) {
            helper.setCc(cc);
        }
        helper.setTo(emailTo);
        // helper.setTo("amit.gupta@smartdukaan.com");
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");
        helper.setFrom(senderAddress);
        if (attachments != null) {
            for (File file : attachments) {
                helper.addAttachment(file.getName(), file);
            }
        }
        mailSender.send(message);
    }

    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;
        }

        @Override
        public String toString() {
            return "Attachment [fileName=" + fileName + ", inputStreamSource=" + inputStreamSource + "]";
        }
    }

    public static void sendMailWithAttachment(JavaMailSender mailSender, String[] emailTo, String[] cc, String subject,
                                              String body, String fileName, InputStreamSource inputStreamSource) throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setSubject(subject);
        helper.setText(body);
        if (cc != null) {
            helper.setCc(cc);
        }
        helper.setTo(emailTo);
        helper.addAttachment(fileName, inputStreamSource);
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");
        helper.setFrom(senderAddress);
        mailSender.send(message);
    }

    public static void sendMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc, String[] bcc,
                                               String subject, String body, Attachment... attachments) throws Exception {
        sendMailWithAttachments(mailSender, emailTo, cc, bcc,
                subject, body, false, attachments);
    }

    public static void sendMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc, String[] bcc,
                                               String subject, String body, boolean html, Attachment... attachments) throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setSubject(subject);
        helper.setText(body, html);
        if (cc != null) {
            helper.setCc(cc);
        }
        if (bcc != null) {
            helper.setBcc(bcc);
        }
        helper.setTo(emailTo);
        for (Attachment attachment : attachments) {
            //saveInputStreamSourceToHome(attachment.getInputStreamSource(), attachment.getFileName());
            helper.addAttachment(attachment.getFileName(), attachment.getInputStreamSource());
        }
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");
        helper.setFrom(senderAddress);
        mailSender.send(message);
    }

    public static void sendHtmlMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc,
                                                   String subject, String body, Attachment... attachments) throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setSubject(subject);
        helper.setText(body, true);
        // helper.setText(body, true);
        if (cc != null) {
            helper.setCc(cc);
        }
        helper.setTo(emailTo);
        for (Attachment attachment : attachments) {
            if (attachment == null)
                break;
            helper.addAttachment(attachment.getFileName(), attachment.getInputStreamSource());
        }
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");
        helper.setFrom(senderAddress);
        mailSender.send(message);
    }

    public static String getIconUrl(int entityId, String host, int port, String webapp) {
        return "";
    }

    public static void main(String[] args) throws Exception {
        Utils.sendSms("Hello", "9990381569");
    }

    public static void sendEmbeddedHtmlMail(JavaMailSender mailSender, String[] emailTo, String[] cc, String subject,
                                            String body, Map<? extends Serializable, File> map) throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setSubject(subject);
        Multipart mp = new MimeMultipart();

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(body, "text/html");
        mp.addBodyPart(messageBodyPart);

        // helper.setText(body, true);
        if (cc != null) {
            helper.setCc(cc);
        }
        helper.setTo(emailTo);
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");
        helper.setFrom(senderAddress);
        for (Map.Entry<? extends Serializable, File> entry : map.entrySet()) {
            entry.getKey();
            entry.getValue();
            MimeBodyPart imagePart = new MimeBodyPart();
            imagePart.setHeader("Content-ID", entry.getKey() + "");
            imagePart.setDisposition(MimeBodyPart.INLINE);
            imagePart.attachFile(entry.getValue());
            mp.addBodyPart(imagePart);

        }
        message.setContent(mp);
        mailSender.send(message);

    }

    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 sendMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc, String subject,
                                               String body, Attachment... attachments) throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setSubject(subject);
        helper.setText(body, true);
        if (cc != null) {
            helper.setCc(cc);
        }
        helper.setTo(emailTo);
        for (Attachment attachment : attachments) {
            helper.addAttachment(attachment.getFileName(), attachment.getInputStreamSource());
            //saveInputStreamSourceToHome(attachment.getInputStreamSource(), attachment.getFileName());
        }
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");
        helper.setFrom(senderAddress);
        mailSender.send(message);
    }

    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 exist
        if (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 buffer
            int 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 directory
        String 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 contents
        try (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;
    }

}