Subversion Repositories SmartDukaan

Rev

Rev 35102 | 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;
21894 ashik.ali 6
import com.spice.profitmandi.thrift.clients.InventoryClient;
23509 amit.gupta 7
import com.spice.profitmandi.thrift.clients.WarehouseClient;
21894 ashik.ali 8
import in.shop2020.model.v1.inventory.InventoryService;
9
import in.shop2020.model.v1.inventory.StateInfo;
23509 amit.gupta 10
import in.shop2020.model.v1.inventory.Warehouse;
23884 amit.gupta 11
import in.shop2020.model.v1.order.OrderStatusGroups;
21894 ashik.ali 12
import in.shop2020.model.v1.order.RechargeOrderStatus;
13
import in.shop2020.model.v1.order.RechargePlan;
23509 amit.gupta 14
import in.shop2020.warehouse.InventoryItem;
15
import in.shop2020.warehouse.WarehouseService;
30122 amit.gupta 16
import org.apache.commons.io.FileUtils;
17
import org.apache.commons.lang3.StringEscapeUtils;
18
import org.apache.logging.log4j.LogManager;
19
import org.apache.logging.log4j.Logger;
20
import org.springframework.core.io.InputStreamSource;
21
import org.springframework.mail.javamail.JavaMailSender;
22
import org.springframework.mail.javamail.MimeMessageHelper;
21543 ashik.ali 23
 
30122 amit.gupta 24
import javax.mail.Multipart;
25
import javax.mail.internet.InternetAddress;
26
import javax.mail.internet.MimeBodyPart;
27
import javax.mail.internet.MimeMessage;
28
import javax.mail.internet.MimeMultipart;
35204 amit 29
import java.io.*;
32955 amit.gupta 30
import java.time.*;
30122 amit.gupta 31
import java.util.*;
32
import java.util.concurrent.ConcurrentHashMap;
33
import java.util.function.Function;
34
import java.util.function.Predicate;
35
import java.util.regex.Matcher;
36
import java.util.regex.Pattern;
37
 
