Subversion Repositories SmartDukaan

Rev

Rev 37711 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
21561 ashik.ali 1
package com.spice.profitmandi.web.config;
21555 kshitij.so 2
 
32569 amit.gupta 3
import com.fasterxml.jackson.core.JsonParser;
37161 ranu 4
import com.fasterxml.jackson.databind.*;
37072 amit 5
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
32569 amit.gupta 6
import com.fasterxml.jackson.databind.deser.std.StringDeserializer;
7
import com.fasterxml.jackson.databind.module.SimpleModule;
31282 amit.gupta 8
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
9
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
33618 tejus.loha 10
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
31282 amit.gupta 11
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
33618 tejus.loha 12
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
31282 amit.gupta 13
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
14
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
29993 amit.gupta 15
import com.google.gson.Gson;
16
import com.google.gson.GsonBuilder;
37513 ranu 17
import com.spice.profitmandi.common.services.AuthenticatedIdentityMailSender;
37630 amit 18
import com.spice.profitmandi.common.services.MailRecipientFilter;
19
import com.spice.profitmandi.common.services.RecipientFilteringMailSender;
29993 amit.gupta 20
import com.spice.profitmandi.common.util.Utils;
21
import com.spice.profitmandi.dao.convertor.LocalDateTimeJsonConverter;
23869 amit.gupta 22
import org.apache.logging.log4j.LogManager;
23568 govind 23
import org.apache.logging.log4j.Logger;
28339 tejbeer 24
import org.apache.velocity.app.VelocityEngine;
25
import org.apache.velocity.exception.VelocityException;
21555 kshitij.so 26
import org.springframework.context.annotation.Bean;
27
import org.springframework.context.annotation.ComponentScan;
37630 amit 28
import org.springframework.context.annotation.Lazy;
21555 kshitij.so 29
import org.springframework.context.annotation.Configuration;
37476 amit 30
import org.springframework.context.annotation.Primary;
21555 kshitij.so 31
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
32
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
33
import org.springframework.core.io.ClassPathResource;
34
import org.springframework.core.io.Resource;
23985 tejbeer 35
import org.springframework.mail.javamail.JavaMailSender;
36
import org.springframework.mail.javamail.JavaMailSenderImpl;
28339 tejbeer 37
import org.springframework.ui.velocity.VelocityEngineFactoryBean;
21555 kshitij.so 38
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
21625 kshitij.so 39
import org.springframework.web.servlet.ViewResolver;
24507 amit.gupta 40
import org.springframework.web.servlet.view.BeanNameViewResolver;
21625 kshitij.so 41
import org.springframework.web.servlet.view.velocity.VelocityConfigurer;
31513 amit.gupta 42
import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver;
21555 kshitij.so 43
 
29993 amit.gupta 44
import java.io.IOException;
45
import java.math.RoundingMode;
46
import java.text.DecimalFormat;
47
import java.text.NumberFormat;
33618 tejus.loha 48
import java.time.LocalDate;
29993 amit.gupta 49
import java.time.LocalDateTime;
50
import java.time.format.DateTimeFormatter;
31282 amit.gupta 51
import java.time.format.DateTimeFormatterBuilder;
29993 amit.gupta 52
import java.util.HashMap;
53
import java.util.Locale;
54
import java.util.Map;
55
import java.util.Properties;
25300 tejbeer 56
 
