Subversion Repositories SmartDukaan

Rev

Rev 36623 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
21543 ashik.ali 1
package com.spice.profitmandi.common.util;
2
 
26066 amit.gupta 3
import com.google.gson.Gson;
22215 ashik.ali 4
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
26079 amit.gupta 5
import com.spice.profitmandi.common.web.client.RestClient;
30122 amit.gupta 6
import org.apache.commons.io.FileUtils;
7
import org.apache.commons.lang3.StringEscapeUtils;
8
import org.apache.logging.log4j.LogManager;
9
import org.apache.logging.log4j.Logger;
10
import org.springframework.core.io.InputStreamSource;
37477 amit 11
import com.spice.profitmandi.common.mail.MailQueue;
12
import com.spice.profitmandi.common.mail.MailQueueHolder;
13
import com.spice.profitmandi.common.mail.MailRequest;
14
import org.springframework.core.io.FileSystemResource;
15
import java.io.File;
16
import java.io.Serializable;
17
import java.util.ArrayList;
18
import java.util.List;
19
import java.util.Map;
30122 amit.gupta 20
import org.springframework.mail.javamail.JavaMailSender;
21
import org.springframework.mail.javamail.MimeMessageHelper;
21543 ashik.ali 22
 
30122 amit.gupta 23
import javax.mail.Multipart;
24
import javax.mail.internet.InternetAddress;
25
import javax.mail.internet.MimeBodyPart;
26
import javax.mail.internet.MimeMessage;
27
import javax.mail.internet.MimeMultipart;
35204 amit 28
import java.io.*;
32955 amit.gupta 29
import java.time.*;
30122 amit.gupta 30
import java.util.*;
31
import java.util.concurrent.ConcurrentHashMap;
32
import java.util.function.Function;
33
import java.util.function.Predicate;
34
import java.util.regex.Matcher;
35
import java.util.regex.Pattern;
36
 
21543 ashik.ali 37
public class Utils {
31177 tejbeer 38
 
35102 amit 39
    public static final float FLOAT_EPSILON = 0.001f;
21986 kshitij.so 40
 
35102 amit 41
    public static final double DOUBLE_EPSILON = 0.001d;
31177 tejbeer 42
 
33045 amit.gupta 43
 
35102 amit 44
    public static String[] getAlphaNumericParts(String alphaNumericString) {
45
        String[] parts = alphaNumericString.split("(?<=\\D)(?=\\d)");
46
        return parts;
47
    }
33045 amit.gupta 48
 
35102 amit 49
    private static final Logger logger = LogManager.getLogger(Utils.class);
50
    public static final String EXPORT_ENTITIES_PATH = getExportPath();
51
    public static final String PRODUCT_PROPERTIES_SNIPPET = "ProductPropertiesSnippet.html";
52
    public static final String DOCUMENT_STORE = "/profitmandi/documents/";
53
    private Gson gson = new Gson();
54
    private static final Map<Integer, String> helpMap = new HashMap<>(6);
55
    private static final Map<Integer, String> dthIdAliasMap = new HashMap<>(7);
56
    private static Map<Long, String> mobileProvidersMap;
57
    private static Map<Long, String> dthProvidersMap;
58
    private static Map<Long, String> allProviders;
59
    public static final String SYSTEM_PARTNER = "testpxps@gmail.com";
60
    public static final int SYSTEM_PARTNER_ID = 175120474;
61
    private static final RestClient rc = new RestClient();
62
    private static final String regex = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$";
63
    public static final LocalTime MAX_TIME = LocalTime.of(23, 59, 59);
64
    // Compile regular expression to get the pattern
65
    private static final Pattern pattern = Pattern.compile(regex);
24440 amit.gupta 66
 
35102 amit 67
    public static boolean validateEmail(String email) {
68
        if (email == null) {
69
            return false;
70
        }
71
        Matcher matcher = pattern.matcher(email);
72
        return matcher.matches();
73
    }
31177 tejbeer 74
 
35102 amit 75
    @SuppressWarnings("serial")
76
    public static final Map<String, String> MIME_TYPE = Collections.unmodifiableMap(new HashMap<String, String>() {
77
        {
78
            put("image/png", "png");
79
            put("image/jpeg", "jpeg");
80
            put("image/pjpeg", "jpeg");
81
            put("application/pdf", "pdf");
82
            put("application/msword", "doc");
83
            put("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx");
84
            put("application/vnd.ms-excel", "xls");
85
            put("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx");
86
        }
87
    });
21543 ashik.ali 88
 
35102 amit 89
    private static String getExportPath() {
90
        String exportPath = "/var/lib/tomcat7/webapps/export/html/entities/";
91
        /*
92
         * String exportPath = null;
93
         *
94
         * try { ConfigClient client = ConfigClient.getClient(); exportPath =
95
         * client.get("export_entities_path"); } catch (Exception ce) {
96
         * logger.error("Unable to read export path from the config client: ", ce);
97
         * logger.warn("Setting the default export path"); exportPath =
98
         * "/var/lib/tomcat7/webapps/export/html/entities/"; }
99
         */
100
        return exportPath;
101
    }
21986 kshitij.so 102
 
35102 amit 103
    public static LocalDateTime toLocalDateTime(long epochTimeInMillis) {
104
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(epochTimeInMillis), ZoneId.systemDefault());
105
    }