21543 ashik.ali 38
public class Utils {
31177 tejbeer 39
 
35102 amit 40
    public static final float FLOAT_EPSILON = 0.001f;
21986 kshitij.so 41
 
35102 amit 42
    public static final double DOUBLE_EPSILON = 0.001d;
31177 tejbeer 43
 
33045 amit.gupta 44
 
35102 amit 45
    public static String[] getAlphaNumericParts(String alphaNumericString) {
46
        String[] parts = alphaNumericString.split("(?<=\\D)(?=\\d)");
47
        return parts;
48
    }
33045 amit.gupta 49
 
35102 amit 50
    private static final Logger logger = LogManager.getLogger(Utils.class);
51
    public static final String EXPORT_ENTITIES_PATH = getExportPath();
52
    public static final String PRODUCT_PROPERTIES_SNIPPET = "ProductPropertiesSnippet.html";
53
    public static final String DOCUMENT_STORE = "/profitmandi/documents/";
54
    private Gson gson = new Gson();
55
    private static final Map<Integer, String> helpMap = new HashMap<>(6);
56
    private static final Map<Integer, String> dthIdAliasMap = new HashMap<>(7);
57
    private static Map<Long, List<RechargePlan>> operatorPlanMap = new HashMap<>(20);
58
    private static Map<Long, String> mobileProvidersMap;
59
    private static Map<Long, String> dthProvidersMap;
60
    private static Map<Long, String> allProviders;
61
    public static Map<RechargeOrderStatus, String> rechargeStatusMap = new HashMap<>();
62
    public static OrderStatusGroups ORDER_STATUS_GROUPS = new OrderStatusGroups();
63
    public static final String SYSTEM_PARTNER = "testpxps@gmail.com";
64
    public static final int SYSTEM_PARTNER_ID = 175120474;
65
    private static final RestClient rc = new RestClient();
66
    private static final String regex = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$";
67
    public static final LocalTime MAX_TIME = LocalTime.of(23, 59, 59);
68
    // Compile regular expression to get the pattern
69
    private static final Pattern pattern = Pattern.compile(regex);
24440 amit.gupta 70
 
35102 amit 71
    public static boolean validateEmail(String email) {
72
        if (email == null) {
73
            return false;
74
        }
75
        Matcher matcher = pattern.matcher(email);
76
        return matcher.matches();
77
    }
31177 tejbeer 78
 
35102 amit 79
    @SuppressWarnings("serial")
80
    public static final Map<String, String> MIME_TYPE = Collections.unmodifiableMap(new HashMap<String, String>() {
81
        {
82
            put("image/png", "png");
83
            put("image/jpeg", "jpeg");
84
            put("image/pjpeg", "jpeg");
85
            put("application/pdf", "pdf");
86
            put("application/msword", "doc");
87
            put("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx");
88
            put("application/vnd.ms-excel", "xls");
89
            put("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx");
90
        }
91
    });
21543 ashik.ali 92
 
35102 amit 93
    private static String getExportPath() {
94
        String exportPath = "/var/lib/tomcat7/webapps/export/html/entities/";
95
        /*
96
         * String exportPath = null;
97
         *
98
         * try { ConfigClient client = ConfigClient.getClient(); exportPath =
99
         * client.get("export_entities_path"); } catch (Exception ce) {
100
         * logger.error("Unable to read export path from the config client: ", ce);
101
         * logger.warn("Setting the default export path"); exportPath =
102
         * "/var/lib/tomcat7/webapps/export/html/entities/"; }
103
         */
104
        return exportPath;
105
    }
21986 kshitij.so 106
 
35102 amit 107
    public static LocalDateTime toLocalDateTime(long epochTimeInMillis) {
108
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(epochTimeInMillis), ZoneId.systemDefault());
109
    }
32724 amit.gupta 110
 
35102 amit 111
    public static String getRechargeDisplayStatus(RechargeOrderStatus status) {
112
        if (status == null) {
113
            status = RechargeOrderStatus.INIT;
114
        }
115
        String displayStatus = (String) rechargeStatusMap.get(status);
116
        if (displayStatus == null) {
117
            return "";
118
        }
119
        return displayStatus;
120
    }
21543 ashik.ali 121
 
35102 amit 122
    public static boolean copyDocument(String documentPath) {
123
        File source = new File(documentPath);
124
        File dest = new File(DOCUMENT_STORE + source.getName());
125
        try {
126
            FileUtils.copyFile(source, dest);
127
        } catch (IOException e) {
128
            e.printStackTrace();
129
            return false;
130
        }
131
        return true;
132
    }
21543 ashik.ali 133
 
35102 amit 134
    public static Map<Long, String> getMobileProvidersMap() {
135
        return mobileProvidersMap;
136
    }
21543 ashik.ali 137
 
35102 amit 138
    public static Map<Long, String> getDthProvidersMap() {
139
        return dthProvidersMap;
140
    }
21986 kshitij.so 141
 
35102 amit 142
    public static Map<Long, String> getAllProviders() {
143
        return allProviders;
144
    }
21986 kshitij.so 145
 
35102 amit 146
    public static String getProvider(long operatorId) {
147
        return allProviders.get(operatorId);
148
    }
21543 ashik.ali 149
 
35102 amit 150
    public static void sendSms(String text, String mobileNumber) throws Exception {
151
        Map<String, String> paramsMap = new HashMap<>();
152
        paramsMap.put("username", "SmartDukaanT");
153
        paramsMap.put("password", "Smart@91");
154
        paramsMap.put("senderID", "SMTDKN");
155
        paramsMap.put("message", text);
156
        paramsMap.put("mobile", mobileNumber);
157
        paramsMap.put("messageType", "Text");
158
        // rc.getResponse(SMS_GATEWAY, paramsMap, null);
159
    }
