Subversion Repositories SmartDukaan

Rev

Rev 35857 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StringDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
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.LocalDate;
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:messages";
    private static final Logger LOGGER = LogManager.getLogger(AppConfig.class);
    private static Resource resource;
    private static Resource sharedResource;

    public static Resource getResource() {
        return resource;
    }

    public static Resource getSharedResource() {
        return sharedResource;
    }

    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", "325");
        attributesMap.put("cssVersion", "39");
        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.setContentType("text/html;charset=UTF-8");
        bean.setRequestContextAttribute("rc");
        bean.setExposeSpringMacroHelpers(true);
        bean.setAttributesMap(this.velocityAttributesMap());
        return bean;
    }

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

    @Bean
    public VelocityConfigurer velocityConfig() {
        VelocityConfigurer velocityConfigurer = new VelocityConfigurer();
        Properties velocityProperties = new Properties();
       /* velocityProperties.put("velocimacro.library", "macros.vm");
        velocityProperties.put("velocimacro.permissions.allow.inline", "true");
        velocityProperties.put("velocimacro.permissions.allow.inline.to.replace.global", "true");*/
        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);
        messageSource.setDefaultEncoding("UTF-8");

        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();

        Resource appResource;
        Resource sharedResource;

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

        resource = appResource;
        AppConfig.sharedResource = sharedResource;

        // Load shared properties from dao first, then app-specific (app-specific can override)
        propertySourcesPlaceholderConfigurer.setLocations(sharedResource, appResource);
        propertySourcesPlaceholderConfigurer.setIgnoreResourceNotFound(true);

        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
    public JavaMailSender googleMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.gmail.com");
        mailSender.setPort(465);
        mailSender.setUsername("sdtech@smartdukaan.com");
        mailSender.setPassword("gpdschroalhhirox"); // App Password

        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.debug", "true");

        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", ".");
        factory.setPreferFileSystemAccess(false);
        // factory.setResourceLoaderPath("classpath:/templates/");


        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.setProperty("input.encoding", "UTF-8");
        velocityProperties.setProperty("output.encoding", "UTF-8");
        factory.setVelocityProperties(velocityProperties);

        // 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();

        DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_DATE).toFormatter();
        JavaTimeModule jtm = new JavaTimeModule();
        jtm.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(sf));
        jtm.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(df));
        jtm.addSerializer(LocalDate.class, new LocalDateSerializer(dateFormatter));
        jtm.addDeserializer(LocalDate.class, new LocalDateDeserializer(dateFormatter));
        SimpleModule stringModule = new SimpleModule("String trimmer deserialize module");
        stringModule.addDeserializer(String.class, new CustomStringDeserializer());
        ObjectMapper mapper = new ObjectMapper()
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                .registerModule(new ParameterNamesModule()).registerModule(new Jdk8Module()).registerModule(jtm)
                .registerModule(stringModule); // new module, NOT JSR310Module
        return mapper;
    }

    class CustomStringDeserializer extends StringDeserializer {
        @Override
        public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            String text = super.deserialize(p, ctxt);
            //clean up value
            return text.trim();
        }
    }


}