21625 kshitij.so 57
@SuppressWarnings("deprecation")
21555 kshitij.so 58
@Configuration
59
@ComponentScan("com.spice.profitmandi.*")
31511 amit.gupta 60
//@Import(RepositoryRestMvcConfiguration.class)
21555 kshitij.so 61
public class AppConfig {
62
 
32054 tejbeer 63
    private static final String VELOCITY_PATH_PREFIX = "/WEB-INF/views/ftl/";
64
    private static final String VELOCITY_PATH_SUFFIX = ".vm";
32773 raveendra. 65
    private static final String MESSAGE_PATH_SOURCE_NAME = "classpath:messages";
32054 tejbeer 66
    private static final Logger LOGGER = LogManager.getLogger(AppConfig.class);
67
    private static Resource resource;
35832 amit 68
    private static Resource sharedResource;
24639 tejbeer 69
 
32054 tejbeer 70
    public static Resource getResource() {
71
        return resource;
72
    }
21555 kshitij.so 73
 
35832 amit 74
    public static Resource getSharedResource() {
75
        return sharedResource;
76
    }
77
 
32054 tejbeer 78
    public void setResource(Resource resource) {
79
        AppConfig.resource = resource;
80
    }
21625 kshitij.so 81
 
32054 tejbeer 82
    @Bean(value = "velocityAttributesMap")
83
    public Map<String, Object> velocityAttributesMap() {
84
        Map<String, Object> attributesMap = new HashMap<>();
85
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
86
        DateTimeFormatter dateMonthFormatter = DateTimeFormatter.ofPattern("dd''MMM");
87
        DateTimeFormatter datehiphenFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
88
        DateTimeFormatter dateMonthYearFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
89
        DateTimeFormatter dateYearMonthFormatter = DateTimeFormatter.ofPattern("MMM''uu");
31218 tejbeer 90
 
32054 tejbeer 91
        DateTimeFormatter dateMonthChYear = DateTimeFormatter.ofPattern("d''MMM''uu");
92
        DecimalFormat decimalFormatter = new DecimalFormat("0.#");
30859 tejbeer 93
 
32054 tejbeer 94
        NumberFormat numberformat = NumberFormat.getNumberInstance(new Locale("en", "IN"));
30859 tejbeer 95
 
32054 tejbeer 96
        numberformat.setRoundingMode(RoundingMode.HALF_DOWN);
97
        numberformat.setMaximumFractionDigits(2);
98
        numberformat.setMinimumFractionDigits(0);
99
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
100
        attributesMap.put("dateFormatter", dateFormatter);
101
        attributesMap.put("nf", numberformat);
102
        attributesMap.put("dateMonthFormatter", dateMonthFormatter);
103
        attributesMap.put("datehiphenFormatter", datehiphenFormatter);
104
        attributesMap.put("dateYearMonthFormatter", dateYearMonthFormatter);
31218 tejbeer 105
 
32054 tejbeer 106
        attributesMap.put("dateMonthYearFormatter", dateMonthYearFormatter);
107
        attributesMap.put("dateMonthChYear", dateMonthChYear);
108
        attributesMap.put("decimalFormatter", decimalFormatter);
109
        attributesMap.put("noData", "<tr><td colspan=\"20\" style=\"text-align:center;\">No results found for the given criteria</td></tr>");
110
        attributesMap.put("dateTimeFormatter", dateTimeFormatter);
37723 amit 111
        attributesMap.put("version", "433");
37523 ranu 112
        attributesMap.put("cssVersion", "53");
32054 tejbeer 113
        attributesMap.put("isDev", getActiveProfile().equals("dev"));
114
        attributesMap.put("vmUtils", new Utils());
32200 amit.gupta 115
        //attributesMap.put("esc", new EscapeTool());
32054 tejbeer 116
        attributesMap.put("ru", RoundingMode.HALF_UP);
117
        return attributesMap;
118
    }
30470 amit.gupta 119
 
32054 tejbeer 120
    @Bean
121
    public ViewResolver viewResolver() {
122
        VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver();
123
        bean.setPrefix("");
124
        bean.setSuffix(VELOCITY_PATH_SUFFIX);
35587 ranu 125
        bean.setContentType("text/html;charset=UTF-8");
32054 tejbeer 126
        bean.setRequestContextAttribute("rc");
32773 raveendra. 127
        bean.setExposeSpringMacroHelpers(true);
32054 tejbeer 128
        bean.setAttributesMap(this.velocityAttributesMap());
129
        return bean;
130
    }
21625 kshitij.so 131
 
32054 tejbeer 132
    @Bean
133
    public ViewResolver beanNameViewResolver() {
134
        BeanNameViewResolver resolver = new BeanNameViewResolver();
135
        return resolver;
136
    }
24507 amit.gupta 137
 
32054 tejbeer 138
    @Bean
139
    public VelocityConfigurer velocityConfig() {
140
        VelocityConfigurer velocityConfigurer = new VelocityConfigurer();
141
        Properties velocityProperties = new Properties();
35294 ranu 142
       /* velocityProperties.put("velocimacro.library", "macros.vm");
35289 amit 143
        velocityProperties.put("velocimacro.permissions.allow.inline", "true");
35294 ranu 144
        velocityProperties.put("velocimacro.permissions.allow.inline.to.replace.global", "true");*/
32054 tejbeer 145
        velocityProperties.put("directive.set.null.allowed", "true");
36686 ranu 146
        // Read .vm files as UTF-8 and emit UTF-8 — otherwise non-ASCII chars
147
        // (emoji, accents) in templates render as mojibake (e.g. 📷 → ð).
148
        velocityProperties.put("input.encoding", "UTF-8");
149
        velocityProperties.put("output.encoding", "UTF-8");
32054 tejbeer 150
        velocityConfigurer.setVelocityProperties(velocityProperties);
151
        velocityConfigurer.setResourceLoaderPath(VELOCITY_PATH_PREFIX);
152
        return velocityConfigurer;
153
    }
21555 kshitij.so 154
 
32788 amit.gupta 155
    @Bean(name = "messageSource")
156
    public ReloadableResourceBundleMessageSource getReloadableResourceBundleMessageSource() {
32054 tejbeer 157
        LOGGER.debug("creating messageSource bean with message path source name : " + MESSAGE_PATH_SOURCE_NAME);
158
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
159
        messageSource.setBasename(MESSAGE_PATH_SOURCE_NAME);
32773 raveendra. 160
        messageSource.setDefaultEncoding("UTF-8");
161
 
32054 tejbeer 162
        return messageSource;
163
    }
21555 kshitij.so 164
 
32054 tejbeer 165
    @Bean(name = "multipartResolver")
166
    public CommonsMultipartResolver getCommonsMultipartResolver() {
167
        LOGGER.info("creating common multipart resolver bean");
168
        return new CommonsMultipartResolver();
169
    }
21555 kshitij.so 170
 
32054 tejbeer 171
    @Bean
172
    public PropertySourcesPlaceholderConfigurer propertyConfigurer1() {
173
        String activeProfile = getActiveProfile();
21555 kshitij.so 174
 
32054 tejbeer 175
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
21625 kshitij.so 176
 
35381 amit 177
        Resource appResource;
178
        Resource sharedResource;
179
 
32054 tejbeer 180
        if ("prod".equals(activeProfile)) {
35381 amit 181
            appResource = new ClassPathResource("/META-INF/prod.properties");
182
            sharedResource = new ClassPathResource("/shared-prod.properties");
32054 tejbeer 183
        } else if ("staging".equals(activeProfile)) {
35381 amit 184
            appResource = new ClassPathResource("/META-INF/staging.properties");
185
            sharedResource = new ClassPathResource("/shared-staging.properties");
32054 tejbeer 186
        } else {
35381 amit 187
            appResource = new ClassPathResource("/META-INF/dev.properties");
188
            sharedResource = new ClassPathResource("/shared-dev.properties");
32054 tejbeer 189
        }
21555 kshitij.so 190
 
35381 amit 191
        resource = appResource;
35832 amit 192
        AppConfig.sharedResource = sharedResource;
21555 kshitij.so 193
 
35381 amit 194
        // Load shared properties from dao first, then app-specific (app-specific can override)
195
        propertySourcesPlaceholderConfigurer.setLocations(sharedResource, appResource);
196
        propertySourcesPlaceholderConfigurer.setIgnoreResourceNotFound(true);
197
 
32054 tejbeer 198
        return propertySourcesPlaceholderConfigurer;
199
    }
21625 kshitij.so 200
 
32054 tejbeer 201
    private String getActiveProfile() {
202
        Properties properties = new Properties();
203
        try {
204
            properties.load(this.getClass().getClassLoader().getResourceAsStream("META-INF/env.property"));
205
        } catch (IOException e) {
206
            LOGGER.error("Error in reading env property file.Adding default property" + e);
207
            properties.put("profile", "dev");
208
        }
209
        LOGGER.info("Profile is [{}]", properties.get("profile"));
210
        return (String) properties.get("profile");
211
    }
25811 amit.gupta 212
 
37479 amit 213
    /**
214
     * The default sender.
215
     *
216
     * Verified working 2026-08-31: MAIL FROM:<noreply@smartdukaan.com> returns 250
217
     * over IPv4. It does not authenticate -- Workspace authorises it by allowlisted
218
     * source IP -- so it may legitimately send as noreply@.
219
     *
37480 amit 220
     * googleMailSender is the alternative and its credentials are valid -- verified
221
     * 2026-08-31, AUTH OK on both 465 and 587. Use it by qualifier where a message
222
     * must come from the authenticated identity rather than noreply@.
37479 amit 223
     *
37480 amit 224
     * SMTP on this host works over IPv4 only, and that is not specific to the relay:
225
     * over IPv6 the relay answers "550 5.7.1 Invalid credentials for relay" and
226
     * smtp.gmail.com rejects a valid app password with "535 5.7.8 Username and
227
     * Password not accepted". The JVM prefers IPv4, which is the only reason mail
228
     * leaves this box at all. Anything that prefers IPv6 will fail on both paths.
37479 amit 229
     */
230
    @Bean(name = {"gmailRelaySender", "mailSender"})
231
    @Primary
37630 amit 232
    public JavaMailSender getGmailRelaySender(@Lazy MailRecipientFilter mailRecipientFilter) {
233
        RecipientFilteringMailSender mailSender = new RecipientFilteringMailSender();
234
        mailSender.setRecipientFilter(mailRecipientFilter);
36247 amit 235
        mailSender.setHost("smtp-relay.gmail.com");
236
        mailSender.setPort(587);
34667 amit.gupta 237
 
36247 amit 238
        Properties props = mailSender.getJavaMailProperties();
239
        props.put("mail.smtp.starttls.enable", "true");
240
        props.put("mail.smtp.auth", "false");
241
        props.put("mail.smtp.localhost", "smartdukaan.com");
242
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");
243
        props.put("mail.smtp.ssl.trust", "smtp-relay.gmail.com");
244
        props.put("mail.transport.protocol", "smtp");
37365 amit 245
        props.put("mail.smtp.connectiontimeout", "30000");
246
        props.put("mail.smtp.timeout", "120000");
247
        props.put("mail.smtp.writetimeout", "120000");
36247 amit 248
 
249
        return mailSender;
250
    }
251
 
252
 
37476 amit 253
    /**
254
     * The default sender. Authenticates as sdtech@smartdukaan.com and rewrites every
255
     * From to that identity — Workspace binds an authenticated session to one address
256
     * and rejects any other. Also answers to "mailSender" so unqualified
257
     * JavaMailSender injections resolve here.
258
     */
37479 amit 259
    @Bean(name = "googleMailSender")
37630 amit 260
    public JavaMailSender googleMailSender(@Lazy MailRecipientFilter mailRecipientFilter) {
261
        AuthenticatedIdentityMailSender mailSender = new AuthenticatedIdentityMailSender();
262
        mailSender.setRecipientFilter(mailRecipientFilter);
34636 ranu 263
        mailSender.setHost("smtp.gmail.com");
264
        mailSender.setPort(465);
265
        mailSender.setUsername("sdtech@smartdukaan.com");
37369 amit 266
        mailSender.setPassword("wbdwyqrcgosrkwdn"); // App Password
34636 ranu 267
 
268
        Properties props = mailSender.getJavaMailProperties();
269
        props.put("mail.smtp.auth", "true");
270
        props.put("mail.smtp.ssl.enable", "true");
271
        props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
272
        props.put("mail.smtp.socketFactory.port", "465");
273
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
37365 amit 274
        props.put("mail.smtp.connectiontimeout", "30000");
275
        props.put("mail.smtp.timeout", "120000");
276
        props.put("mail.smtp.writetimeout", "120000");
34636 ranu 277
 
278
        return mailSender;
279
    }
280
 
32054 tejbeer 281
    @Bean(name = "gson")
282
    public Gson gson() {
25300 tejbeer 283
 
32054 tejbeer 284
        Gson gson = new GsonBuilder().serializeNulls().registerTypeAdapter(LocalDateTime.class, new LocalDateTimeJsonConverter()).create();
25300 tejbeer 285
 
32054 tejbeer 286
        return gson;
25300 tejbeer 287
 
32054 tejbeer 288
    }
25300 tejbeer 289
 
32054 tejbeer 290
    @Bean(name = "veloctyEngine")
291
    public VelocityEngine velocityEngine() throws VelocityException, IOException {
292
        VelocityEngineFactoryBean factory = new VelocityEngineFactoryBean();
293
        // Properties props = new Properties();
294
        // props.put("resource.loader", "file");
28339 tejbeer 295
 
32054 tejbeer 296
        // props.put("file.resource.loader.description", "Velocity File Resource
297
        // Loader");
298
        // props.put("file.resource.loader.class",
299
        // "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
300
        // props.put("file.resource.loader.cache", true);
301
        // props.put("file.resource.loader.path", ".");
32773 raveendra. 302
        factory.setPreferFileSystemAccess(false);
303
        // factory.setResourceLoaderPath("classpath:/templates/");
28339 tejbeer 304
 
32773 raveendra. 305
 
32054 tejbeer 306
        Properties velocityProperties = new Properties();
307
        velocityProperties.put("resource.loader", "class");
308
        velocityProperties.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
309
        velocityProperties.put("file.resource.loader.cache", true);
310
        velocityProperties.put("file.resource.loader.unicode", true);
311
        velocityProperties.put("input.encoding", "UTF-8");
312
        velocityProperties.put("output.encoding", "UTF-8");
313
        velocityProperties.put("overrideLogging", true);
32773 raveendra. 314
        velocityProperties.setProperty("input.encoding", "UTF-8");
315
        velocityProperties.setProperty("output.encoding", "UTF-8");
316
        factory.setVelocityProperties(velocityProperties);
28339 tejbeer 317
 
32054 tejbeer 318
        // velocityProperties.put("file.resource.loader.path", ".");
28339 tejbeer 319
 
32054 tejbeer 320
        factory.setVelocityProperties(velocityProperties);
321
        return factory.createVelocityEngine();
28339 tejbeer 322
 
32054 tejbeer 323
    }
28339 tejbeer 324
 
32054 tejbeer 325
    @Bean
326
    public ObjectMapper objectMapper() {
327
        DateTimeFormatter df = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_DATE).optionalStart().appendLiteral('T').optionalEnd().appendLiteral(' ').append(DateTimeFormatter.ISO_LOCAL_TIME).toFormatter();
328
        DateTimeFormatter sf = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_DATE).appendLiteral('T').append(DateTimeFormatter.ISO_LOCAL_TIME).toFormatter();