24440 amit.gupta 160
 
35102 amit 161
    public static void sendMailWithAttachments(JavaMailSender mailSender, String emailTo, String[] cc, String subject,
162
                                               String body, List<File> attachments) throws Exception {
163
        MimeMessage message = mailSender.createMimeMessage();
164
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
165
        helper.setSubject(subject);
166
        helper.setText(body);
167
        if (cc != null) {
168
            helper.setCc(cc);
169
        }
170
        helper.setTo(emailTo);
171
        // helper.setTo("amit.gupta@smartdukaan.com");
172
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");
173
        helper.setFrom(senderAddress);
174
        if (attachments != null) {
175
            for (File file : attachments) {
176
                helper.addAttachment(file.getName(), file);
177
            }
178
        }
179
        mailSender.send(message);
180
    }
25764 amit.gupta 181
 
35102 amit 182
    public static class Attachment {
183
        public Attachment(String fileName, InputStreamSource inputStreamSource) {
184
            this.fileName = fileName;
185
            this.inputStreamSource = inputStreamSource;
186
        }
25764 amit.gupta 187
 
35102 amit 188
        private String fileName;
189
        private InputStreamSource inputStreamSource;
25764 amit.gupta 190
 
35102 amit 191
        public String getFileName() {
192
            return fileName;
193
        }
25764 amit.gupta 194
 
35102 amit 195
        public void setFileName(String fileName) {
196
            this.fileName = fileName;
197
        }
25764 amit.gupta 198
 
35102 amit 199
        public InputStreamSource getInputStreamSource() {
200
            return inputStreamSource;
201
        }
25764 amit.gupta 202
 
35102 amit 203
        public void setInputStreamSource(InputStreamSource inputStreamSource) {
204
            this.inputStreamSource = inputStreamSource;
205
        }
25764 amit.gupta 206
 
35102 amit 207
        @Override
208
        public String toString() {
209
            return "Attachment [fileName=" + fileName + ", inputStreamSource=" + inputStreamSource + "]";
210
        }
211
    }
25764 amit.gupta 212
 
35102 amit 213
    public static void sendMailWithAttachment(JavaMailSender mailSender, String[] emailTo, String[] cc, String subject,
214
                                              String body, String fileName, InputStreamSource inputStreamSource) throws Exception {
215
        MimeMessage message = mailSender.createMimeMessage();
216
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
217
        helper.setSubject(subject);
218
        helper.setText(body);
219
        if (cc != null) {
220
            helper.setCc(cc);
221
        }
222
        helper.setTo(emailTo);
223
        helper.addAttachment(fileName, inputStreamSource);
224
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");
225
        helper.setFrom(senderAddress);
226
        mailSender.send(message);
227
    }
25764 amit.gupta 228
 
35102 amit 229
    public static void sendMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc, String[] bcc,
230
                                               String subject, String body, Attachment... attachments) throws Exception {
231
        sendMailWithAttachments(mailSender, emailTo, cc, bcc,
232
                subject, body, false, attachments);
233
    }
25764 amit.gupta 234
 
35102 amit 235
    public static void sendMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc, String[] bcc,
236
                                               String subject, String body, boolean html, Attachment... attachments) throws Exception {
237
        MimeMessage message = mailSender.createMimeMessage();
238
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
239
        helper.setSubject(subject);
240
        helper.setText(body, html);
241
        if (cc != null) {
242
            helper.setCc(cc);
243
        }
244
        if (bcc != null) {
245
            helper.setBcc(bcc);
246
        }
247
        helper.setTo(emailTo);
248
        for (Attachment attachment : attachments) {
35204 amit 249
            //saveInputStreamSourceToHome(attachment.getInputStreamSource(), attachment.getFileName());
35102 amit 250
            helper.addAttachment(attachment.getFileName(), attachment.getInputStreamSource());
251
        }
252
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");
253
        helper.setFrom(senderAddress);
254
        mailSender.send(message);
255
    }