32724 amit.gupta 106
 
35102 amit 107
    public static boolean copyDocument(String documentPath) {
108
        File source = new File(documentPath);
109
        File dest = new File(DOCUMENT_STORE + source.getName());
110
        try {
111
            FileUtils.copyFile(source, dest);
112
        } catch (IOException e) {
113
            e.printStackTrace();
114
            return false;
115
        }
116
        return true;
117
    }
21543 ashik.ali 118
 
35102 amit 119
    public static Map<Long, String> getMobileProvidersMap() {
120
        return mobileProvidersMap;
121
    }
21543 ashik.ali 122
 
35102 amit 123
    public static Map<Long, String> getDthProvidersMap() {
124
        return dthProvidersMap;
125
    }
21986 kshitij.so 126
 
35102 amit 127
    public static Map<Long, String> getAllProviders() {
128
        return allProviders;
129
    }
21986 kshitij.so 130
 
35102 amit 131
    public static String getProvider(long operatorId) {
132
        return allProviders.get(operatorId);
133
    }
21543 ashik.ali 134
 
35102 amit 135
    public static void sendSms(String text, String mobileNumber) throws Exception {
136
        Map<String, String> paramsMap = new HashMap<>();
137
        paramsMap.put("username", "SmartDukaanT");
138
        paramsMap.put("password", "Smart@91");
139
        paramsMap.put("senderID", "SMTDKN");
140
        paramsMap.put("message", text);
141
        paramsMap.put("mobile", mobileNumber);
142
        paramsMap.put("messageType", "Text");
143
        // rc.getResponse(SMS_GATEWAY, paramsMap, null);
144
    }
24440 amit.gupta 145
 
37477 amit 146
    /*
147
     * Mail helpers. These no longer send anything themselves.
148
     *
149
     * Each used to build its own MimeMessage, hardcode From: noreply@smartdukaan.com,
150
     * and push it straight down whichever JavaMailSender the caller passed. That From
151
     * is precisely why mail was being refused — an authenticated Workspace session may
152
     * send only as the account it logged in as, and noreply@ is a different identity.
153
     * A failed send also took the calling job down with it, which is how one expired
154
     * credential came to mark ten report jobs FAILED.
155
     *
156
     * They now hand the mail to the outbox, which owns retry, de-duplication and the
157
     * choice of transport. The JavaMailSender parameter is ignored and kept only so the
158
     * 27 existing call sites continue to compile; new code should inject
159
     * {@link com.spice.profitmandi.common.mail.MailQueue} and build a MailRequest.
160
     */
161
 
162
    @Deprecated
35102 amit 163
    public static void sendMailWithAttachments(JavaMailSender mailSender, String emailTo, String[] cc, String subject,
37477 amit 164
                                               String body, List<File> attachments) {
165
        queue(MailRequest.to(emailTo).cc(cc).subject(subject).body(body)
166
                .attach(fromFiles(attachments)));
35102 amit 167
    }
25764 amit.gupta 168
 
37477 amit 169
    @Deprecated
170
    public static void sendMailWithAttachment(JavaMailSender mailSender, String[] emailTo, String[] cc, String subject,
171
                                              String body, String fileName, InputStreamSource inputStreamSource) {
172
        queue(MailRequest.to(emailTo).cc(cc).subject(subject).body(body)
173
                .attach(new Attachment(fileName, inputStreamSource)));
174
    }
25764 amit.gupta 175
 
37477 amit 176
    @Deprecated
177
    public static void sendMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc, String[] bcc,
178
                                               String subject, String body, Attachment... attachments) {
179
        sendMailWithAttachments(mailSender, emailTo, cc, bcc, subject, body, false, attachments);
180
    }
25764 amit.gupta 181
 
