Subversion Repositories SmartDukaan

Rev

Rev 31904 | Rev 32049 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.spice.profitmandi.common.util.Utils;
import com.spice.profitmandi.dao.convertor.LocalDateTimeJsonConverter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.ui.velocity.VelocityEngineFactoryBean;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.BeanNameViewResolver;
import org.springframework.web.servlet.view.velocity.VelocityConfigurer;
import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver;

import java.io.IOException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

@SuppressWarnings("deprecation")
@Configuration
@ComponentScan("com.spice.profitmandi.*")
//@Import(RepositoryRestMvcConfiguration.class)
public class AppConfig {

        private static final String VELOCITY_PATH_PREFIX = "/WEB-INF/views/ftl/";
        private static final String VELOCITY_PATH_SUFFIX = ".vm";
        private static final String MESSAGE_PATH_SOURCE_NAME = "classpath:message";
        private static final Logger LOGGER = LogManager.getLogger(AppConfig.class);
        private static Resource resource;

        public static Resource getResource() {
                return resource;
        }

        public void setResource(Resource resource) {
                AppConfig.resource = resource;
        }

        @Bean(value = "velocityAttributesMap")
        public Map<String, Object> velocityAttributesMap() {
                Map<String, Object> attributesMap = new HashMap<>();
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
                DateTimeFormatter dateMonthFormatter = DateTimeFormatter.ofPattern("dd''MMM");
                DateTimeFormatter datehiphenFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                DateTimeFormatter dateMonthYearFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
                DateTimeFormatter dateYearMonthFormatter = DateTimeFormatter.ofPattern("MMM''uu");

                DateTimeFormatter dateMonthChYear = DateTimeFormatter.ofPattern("d''MMM''uu");
                DecimalFormat decimalFormatter = new DecimalFormat("0.#");

                NumberFormat numberformat = NumberFormat.getNumberInstance(new Locale("en", "IN"));

                numberformat.setRoundingMode(RoundingMode.HALF_DOWN);
                numberformat.setMaximumFractionDigits(2);
                numberformat.setMinimumFractionDigits(0);
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
                attributesMap.put("dateFormatter", dateFormatter);
                attributesMap.put("nf", numberformat);
                attributesMap.put("dateMonthFormatter", dateMonthFormatter);
                attributesMap.put("datehiphenFormatter", datehiphenFormatter);
                attributesMap.put("dateYearMonthFormatter", dateYearMonthFormatter);

                attributesMap.put("dateMonthYearFormatter", dateMonthYearFormatter);
                attributesMap.put("dateMonthChYear", dateMonthChYear);
                attributesMap.put("decimalFormatter", decimalFormatter);
                attributesMap.put("noData",
                                "<tr><td colspan=\"20\" style=\"text-align:center;\">No results found for the given criteria</td></tr>");
                attributesMap.put("dateTimeFormatter", dateTimeFormatter);
                attributesMap.put("version", "166");
                attributesMap.put("cssVersion", "10");
                attributesMap.put("isDev", getActiveProfile().equals("dev"));
                attributesMap.put("vmUtils", new Utils());
                //attributesMap.put("esc", new EscapeTool());
                attributesMap.put("ru", RoundingMode.HALF_UP);
                return attributesMap;
        }

        @Bean
        public ViewResolver viewResolver() {
                VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver();
                bean.setPrefix("");
                bean.setSuffix(VELOCITY_PATH_SUFFIX);
                bean.setRequestContextAttribute("rc");
                bean.setAttributesMap(this.velocityAttributesMap());
                return bean;
        }

//      @Bean
//      public ViewResolver freemarkerViewResolver() {
//              FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
//              resolver.setCache(true);
//              resolver.setPrefix("");
//              resolver.setSuffix(".ftl");
//              return resolver;
//      }

        @Bean
        public ViewResolver beanNameViewResolver() {
                BeanNameViewResolver resolver = new BeanNameViewResolver();
                return resolver;
        }

        @Bean
        public VelocityConfigurer velocityConfig() {
                VelocityConfigurer velocityConfigurer = new VelocityConfigurer();
                Properties velocityProperties = new Properties();
                velocityProperties.put("directive.set.null.allowed", "true");
                velocityConfigurer.setVelocityProperties(velocityProperties);
                velocityConfigurer.setResourceLoaderPath(VELOCITY_PATH_PREFIX);
                return velocityConfigurer;
        }

        @Bean(name = "messageSource")
        public ReloadableResourceBundleMessageSource getReloadableResourceBundleMessageSource() {
                LOGGER.debug("creating messageSource bean with message path source name : " + MESSAGE_PATH_SOURCE_NAME);
                ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
                messageSource.setBasename(MESSAGE_PATH_SOURCE_NAME);
                return messageSource;
        }

        @Bean(name = "multipartResolver")
        public CommonsMultipartResolver getCommonsMultipartResolver() {
                LOGGER.info("creating common multipart resolver bean");
                return new CommonsMultipartResolver();
        }