24440 amit.gupta 256
 
35102 amit 257
    public static void sendHtmlMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc,
258
                                                   String subject, String body, Attachment... attachments) throws Exception {
259
        MimeMessage message = mailSender.createMimeMessage();
260
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
261
        helper.setSubject(subject);
262
        helper.setText(body, true);
263
        // helper.setText(body, true);
264
        if (cc != null) {
265
            helper.setCc(cc);
266
        }
267
        helper.setTo(emailTo);
268
        for (Attachment attachment : attachments) {
269
            if (attachment == null)
270
                break;
271
            helper.addAttachment(attachment.getFileName(), attachment.getInputStreamSource());
272
        }
273
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");
274
        helper.setFrom(senderAddress);
275
        mailSender.send(message);
276
    }
21986 kshitij.so 277
 
35102 amit 278
    public static String[] getOrderStatus(RechargeOrderStatus status) {
279
        if (status == null) {
280
            status = RechargeOrderStatus.INIT;
281
        }
282
        if (status.equals(RechargeOrderStatus.PAYMENT_FAILED) || status.equals(RechargeOrderStatus.PAYMENT_PENDING)) {
283
            return new String[]{"false", "PAYMENT FAILED", "Payment failed at the payment gateway."};
284
        } else if (status.equals(RechargeOrderStatus.PAYMENT_SUCCESSFUL)
285
                || status.equals(RechargeOrderStatus.RECHARGE_UNKNOWN)) {
286
            if (status.equals(RechargeOrderStatus.PAYMENT_SUCCESSFUL)) {
287
                return new String[]{"false", "PAYMENT SUCCESSFUL",
288
                        "Your Payment was successful but due to some internal error with the operator's system we are not sure if the recharge was successful."
289
                                + " We have put your recharge under process."
290
                                + " As soon as we get a confirmation on this transaction, we will notify you."};
291
            } else {
292
                return new String[]{"false", "RECHARGE IN PROCESS",
293
                        "Your Payment is successful.We have put your recharge under process."
294
                                + " Please wait while we check with the operator."};
295
            }
296
        } else if (status.equals(RechargeOrderStatus.RECHARGE_FAILED)
297
                || status.equals(RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)) {
298
            return new String[]{"false", "RECHARGE FAILED",
299
                    "Your Payment was successful but unfortunately the recharge failed.Don't worry your payment is safe with us."
300
                            + " The entire Amount has been refunded to your wallet."};
301
        } else if (status.equals(RechargeOrderStatus.RECHARGE_SUCCESSFUL)) {
302
            return new String[]{"false", "SUCCESS", "Congratulations! Your device is successfully recharged."};
303
        } else if (status.equals(RechargeOrderStatus.PARTIALLY_REFUNDED)
304
                || status.equals(RechargeOrderStatus.REFUNDED)) {
305
            return new String[]{"false", "PAYMENT REFUNDED",
306
                    "The payment associated with this recharge order has been refunded."};
307
        } else {
308
            return new String[]{"true", "ERROR", "INVALID INPUT"};
309
        }
310
    }
25764 amit.gupta 311
 
35102 amit 312
    public static String getIconUrl(int entityId, String host, int port, String webapp) {
313
        return "";
314
    }
23509 amit.gupta 315
 
24440 amit.gupta 316
 
35102 amit 317
    private static WarehouseService.Client getWarehouseClient() throws Exception {
318
        try {
319
            WarehouseClient client = new WarehouseClient();
320
            WarehouseService.Client warehouseClient = client.getClient();
321
            return warehouseClient;
322
        } catch (Exception e) {
323
            throw e;
324
        }
325
    }
24440 amit.gupta 326
 
