Subversion Repositories SmartDukaan

Rev

Rev 37458 | Rev 37479 | 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;
17
import com.spice.profitmandi.common.util.Utils;
18
import com.spice.profitmandi.dao.convertor.LocalDateTimeJsonConverter;
23869 amit.gupta 19
import org.apache.logging.log4j.LogManager;
23568 govind 20
import org.apache.logging.log4j.Logger;
28339 tejbeer 21
import org.apache.velocity.app.VelocityEngine;
22
import org.apache.velocity.exception.VelocityException;
21555 kshitij.so 23
import org.springframework.context.annotation.Bean;
24
import org.springframework.context.annotation.ComponentScan;
25
import org.springframework.context.annotation.Configuration;
37476 amit 26
import org.springframework.context.annotation.Primary;
21555 kshitij.so 27
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
28
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
29
import org.springframework.core.io.ClassPathResource;
30
import org.springframework.core.io.Resource;
23985 tejbeer 31
import org.springframework.mail.javamail.JavaMailSender;
37455 amit 32
import com.spice.profitmandi.common.services.AuthenticatedIdentityMailSender;
23985 tejbeer 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);
37458 aman 108
        attributesMap.put("version", "409");
37003 ranu 109
        attributesMap.put("cssVersion", "52");
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
 
36247 amit 210
    @Bean(name = "gmailRelaySender")
211
    public JavaMailSender getGmailRelaySender() {
212
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
213
        mailSender.setHost("smtp-relay.gmail.com");
214
        mailSender.setPort(587);
34667 amit.gupta 215
 
36247 amit 216
        Properties props = mailSender.getJavaMailProperties();
217
        props.put("mail.smtp.starttls.enable", "true");
218
        props.put("mail.smtp.auth", "false");
219
        props.put("mail.smtp.localhost", "smartdukaan.com");
220
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");
221
        props.put("mail.smtp.ssl.trust", "smtp-relay.gmail.com");
222
        props.put("mail.transport.protocol", "smtp");
37365 amit 223
        props.put("mail.smtp.connectiontimeout", "30000");
224
        props.put("mail.smtp.timeout", "120000");
225
        props.put("mail.smtp.writetimeout", "120000");
36247 amit 226
 
227
        return mailSender;
228
    }
229
 
230
 
37476 amit 231
    /**
232
     * The default sender. Authenticates as sdtech@smartdukaan.com and rewrites every
233
     * From to that identity — Workspace binds an authenticated session to one address
234
     * and rejects any other. Also answers to "mailSender" so unqualified
235
     * JavaMailSender injections resolve here.
236
     */
237
    @Bean(name = {"googleMailSender", "mailSender"})
238
    @Primary
32054 tejbeer 239
    public JavaMailSender googleMailSender() {
37455 amit 240
        JavaMailSenderImpl mailSender = new AuthenticatedIdentityMailSender();
34636 ranu 241
        mailSender.setHost("smtp.gmail.com");
242
        mailSender.setPort(465);
243
        mailSender.setUsername("sdtech@smartdukaan.com");
37369 amit 244
        mailSender.setPassword("wbdwyqrcgosrkwdn"); // App Password
34636 ranu 245
 
246
        Properties props = mailSender.getJavaMailProperties();
247
        props.put("mail.smtp.auth", "true");
248
        props.put("mail.smtp.ssl.enable", "true");
249
        props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
250
        props.put("mail.smtp.socketFactory.port", "465");
251
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
37365 amit 252
        props.put("mail.smtp.connectiontimeout", "30000");
253
        props.put("mail.smtp.timeout", "120000");
254
        props.put("mail.smtp.writetimeout", "120000");
34636 ranu 255
 
256
        return mailSender;
257
    }
258
 
32054 tejbeer 259
    @Bean(name = "gson")
260
    public Gson gson() {
25300 tejbeer 261
 
32054 tejbeer 262
        Gson gson = new GsonBuilder().serializeNulls().registerTypeAdapter(LocalDateTime.class, new LocalDateTimeJsonConverter()).create();
25300 tejbeer 263
 
32054 tejbeer 264
        return gson;
25300 tejbeer 265
 
32054 tejbeer 266
    }
25300 tejbeer 267
 
32054 tejbeer 268
    @Bean(name = "veloctyEngine")