        @Bean
        public PropertySourcesPlaceholderConfigurer propertyConfigurer1() {
                String activeProfile = getActiveProfile();

                PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();

                if ("prod".equals(activeProfile)) {
                        resource = new ClassPathResource("/META-INF/prod.properties");
                } else if ("staging".equals(activeProfile)) {
                        resource = new ClassPathResource("/META-INF/staging.properties");
                } else {
                        resource = new ClassPathResource("/META-INF/dev.properties");
                }

                propertySourcesPlaceholderConfigurer.setLocation(resource);

                return propertySourcesPlaceholderConfigurer;
        }

        private String getActiveProfile() {
                Properties properties = new Properties();
                try {
                        properties.load(this.getClass().getClassLoader().getResourceAsStream("META-INF/env.property"));
                } catch (IOException e) {
                        LOGGER.error("Error in reading env property file.Adding default property" + e);
                        properties.put("profile", "dev");
                }
                LOGGER.info("Profile is [{}]", properties.get("profile"));
                return (String) properties.get("profile");
        }

        @Bean(name = "mailSender")
        public JavaMailSender getSendgridMailSender() {
                JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

                // Using gmail
                mailSender.setHost("smtp.sendgrid.net");
                mailSender.setPort(587);
                mailSender.setUsername("apikey");
                mailSender.setPassword("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");

                Properties javaMailProperties = new Properties();
                javaMailProperties.put("mail.smtp.starttls.enable", "false");
                javaMailProperties.put("mail.smtp.auth", "true");
                javaMailProperties.put("mail.transport.protocol", "smtp");
                javaMailProperties.put("mail.debug", "true");// Prints out everything on
                // screen

                mailSender.setJavaMailProperties(javaMailProperties);
                return mailSender;
        }

        //@Bean(name = "mailSender")
        public JavaMailSender googleMailSender() {
                JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
                // Using gmail
                mailSender.setHost("smtp.gmail.com");
                mailSender.setPort(587);
                mailSender.setUsername("build@shop2020.in");
                mailSender.setPassword("cafe@nes");

                Properties javaMailProperties = new Properties();
                javaMailProperties.put("mail.smtp.starttls.enable", "true");
                javaMailProperties.put("mail.smtp.auth", "true");
                javaMailProperties.put("mail.transport.protocol", "smtp");
                javaMailProperties.put("mail.debug", "true");// Prints out everything on screen
                mailSender.setJavaMailProperties(javaMailProperties);
                return mailSender;
        }

        @Bean(name = "gson")
        public Gson gson() {

                Gson gson = new GsonBuilder().serializeNulls()
                                .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeJsonConverter()).create();

                return gson;

        }

        @Bean(name = "veloctyEngine")
        public VelocityEngine velocityEngine() throws VelocityException, IOException {
                VelocityEngineFactoryBean factory = new VelocityEngineFactoryBean();
                // Properties props = new Properties();
                // props.put("resource.loader", "file");

                // props.put("file.resource.loader.description", "Velocity File Resource
                // Loader");
                // props.put("file.resource.loader.class",
                // "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
                // props.put("file.resource.loader.cache", true);
                // props.put("file.resource.loader.path", ".");

                Properties velocityProperties = new Properties();
                velocityProperties.put("resource.loader", "class");
                velocityProperties.put("class.resource.loader.class",
                                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
                velocityProperties.put("file.resource.loader.cache", true);
                velocityProperties.put("file.resource.loader.unicode", true);
                velocityProperties.put("input.encoding", "UTF-8");
                velocityProperties.put("output.encoding", "UTF-8");
                velocityProperties.put("overrideLogging", true);

                // velocityProperties.put("file.resource.loader.path", ".");

                factory.setVelocityProperties(velocityProperties);
                return factory.createVelocityEngine();

        }

        @Bean
        public ObjectMapper objectMapper() {
                DateTimeFormatter df = new DateTimeFormatterBuilder().parseCaseInsensitive()
                                .append(DateTimeFormatter.ISO_LOCAL_DATE).optionalStart().appendLiteral('T').optionalEnd()
                                .appendLiteral(' ').append(DateTimeFormatter.ISO_LOCAL_TIME).toFormatter();
                DateTimeFormatter sf = new DateTimeFormatterBuilder().parseCaseInsensitive()
                                .append(DateTimeFormatter.ISO_LOCAL_DATE).appendLiteral('T').append(DateTimeFormatter.ISO_LOCAL_TIME)
                                .toFormatter();
                LocalDateTimeSerializer serializer = new LocalDateTimeSerializer(sf);
                LocalDateTimeDeserializer deserializer = new LocalDateTimeDeserializer(df);
                JavaTimeModule jtm = new JavaTimeModule();
                jtm.addSerializer(LocalDateTime.class, serializer);
                jtm.addDeserializer(LocalDateTime.class, deserializer);
                ObjectMapper mapper = new ObjectMapper().registerModule(new ParameterNamesModule())
                                .registerModule(new Jdk8Module()).registerModule(jtm); // new module, NOT JSR310Module
                return mapper;
        }

}