35102 amit 327
    public static Map<String, Warehouse> getWarehouseByImeis(List<String> imeis) throws Exception {
328
        List<InventoryItem> inventoryItems = getWarehouseClient().getInventoryItemsBySerailNumbers(imeis);
329
        Map<String, InventoryItem> imeiInventoryItemMap = new HashMap<>();
330
        for (InventoryItem inventoryItem : inventoryItems) {
331
            imeiInventoryItemMap.put(inventoryItem.getSerialNumber(), inventoryItem);
332
        }
333
        Map<Integer, Warehouse> warehouseMap = new HashMap<>();
334
        Map<String, Warehouse> serialNumberWarehouseMap = new HashMap<>();
335
        InventoryClient client = new InventoryClient();
336
        InventoryService.Client inventoryClient = client.getClient();
337
        logger.info("[imeiInventoryItemMap] {}", imeiInventoryItemMap);
338
        for (InventoryItem inventory : new HashSet<>(imeiInventoryItemMap.values())) {
339
            Warehouse phWarehouse = null;
340
            if (warehouseMap.containsKey(inventory.getPhysicalWarehouseId())) {
341
                phWarehouse = warehouseMap.get((int) inventory.getPhysicalWarehouseId());
342
            } else {
343
                phWarehouse = inventoryClient.getWarehouse(inventory.getPhysicalWarehouseId());
344
                warehouseMap.put((int) inventory.getPhysicalWarehouseId(), phWarehouse);
345
            }
346
            serialNumberWarehouseMap.put(inventory.getSerialNumber(), phWarehouse);
24440 amit.gupta 347
 
35102 amit 348
        }
349
        return serialNumberWarehouseMap;
350
    }
24440 amit.gupta 351
 
35102 amit 352
    public static Map<Integer, Warehouse> getWarehousesByIds(Set<Integer> warehouseIds) throws Exception {
353
        InventoryClient client = new InventoryClient();
354
        InventoryService.Client inventoryClient = client.getClient();
355
        Map<Integer, Warehouse> warehouseMap = new HashMap<>();
356
        for (Integer warehouseId : warehouseIds) {
357
            warehouseMap.put(warehouseId, inventoryClient.getWarehouse(warehouseId));
358
        }
359
        return warehouseMap;
360
    }
24440 amit.gupta 361
 
35102 amit 362
    public static String getStateCode(String stateName) throws Exception {
363
        return getStateInfo(stateName).getStateCode();
364
    }
24440 amit.gupta 365
 
35102 amit 366
    public static long getStateId(String stateName) throws ProfitMandiBusinessException {
367
        try {
368
            return getStateInfo(stateName).getId();
369
        } catch (Exception e) {
370
            e.printStackTrace();
371
            throw new ProfitMandiBusinessException("State Name", stateName, "Could not fetch state");
372
        }
373
    }
24440 amit.gupta 374
 
35102 amit 375
    public static StateInfo getStateByStateId(long stateId) throws Exception {
376
        InventoryClient client = new InventoryClient();
377
        InventoryService.Client inventoryClient = client.getClient();
378
        Map<Long, StateInfo> map = inventoryClient.getStateMaster();
379
        return map.get(stateId);
380
    }
24440 amit.gupta 381
 
35102 amit 382
    public static StateInfo getStateInfo(String stateName) throws Exception {
383
        try {
384
            InventoryClient client = new InventoryClient();
385
            InventoryService.Client inventoryClient = client.getClient();
386
            Map<Long, StateInfo> map = inventoryClient.getStateMaster();
387
            List<StateInfo> stateInfos = new ArrayList<>(map.values());
388
            logger.info("State Name: {}", stateName);
389
            for (StateInfo stateInfo : stateInfos) {
390
                logger.info("State Name from service: {}", stateInfo.getStateName());
391
                if (stateName.toUpperCase().equals(stateInfo.getStateName().toUpperCase())) {
392
                    return stateInfo;
393
                }
394
            }
395
            throw new Exception("Not found");
396
        } catch (Exception e) {
397
            e.printStackTrace();
398
            throw e;
399
        }
400
    }
