Subversion Repositories SmartDukaan

Rev

Rev 35102 | 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 com.spice.profitmandi.thrift.clients.InventoryClient;
import com.spice.profitmandi.thrift.clients.WarehouseClient;
import in.shop2020.model.v1.inventory.InventoryService;
import in.shop2020.model.v1.inventory.StateInfo;
import in.shop2020.model.v1.inventory.Warehouse;
import in.shop2020.model.v1.order.OrderStatusGroups;
import in.shop2020.model.v1.order.RechargeOrderStatus;
import in.shop2020.model.v1.order.RechargePlan;
import in.shop2020.warehouse.InventoryItem;
import in.shop2020.warehouse.WarehouseService;
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, List<RechargePlan>> operatorPlanMap = new HashMap<>(20);
    private static Map<Long, String> mobileProvidersMap;
    private static Map<Long, String> dthProvidersMap;
    private static Map<Long, String> allProviders;
    public static Map<RechargeOrderStatus, String> rechargeStatusMap = new HashMap<>();
    public static OrderStatusGroups ORDER_STATUS_GROUPS = new OrderStatusGroups();
    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 String getRechargeDisplayStatus(RechargeOrderStatus status) {
        if (status == null) {
            status = RechargeOrderStatus.INIT;
        }
        String displayStatus = (String) rechargeStatusMap.get(status);
        if (displayStatus == null) {
            return "";
        }
        return displayStatus;
    }

    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[] getOrderStatus(RechargeOrderStatus status) {
        if (status == null) {
            status = RechargeOrderStatus.INIT;
        }
        if (status.equals(RechargeOrderStatus.PAYMENT_FAILED) || status.equals(RechargeOrderStatus.PAYMENT_PENDING)) {
            return new String[]{"false", "PAYMENT FAILED", "Payment failed at the payment gateway."};
        } else if (status.equals(RechargeOrderStatus.PAYMENT_SUCCESSFUL)
                || status.equals(RechargeOrderStatus.RECHARGE_UNKNOWN)) {
            if (status.equals(RechargeOrderStatus.PAYMENT_SUCCESSFUL)) {
                return new String[]{"false", "PAYMENT SUCCESSFUL",
                        "Your Payment was successful but due to some internal error with the operator's system we are not sure if the recharge was successful."
                                + " We have put your recharge under process."
                                + " As soon as we get a confirmation on this transaction, we will notify you."};
            } else {
                return new String[]{"false", "RECHARGE IN PROCESS",
                        "Your Payment is successful.We have put your recharge under process."
                                + " Please wait while we check with the operator."};
            }
        } else if (status.equals(RechargeOrderStatus.RECHARGE_FAILED)
                || status.equals(RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)) {
            return new String[]{"false", "RECHARGE FAILED",
                    "Your Payment was successful but unfortunately the recharge failed.Don't worry your payment is safe with us."
                            + " The entire Amount has been refunded to your wallet."};
        } else if (status.equals(RechargeOrderStatus.RECHARGE_SUCCESSFUL)) {
            return new String[]{"false", "SUCCESS", "Congratulations! Your device is successfully recharged."};
        } else if (status.equals(RechargeOrderStatus.PARTIALLY_REFUNDED)
                || status.equals(RechargeOrderStatus.REFUNDED)) {
            return new String[]{"false", "PAYMENT REFUNDED",
                    "The payment associated with this recharge order has been refunded."};
        } else {
            return new String[]{"true", "ERROR", "INVALID INPUT"};
        }
    }

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


    private static WarehouseService.Client getWarehouseClient() throws Exception {
        try {
            WarehouseClient client = new WarehouseClient();
            WarehouseService.Client warehouseClient = client.getClient();
            return warehouseClient;
        } catch (Exception e) {
            throw e;
        }
    }

    public static Map<String, Warehouse> getWarehouseByImeis(List<String> imeis) throws Exception {
        List<InventoryItem> inventoryItems = getWarehouseClient().getInventoryItemsBySerailNumbers(imeis);
        Map<String, InventoryItem> imeiInventoryItemMap = new HashMap<>();
        for (InventoryItem inventoryItem : inventoryItems) {
            imeiInventoryItemMap.put(inventoryItem.getSerialNumber(), inventoryItem);
        }
        Map<Integer, Warehouse> warehouseMap = new HashMap<>();
        Map<String, Warehouse> serialNumberWarehouseMap = new HashMap<>();
        InventoryClient client = new InventoryClient();
        InventoryService.Client inventoryClient = client.getClient();
        logger.info("[imeiInventoryItemMap] {}", imeiInventoryItemMap);
        for (InventoryItem inventory : new HashSet<>(imeiInventoryItemMap.values())) {
            Warehouse phWarehouse = null;
            if (warehouseMap.containsKey(inventory.getPhysicalWarehouseId())) {
                phWarehouse = warehouseMap.get((int) inventory.getPhysicalWarehouseId());
            } else {
                phWarehouse = inventoryClient.getWarehouse(inventory.getPhysicalWarehouseId());
                warehouseMap.put((int) inventory.getPhysicalWarehouseId(), phWarehouse);
            }
            serialNumberWarehouseMap.put(inventory.getSerialNumber(), phWarehouse);

        }
        return serialNumberWarehouseMap;
    }

    public static Map<Integer, Warehouse> getWarehousesByIds(Set<Integer> warehouseIds) throws Exception {
        InventoryClient client = new InventoryClient();
        InventoryService.Client inventoryClient = client.getClient();
        Map<Integer, Warehouse> warehouseMap = new HashMap<>();
        for (Integer warehouseId : warehouseIds) {
            warehouseMap.put(warehouseId, inventoryClient.getWarehouse(warehouseId));
        }
        return warehouseMap;
    }

    public static String getStateCode(String stateName) throws Exception {
        return getStateInfo(stateName).getStateCode();
    }

    public static long getStateId(String stateName) throws ProfitMandiBusinessException {
        try {
            return getStateInfo(stateName).getId();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ProfitMandiBusinessException("State Name", stateName, "Could not fetch state");
        }
    }

    public static StateInfo getStateByStateId(long stateId) throws Exception {
        InventoryClient client = new InventoryClient();
        InventoryService.Client inventoryClient = client.getClient();
        Map<Long, StateInfo> map = inventoryClient.getStateMaster();
        return map.get(stateId);
    }

    public static StateInfo getStateInfo(String stateName) throws Exception {
        try {
            InventoryClient client = new InventoryClient();
            InventoryService.Client inventoryClient = client.getClient();
            Map<Long, StateInfo> map = inventoryClient.getStateMaster();
            List<StateInfo> stateInfos = new ArrayList<>(map.values());
            logger.info("State Name: {}", stateName);
            for (StateInfo stateInfo : stateInfos) {
                logger.info("State Name from service: {}", stateInfo.getStateName());
                if (stateName.toUpperCase().equals(stateInfo.getStateName().toUpperCase())) {
                    return stateInfo;
                }
            }
            throw new Exception("Not found");
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

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

}