Untitled

 avatar
unknown
plain_text
2 years ago
17 kB
12
Indexable
@Slf4j
@Configuration
public class AsyncConfig implements AsyncConfigurer {

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("default-worker-");
        executor.setMaxPoolSize(10);
        return executor;
    }

    @Bean("statisticsThreadPool")
    public ThreadPoolTaskExecutor statisticsThreadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("stat-worker-");
        executor.setCorePoolSize(3);
        executor.setMaxPoolSize(10);
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> {
            log.error("async exception: " + ex.getMessage());
            log.error("method: " + method.getName());
            for (Object param : params) {
                log.error("param: " + param);
            }
        };
    }

    @Bean
    public DelegatingSecurityContextAsyncTaskExecutor taskExecutor(
            ThreadPoolTaskExecutor threadPoolTaskExecutor) {
        return new DelegatingSecurityContextAsyncTaskExecutor(threadPoolTaskExecutor);
    }
}


///////////////////////////////////////////
@Configuration
@Slf4j
public class AwsConfig {

    @Value("${multicp.aws.profile:default}")
    private String multiCpProfile;

    @Bean
    public AmazonS3 multiCpS3() {
        log.info("Creating amazonS3 for multi cp...");
        return AmazonS3ClientBuilder
                .standard()
                .withRegion(Regions.CN_NORTH_1)
                .withCredentials(new ProfileCredentialsProvider(multiCpProfile))
                .withForceGlobalBucketAccessEnabled(true)
                .build();
    }

    @Bean
    public AmazonS3 portalS3() {
        log.info("Creating amazonS3 for portal...");

        return AmazonS3ClientBuilder
                .standard()
                .withRegion(Regions.US_EAST_1)
                .withForceGlobalBucketAccessEnabled(true)
                .build();
    }

    @Bean
    public AmazonCloudFront portalCloudFront() {
        log.info("Creating cloudfront for portal...");

        return AmazonCloudFrontClientBuilder
                .standard()
                .withRegion(Regions.US_EAST_1)
                .build();
    }

    @Bean
    public AmazonSimpleEmailService simpleEmailService() {
        return AmazonSimpleEmailServiceClientBuilder
                .standard()
                .withRegion(Regions.US_EAST_1)
                .build();
    }
}
/////////////////////////////////////////////
@Configuration
@EnableCaching
public class EhcacheConfig {


    public static final String CONTENTS_PUSH_STATS_OVER_ALL = "contents_push_stats_over_all";

    @Bean(name = "cacheManager")
    public EhCacheCacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheManager());
    }

    private CacheManager ehCacheManager() {
        net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
        config.setName("portal-dashboard-api");
        config.setDynamicConfig(true);
        config.updateCheck(false);

        setCacheContentsPushStatsOverAll(config);

        return net.sf.ehcache.CacheManager.newInstance(config);
    }

   

    private void setCacheContentsPushStatsOverAll(net.sf.ehcache.config.Configuration config) {
        CacheConfiguration cache = createCache(CONTENTS_PUSH_STATS_OVER_ALL,
                MemoryStoreEvictionPolicy.LRU, 50, 24 * 60 * 60);
        config.addCache(cache);
    }

    private CacheConfiguration createCache(String name, MemoryStoreEvictionPolicy evictionPolicy,
                                           int maxEntriesLocalHeap, int timeToLiveSeconds) {
        CacheConfiguration cache = new CacheConfiguration();
        cache.setName(name);
        cache.setMemoryStoreEvictionPolicyFromObject(evictionPolicy);
        cache.setMaxEntriesLocalHeap(maxEntriesLocalHeap);
        cache.setTimeToLiveSeconds(timeToLiveSeconds);
        cache.statistics(true);
        return cache;
    }
}
////////////////////////////////////////////
@Configuration
public class EncryptorConfig {
    private static final String JASYPT_ALGORITHM = "PBEWithMD5AndDES";
    private static final String JASYPT_PASSWORD_SALT = getJasyptPassword();

    @Bean(name = "jasyptStringEncryptor")
    public static StringEncryptor jasyptStringEncryptor() {
        StandardPBEStringEncryptor configurationEncryptor = new StandardPBEStringEncryptor();
        configurationEncryptor.setConfig(environmentVariablesConfiguration());
        return configurationEncryptor;
    }

    private static String getJasyptPassword() {
        byte[] bytesFromFile = ResourceUtils.readBytesFromResource(
                "encrypted.jasypt_password");
        byte[] saltKey = bytesFromFile;

        if (Profiles.isActiveProfile(Profiles.PRD) || Profiles.isActiveProfile(Profiles.STG)) {
            AWSKMS kmsClient = getAwskms();
            ByteBuffer ciphertextBlob = ByteBuffer.wrap(bytesFromFile);
            DecryptResult decryptResult =
                    kmsClient.decrypt(new DecryptRequest().withCiphertextBlob(ciphertextBlob));
            saltKey = decryptResult.getPlaintext().array();
        }

        return new String(saltKey, StandardCharsets.UTF_8);
    }