23509 amit.gupta 401
 
35102 amit 402
    public static void main(String[] args) throws Exception {
403
        Utils.sendSms("Hello", "9990381569");
404
    }
27285 tejbeer 405
 
35102 amit 406
    public static void sendEmbeddedHtmlMail(JavaMailSender mailSender, String[] emailTo, String[] cc, String subject,
407
                                            String body, Map<? extends Serializable, File> map) throws Exception {
408
        MimeMessage message = mailSender.createMimeMessage();
409
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
410
        helper.setSubject(subject);
411
        Multipart mp = new MimeMultipart();
27285 tejbeer 412
 
35102 amit 413
        MimeBodyPart messageBodyPart = new MimeBodyPart();
414
        messageBodyPart.setContent(body, "text/html");
415
        mp.addBodyPart(messageBodyPart);
25998 amit.gupta 416
 
35102 amit 417
        // helper.setText(body, true);
418
        if (cc != null) {
419
            helper.setCc(cc);
420
        }
421
        helper.setTo(emailTo);
422
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");
423
        helper.setFrom(senderAddress);
424
        for (Map.Entry<? extends Serializable, File> entry : map.entrySet()) {
425
            entry.getKey();
426
            entry.getValue();
427
            MimeBodyPart imagePart = new MimeBodyPart();
428
            imagePart.setHeader("Content-ID", entry.getKey() + "");
429
            imagePart.setDisposition(MimeBodyPart.INLINE);
430
            imagePart.attachFile(entry.getValue());
431
            mp.addBodyPart(imagePart);
25764 amit.gupta 432
 
35102 amit 433
        }
434
        message.setContent(mp);
435
        mailSender.send(message);
27285 tejbeer 436
 
35102 amit 437
    }
32199 amit.gupta 438
 
35102 amit 439
    public String html(String string) {
440
        return org.apache.commons.lang.StringEscapeUtils.escapeHtml(String.valueOf(string));
441
    }
25764 amit.gupta 442
 
35102 amit 443
    public String htmlJson(Object object) {
444
        return StringEscapeUtils.escapeHtml4(gson.toJson(object));
445
    }
27285 tejbeer 446
 
35102 amit 447
    public static String getHyphenatedString(String s) {
448
        s = s.trim().replaceAll("\\s+", " ");
449
        s = s.replaceAll("\\s", "-");
450
        return s.toLowerCase();
451
    }
30122 amit.gupta 452
 
35102 amit 453
    public static void sendMailWithAttachments(JavaMailSender mailSender, String[] emailTo, String[] cc, String subject,
454
                                               String body, Attachment... attachments) throws Exception {
455
        MimeMessage message = mailSender.createMimeMessage();
456
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
457
        helper.setSubject(subject);
458
        helper.setText(body, true);
459
        if (cc != null) {
460
            helper.setCc(cc);
461
        }
462
        helper.setTo(emailTo);
463
        for (Attachment attachment : attachments) {
464
            helper.addAttachment(attachment.getFileName(), attachment.getInputStreamSource());
35204 amit 465
            //saveInputStreamSourceToHome(attachment.getInputStreamSource(), attachment.getFileName());
35102 amit 466
        }
467
        InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "SmartDukaan Care");
468
        helper.setFrom(senderAddress);
469
        mailSender.send(message);
470
    }
33354 amit.gupta 471
 
35102 amit 472
    public static int compareFloat(float f1, float f2) {
473
        if (Math.abs(f1 - f2) < DOUBLE_EPSILON) {
474
            return 0;
475
        }
26534 amit.gupta 476
 
35102 amit 477
        return Float.compare(f1, f2);
478
    }
31177 tejbeer 479
 