33618 tejus.loha 329
 
330
        DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_DATE).toFormatter();
32054 tejbeer 331
        JavaTimeModule jtm = new JavaTimeModule();
33618 tejus.loha 332
        jtm.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(sf));
333
        jtm.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(df));
334
        jtm.addSerializer(LocalDate.class, new LocalDateSerializer(dateFormatter));
335
        jtm.addDeserializer(LocalDate.class, new LocalDateDeserializer(dateFormatter));
32569 amit.gupta 336
        SimpleModule stringModule = new SimpleModule("String trimmer deserialize module");
337
        stringModule.addDeserializer(String.class, new CustomStringDeserializer());
32186 amit.gupta 338
        ObjectMapper mapper = new ObjectMapper()
32187 amit.gupta 339
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
32569 amit.gupta 340
                .registerModule(new ParameterNamesModule()).registerModule(new Jdk8Module()).registerModule(jtm)
341
                .registerModule(stringModule); // new module, NOT JSR310Module
32054 tejbeer 342
        return mapper;
343
    }
31282 amit.gupta 344
 
37072 amit 345
    class CustomStringDeserializer extends StringDeserializer implements ContextualDeserializer {
346
 
347
        // Fields whose exact bytes matter — never normalize (credentials, tokens, payloads).
348
        private final java.util.regex.Pattern SENSITIVE_FIELD =
349
                java.util.regex.Pattern.compile("(?i)(password|passwd|pwd|otp|pin|token|secret|signature|hash|base64|apikey|api_key)");
350
 
351
        private final boolean normalize;
352
 
353
        CustomStringDeserializer() {
354
            this(true);
355
        }
356
 
357
        CustomStringDeserializer(boolean normalize) {
358
            this.normalize = normalize;
359
        }
360
 
32569 amit.gupta 361
        @Override
37072 amit 362
        public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
363
            if (property != null && SENSITIVE_FIELD.matcher(property.getName()).find()) {
364
                return new CustomStringDeserializer(false);
365
            }
366
            return this;
367
        }
368
 
369
        @Override
32569 amit.gupta 370
        public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
371
            String text = super.deserialize(p, ctxt);
37072 amit 372
            if (!normalize) {
373
                return text;
374
            }
375
            // trim + NBSP/tab/zero-width -> single space + collapse doubles
376
            return com.spice.profitmandi.common.util.StringUtils.normalizeWhitespace(text);
32569 amit.gupta 377
        }
378
    }
379
 
380
 
21555 kshitij.so 381
}