269
    public VelocityEngine velocityEngine() throws VelocityException, IOException {
270
        VelocityEngineFactoryBean factory = new VelocityEngineFactoryBean();
271
        // Properties props = new Properties();
272
        // props.put("resource.loader", "file");
28339 tejbeer 273
 
32054 tejbeer 274
        // props.put("file.resource.loader.description", "Velocity File Resource
275
        // Loader");
276
        // props.put("file.resource.loader.class",
277
        // "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
278
        // props.put("file.resource.loader.cache", true);
279
        // props.put("file.resource.loader.path", ".");
32773 raveendra. 280
        factory.setPreferFileSystemAccess(false);
281
        // factory.setResourceLoaderPath("classpath:/templates/");
28339 tejbeer 282
 
32773 raveendra. 283
 
32054 tejbeer 284
        Properties velocityProperties = new Properties();
285
        velocityProperties.put("resource.loader", "class");
286
        velocityProperties.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
287
        velocityProperties.put("file.resource.loader.cache", true);
288
        velocityProperties.put("file.resource.loader.unicode", true);
289
        velocityProperties.put("input.encoding", "UTF-8");
290
        velocityProperties.put("output.encoding", "UTF-8");
291
        velocityProperties.put("overrideLogging", true);
32773 raveendra. 292
        velocityProperties.setProperty("input.encoding", "UTF-8");
293
        velocityProperties.setProperty("output.encoding", "UTF-8");
294
        factory.setVelocityProperties(velocityProperties);
28339 tejbeer 295
 
32054 tejbeer 296
        // velocityProperties.put("file.resource.loader.path", ".");
28339 tejbeer 297
 
32054 tejbeer 298
        factory.setVelocityProperties(velocityProperties);
299
        return factory.createVelocityEngine();
28339 tejbeer 300
 
32054 tejbeer 301
    }
28339 tejbeer 302
 
32054 tejbeer 303
    @Bean
304
    public ObjectMapper objectMapper() {
305
        DateTimeFormatter df = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_DATE).optionalStart().appendLiteral('T').optionalEnd().appendLiteral(' ').append(DateTimeFormatter.ISO_LOCAL_TIME).toFormatter();
306
        DateTimeFormatter sf = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_DATE).appendLiteral('T').append(DateTimeFormatter.ISO_LOCAL_TIME).toFormatter();
33618 tejus.loha 307
 
308
        DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_DATE).toFormatter();
32054 tejbeer 309
        JavaTimeModule jtm = new JavaTimeModule();
33618 tejus.loha 310
        jtm.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(sf));
311
        jtm.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(df));
312
        jtm.addSerializer(LocalDate.class, new LocalDateSerializer(dateFormatter));
313
        jtm.addDeserializer(LocalDate.class, new LocalDateDeserializer(dateFormatter));
32569 amit.gupta 314
        SimpleModule stringModule = new SimpleModule("String trimmer deserialize module");
315
        stringModule.addDeserializer(String.class, new CustomStringDeserializer());
32186 amit.gupta 316
        ObjectMapper mapper = new ObjectMapper()
32187 amit.gupta 317
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
32569 amit.gupta 318
                .registerModule(new ParameterNamesModule()).registerModule(new Jdk8Module()).registerModule(jtm)
319
                .registerModule(stringModule); // new module, NOT JSR310Module
32054 tejbeer 320
        return mapper;
321
    }
31282 amit.gupta 322
 
37072 amit 323
    class CustomStringDeserializer extends StringDeserializer implements ContextualDeserializer {
324
 
325
        // Fields whose exact bytes matter — never normalize (credentials, tokens, payloads).
326
        private final java.util.regex.Pattern SENSITIVE_FIELD =
327
                java.util.regex.Pattern.compile("(?i)(password|passwd|pwd|otp|pin|token|secret|signature|hash|base64|apikey|api_key)");
328
 
329
        private final boolean normalize;
330
 
331
        CustomStringDeserializer() {
332
            this(true);
333
        }
334
 
335
        CustomStringDeserializer(boolean normalize) {
336
            this.normalize = normalize;
337
        }
338
 
32569 amit.gupta 339
        @Override
37072 amit 340
        public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
341
            if (property != null && SENSITIVE_FIELD.matcher(property.getName()).find()) {
342
                return new CustomStringDeserializer(false);
343
            }
344
            return this;
345
        }
346
 
347
        @Override
32569 amit.gupta 348
        public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
349
            String text = super.deserialize(p, ctxt);
37072 amit 350
            if (!normalize) {
351
                return text;
352
            }
353
            // trim + NBSP/tab/zero-width -> single space + collapse doubles
354
            return com.spice.profitmandi.common.util.StringUtils.normalizeWhitespace(text);
32569 amit.gupta 355
        }
356
    }
357
 
358
 
21555 kshitij.so 359
}