35102 amit 480
    public static int compareDouble(double d1, double d2) {
481
        if (Math.abs(d1 - d2) < DOUBLE_EPSILON) {
482
            return 0;
483
        }
484
        return Double.compare(d1, d2);
485
    }
30122 amit.gupta 486
 
35102 amit 487
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
488
        Set<Object> seen = ConcurrentHashMap.newKeySet();
489
        return t -> seen.add(keyExtractor.apply(t));
490
    }
31903 amit.gupta 491
 
35102 amit 492
    public static <T> Predicate<T> smallestByKey(Function<? super T, ?> keyExtractor) {
493
        Set<Object> seen = ConcurrentHashMap.newKeySet();
494
        return t -> seen.add(keyExtractor.apply(t));
495
    }
32955 amit.gupta 496
 
35102 amit 497
    public static LocalDate convertToLocalDate(Date dateToConvert) {
498
        return Instant.ofEpochMilli(dateToConvert.getTime())
499
                .atZone(ZoneId.systemDefault())
500
                .toLocalDate();
501
    }
502
 
503
    public static LocalDateTime convertToLocalDateTime(Date dateToConvert) {
504
        return Instant.ofEpochMilli(dateToConvert.getTime())
505
                .atZone(ZoneId.systemDefault())
506
                .toLocalDateTime();
507
    }
508
 
35204 amit 509
    /**
510
     * Saves the given InputStream to the specified File.
511
     * Automatically creates parent directories if they don't exist.
512
     *
513
     * @param inputStream the source InputStream
514
     * @param file        the destination file
515
     * @throws IOException if an I/O error occurs
516
     */
517
    public static void saveStreamToFile(InputStream inputStream, File file) throws IOException {
518
        // Ensure parent directories exist
519
        if (file.getParentFile() != null && !file.getParentFile().exists()) {
520
            file.getParentFile().mkdirs();
521
        }
522
 
523
        try (InputStream in = inputStream;
524
             OutputStream out = new FileOutputStream(file)) {
525
            byte[] buffer = new byte[8192];  // 8 KB buffer
526
            int bytesRead;
527
            while ((bytesRead = in.read(buffer)) != -1) {
528
                out.write(buffer, bytesRead == 0 ? 0 : 0, bytesRead);
529
            }
530
        }
531
    }
532
 
533
    /**
534
     * Saves a Spring InputStreamSource to the specified file.
535
     * Works on all OS (Windows, macOS, Linux) and Java 8+.
536
     */
537
    /**
538
     * Saves a Spring InputStreamSource to a file inside the user's home directory.
539
     * Works on Java 8+ and all operating systems.
540
     *
541
     * @param source    the InputStreamSource (e.g., MultipartFile, ByteArrayResource)
542
     * @param fileName  the file name (without path)
543
     * @return the created File reference
544
     * @throws IOException if an error occurs during write
545
     */
546
    public static File saveInputStreamSourceToHome(InputStreamSource source, String fileName) throws IOException {
547
        // Get user home directory
548
        String userHome = System.getProperty("user.home");
549
 
550
        // Build the file path (home + filename)
551
        File targetFile = new File(userHome, fileName);
552
 
553
        // Ensure parent directories exist (in case filename contains subfolders)
554
        if (targetFile.getParentFile() != null && !targetFile.getParentFile().exists()) {
555
            targetFile.getParentFile().mkdirs();
556
        }
557
 
558
        // Copy the stream contents
559
        try (InputStream in = source.getInputStream();
560
             OutputStream out = new FileOutputStream(targetFile)) {
561
 
562
            byte[] buffer = new byte[8192];
563
            int bytesRead;
564
            while ((bytesRead = in.read(buffer)) != -1) {
565
                out.write(buffer, 0, bytesRead);
566
            }
567
        }
568
        logger.info("Saving InputStreamSource to home directory: {}", targetFile.getAbsolutePath());
569
 
570
        return targetFile;
571
    }
572
 
26084 amit.gupta 573
}