Subversion Repositories SmartDukaan

Rev

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