    private static AWSKMS getAwskms() {
        AWSKMSClientBuilder awskmsClientBuilder = AWSKMSClientBuilder
                .standard();
        if (Profiles.isActiveProfile(Profiles.STG)) {
            awskmsClientBuilder = awskmsClientBuilder.withRegion(Regions.AP_SOUTHEAST_1);
        }
        return awskmsClientBuilder.build();
    }

    public static PBEConfig environmentVariablesConfiguration() {
        EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
        config.setAlgorithm(JASYPT_ALGORITHM);
        config.setPassword(JASYPT_PASSWORD_SALT);
        return config;
    }
}
//////////////////////////////////////////////////////
@Configuration
@Slf4j
public class FeatureApiProxyConfig {
    private static final String FEATURE_API_PROXY_CONFIG_JSON = "feature-api-proxy-config.json";

    private final FeatureApiProxyInfo featureApiProxyInfo;

    private static final StringEncryptor CONFIG_ENCRYPTOR =
            EncryptorConfig.jasyptStringEncryptor();

    public FeatureApiProxyConfig(@Lazy FeatureApiProxyInfo featureApiProxyInfo) {
        this.featureApiProxyInfo = featureApiProxyInfo;
    }

    @Bean
    public FeatureApiProxyInfo featureApiProxy() throws IOException {
        FeatureApiProxyInfo.FeatureApiProxySetting proxy = null;
        try (InputStream inputStream = new ClassPathResource(FEATURE_API_PROXY_CONFIG_JSON)
                .getInputStream()) {
            proxy = new ObjectMapper().readValue(inputStream,
                    FeatureApiProxyInfo.FeatureApiProxySetting.class);
        } catch (IOException e) {
            log.error("Failed to read {}", FEATURE_API_PROXY_CONFIG_JSON);
            throw new IOException(e);
        }

        log.info("featureApiProxyInfo init : " + proxy);
        return new FeatureApiProxyInfo(proxy);
    }

    /**
     * FeatureApiProxyInfo
     */
    @Data
    public static class FeatureApiProxyInfo {
        private FeatureApiProxySetting proxySetting;
        private Map<String, FeatureApiInfo> apiInfoMap;

        public FeatureApiProxyInfo(FeatureApiProxySetting settings) {
            if (settings != null && settings.apiList != null) {
                if (settings.apiList.stream()
                        .anyMatch(apiInfo ->
                                apiInfo.getProxyApiUriPrefix().split("/").length != 3)) {
                    throw new InvalidDataException("Proxy-api-uri-prefix must be in 2depth.");
                }
                this.proxySetting = settings;
                apiInfoMap = new ConcurrentHashMap<>();

                proxySetting.apiList.sort(
                        Comparator.comparing(FeatureApiInfo::getProxyApiUriPrefix));
            }
        }

        public FeatureApiInfo getApiInfo(String requestUri) {
            if (proxySetting == null) {
                throw new UrlNotFoundException(requestUri);
            }

            return apiInfoMap.computeIfAbsent(requestUri, s ->
                    proxySetting.apiList.stream()
                            .filter(item -> matchToProxyApiUriPrefix(requestUri,
                                    item.getProxyApiUriPrefix()))
                            .findFirst()
                            .orElseThrow(() -> new UrlNotFoundException(requestUri)));
        }

        private boolean matchToProxyApiUriPrefix(String requestUri, String prefix) {
            if (!requestUri.startsWith(prefix)) {
                return false;
            }

            String[] parsedUri = requestUri.split("/");
            String[] parsedPrefix = prefix.split("/");

            return parsedUri[1].equals(parsedPrefix[1]) && parsedUri[2].equals(parsedPrefix[2]);
        }

        /**
         * FeatureApiProxySetting
         */
        @Data
        public static class FeatureApiProxySetting {
            private String portalApiEndpoint;
            private List<FeatureApiInfo> apiList;
        }

        /**
         * FeatureApiInfo
         */
        @Data
        public static class FeatureApiInfo {
            private String name;
            private String title;
            private String proxyApiUriPrefix;
            private SwaggerInfo swaggerInfo;
            private String targetApiEndpoint;
            private ApiAuthorization authorization;
            private List<String> allowedHeaders;
        }

        /**
         * SwaggerInfo
         */
        @Data
        public static class SwaggerInfo {
            private String version;
            private String apiDocsUrl;
        }

        /**
         * ApiAuthorization
         */
        @Data
        public static class ApiAuthorization {
            private Type type;
            private String key;
            private String value;
            private String role;

            public void setValue(String value) {
                if (value != null && value.startsWith("ENC(") && value.endsWith(")")) {
                    value = CONFIG_ENCRYPTOR.decrypt(value.substring(4, value.length() - 1));
                }
                this.value = value;
            }