37477 amit 182
    @Deprecated
183
    public static void sendMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc, String[] bcc,
184
                                               String subject, String body, boolean html, Attachment... attachments) {
185
        MailRequest request = MailRequest.to(emailTo).cc(cc).bcc(bcc).subject(subject).attach(attachments);
186
        queue(html ? request.html(body) : request.body(body));
187
    }
25764 amit.gupta 188
 
37477 amit 189
    @Deprecated
190
    public static void sendHtmlMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc,
191
                                                   String subject, String body, Attachment... attachments) {
192
        queue(MailRequest.to(emailTo).cc(cc).subject(subject).html(body).attach(attachments));
35102 amit 193
    }
25764 amit.gupta 194
 
37477 amit 195
    /**
196
     * Inline images become ordinary attachments: the outbox stores attachments, not
197
     * CID-referenced parts. The mail still carries its images rather than being lost.
198
     */
199
    @Deprecated
200
    public static void sendEmbeddedHtmlMail(JavaMailSender mailSender, String[] emailTo, String[] cc, String subject,
201
                                            String body, Map<? extends Serializable, File> inlineImages) {
202
        List<Attachment> images = new ArrayList<>();
203
        if (inlineImages != null) {
204
            for (Map.Entry<? extends Serializable, File> entry : inlineImages.entrySet()) {
205
                File file = entry.getValue();
206
                if (file != null) {
207
                    images.add(new Attachment(file.getName(), new FileSystemResource(file)));
208
                }
209
            }
35102 amit 210
        }
37477 amit 211
        queue(MailRequest.to(emailTo).cc(cc).subject(subject).html(body)
212
                .attach(images.toArray(new Attachment[0])));
35102 amit 213
    }
25764 amit.gupta 214
 
37477 amit 215
    @Deprecated
216
    public static void sendMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc, String subject,
217
                                               String body, List<File> attachments) {
218
        queue(MailRequest.to(emailTo).cc(cc).subject(subject).body(body)
219
                .attach(fromFiles(attachments)));
35102 amit 220
    }
25764 amit.gupta 221
 
37477 amit 222
    private static void queue(MailRequest request) {
223
        MailQueue queue = MailQueueHolder.get();
224
        if (queue != null) {
225
            queue.queue(request.source("Utils"));
35102 amit 226
        }
227
    }
24440 amit.gupta 228
 
37477 amit 229
    private static Attachment[] fromFiles(List<File> files) {
230
        if (files == null || files.isEmpty()) {
231
            return null;
35102 amit 232
        }
37477 amit 233
        List<Attachment> converted = new ArrayList<>(files.size());
234
        for (File file : files) {
235
            if (file != null) {
236
                converted.add(new Attachment(file.getName(), new FileSystemResource(file)));
237
            }
35102 amit 238
        }
37477 amit 239
        return converted.toArray(new Attachment[0]);
35102 amit 240
    }
21986 kshitij.so 241
 
35102 amit 242
    public static String getIconUrl(int entityId, String host, int port, String webapp) {
243
        return "";
244
    }
23509 amit.gupta 245
 
37477 amit 246
    public static String getHyphenatedString(String s) {
247
        s = s.trim().replaceAll("\\s+", " ");
248
        s = s.replaceAll("\\s", "-");
249
        return s.toLowerCase();
250
    }
251
 
35102 amit 252
    public static void main(String[] args) throws Exception {
253
        Utils.sendSms("Hello", "9990381569");
254
    }
27285 tejbeer 255
 
37477 amit 256
    public static class Attachment {
257
        public Attachment(String fileName, InputStreamSource inputStreamSource) {
258
            this.fileName = fileName;
259
            this.inputStreamSource = inputStreamSource;
260
        }
27285 tejbeer 261
 
37477 amit 262
        private String fileName;
263
        private InputStreamSource inputStreamSource;
25998 amit.gupta 264
 
37477 amit 265
        public String getFileName() {
266
            return fileName;
35102 amit 267
        }
25764 amit.gupta 268
 
37477 amit 269
        public void setFileName(String fileName) {
270
            this.fileName = fileName;
35102 amit 271
        }
27285 tejbeer 272
 
37477 amit 273
        public InputStreamSource getInputStreamSource() {
274
            return inputStreamSource;
275
        }
32199 amit.gupta 276
 
37477 amit 277
        public void setInputStreamSource(InputStreamSource inputStreamSource) {
278
            this.inputStreamSource = inputStreamSource;
279
        }
25764 amit.gupta 280
 
37477 amit 281
        @Override
282
        public String toString() {
283
            return "Attachment [fileName=" + fileName + ", inputStreamSource=" + inputStreamSource + "]";
284
        }
35102 amit 285
    }
27285 tejbeer 286
 
30122 amit.gupta 287
 
35102 amit 288
    public static int compareFloat(float f1, float f2) {
289
        if (Math.abs(f1 - f2) < DOUBLE_EPSILON) {
290
            return 0;
291
        }
26534 amit.gupta 292
 
35102 amit 293
        return Float.compare(f1, f2);
294
    }
31177 tejbeer 295
 
35102 amit 296
    public static int compareDouble(double d1, double d2) {
297
        if (Math.abs(d1 - d2) < DOUBLE_EPSILON) {
298
            return 0;
299
        }
300
        return Double.compare(d1, d2);
301
    }
30122 amit.gupta 302
 
35102 amit 303
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
304
        Set<Object> seen = ConcurrentHashMap.newKeySet();
305
        return t -> seen.add(keyExtractor.apply(t));
306
    }
31903 amit.gupta 307
 
35102 amit 308
    public static <T> Predicate<T> smallestByKey(Function<? super T, ?> keyExtractor) {
309
        Set<Object> seen = ConcurrentHashMap.newKeySet();
310
        return t -> seen.add(keyExtractor.apply(t));
311
    }
32955 amit.gupta 312
 
35102 amit 313
    public static LocalDate convertToLocalDate(Date dateToConvert) {
314
        return Instant.ofEpochMilli(dateToConvert.getTime())
315
                .atZone(ZoneId.systemDefault())
316
                .toLocalDate();
317
    }
318
 
319
    public static LocalDateTime convertToLocalDateTime(Date dateToConvert) {
320
        return Instant.ofEpochMilli(dateToConvert.getTime())
321
                .atZone(ZoneId.systemDefault())
322
                .toLocalDateTime();
323
    }
324
 
35204 amit 325
    /**
326
     * Saves the given InputStream to the specified File.
327
     * Automatically creates parent directories if they don't exist.
328
     *
329
     * @param inputStream the source InputStream
330
     * @param file        the destination file
331
     * @throws IOException if an I/O error occurs
332
     */
333
    public static void saveStreamToFile(InputStream inputStream, File file) throws IOException {
334
        // Ensure parent directories exist
335
        if (file.getParentFile() != null && !file.getParentFile().exists()) {
336
            file.getParentFile().mkdirs();
337
        }
338
 
339
        try (InputStream in = inputStream;
340
             OutputStream out = new FileOutputStream(file)) {
341
            byte[] buffer = new byte[8192];  // 8 KB buffer
342
            int bytesRead;
343
            while ((bytesRead = in.read(buffer)) != -1) {
344
                out.write(buffer, bytesRead == 0 ? 0 : 0, bytesRead);
345
            }
346
        }
347
    }
348
 
349
    /**
350
     * Saves a Spring InputStreamSource to the specified file.
351
     * Works on all OS (Windows, macOS, Linux) and Java 8+.
352
     */
353
    /**
354
     * Saves a Spring InputStreamSource to a file inside the user's home directory.
355
     * Works on Java 8+ and all operating systems.
356
     *
357
     * @param source    the InputStreamSource (e.g., MultipartFile, ByteArrayResource)
358
     * @param fileName  the file name (without path)
359
     * @return the created File reference
360
     * @throws IOException if an error occurs during write
361
     */
362
    public static File saveInputStreamSourceToHome(InputStreamSource source, String fileName) throws IOException {
363
        // Get user home directory
364
        String userHome = System.getProperty("user.home");
365
 
366
        // Build the file path (home + filename)
367
        File targetFile = new File(userHome, fileName);
368
 
369
        // Ensure parent directories exist (in case filename contains subfolders)
370
        if (targetFile.getParentFile() != null && !targetFile.getParentFile().exists()) {
371
            targetFile.getParentFile().mkdirs();
372
        }
373
 
374
        // Copy the stream contents
375
        try (InputStream in = source.getInputStream();
376
             OutputStream out = new FileOutputStream(targetFile)) {
377
 
378
            byte[] buffer = new byte[8192];
379
            int bytesRead;
380
            while ((bytesRead = in.read(buffer)) != -1) {
381
                out.write(buffer, 0, bytesRead);
382
            }
383
        }
384
        logger.info("Saving InputStreamSource to home directory: {}", targetFile.getAbsolutePath());
385
 
386
        return targetFile;
387
    }
388
 
26084 amit.gupta 389
}