            public enum Type {
                @JsonProperty("header")
                HEADER,
                @JsonProperty("SAHeader")
                SA_HEADER,
                @JsonProperty("queryParam")
                QUERY_PARAM
            }
        }
    }
}
////////////////////////////////////////////
@Configuration
public class MessageSenderConfig {
    @Value("${slack.webhooks.url:}")
    private String slackWebhooksUrl;

    @Autowired
    private Environment environment;

    @Bean(name = "slackMessageSender")
    @ConditionalOnProperty(prefix = "message", name = "channel", havingValue = "slack")
    public MessageSender slackMessageSender() {
        return new SlackMessageSender(slackWebhooksUrl, environment.getActiveProfiles()[0]);
    }

    @Bean(name = "consoleMessageSender")
    @ConditionalOnProperty(prefix = "message", name = "channel", havingValue = "console",
            matchIfMissing = true)
    public MessageSender consoleMessageSender() {
        return new ConsoleMessageSender();
    }
}
/////////////////////////////////////////
@Configuration
@Profile({Profiles.LOCAL, Profiles.DEV, Profiles.STG})
public class OpenApiConfig {

    public static final String X_SERVER_AUTH = "X-Server-Auth";

    @Autowired
    private FeatureApiProxyInfo featureApiProxy;

    @Bean
    public OpenAPI openAPI() {
        Info info = new Info()
                .title("Internet Portal Dashboard API")
                .description("Internet Portal Dashboard API");
        return new OpenAPI()
                .addServersItem(new Server().url("/"))
                .components(new Components().addSecuritySchemes(X_SERVER_AUTH,
                        new SecurityScheme().type(Type.APIKEY).in(In.HEADER).name(X_SERVER_AUTH)))
                .addSecurityItem(new SecurityRequirement().addList(X_SERVER_AUTH))
                .info(info);
    }

    @Primary
    @Bean
    public SwaggerUiConfigProperties swaggerUiConfigProperties(
            SwaggerUiConfigProperties swaggerUiConfigProperties) {
        Set<SwaggerUrl> swaggerUrls =
                featureApiProxy.getProxySetting().getApiList().stream()
                        .filter(apiInfo -> apiInfo.getSwaggerInfo() != null)
                        .map(apiInfo -> {
                            SwaggerUrl swaggerUrl = new SwaggerUrl();
                            swaggerUrl.setName(apiInfo.getName());
                            swaggerUrl.setUrl("/features/portal-api-docs"
                                    + apiInfo.getProxyApiUriPrefix());
                            return swaggerUrl;
                        }).collect(Collectors.toSet());

        SwaggerUrl portal = new SwaggerUrl();
        portal.setName("InternetPortal");
        portal.setUrl("/v3/api-docs");
        swaggerUrls.add(portal);
        swaggerUiConfigProperties.setUrls(swaggerUrls);
        swaggerUiConfigProperties.setUrlsPrimaryName("InternetPortal");

        return swaggerUiConfigProperties;
    }
}
/////////////////////////////////////////
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        MappingJackson2HttpMessageConverter textHttpMessageConverter =
                new MappingJackson2HttpMessageConverter();
        List<MediaType> textMediaTypes = new ArrayList<>();
        textMediaTypes.add(MediaType.TEXT_PLAIN);
        textHttpMessageConverter.setSupportedMediaTypes(textMediaTypes);

        HttpMessageConverter<?> stringHttpMessageConverter =
                new StringHttpMessageConverter(Charset.forName("UTF-8"));

        RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());

        List<HttpMessageConverter<?>> messageConverters =
                restTemplate.getMessageConverters();
        messageConverters.add(textHttpMessageConverter);
        messageConverters.add(0, stringHttpMessageConverter);
        restTemplate.setMessageConverters(messageConverters);

        return restTemplate;
    }

    @Bean
    public RetryTemplate retryTemplate() {
        RetryTemplate retryTemplate = new RetryTemplate();

        FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
        fixedBackOffPolicy.setBackOffPeriod(TimeUnit.SECONDS.toMillis(2));
        retryTemplate.setBackOffPolicy(fixedBackOffPolicy);

        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(5);
        retryTemplate.setRetryPolicy(retryPolicy);

        return retryTemplate;
    }
}
//////////////////////////////////
@Configuration
@Slf4j
public class RootConfig {

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper().registerModule(new JavaTimeModule());
    }

    @Bean
    public ModelMapper modelMapper() {
        ModelMapper modelMapper = new ModelMapper();
        TypeMap<ExperimentDetailVo, Experiment> propertyMapper =
                modelMapper.createTypeMap(ExperimentDetailVo.class, Experiment.class);
        propertyMapper.addMappings(mapper -> mapper.skip(Experiment::setTesters));
        propertyMapper.addMappings(mapper -> mapper.skip(Experiment::setRules));
        propertyMapper.addMappings(mapper -> mapper.skip(Experiment::setVariants));
        propertyMapper.addMappings(mapper -> mapper.skip(Experiment::setSiLogs));
        propertyMapper.addMappings(mapper -> mapper.skip(Experiment::setMeasures));
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
        return modelMapper;
    }
}

Editor is loading...
Leave a Comment