@org.springframework.retry.annotation.EnableRetry

Here are the examples of the java api @org.springframework.retry.annotation.EnableRetry taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

50 Examples 7

19 View Source File : RetryConfig.java
License : MIT License
Project Creator : jarvisqi

/**
 * 配置重试
 */
@Configuration
@EnableRetry
public clreplaced RetryConfig {
}

19 View Source File : ObjectStorePublishingConfig.java
License : Apache License 2.0
Project Creator : covid-be-app

/**
 * Manages the instantiation of the {@link ObjectStoreClient} bean.
 */
@Configuration
@EnableRetry
public clreplaced ObjectStorePublishingConfig {

    private static final Region DEFAULT_REGION = Region.EU_CENTRAL_1;

    @Bean
    public ObjectStoreClient createObjectStoreClient(DistributionServiceConfig distributionServiceConfig) {
        return createClient(distributionServiceConfig.getObjectStore());
    }

    private ObjectStoreClient createClient(ObjectStore objectStore) {
        AwsCredentialsProviderChain credentialsProvider = AwsCredentialsProviderChain.of(DefaultCredentialsProvider.create(), StaticCredentialsProvider.create(AwsBasicCredentials.create(objectStore.getAccessKey(), objectStore.getSecretKey())));
        String endpoint = removeTrailingSlash(objectStore.getEndpoint()) + ":" + objectStore.getPort();
        return new S3ClientWrapper(S3Client.builder().region(DEFAULT_REGION).endpointOverride(URI.create(endpoint)).credentialsProvider(credentialsProvider).build());
    }

    private String removeTrailingSlash(String string) {
        return string.endsWith("/") ? string.substring(0, string.length() - 1) : string;
    }

    /**
     * Creates a {@link ThreadPoolTaskExecutor}, which is used to submit object store upload tasks.
     */
    @Bean
    public ThreadPoolTaskExecutor createExecutor(DistributionServiceConfig distributionServiceConfig) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(distributionServiceConfig.getObjectStore().getMaxNumberOfS3Threads());
        executor.setMaxPoolSize(distributionServiceConfig.getObjectStore().getMaxNumberOfS3Threads());
        executor.setThreadNamePrefix("object-store-operation-worker-");
        executor.initialize();
        return executor;
    }
}

19 View Source File : TestReporterConfiguration.java
License : Apache License 2.0
Project Creator : ATLANTBH

/**
 * Test reporter app configuration.
 */
@Configuration
@EnableRetry
public clreplaced TestReporterConfiguration extends WebMvcConfigurerAdapter {

    private static Integer CACHE_TIME = 21600;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // Serve replacedets from public dir
        registry.addResourceHandler("/dist/**").addResourceLocations("clreplacedpath:/public/dist/").setCachePeriod(CACHE_TIME).resourceChain(true).addResolver(new GzipResourceResolver());
        // Serve index for all other routes
        registry.addResourceHandler("/**").setCachePeriod(CACHE_TIME).resourceChain(true).addResolver(new IndexResourceResolver());
    }

    @Bean
    public BeanPostProcessor dataSourceWrapper() {
        return new RetriableDataSourceBeanPostProcessor();
    }

    public static clreplaced IndexResourceResolver extends PathResourceResolver {

        @Override
        public Resource resolveResource(HttpServletRequest request, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) {
            return new ClreplacedPathResource("public/index.html", this.getClreplaced().getClreplacedLoader());
        }
    }

    @Order(Ordered.HIGHEST_PRECEDENCE)
    private clreplaced RetriableDataSourceBeanPostProcessor implements BeanPostProcessor {

        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            if (bean instanceof DataSource) {
                bean = new RetriableDataSource((DataSource) bean);
            }
            return bean;
        }

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            return bean;
        }
    }
}

18 View Source File : TransactionCoreAutoConfiguration.java
License : MIT License
Project Creator : keets2012

@Configuration
@EnableConfigurationProperties(TxConfig.clreplaced)
@ConditionalOnBean({ DiscoveryClient.clreplaced })
@EnableFeignClients(basePackages = { "com.blueskykong.lottor.core.feign" })
@EnableRetry
public clreplaced TransactionCoreAutoConfiguration {

    @Bean
    public TransactionThreadPool transactionThreadPool(TxConfig txConfig) {
        return new TransactionThreadPool(txConfig);
    }

    @Bean
    public NettyClientService nettyClientService(NettyClientHandlerInitializer nettyClientHandlerInitializer, ManagerClient managerClient) {
        return new NettyClientServiceImpl(nettyClientHandlerInitializer, managerClient);
    }

    @Bean
    public TxManagerMessageService txManagerMessageService(NettyClientMessageHandler nettyClientMessageHandler) {
        return new NettyMessageServiceImpl(nettyClientMessageHandler);
    }

    @Configuration
    protected static clreplaced InitialService {

        @Bean
        @Primary
        public InitService initService(NettyClientService nettyClientService, TxOperateService txOperateService) {
            return new InitServiceImpl(nettyClientService, txOperateService);
        }

        @Bean
        public ExternalNettyService externalNettyService(TxTransactionInterceptor txTransactionInterceptor) {
            return new ExternalNettyServiceImpl(txTransactionInterceptor);
        }

        @Bean
        public AspectTransactionService aspectTransactionService(TxTransactionFactoryService txTransactionFactoryService) {
            return new AspectTransactionServiceImpl(txTransactionFactoryService);
        }

        @Bean
        public TxTransactionFactoryService txTransactionFactoryService() {
            return new TxTransactionFactoryServiceImpl();
        }

        @Bean
        public ObjectSerializer objectSerializer(TxConfig nettyConfig) {
            final SerializeProtocolEnum serializeProtocolEnum = SerializeProtocolEnum.acquireSerializeProtocol(nettyConfig.getNettySerializer());
            final ServiceLoader<ObjectSerializer> objectSerializers = ServiceBootstrap.loadAll(ObjectSerializer.clreplaced);
            final Optional<ObjectSerializer> serializer = StreamSupport.stream(objectSerializers.spliterator(), false).filter(objectSerializer -> Objects.equals(objectSerializer.getScheme(), serializeProtocolEnum.getSerializeProtocol())).findFirst();
            return serializer.orElse(new KryoSerializer());
        }
    }

    @Configuration
    protected static clreplaced Compensation {

        @Bean
        public TxOperateService txCompensationService(ModelNameService modelNameService) {
            return new TxOperateServiceImpl(modelNameService);
        }

        @Bean
        public TxOperateCommand command(TxOperateService txOperateService) {
            return new TxOperateCommand(txOperateService);
        }
    }

    @Configuration
    protected static clreplaced TransactionHandler {

        @Bean
        public TxTransactionHandler consumedTransactionHandler(TxManagerMessageService txManagerMessageService, TxOperateService txOperateService) {
            return new ConsumedTransactionHandler(txManagerMessageService, txOperateService);
        }

        @Bean
        public TxTransactionHandler confirmTxTransactionHandler(TxManagerMessageService txManagerMessageService, TxOperateCommand txOperateCommand) {
            return new ConfirmTxTransactionHandler(txManagerMessageService, txOperateCommand);
        }

        @Bean
        public TxTransactionHandler startTxTransactionHandler(TxManagerMessageService txManagerMessageService, TxOperateCommand txOperateCommand, ObjectSerializer objectSerializer, ModelNameService modelNameService) {
            return new StartTxTransactionHandler(txManagerMessageService, txOperateCommand, objectSerializer, modelNameService);
        }
    }

    @Configuration
    protected static clreplaced TransactionBootstrap {

        @Bean
        public TxTransactionInitialize txTransactionInitialize(InitService initService) {
            return new TxTransactionInitialize(initService);
        }

        @Bean
        public TxTransactionBootstrap txTransactionBootstrap(TxTransactionInitialize txTransactionInitialize, TxConfig txConfig) {
            return new TxTransactionBootstrap(txTransactionInitialize, txConfig);
        }
    }

    @Configuration
    protected static clreplaced NettyHandler {

        @Bean
        public NettyClientMessageHandler nettyClientMessageHandler(ModelNameService modelNameService, TxOperateCommand txOperateCommand) {
            return new NettyClientMessageHandler(modelNameService, txOperateCommand);
        }

        @Bean
        public NettyClientHandlerInitializer nettyClientHandlerInitializer(NettyClientMessageHandler nettyClientMessageHandler) {
            return new NettyClientHandlerInitializer(nettyClientMessageHandler);
        }
    }
}

18 View Source File : CoreAutoConfig.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : hxnlyw

/**
 * @author gourd.hu
 * @date 2018-11-20
 */
@Configuration
@EnableRetry
@Import({ ConverterConfig.clreplaced, AsyncPoolConfig.clreplaced, AsyncServiceImpl.clreplaced })
public clreplaced CoreAutoConfig {
}

18 View Source File : Application.java
License : Apache License 2.0
Project Creator : houbb

/**
 * <p> </p>
 *
 * <pre> Created: 2018/6/23 上午11:14  </pre>
 * <pre> Project: spring-boot  </pre>
 *
 * @author houbinbin
 * @version 1.0
 * @since JDK 1.7
 */
@SpringBootApplication
@EnableRetry
public clreplaced Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.clreplaced, args);
        System.out.println("Retry start at http://localhost:18080/retry/");
        System.out.println("Time start at http://localhost:18080/retry/time");
    }
}

18 View Source File : ClientConfiguration.java
License : Apache License 2.0
Project Creator : hashgraph

@Configuration
@RequiredArgsConstructor
@EnableRetry
clreplaced ClientConfiguration {

    private final AcceptanceTestProperties acceptanceTestProperties;

    @Bean
    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    SDKClient sdkClient() throws InterruptedException {
        return new SDKClient(acceptanceTestProperties);
    }

    @Bean
    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    MirrorNodeClient mirrorNodeClient() throws InterruptedException {
        return new MirrorNodeClient(sdkClient());
    }

    @Bean
    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    TopicClient topicClient() throws InterruptedException {
        return new TopicClient(sdkClient());
    }

    @Bean
    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    AccountClient accountClient() throws InterruptedException {
        return new AccountClient(sdkClient());
    }

    @Bean
    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    TokenClient tokenClient() throws InterruptedException {
        return new TokenClient(sdkClient());
    }

    @Bean
    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    ScheduleClient scheduleClient() throws InterruptedException {
        return new ScheduleClient(sdkClient());
    }

    @Bean
    RetryTemplate retryTemplate() {
        RetryTemplate retryTemplate = new RetryTemplate();
        FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
        fixedBackOffPolicy.setBackOffPeriod(acceptanceTestProperties.getSubscribeRetryBackoffPeriod().toMillis());
        retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(acceptanceTestProperties.getSubscribeRetries());
        retryTemplate.setRetryPolicy(retryPolicy);
        return retryTemplate;
    }

    @Bean
    WebClient webClient() {
        TcpClient tcpClient = TcpClient.create().option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).doOnConnected(connection -> {
            connection.addHandlerLast(new ReadTimeoutHandler(5000, TimeUnit.MILLISECONDS));
            connection.addHandlerLast(new WriteTimeoutHandler(5000, TimeUnit.MILLISECONDS));
        }).wiretap(true);
        // support snake_case to avoid manually mapping JsonProperty on all properties
        ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        Jackson2JsonDecoder jackson2JsonDecoder = new Jackson2JsonDecoder(objectMapper, MediaType.APPLICATION_JSON);
        Jackson2JsonEncoder jackson2JsonEncoder = new Jackson2JsonEncoder(objectMapper, MediaType.APPLICATION_JSON);
        return WebClient.builder().baseUrl(acceptanceTestProperties.getRestPollingProperties().getBaseUrl()).clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient))).codecs(clientCodecConfigurer -> {
            clientCodecConfigurer.defaultCodecs().jackson2JsonDecoder(jackson2JsonDecoder);
            clientCodecConfigurer.defaultCodecs().jackson2JsonEncoder(jackson2JsonEncoder);
        }).defaultHeaders(httpHeaders -> {
            httpHeaders.setAccept((List.of(MediaType.APPLICATION_JSON)));
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            httpHeaders.setCacheControl(CacheControl.noStore());
        }).build();
    }
}

/**
 * The Application clreplaced.
 */
@SpringBootApplication
@EnableRetry
@EnableConfigurationProperties(EfgsProperties.clreplaced)
public clreplaced FederationGatewayApplication extends SpringBootServletInitializer {

    /**
     * The main Method.
     *
     * @param args the args for the main method
     */
    public static void main(String[] args) {
        SpringApplication.run(FederationGatewayApplication.clreplaced, args);
    }
}

18 View Source File : MediaUpload.java
License : Apache License 2.0
Project Creator : airyhq

@Service
@EnableRetry
public clreplaced MediaUpload {

    private final AmazonS3 amazonS3Client;

    private final String bucket;

    private final URL host;

    public MediaUpload(AmazonS3 amazonS3Client, @Value("${storage.s3.bucket}") String bucket, @Value("${storage.s3.path}") String path) throws MalformedURLException {
        this.amazonS3Client = amazonS3Client;
        this.bucket = bucket;
        URL bucketHost = new URL(String.format("https://%s.s3.amazonaws.com/", bucket));
        this.host = new URL(bucketHost, path);
    }

    public boolean isUserStorageUrl(URL dataUrl) {
        return dataUrl.getHost().equals(host.getHost());
    }

    @Retryable
    public String uploadMedia(final InputStream is, final String fileName) throws Exception {
        final String contentType = resolveContentType(fileName, is);
        final ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(contentType);
        final PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName, is, objectMetadata).withCannedAcl(CannedAccessControlList.PublicRead);
        amazonS3Client.putObject(putObjectRequest);
        return new URL(host, fileName).toString();
    }

    private String resolveContentType(final String fileName, final InputStream is) throws IOException {
        final String contentType = URLConnection.guessContentTypeFromStream(is);
        return contentType == null ? URLConnection.guessContentTypeFromName(fileName) : contentType;
    }
}

18 View Source File : AerospikeRestClientApplication.java
License : Apache License 2.0
Project Creator : aerospike

@SpringBootApplication
@EnableRetry
public clreplaced AerospikeRestClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(AerospikeRestClientApplication.clreplaced, args);
    }
}

18 View Source File : Xs2aProtocolConfiguration.java
License : Apache License 2.0
Project Creator : adorsys

@Configuration
@EnableRetry
@EnableConfigurationProperties
@EnableTransactionManagement
@ComponentScan(basePackages = { "de.adorsys.opba.protocol.xs2a.config", "de.adorsys.opba.protocol.xs2a.service", "de.adorsys.opba.protocol.xs2a.entrypoint" })
public clreplaced Xs2aProtocolConfiguration {
}

18 View Source File : HbciProtocolConfiguration.java
License : Apache License 2.0
Project Creator : adorsys

@Configuration
@EnableRetry
@EnableConfigurationProperties
@EnableTransactionManagement
@ComponentScan(basePackages = { "de.adorsys.opba.protocol.hbci.config", "de.adorsys.opba.protocol.hbci.service", "de.adorsys.opba.protocol.hbci.entrypoint" })
public clreplaced HbciProtocolConfiguration {
}

18 View Source File : RetryableConfig.java
License : Apache License 2.0
Project Creator : adorsys

@Slf4j
@EnableRetry
@Configuration
public clreplaced RetryableConfig {

    public static final String TEST_RETRY_OPS = "TEST_RETRY_OPS";

    @Bean(name = TEST_RETRY_OPS)
    RetryOperations retryOperations(@Value("${test.retry.max}") int maxRetries) {
        RetryTemplate withRetry = new RetryTemplate();
        withRetry.setBackOffPolicy(new ExponentialBackOffPolicy());
        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(maxRetries);
        withRetry.setRetryPolicy(retryPolicy);
        withRetry.registerListener(new LogRetryListener());
        return withRetry;
    }

    private static clreplaced LogRetryListener extends RetryListenerSupport {

        @Override
        public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
            log.info("Caught for retry {}", throwable.getMessage());
        }
    }
}

17 View Source File : CommonConfig.java
License : Eclipse Public License 1.0
Project Creator : zhaoqilong3031

@EnableEurekaClient
@EnableHystrix
@EnableRetry
@Configuration
@ComponentScan(basePackages = { "com.zhaoql.tcc.coordinator.manager" })
@Import(value = { CustomExceptionHandler.clreplaced })
public clreplaced CommonConfig {

    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

17 View Source File : RestTemplateConfiguration.java
License : Apache License 2.0
Project Creator : Xlinlin

/**
 * [简要描述]: 初始化rest template
 * [详细描述]: 开启重试
 *
 * @author llxiao
 * @version 1.0, 2019/11/30 10:43
 * @since JDK 1.8
 */
@Configuration
@ComponentScan("com.xiao.custom.rest.starter.autoconfigure")
@Slf4j
@EnableRetry
public clreplaced RestTemplateConfiguration {

    /**
     * [简要描述]:okHttp支持<br/>
     * [详细描述]:<br/>
     *
     * @param okHttpProperties :
     * @return org.springframework.http.client.ClientHttpRequestFactory
     * xiaolinlin  2020/1/16 - 18:43
     */
    @Bean
    @ConditionalOnProperty(value = "rest.okhttp.enable", havingValue = "true")
    @ConditionalOnMissingBean(ClientHttpRequestFactory.clreplaced)
    public ClientHttpRequestFactory okHttpHttpRequestFactory(OkHttpProperties okHttpProperties) {
        log.info("Init request factory for okHttp!");
        OkHttp3ClientHttpRequestFactory clientHttpRequestFactory = new OkHttp3ClientHttpRequestFactory(buildOkHttpsClient().build());
        // 连接超时
        clientHttpRequestFactory.setConnectTimeout(okHttpProperties.getConnectionTimeout());
        // 读超时
        clientHttpRequestFactory.setReadTimeout(okHttpProperties.getReadTimeout());
        // 写超时
        clientHttpRequestFactory.setWriteTimeout(okHttpProperties.getWriteTimeout());
        return clientHttpRequestFactory;
    }

    /**
     * [简要描述]:http pool支持<br/>
     * [详细描述]:<br/>
     *
     * @param httpPoolProperties :
     * @return org.springframework.http.client.ClientHttpRequestFactory
     * xiaolinlin  2020/1/16 - 18:43
     */
    @Bean
    @ConditionalOnProperty(value = "rest.pool.enable", havingValue = "true")
    @ConditionalOnMissingBean(ClientHttpRequestFactory.clreplaced)
    public ClientHttpRequestFactory httpPoolRequestFactory(HttpPoolProperties httpPoolProperties) {
        log.info("Init request factory for http pool");
        SSLConnectionSocketFactory socketFactory = null;
        SSLContext sslContext = buildSslContext();
        if (null != sslContext) {
            socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        } else {
            socketFactory = SSLConnectionSocketFactory.getSocketFactory();
        }
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", socketFactory).build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        connectionManager.setMaxTotal(httpPoolProperties.getMaxTotal());
        connectionManager.setDefaultMaxPerRoute(httpPoolProperties.getDefaultMaxPerRoute());
        connectionManager.setValidateAfterInactivity(httpPoolProperties.getValidateAfterInactivity());
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(httpPoolProperties.getSocketTimeout()).setConnectTimeout(httpPoolProperties.getConnectTimeout()).setConnectionRequestTimeout(httpPoolProperties.getConnectionRequestTimeout()).build();
        return new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setConnectionManager(connectionManager).build());
    }

    /**
     * [简要描述]:RestTemplate<br/>
     * [详细描述]:<br/>
     *
     * @param clientHttpRequestFactory :
     * @return org.springframework.web.client.RestTemplate
     * xiaolinlin  2020/1/16 - 18:47
     */
    @Bean
    @ConditionalOnMissingBean(RestTemplate.clreplaced)
    public RestTemplate restTemplate(ClientHttpRequestFactory clientHttpRequestFactory) {
        log.info("Init rest template!");
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        // 拦截
        restTemplate.setInterceptors(Collections.singletonList(new RestInterceptor()));
        return restTemplate;
    }

    /**
     * [简要描述]:集成重试机制<br/>
     * [详细描述]:<br/>
     *
     * @param restTemplate :
     * @return com.purcotton.omni.rest.stater.common.service.impl.HttpRetryService
     * xiaolinlin  2020/1/16 - 18:47
     */
    @Bean
    public HttpRetryService retryService(RestTemplate restTemplate) {
        log.info("Init http retry support!");
        return new HttpRetryService(restTemplate);
    }

    /**
     * [简要描述]:http 同步服务<br/>
     * [详细描述]:<br/>
     *
     * @param retryService: 支持重试请求
     * @return com.purcotton.omni.rest.stater.common.service.HttpClientService
     * xiaolinlin  2020/1/16 - 18:48
     */
    @Bean
    @ConditionalOnProperty(value = "rest.http.service.sync", havingValue = "true")
    @ConditionalOnMissingBean(HttpClientService.clreplaced)
    public HttpClientService httpClientService(HttpRetryService retryService) {
        log.info("Use sync http client service!");
        return new HttpClientServiceImpl(retryService);
    }

    /**
     * [简要描述]:http 异步服务<br/>
     * [详细描述]:<br/>
     *
     * @param retryService : 支持重试请求
     * @return com.purcotton.omni.rest.stater.common.service.HttpClientService
     * xiaolinlin  2020/1/16 - 18:48
     */
    @Bean
    @ConditionalOnProperty(value = "rest.http.service.async", havingValue = "true")
    @ConditionalOnMissingBean(HttpClientService.clreplaced)
    public HttpClientService asyncHttpClientService(HttpRetryService retryService) {
        log.info("User async http client service!");
        return new HttpClientAsyncServiceImpl(retryService);
    }

    /**
     * [简要描述]:okhttp3 跳过https验证<br/>
     * [详细描述]:<br/>
     *
     * @return okhttp3.OkHttpClient.Builder
     * xiaolinlin  2020/1/4 - 10:31
     */
    private OkHttpClient.Builder buildOkHttpsClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        TrustManager[] trustAllCerts = buildTrustManagers();
        SSLContext sslContext = buildSslContext();
        if (null != sslContext && null != trustAllCerts) {
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
        }
        builder.hostnameVerifier((hostname, session) -> true);
        return builder;
    }

    private SSLContext buildSslContext() {
        TrustManager[] trustAllCerts = buildTrustManagers();
        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            log.error("Init SSLContext error :\n", e);
        }
        return sslContext;
    }

    private TrustManager[] buildTrustManagers() {
        return new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };
    }
}

17 View Source File : AppInitializer.java
License : MIT License
Project Creator : valb3r

@EnableRetry
@SpringBootApplication(scanBasePackages = { "com.gtc.tradinggateway.aspect", "com.gtc.tradinggateway.service", "com.gtc.tradinggateway.controller", "com.gtc.tradinggateway.config" }, exclude = ActiveMQAutoConfiguration.clreplaced)
@EnableAspectJAutoProxy(proxyTargetClreplaced = true)
public clreplaced AppInitializer {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(AppInitializer.clreplaced);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);
    }
}

17 View Source File : ApplicationConfig.java
License : Apache License 2.0
Project Creator : ticktok-io

@Configuration
@EnableRetry
@EnableScheduling
@EnableAutoConfiguration(exclude = HypermediaAutoConfiguration.clreplaced)
public clreplaced ApplicationConfig {

    @Bean
    public Clock systemClock() {
        return Clock.systemUTC();
    }
}

17 View Source File : DefaultServiceConfig.java
License : Apache License 2.0
Project Creator : telstra

@Configuration
@EnableRetry
@PropertySource("file:${kilda.config.file:kilda.properties}")
@ComponentScan(basePackages = { "org.openkilda.testing.service", "org.openkilda.testing.tools" })
public clreplaced DefaultServiceConfig {

    @Bean(name = "northboundRestTemplate")
    public RestTemplate northboundRestTemplate(@Value("${northbound.endpoint}") String endpoint, @Value("${northbound.username}") String username, @Value("${northbound.preplacedword}") String preplacedword) {
        RestTemplate restTemplate = buildRestTemplateWithAuth(endpoint, username, preplacedword);
        restTemplate.getInterceptors().add(plusEncoderInterceptor());
        return restTemplate;
    }

    @Bean(name = "floodlightRestTemplate")
    public RestTemplate floodlightRestTemplate(@Value("#{'${floodlight.endpoints}'.split(',')[0]}") String endpoint, @Value("${floodlight.username}") String username, @Value("${floodlight.preplacedword}") String preplacedword) {
        return buildRestTemplateWithAuth(endpoint, username, preplacedword);
    }

    @Bean(name = "elasticSearchRestTemplate")
    public RestTemplate elasticSearchRestTemplate(@Value("${elasticsearch.endpoint}") String endpoint, @Value("${elasticsearch.username}") String username, @Value("${elasticsearch.preplacedword}") String preplacedword) {
        return buildRestTemplateWithAuth(endpoint, username, preplacedword);
    }

    @Bean(name = "traffExamRestTemplate")
    public RestTemplate traffExamRestTemplate() {
        return buildLoggingRestTemplate();
    }

    @Bean(name = "lockKeeperRestTemplates")
    public Map<String, RestTemplate> lockKeeperRestTemplates(@Value("${lockkeeper.port}") Integer lockKeeperPort, @Value("#{'${floodlight.regions}'.split(',')}") List<String> regions, @Value("#{'${floodlight.endpoints}'.split(',')}") List<String> flEndpoints) {
        Map<String, RestTemplate> result = new HashMap<>();
        for (int i = 0; i < flEndpoints.size(); i++) {
            String lockKeeperEndpoint = flEndpoints.get(i).replaceFirst("(.*):\\d+", "$1:" + lockKeeperPort);
            result.put(regions.get(i), buildLoggingRestTemplate(lockKeeperEndpoint));
        }
        return result;
    }

    @Bean
    public List<Floodlight> floodlights(@Value("#{'${floodlight.openflows}'.split(',')}") List<String> openflows, @Value("#{'${floodlight.endpoints}'.split(',')}") List<String> endpoints, @Value("#{'${floodlight.containers}'.split(',')}") List<String> containers, @Value("#{'${floodlight.regions}'.split(',')}") List<String> regions, @Value("#{'${floodlight.modes}'.split(',')}") List<String> modes) {
        if (openflows.size() != endpoints.size() || openflows.size() != containers.size() || openflows.size() != regions.size() || openflows.size() != modes.size()) {
            throw new IllegalArgumentException("Floodlight test properties are illegal. Sizes of floodlight.openflows," + " floodlight.endpoints, floodlight.containers, floodlight.regions, floodlight.modes should be " + "equal");
        }
        List<Floodlight> floodlights = new ArrayList<>();
        for (int i = 0; i < regions.size(); i++) {
            floodlights.add(new Floodlight(openflows.get(i), containers.get(i), regions.get(i), new FloodlightServiceImpl(endpoints.get(i)), EnumUtils.getEnumIgnoreCase(FloodlightConnectMode.clreplaced, modes.get(i))));
        }
        return floodlights;
    }

    @Bean(name = "otsdbRestTemplate")
    public RestTemplate otsdbRestTemplate(@Value("${opentsdb.endpoint}") String endpoint) {
        return buildLoggingRestTemplate(endpoint);
    }

    @Bean(name = "labApiRestTemplate")
    public RestTemplate labApiRestTemplate(@Value("${lab-api.endpoint}") String endpoint) {
        return buildLoggingRestTemplate(endpoint);
    }

    @Bean(name = "grpcRestTemplate")
    public RestTemplate grpcRestTemplate(@Value("${grpc.endpoint}") String endpoint, @Value("${grpc.username}") String username, @Value("${grpc.preplacedword}") String preplacedword) {
        return buildRestTemplateWithAuth(endpoint, username, preplacedword);
    }

    /**
     * Build rest template with enabled logging support.
     */
    public static RestTemplate buildLoggingRestTemplate(String endpoint) {
        final RestTemplate restTemplate = buildLoggingRestTemplate();
        restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(endpoint));
        return restTemplate;
    }

    /**
     * Build rest template with enabled logging support.
     */
    public static RestTemplate buildLoggingRestTemplate() {
        final RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory()));
        List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
        interceptors.add(new LoggingRequestInterceptor());
        restTemplate.setErrorHandler(new ExtendedErrorHandler());
        return restTemplate;
    }

    /**
     * Build rest template with enabled logging support and basic auth.
     */
    public static RestTemplate buildRestTemplateWithAuth(String endpoint, String username, String preplacedword) {
        RestTemplate restTemplate = buildLoggingRestTemplate(endpoint);
        restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor(username, preplacedword));
        return restTemplate;
    }

    private ClientHttpRequestInterceptor plusEncoderInterceptor() {
        return new ClientHttpRequestInterceptor() {

            @Override
            public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
                return execution.execute(new HttpRequestWrapper(request) {

                    @Override
                    public URI getURI() {
                        URI uri = super.getURI();
                        String escapedQuery = StringUtils.replace(uri.getRawQuery(), "+", "%2B");
                        return UriComponentsBuilder.fromUri(uri).replaceQuery(escapedQuery).build(true).toUri();
                    }
                }, body);
            }
        };
    }
}

17 View Source File : SkillService.java
License : MIT License
Project Creator : sinnerschrader

/**
 * Services handling skills management (create, rename, suggest, delete, ...)
 *
 * @author torree
 */
@Service
@EnableRetry
public clreplaced SkillService {

    private static final Logger logger = LoggerFactory.getLogger(SkillService.clreplaced);

    private final SkillRepository skillRepository;

    private final UserRepository UserRepository;

    @Autowired
    public SkillService(SkillRepository skillRepository, UserRepository UserRepository) {
        this.skillRepository = skillRepository;
        this.UserRepository = UserRepository;
    }

    private List<Skill> getAllSkills(boolean excludeHidden) {
        return excludeHidden ? skillRepository.findAllExcludeHidden() : skillRepository.findAll();
    }

    public List<Skill> findSkill(String search, boolean excludeHidden, int count) {
        List<Skill> found;
        // empty search => find all
        if (StringUtils.isEmpty(search)) {
            found = getAllSkills(excludeHidden);
        } else {
            found = skillRepository.findByNameStemLike(SkillUtils.toStem(search)).stream().filter(skill -> !excludeHidden || !skill.isHidden()).sorted(new SkillAutocompleteComparator(search)).collect(Collectors.toList());
        }
        // if count is set, limit number of results...
        if (count > 0) {
            found = found.stream().limit(count).collect(Collectors.toList());
        }
        return found;
    }

    public Skill getSkillByName(String name) {
        return skillRepository.findByName(name);
    }

    public SkillSearchResult searchSkillsByNames(List<String> names, boolean excludeHidden) throws SkillNotFoundException {
        var mapped = new HashMap<String, Skill>();
        var unmapped = new HashSet<String>();
        for (String name : names) {
            var found = skillRepository.findByNameStem(SkillUtils.toStem(name));
            if (found != null && (!excludeHidden || !found.isHidden())) {
                mapped.put(name, found);
            } else {
                unmapped.add(name);
            }
        }
        return new SkillSearchResult(mapped, unmapped);
    }

    private List<SuggestionSkill> aggregateSuggestions(Collection<Skill> skills) {
        List<SuggestionSkill> unaggregated = skills.stream().flatMap(s -> s.getSuggestions().stream()).collect(Collectors.toList());
        List<SuggestionSkill> aggregated = new ArrayList<>();
        for (SuggestionSkill s : unaggregated) {
            var present = aggregated.stream().filter(a -> a.getName().equals(s.getName())).findAny();
            if (present.isPresent()) {
                present.get().incrementCount(s.getCount());
            } else {
                aggregated.add(s);
            }
        }
        return aggregated;
    }

    public List<Skill> getSuggestionSkills(List<String> references, int count) {
        if (count < 1) {
            throw new IllegalArgumentException("count must be a positive integer");
        }
        List<SuggestionSkill> suggestions;
        if (CollectionUtils.isEmpty(references)) {
            suggestions = aggregateSuggestions(skillRepository.findAllExcludeHidden());
        } else {
            var sanitizedReferenceskills = searchSkillsByNames(references, true).mappedSkills();
            var sanitizedReferenceNames = sanitizedReferenceskills.stream().map(Skill::getName).collect(Collectors.toList());
            suggestions = aggregateSuggestions(sanitizedReferenceskills).stream().filter(s -> !sanitizedReferenceNames.contains(s.getName())).collect(Collectors.toList());
        }
        return suggestions.stream().sorted(Comparator.comparingInt(SuggestionSkill::getCount).reversed()).limit(count).map(s -> skillRepository.findByName(s.getName())).filter(s -> !s.isHidden()).collect(Collectors.toList());
    }

    public void registerSkillSearch(Collection<Skill> searchedSkills) throws IllegalArgumentException {
        if (searchedSkills.size() < 2) {
            logger.debug("Searched for less than two skills, cannot update mutual suggestions");
            return;
        }
        for (Skill skill : searchedSkills) {
            var others = searchedSkills.stream().filter(x -> !x.equals(skill)).collect(Collectors.toList());
            for (Skill updateable : others) {
                skill.incrementSuggestion(updateable.getName());
            }
        }
        try {
            skillRepository.saveAll(searchedSkills);
        } catch (OptimisticLockingFailureException e) {
            logger.error("Failed to register search for {} - optimistic locking error; will ignore search", searchedSkills);
        }
        logger.info("Successfully registered search for {}", searchedSkills);
    }

    @Retryable(include = OptimisticLockingFailureException.clreplaced, maxAttempts = 10)
    public void createSkill(String name, String description, boolean isHidden, Set<String> subSkills) throws EmptyArgumentException, DuplicateSkillException {
        name = SkillUtils.sanitizeName(name);
        subSkills = subSkills.stream().map(SkillUtils::sanitizeName).filter(n -> !StringUtils.isEmpty(n)).collect(Collectors.toSet());
        if (StringUtils.isEmpty(name)) {
            throw new EmptyArgumentException("name is empty");
        }
        if (skillRepository.findByName(name) != null) {
            logger.debug("Failed to create skill {}: already exists", name);
            throw new DuplicateSkillException("skill already existing");
        }
        // check if subSkills are known
        if (!isValidSubSkills(subSkills)) {
            logger.debug("Failed to set subskills on skill {}: subskill not found", name);
            throw new SkillNotFoundException("cannot set subskill: not found");
        }
        try {
            skillRepository.insert(new Skill(name, description, new ArrayList<>(), isHidden, subSkills));
            logger.info("Successfully created skill {}", name);
        } catch (DuplicateKeyException e) {
            logger.debug("Failed to create skill {}: already exists");
            throw new DuplicateSkillException("skill already existing");
        }
    }

    @Retryable(include = OptimisticLockingFailureException.clreplaced, maxAttempts = 10)
    public void updateSkill(String name, String newName, String description, Boolean hidden, Set<String> subSkills) throws IllegalArgumentException, DuplicateSkillException {
        name = SkillUtils.sanitizeName(name);
        newName = SkillUtils.sanitizeName(newName);
        subSkills = subSkills.stream().map(SkillUtils::sanitizeName).filter(n -> !StringUtils.isEmpty(n)).collect(Collectors.toSet());
        Skill oldSkill;
        Skill newSkill;
        if (StringUtils.isEmpty(name)) {
            throw new SkillNotFoundException("skill not found");
        }
        oldSkill = skillRepository.findByName(name);
        if (oldSkill == null) {
            logger.info("Failed to update {}: skill not found", name);
            throw new SkillNotFoundException("skill not found");
        }
        if (skillRepository.findByName(newName) != null) {
            logger.info("Failed to update skill {}: new name {} already exists", name, newName);
            throw new DuplicateSkillException("skillname already exists");
        }
        if (!isValidSubSkills(subSkills)) {
            logger.info("Failed to update skill {}: one or more subskills not found");
            throw new SkillNotFoundException("one new subskill cannot be found");
        }
        // @formatter:off
        newSkill = new Skill(StringUtils.isEmpty(newName) ? oldSkill.getName() : newName, description == null ? oldSkill.getDescription() : description, oldSkill.getSuggestions(), hidden == null ? oldSkill.isHidden() : hidden, CollectionUtils.isEmpty(subSkills) ? oldSkill.getSubSkillNames() : subSkills);
        // @formatter:on
        if (newSkill.equals(oldSkill)) {
            logger.info("Failed to update skill {}: new values contain no changes");
            return;
        }
        skillRepository.delete(oldSkill);
        skillRepository.insert(newSkill);
        if (!StringUtils.isEmpty(newName)) {
            updateInSubskills(oldSkill, newSkill);
            updateInSuggestions(oldSkill, newSkill);
            updateInPersons(oldSkill, newSkill);
        } else if (hidden != null) {
            updateInPersons(oldSkill, newSkill);
        }
    }

    @Retryable(include = OptimisticLockingFailureException.clreplaced, maxAttempts = 10)
    private void updateInSuggestions(Skill oldSkill, Skill newSkill) {
        var containingSkills = skillRepository.findBySuggestion(oldSkill.getName());
        containingSkills.forEach(s -> s.renameSuggestion(oldSkill.getName(), newSkill.getName()));
        skillRepository.saveAll(containingSkills);
    }

    @Retryable(include = OptimisticLockingFailureException.clreplaced, maxAttempts = 10)
    private void updateInSubskills(Skill oldSkill, Skill newSkill) {
        var containingSkills = skillRepository.findBySubskillName(oldSkill.getName());
        containingSkills.forEach(s -> s.renameSubSkill(oldSkill.getName(), newSkill.getName()));
        skillRepository.saveAll(containingSkills);
    }

    @Retryable(include = OptimisticLockingFailureException.clreplaced, maxAttempts = 10)
    private void updateInPersons(Skill oldSkill, Skill newSkill) {
        logger.debug("updating Skill {} in users", oldSkill.getName());
        var users = UserRepository.findBySkill(oldSkill.getName());
        users.forEach(p -> {
            var oldUserSkill = p.getSkill(oldSkill.getName(), true);
            p.addUpdateSkill(newSkill.getName(), oldUserSkill.getSkillLevel(), oldUserSkill.getWillLevel(), newSkill.isHidden(), oldUserSkill.isMentor());
        });
        UserRepository.saveAll(users);
    }

    @Retryable(include = OptimisticLockingFailureException.clreplaced, maxAttempts = 10)
    public void deleteSkill(String name, String migrateTo) throws IllegalArgumentException {
        var deleteSkill = skillRepository.findByName(name);
        if (deleteSkill == null) {
            logger.debug("Failed to delete skill {}: not found", name);
            throw new SkillNotFoundException("skill not found");
        }
        if (!StringUtils.isEmpty(migrateTo)) {
            var migrateSkill = skillRepository.findByName(migrateTo);
            migratePersonalSkills(deleteSkill, migrateSkill);
        }
        // delete from persons
        for (User user : UserRepository.findBySkill(name)) {
            user.removeSkill(name);
            UserRepository.save(user);
        }
        // delete from known skills
        skillRepository.delete(skillRepository.findByName(name));
        // delete in suggestion
        for (Skill skill : skillRepository.findBySuggestion(name)) {
            skill.deleteSuggestion(name);
            skillRepository.save(skill);
        }
        logger.info("Successfully deleted skill {}", name);
    }

    private void migratePersonalSkills(Skill from, Skill to) throws IllegalArgumentException {
        if (from == null || to == null) {
            logger.info("Failed to migrate {} to {}: not found", from, to);
            throw new SkillNotFoundException("Failed to migrate personal skills");
        } else if (from.getName().equals(to.getName())) {
            logger.info("Failed to migrate {} to {}: source and target equal");
            throw new IllegalArgumentException("Source and target may not be equal");
        }
        var migrateables = UserRepository.findBySkill(from.getName()).stream().filter(user -> !user.hreplacedkill(to.getName())).collect(Collectors.toList());
        migrateables.forEach(user -> {
            var oldSkill = user.getSkill(from.getName(), true);
            user.addUpdateSkill(to.getName(), oldSkill.getSkillLevel(), oldSkill.getWillLevel(), to.isHidden(), oldSkill.isMentor());
            user.removeSkill(from.getName());
        });
        UserRepository.saveAll(migrateables);
    }

    @Retryable(include = OptimisticLockingFailureException.clreplaced, maxAttempts = 10)
    public boolean isHidden(String skillName) {
        var skill = skillRepository.findByName(skillName);
        if (skill == null) {
            throw new SkillNotFoundException("skill not found");
        }
        return skill.isHidden();
    }

    private boolean isValidSubSkills(Collection<String> subSkills) {
        return CollectionUtils.isEmpty(subSkills) || subSkills.size() == skillRepository.findByNameIn(subSkills).size();
    }
}

17 View Source File : AlertManagerApplication.java
License : Apache License 2.0
Project Creator : Romeh

@SpringBootApplication
@EnableScheduling
@EnableRetry
public clreplaced AlertManagerApplication {

    public static void main(String[] args) {
        SpringApplication.run(AlertManagerApplication.clreplaced, args);
    }
}

17 View Source File : Application.java
License : Eclipse Public License 1.0
Project Creator : rhwayfun

@SpringBootApplication
@EnableRetry
public clreplaced Application implements EmbeddedServletContainerCustomizer {

    /**
     * Logger
     */
    private static Logger log = LoggerFactory.getLogger(Application.clreplaced);

    public static void main(String[] args) {
        try {
            System.setProperty("server.port", String.valueOf(9999));
            SpringApplication.run(Application.clreplaced, args);
            log.info("Application start success.");
        } catch (Exception e) {
            log.error("Application start failed.", e);
        }
    }

    @Override
    public void customize(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) {
        if (configurableEmbeddedServletContainer instanceof JettyEmbeddedServletContainerFactory) {
            final JettyEmbeddedServletContainerFactory jetty = (JettyEmbeddedServletContainerFactory) configurableEmbeddedServletContainer;
            final JettyServerCustomizer customizer = server -> {
                Handler handler = server.getHandler();
                WebAppContext webAppContext = (WebAppContext) handler;
                webAppContext.setBaseResource(Resource.newClreplacedPathResource("webapp"));
            };
            jetty.addServerCustomizers(customizer);
        }
    }
}

17 View Source File : WSRadarCovidConfig.java
License : Mozilla Public License 2.0
Project Creator : RadarCOVID

@Configuration
@Profile({ "radarcovid-local", "radarcovid-pre", "radarcovid-pro" })
@EnableRetry
public clreplaced WSRadarCovidConfig extends WSBaseConfig {

    @Value("${datasource.username}")
    String dataSourceUser;

    @Value("${datasource.preplacedword}")
    String dataSourcePreplacedword;

    @Value("${datasource.url}")
    String dataSourceUrl;

    @Value("${datasource.schema:}")
    String dataSourceSchema;

    @Value("${datasource.driverClreplacedName}")
    String dataSourceDriver;

    @Value("${datasource.failFast}")
    String dataSourceFailFast;

    @Value("${datasource.minimumIdle}")
    int dataSourceMinimumIdle;

    @Value("${datasource.maximumPoolSize}")
    int dataSourceMaximumPoolSize;

    @Value("${datasource.maxLifetime}")
    int dataSourceMaxLifetime;

    @Value("${datasource.idleTimeout}")
    int dataSourceIdleTimeout;

    @Value("${datasource.connectionTimeout}")
    int dataSourceConnectionTimeout;

    @Value("${ws.ecdsa.credentials.privateKey:}")
    private String privateKey;

    @Value("${ws.ecdsa.credentials.publicKey:}")
    public String publicKey;

    @Bean(destroyMethod = "close")
    public DataSource dataSource() {
        HikariConfig config = new HikariConfig();
        Properties props = new Properties();
        props.put("url", dataSourceUrl);
        props.put("user", dataSourceUser);
        props.put("preplacedword", dataSourcePreplacedword);
        if (StringUtils.isNotEmpty(dataSourceSchema))
            config.setSchema(dataSourceSchema);
        config.setDataSourceProperties(props);
        config.setDataSourceClreplacedName(dataSourceDriver);
        config.setMinimumIdle(dataSourceMinimumIdle);
        config.setMaximumPoolSize(dataSourceMaximumPoolSize);
        config.setMaxLifetime(dataSourceMaxLifetime);
        config.setIdleTimeout(dataSourceIdleTimeout);
        config.setConnectionTimeout(dataSourceConnectionTimeout);
        return new HikariDataSource(config);
    }

    @Bean
    @ConditionalOnProperty(name = "datasource.flyway.load", havingValue = "true", matchIfMissing = true)
    @Override
    public Flyway flyway() {
        Flyway flyWay = Flyway.configure().dataSource(dataSource()).locations("clreplacedpath:/db/migration/pgsql").load();
        flyWay.migrate();
        return flyWay;
    }

    @Bean
    @ConditionalOnProperty(name = "datasource.flyway.load", havingValue = "false", matchIfMissing = true)
    public Flyway flywayNoLoad() {
        Flyway flyWay = Flyway.configure().dataSource(dataSource()).locations("clreplacedpath:/db/migration/pgsql").load();
        return flyWay;
    }

    @Override
    public String getDbType() {
        return "pgsql";
    }

    @Bean
    KeyVault keyVault() {
        var privateKey = getPrivateKey();
        var publicKey = getPublicKey();
        if (privateKey.isEmpty() || publicKey.isEmpty()) {
            var kp = super.getKeyPair(algorithm);
            var gaenKp = new KeyVault.KeyVaultKeyPair("gaen", kp);
            var nextDayJWTKp = new KeyVault.KeyVaultKeyPair("nextDayJWT", kp);
            var hashFilterKp = new KeyVault.KeyVaultKeyPair("hashFilter", kp);
            return new KeyVault(gaenKp, nextDayJWTKp, hashFilterKp);
        }
        var gaen = new KeyVault.KeyVaultEntry("gaen", getPrivateKey(), getPublicKey(), "EC");
        var nextDayJWT = new KeyVault.KeyVaultEntry("nextDayJWT", getPrivateKey(), getPublicKey(), "EC");
        var hashFilter = new KeyVault.KeyVaultEntry("hashFilter", getPrivateKey(), getPublicKey(), "EC");
        try {
            return new KeyVault(gaen, nextDayJWT, hashFilter);
        } catch (PrivateKeyNoSuitableEncodingFoundException | PublicKeyNoSuitableEncodingFoundException e) {
            throw new RuntimeException(e);
        }
    }

    String getPrivateKey() {
        return new String(Base64.getDecoder().decode(privateKey));
    }

    String getPublicKey() {
        return new String(Base64.getDecoder().decode(publicKey));
    }

    @Profile("debug-sedia")
    @Configuration
    public static clreplaced DebugConfig {

        @Value("${ws.exposedlist.debug.releaseBucketDuration: 86400000}")
        long releaseBucketDuration;

        @Value("${ws.exposedlist.debug.requestTime: 1500}")
        long requestTime;

        @Autowired
        KeyVault keyVault;

        @Autowired
        Flyway flyway;

        @Autowired
        DataSource dataSource;

        @Autowired
        ProtoSignature gaenSigner;

        @Autowired
        ValidateRequest backupValidator;

        @Autowired
        ValidationUtils gaenValidationUtils;

        @Autowired
        Environment env;

        protected boolean isProd() {
            return Arrays.asList(env.getActiveProfiles()).contains("radarcovid-prod");
        }

        protected boolean isDev() {
            return Arrays.asList(env.getActiveProfiles()).contains("radarcovid-local");
        }

        @Bean
        DebugGAENDataService dataService() {
            String dbType = "";
            if (isProd()) {
                dbType = "pgsql";
            } else if (isDev()) {
                dbType = "hsqldb";
            }
            return new DebugJDBCGAENDataServiceImpl(dbType, dataSource);
        }

        @Bean
        public InsertManager insertManagerDebug() {
            var manager = InsertManager.getDebugInsertManager(dataService(), gaenValidationUtils);
            manager.addFilter(new replacedertKeyFormat(gaenValidationUtils));
            manager.addFilter(new RemoveKeysFromFuture());
            manager.addFilter(new EnforceRetentionPeriod(gaenValidationUtils));
            manager.addFilter(new RemoveFakeKeys());
            manager.addFilter(new EnforceValidRollingPeriod());
            return manager;
        }

        @Bean
        DebugController debugController() {
            return new DebugController(dataService(), gaenSigner, backupValidator, insertManagerDebug(), Duration.ofMillis(releaseBucketDuration), Duration.ofMillis(requestTime));
        }
    }
}

17 View Source File : StartupService.java
License : Apache License 2.0
Project Creator : onap

@Service
@EnableRetry
public clreplaced StartupService {

    private static final Logger logger = LoggerFactory.getLogger(StartupService.clreplaced);

    private final String vnfmDefaultEndpoint;

    private final AaiConnection aaiConnection;

    public StartupService(final ConfigProperties configProperties, final AaiConnection aaiConnection) {
        this.vnfmDefaultEndpoint = configProperties.getVnfmDefaultEndpoint();
        this.aaiConnection = aaiConnection;
    }

    @Retryable(value = { Exception.clreplaced }, maxAttempts = 5, backoff = @Backoff(delay = 5000, multiplier = 2))
    public List<EsrSystemInfo> receiveVnfm() throws VeVnfmException {
        return aaiConnection.receiveVnfm();
    }

    @Recover
    public List<EsrSystemInfo> recoverReceiveVnfm(final Throwable t) {
        logger.warn("Connection to AAI failed");
        final EsrSystemInfo info = new EsrSystemInfo();
        info.setServiceUrl(vnfmDefaultEndpoint);
        logger.warn("This EsrSystemInfo is used by default: {}", info);
        return Collections.singletonList(info);
    }
}

17 View Source File : GatewayManagerRestClient.java
License : GNU General Public License v2.0
Project Creator : futurewei-cloud

@Configuration
@EnableRetry
@Slf4j
public clreplaced GatewayManagerRestClient extends AbstractRestClient {

    @Value("${microservices.zeta.management.url:\"\"}")
    private String zetaManagerUrl;

    @Value("${microservices.dpm.service.url:\"\"}")
    private String dpmManagerUrl;

    public ZetaGatewayIpJson createVPCInZetaGateway(Object args) throws Exception {
        String url = zetaManagerUrl + "/vpcs";
        VpcInfoSub vpcInfoSub = (VpcInfoSub) args;
        ObjectMapper Obj = new ObjectMapper();
        String jsonStr = Obj.writeValuereplacedtring(vpcInfoSub);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEnreplacedy<String> request = new HttpEnreplacedy<>(jsonStr, headers);
        Object response = restTemplate.postForObject(url, request, Object.clreplaced);
        ZetaGatewayIpJson result = new ZetaGatewayIpJson();
        if (response != null) {
            ObjectMapper mapper = new ObjectMapper();
            result = mapper.convertValue(response, new TypeReference<ZetaGatewayIpJson>() {
            });
        }
        return result;
    }

    public void deleteVPCInZetaGateway(String vpcId) throws Exception {
        String url = zetaManagerUrl + "/vpcs/" + vpcId;
        restTemplate.delete(url);
    }

    @Retryable(maxAttempts = 4)
    public String createDPMCacheGateway(Object args1, Object args2) throws Exception {
        log.info("send request to create DPM GatewayInfo cache");
        String projectId = (String) args1;
        GatewayInfo gatewayInfo = (GatewayInfo) args2;
        String url = dpmManagerUrl + "/project/" + projectId + "/gatewayinfo";
        HttpEnreplacedy<GatewayInfoJson> request = new HttpEnreplacedy<>(new GatewayInfoJson(gatewayInfo));
        return restTemplate.postForObject(url, request, String.clreplaced);
    }

    public void updateDPMCacheGateway(String projectId, GatewayInfo gatewayInfo) throws Exception {
        String url = dpmManagerUrl + "/project/" + projectId + "/gatewayinfo/" + gatewayInfo.getResourceId();
        HttpEnreplacedy<GatewayInfoJson> request = new HttpEnreplacedy<>(new GatewayInfoJson(gatewayInfo));
        restTemplate.put(url, request);
    }

    public void deleteDPMCacheGateway(String projectId, String vpcId) {
        String url = dpmManagerUrl + "/project/" + projectId + "/gatewayinfo/" + vpcId;
        restTemplate.delete(url);
    }
}

17 View Source File : Application.java
License : The Unlicense
Project Creator : diegopacheco

@Configuration
@EnableRetry
@SpringBootApplication
@ComponentScan(basePackages = "com")
public clreplaced Application implements CommandLineRunner {

    @Bean
    public SimpleService service() {
        return new SimpleService();
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.clreplaced, args);
    }

    @Override
    public void run(String... args) throws Exception {
        service().service();
        RetryTemplate template = new RetryTemplate();
        TimeoutRetryPolicy policy = new TimeoutRetryPolicy();
        policy.setTimeout(30000L);
        template.setRetryPolicy(policy);
        String result = template.execute(new RetryCallback<String, Exception>() {

            public String doWithRetry(RetryContext context) {
                return "Works";
            }
        });
        System.out.println("works: " + result);
    }
}

17 View Source File : DataSourceConfiguration.java
License : Apache License 2.0
Project Creator : Decathlon

/**
 * When starting ARA server at the same time as the database (with eg. Docker Compose), make sure the application waits
 * for a live database connection during a few seconds before failing to start up.
 */
@Configuration
@EnableRetry
@ComponentScan("com.decathlon.ara.domain")
@ComponentScan("com.decathlon.ara.repository")
@ComponentScan("com.decathlon.ara.configuration")
public clreplaced DataSourceConfiguration {

    @Bean
    public BeanPostProcessor dataSourceWrapper() {
        return new RetryableDataSourceBeanPostProcessor();
    }

    @Order(Ordered.HIGHEST_PRECEDENCE)
    private clreplaced RetryableDataSourceBeanPostProcessor implements BeanPostProcessor {

        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) {
            if (bean instanceof DataSource) {
                bean = new RetryableDataSource((DataSource) bean);
            }
            return bean;
        }

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) {
            return bean;
        }
    }
}

17 View Source File : PlatformZipkinApplication.java
License : GNU Lesser General Public License v2.1
Project Creator : abixen

@EnableRetry
@SpringBootApplication
@EnableZipkinStreamServer
public clreplaced PlatformZipkinApplication {

    public static void main(String[] args) {
        SpringApplication.run(PlatformZipkinApplication.clreplaced, args);
    }
}

17 View Source File : PlatformWebClientApplication.java
License : GNU Lesser General Public License v2.1
Project Creator : abixen

@EnableRetry
@EnableZuulProxy
@EnableEurekaClient
@EnableFeignClients(basePackages = { "com.abixen.platform.client.web" })
@EnableCircuitBreaker
@SpringBootApplication
public clreplaced PlatformWebClientApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(PlatformWebClientApplication.clreplaced);
    }

    public static void main(String[] args) {
        SpringApplication.run(PlatformWebClientApplication.clreplaced, args);
    }
}

@Profile({ DEV, DOCKER })
@Configuration
@EnableRetry
@EnableRedisHttpSession
@EnableEurekaClient
@EnableCircuitBreaker
public clreplaced CoreCloudIntegrationConfiguration {
}

@EnableRetry
@SpringBootApplication
@EnableRedisHttpSession
@EnableEurekaClient
@EnableCircuitBreaker
@EnableFeignClients(basePackages = { BusinessIntelligenceServicePackages.CLIENT })
public clreplaced BusinessIntelligenceServiceApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(BusinessIntelligenceServiceApplication.clreplaced);
    }

    public static void main(String[] args) {
        SpringApplication.run(BusinessIntelligenceServiceApplication.clreplaced, args);
    }
}

16 View Source File : SessionService.java
License : MIT License
Project Creator : sinnerschrader

/**
 * Manage all sessions
 * NOTE: there can be multiple sessions
 * for one username
 *
 * @author torree
 */
@Service
@EnableRetry
public clreplaced SessionService {

    private static final Logger logger = LoggerFactory.getLogger(SessionService.clreplaced);

    // Minutes of inactivity before the session is destroyed
    @Value("${sessionExpireDuration}")
    private int expireDuration;

    @Value("${oAuthUrl}")
    private String oAuthUrl;

    private final SessionRepository sessionRepo;

    private final UserRepository UserRepository;

    private final LdapService ldapService;

    @Autowired
    public SessionService(SessionRepository sessionRepo, UserRepository UserRepository, LdapService ldapService) {
        this.sessionRepo = sessionRepo;
        this.UserRepository = UserRepository;
        this.ldapService = ldapService;
    }

    private boolean isTokenInProxy(String token) {
        try {
            var authUrl = new URL(oAuthUrl);
            var connection = (HttpURLConnection) authUrl.openConnection();
            connection.addRequestProperty("Cookie", "_oauth2_proxy=" + token);
            connection.connect();
            var responseCode = connection.getResponseCode();
            connection.disconnect();
            logger.debug("Successfully checked token with oauth proxy, result {}", responseCode);
            return responseCode == HttpStatus.ACCEPTED.value();
        } catch (IOException e) {
            logger.error("Failed to check session token at oauth Proxy");
            return false;
        }
    }

    @Retryable(include = OptimisticLockingFailureException.clreplaced, maxAttempts = 10)
    private boolean isTokenInDB(String token) {
        return sessionRepo.findByToken(token) != null;
    }

    public String extractMail(String token) {
        return new String(Base64.getDecoder().decode(token.split("\\|")[0]));
    }

    @Retryable(include = OptimisticLockingFailureException.clreplaced, maxAttempts = 10)
    public User getUserByToken(String token) {
        var session = getSession(token);
        if (session == null) {
            return null;
        }
        var user = UserRepository.findByMail(session.getMail());
        if (user == null) {
            user = ldapService.createUserByMail(extractMail(token));
        }
        return user;
    }

    @Retryable(include = OptimisticLockingFailureException.clreplaced, maxAttempts = 10)
    private Session getSession(String token) {
        logger.debug("Getting session for token {}", token);
        if (isTokenInDB(token)) {
            logger.debug("Successfully found token {} in DB", token);
            return sessionRepo.findByToken(token);
        }
        if (isTokenInProxy(token)) {
            logger.debug("Successfully validated token {} with proxy", token);
            if (UserRepository.findByMail(extractMail(token)) == null) {
                // user not in db yet, will create
                var newUser = ldapService.createUserByMail(extractMail(token));
                UserRepository.insert(newUser);
                logger.info("Successfully created new user {}", newUser.getId());
            }
            // session not in DB, but in proxy -> create new session and revalidate old ones
            refreshUserSessions(extractMail(token));
            var newSession = new Session(token);
            sessionRepo.insert(newSession);
            return newSession;
        }
        logger.debug("Failed to get Session for token {}: no session found", token);
        return null;
    }

    @Retryable(include = OptimisticLockingFailureException.clreplaced, maxAttempts = 10)
    private void refreshUserSessions(String mail) {
        var cleanables = sessionRepo.findByMail(mail).stream().filter(session -> !isTokenInProxy(session.getToken())).collect(Collectors.toList());
        logger.debug("will remove {} sessions for mail {}", cleanables.size(), mail);
        sessionRepo.deleteAll(cleanables);
    }

    @Retryable(include = OptimisticLockingFailureException.clreplaced, maxAttempts = 10)
    public boolean checkToken(String token, String userId) {
        logger.debug("checking token {} for user {}", token, userId);
        return getSession(token) != null && getUserByToken(token) != null && getUserByToken(token).getId().equals(userId);
    }

    public boolean checkTokenRole(String token, Role role) {
        logger.debug("checking token {} for role {}", token, role.toString());
        return getSession(token) != null && getUserByToken(token).getLdapDetails().getRole() == role;
    }

    @Retryable(include = OptimisticLockingFailureException.clreplaced, maxAttempts = 10)
    public void cleanUp() {
        var cleanables = sessionRepo.findAll().stream().filter(session -> !isTokenInProxy(session.getToken()) || UserRepository.findByMail(session.getMail()) == null).collect(Collectors.toList());
        logger.info("Starting session cleanup, will remove {} sessions", cleanables.size());
        sessionRepo.deleteAll(cleanables);
    }
}

16 View Source File : AemOrchestrator.java
License : Apache License 2.0
Project Creator : shinesolutions

@SpringBootApplication
@ComponentScan
@EnableRetry
public clreplaced AemOrchestrator {

    private final static Logger logger = LoggerFactory.getLogger(AemOrchestrator.clreplaced);

    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext context = SpringApplication.run(AemOrchestrator.clreplaced, args);
        // Need to wait for Author ELB is be in a healthy state before reading messages from the SQS queue
        ResourceReadyChecker resourceReadyChecker = context.getBean(ResourceReadyChecker.clreplaced);
        boolean isStartupOk = false;
        if (resourceReadyChecker.isResourcesReady()) {
            OrchestratorMessageListener messageReceiver = context.getBean(OrchestratorMessageListener.clreplaced);
            try {
                messageReceiver.start();
                isStartupOk = true;
            } catch (Exception e) {
                logger.error("Failed to start message receiver", e);
            }
        }
        if (isStartupOk) {
            logger.info("AEM Orchestrator started");
        } else {
            logger.info("Failed to start AEM Orchestrator");
            // Exit the application
            context.close();
        }
    }
}

16 View Source File : BookmarksApplication.java
License : MIT License
Project Creator : PacktPublishing

@SpringBootApplication
@EnableCircuitBreaker
@EnableRetry
@Slf4j
public clreplaced BookmarksApplication {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(BookmarksApplication.clreplaced);
        if (noActiveProfiles(args)) {
            app.setAdditionalProfiles("dev", System.getProperty("user.name"));
        }
        ConfigurableApplicationContext context = app.run(args);
        log.info("");
        log.info("#######################");
        log.info("##### Initialized! ####");
        log.info("#######################");
        log.info(" go to: http://localhost:8080");
    }

    private static boolean noActiveProfiles(String[] args) {
        return new StandardServletEnvironment().getActiveProfiles().length == 0 && Arrays.stream(args).noneMatch(param -> param.startsWith("--spring.profiles.active"));
    }
}

16 View Source File : CommonConfiguration.java
License : GNU General Public License v3.0
Project Creator : JuniperBot

@EnableAsync
@EnableRetry
@EnableScheduling
@EnableAspectJAutoProxy
@EnableTransactionManagement
@EnreplacedyScan("ru.juniperbot")
@EnableJpaRepositories("ru.juniperbot")
@ComponentScan("ru.juniperbot")
@Import({ MBeanConfiguration.clreplaced, RabbitConfiguration.clreplaced })
@Configuration
public clreplaced CommonConfiguration {

    public final static String SCHEDULER = "taskScheduler";

    @Autowired
    private CommonProperties commonProperties;

    @Bean(SCHEDULER)
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(commonProperties.getExecution().getSchedulerPoolSize());
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        scheduler.setAwaitTerminationSeconds(30);
        scheduler.setThreadNamePrefix(SCHEDULER);
        return scheduler;
    }

    @Primary
    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(commonProperties.getExecution().getCorePoolSize());
        executor.setMaxPoolSize(commonProperties.getExecution().getMaxPoolSize());
        executor.setThreadNamePrefix("taskExecutor");
        return executor;
    }

    @Primary
    @Bean("cacheManager")
    public JbCacheManager cacheManager() {
        return new JbCacheManagerImpl();
    }

    @Bean
    public MessageSource messageSource() {
        return new JbMessageSource();
    }

    @Bean
    public ThreadPoolTaskExecutorMBean taskExecutorMBean() {
        return new ThreadPoolTaskExecutorMBean("Spring TaskExecutor", (ThreadPoolTaskExecutor) taskExecutor());
    }
}

16 View Source File : DataServiceWithRetry.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : intsmaze

/**
 * github地址: https://github.com/intsmaze
 * 博客地址:https://www.cnblogs.com/intsmaze/
 * 出版书籍《深入理解Flink核心设计与实践原理》
 *
 * @auther: intsmaze(刘洋)
 * @date: 2020/10/15 18:33
 */
@Component
@EnableRetry
public clreplaced DataServiceWithRetry {

    @Autowired
    private DataService dataService;

    public static Logger LOG = LoggerFactory.getLogger(DataServiceWithRetry.clreplaced);

    int makeError = 1;

    /**
     * github地址: https://github.com/intsmaze
     * 博客地址:https://www.cnblogs.com/intsmaze/
     * 出版书籍《深入理解Flink核心设计与实践原理》
     * 重试3次还失败抛出异常,delay第一次多少秒间隔重试,multiplier递增倍数(即下次间隔是上次的多少倍)
     * @auther: intsmaze(刘洋)
     * @date: 2020/10/15 18:33
     */
    @Retryable(value = Exception.clreplaced, maxAttempts = 3, backoff = @Backoff(delay = 2000L, multiplier = 1.5))
    public void insertFlow(FlowData flowData) throws Exception {
        LOG.info("insertFlow method:{}", flowData.toString());
        makeError++;
        if (makeError % 5 == 1) {
            LOG.info("throw new Exception:{}", flowData.toString());
            throw new Exception("手动抛出异常..");
        }
        dataService.insertFlow(flowData);
    }

    /**
     * github地址: https://github.com/intsmaze
     * 博客地址:https://www.cnblogs.com/intsmaze/
     * 出版书籍《深入理解Flink核心设计与实践原理》
     * 重试3次还失败抛出异常,delay第一次多少秒间隔重试,multiplier递增倍数(即下次间隔是上次的多少倍)
     * @auther: intsmaze(刘洋)
     * @date: 2020/10/15 18:33
     */
    @Retryable(value = Exception.clreplaced, maxAttempts = 3, backoff = @Backoff(delay = 2000L, multiplier = 1.5))
    @Cacheable(value = "FlowData.findUUID", key = "#flowData.subTesreplacedem+'-'+#flowData.billNumber+'-'+#flowData.barcode")
    public String findUUID(FlowData flowData) {
        LOG.info("执行findUUID方法");
        return dataService.findUUID(flowData);
    }
}

16 View Source File : ServiceCustomerApplication.java
License : MIT License
Project Creator : coderqianlq

@EnableRetry
@EnableHystrix
@EnableDiscoveryClient
@EnableFeignClients(basePackages = { "com.qianlq.support" })
@SpringBootApplication(scanBasePackages = { "com.qianlq.support", "com.qianlq.customer" })
public clreplaced ServiceCustomerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceCustomerApplication.clreplaced, args);
    }
}

16 View Source File : GatewayApplication.java
License : Apache License 2.0
Project Creator : choerodon

/**
 * 运行主类
 *
 * @author flyleft
 */
@EnableRetry
@EnableCaching
@EnableZuulProxy
@EnableEurekaClient
@EnableDiscoveryClient
@SpringBootApplication(exclude = SecurityAutoConfiguration.clreplaced)
public clreplaced GatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.clreplaced, args);
    }
}

16 View Source File : WebContentServiceApplication.java
License : GNU Lesser General Public License v2.1
Project Creator : abixen

@EnableRetry
@SpringBootApplication
@EnableRedisHttpSession
@EnableEurekaClient
@EnableCircuitBreaker
@EnableFeignClients(basePackages = { WebContentServicePackages.CLIENT })
public clreplaced WebContentServiceApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(WebContentServiceApplication.clreplaced);
    }

    public static void main(String[] args) {
        SpringApplication.run(WebContentServiceApplication.clreplaced, args);
    }
}

@EnableRetry
@Configuration
@ComponentScan
@EnableAutoConfiguration
@SpringBootApplication
@EnableHystrixDashboard
@EnableTurbine
@EnableEurekaClient
public clreplaced PlatformHystrixDashboardApplication {

    public static void main(String[] args) {
        SpringApplication.run(PlatformHystrixDashboardApplication.clreplaced, args);
    }
}

15 View Source File : QualitisServer.java
License : Apache License 2.0
Project Creator : WeBankFinTech

/**
 * @author howeye
 */
@SpringBootApplication(scanBasePackages = "com.webank.wedatasphere.qualitis")
@EnableJpaRepositories(basePackages = "com.webank.wedatasphere.qualitis")
@EnreplacedyScan(basePackages = "com.webank.wedatasphere.qualitis")
@ServletComponentScan(basePackages = "com.webank.wedatasphere.qualitis")
@EnableRetry
public clreplaced QualitisServer {

    public static void main(String[] args) {
        SpringApplication.run(QualitisServer.clreplaced, args);
    }
}

15 View Source File : UserService.java
License : MIT License
Project Creator : sinnerschrader

/**
 * Service handling user management
 *
 * @author torree
 */
@Service
@EnableRetry
public clreplaced UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserService.clreplaced);

    private final UserRepository userRepository;

    private final LdapService ldapService;

    private final SkillService skillService;

    private final SkillRepository skillRepository;

    private final FitnessScoreProperties fitnessScoreProperties;

    @Value("${maxLevelValue}")
    private int maxLevelValue;

    @Autowired
    public UserService(UserRepository userRepository, LdapService ldapService, SkillService skillService, SkillRepository skillRepository, FitnessScoreProperties fitnessScoreProperties) {
        this.userRepository = userRepository;
        this.ldapService = ldapService;
        this.skillService = skillService;
        this.skillRepository = skillRepository;
        this.fitnessScoreProperties = fitnessScoreProperties;
    }

    public List<User> getUsers(SkillSearchResult skillSearch, String company, String location) throws IllegalArgumentException {
        List<User> candidates;
        if (skillSearch.isInputEmpty()) {
            candidates = userRepository.findAll();
        } else {
            var skillNames = skillSearch.mappedSkills().stream().map(Skill::getName).collect(Collectors.toList());
            candidates = userRepository.findBySkills(skillNames).stream().peek(p -> p.setFitnessScore(skillSearch.mappedSkills(), fitnessScoreProperties)).sorted(Comparator.comparingDouble(User::getFitnessScoreValue).reversed()).collect(Collectors.toList());
        }
        // sync needed to search for location and company
        if (!StringUtils.isEmpty(location) || !StringUtils.isEmpty(company)) {
            candidates = ldapService.syncUsers(candidates, false);
            candidates = filterByCompany(candidates, company);
            candidates = filterByLocation(candidates, location);
        }
        logger.debug("Successfully found {} users for search [{}]", candidates.size(), skillSearch.mappedSkills().stream().map(Skill::getName).collect(Collectors.joining(", ")));
        return candidates;
    }

    private List<User> filterByLocation(List<User> unfiltered, String location) {
        if (StringUtils.isEmpty(location)) {
            return unfiltered;
        }
        return unfiltered.stream().filter(user -> user.getLdapDetails().getLocation().equals(location)).collect(Collectors.toList());
    }

    private List<User> filterByCompany(List<User> unfiltered, String company) {
        if (StringUtils.isEmpty(company)) {
            return unfiltered;
        }
        return unfiltered.stream().filter(user -> user.getLdapDetails().getCompany().equals(company)).collect(Collectors.toList());
    }

    public User getUser(String id) {
        var user = userRepository.findByIdIgnoreCase(id);
        if (user == null) {
            logger.debug("Failed to find user {}: not found", id);
            throw new UserNotFoundException("user not found");
        }
        if (user.getLdapDetails() == null) {
            ldapService.syncUser(user);
        }
        logger.debug("Successfully found user {}", id);
        return user;
    }

    @Retryable(include = OptimisticLockingFailureException.clreplaced, maxAttempts = 10)
    public void updateSkills(String username, String skillName, int skillLevel, int willLevel, boolean mentor) throws UserNotFoundException, SkillNotFoundException, EmptyArgumentException {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(skillName)) {
            logger.debug("Failed to modify skills: username or skillName empty");
            throw new EmptyArgumentException("arguments must not be empty or null");
        }
        var user = userRepository.findByIdIgnoreCase(username);
        if (user == null) {
            logger.debug("Failed to add/modify {}'s skills: user not found", username);
            throw new UserNotFoundException("user not found");
        }
        var skill = skillRepository.findByName(skillName);
        if (skill == null || skill.isHidden()) {
            logger.debug("Failed to add/modify {}'s skill {}: skill not found or hidden", username, skillName);
            throw new SkillNotFoundException("skill not found/hidden");
        }
        if (!isValidLevelConfiguration(skillLevel, willLevel)) {
            logger.debug("Failed to add/modify {}'s skill {}: illegal levels {}/{}", username, skillName, skillLevel, willLevel);
            throw new IllegalLevelConfigurationException("Invalid Skill-/WillLevel Configuration");
        }
        user.addUpdateSkill(skillName, skillLevel, willLevel, skillService.isHidden(skillName), mentor);
        userRepository.save(user);
        logger.info("Successfully updated {}'s skill {}", username, skillName);
    }

    @Retryable(include = OptimisticLockingFailureException.clreplaced, maxAttempts = 10)
    public void removeSkills(String username, String skillName) throws UserNotFoundException, SkillNotFoundException, EmptyArgumentException {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(skillName)) {
            logger.debug("Failed to modify skills: username or skillName empty");
            throw new EmptyArgumentException("arguments must not be empty or null");
        }
        var user = userRepository.findByIdIgnoreCase(username);
        if (user == null) {
            logger.debug("Failed to remove {}'s skills: user not found", username);
            throw new UserNotFoundException("user not found");
        }
        if (skillRepository.findByName(skillName) == null) {
            logger.debug("Failed to remove {}'s skill {}: skill not found", username, skillName);
            throw new SkillNotFoundException("skill not found");
        }
        user.removeSkill(skillName);
        userRepository.save(user);
    }

    private boolean isValidLevelConfiguration(int skillLevel, int willLevel) {
        // Both levels must be between 0 and maxLevel
        // at least one level must be 1 or above (see [SKILLWILL-30])
        final boolean isValidSkillLevel = 0 <= skillLevel && skillLevel <= maxLevelValue;
        final boolean isValidWillLevel = 0 <= willLevel && willLevel <= maxLevelValue;
        final boolean isOneGreaterZero = skillLevel > 0 || willLevel > 0;
        return isValidSkillLevel && isValidWillLevel && isOneGreaterZero;
    }

    public List<User> getSimilar(String username, Integer count) throws UserNotFoundException {
        var toSearch = userRepository.findAll();
        var user = toSearch.stream().filter(p -> p.getId().equals(username)).findAny();
        if (!user.isPresent()) {
            logger.debug("Failed to get users similar to {}: user not found", username);
            throw new UserNotFoundException("user not found");
        }
        return ldapService.syncUsers(UserSimilarityUtils.findSimilar(user.get(), toSearch, count), false);
    }

    public Role getRole(String userId) {
        var user = userRepository.findByIdIgnoreCase(userId);
        if (user == null) {
            throw new UserNotFoundException("user not found");
        }
        return user.getLdapDetails().getRole();
    }
}

15 View Source File : PaasCloudTpcApplication.java
License : Apache License 2.0
Project Creator : paascloud

/**
 * The clreplaced Paas cloud mdc application.
 *
 * @author [email protected]
 */
@EnableRetry
@EnableCaching
@EnableHystrix
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
@EnableTransactionManagement
public clreplaced PaasCloudTpcApplication {

    /**
     * The entry point of application.
     *
     * @param args the input arguments
     */
    public static void main(String[] args) {
        SpringApplication.run(PaasCloudTpcApplication.clreplaced, args);
    }

    @Bean
    public SpringLiquibase springLiquibase(DataSource dataSource) {
        SpringLiquibase springLiquibase = new SpringLiquibase();
        springLiquibase.setDataSource(dataSource);
        springLiquibase.setChangeLog("clreplacedpath:/liquibase/index.xml");
        return springLiquibase;
    }
}

15 View Source File : PaasCloudOpcApplication.java
License : Apache License 2.0
Project Creator : paascloud

/**
 * The clreplaced Paas cloud opc application.
 *
 * @author [email protected]
 */
@EnableRetry
@EnableCaching
@EnableHystrix
@EnableSwagger2
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
@EnableTransactionManagement
public clreplaced PaasCloudOpcApplication {

    /**
     * The entry point of application.
     *
     * @param args the input arguments
     */
    public static void main(String[] args) {
        SpringApplication.run(PaasCloudOpcApplication.clreplaced, args);
    }

    /**
     * Get kaptcha bean default kaptcha.
     *
     * @return the default kaptcha
     */
    @Bean(name = "captchaProducer")
    public DefaultKaptcha getKaptchaBean() {
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "yes");
        properties.setProperty("kaptcha.border.color", "105,179,90");
        properties.setProperty("kaptcha.textproducer.font.color", "blue");
        properties.setProperty("kaptcha.image.width", "125");
        properties.setProperty("kaptcha.image.height", "45");
        properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

    @Bean
    public SpringLiquibase springLiquibase(DataSource dataSource) {
        SpringLiquibase springLiquibase = new SpringLiquibase();
        springLiquibase.setDataSource(dataSource);
        springLiquibase.setChangeLog("clreplacedpath:/liquibase/index.xml");
        return springLiquibase;
    }
}

15 View Source File : CircusTrain.java
License : Apache License 2.0
Project Creator : HotelsDotCom

@SpringBootApplication
@EnableRetry
@EnableConfigurationProperties
@ComponentScan(basePackages = { "com.hotels.bdp.circustrain.avro", "com.hotels.bdp.circustrain.aws", "com.hotels.bdp.circustrain.context", "com.hotels.bdp.circustrain.core", "com.hotels.bdp.circustrain.distcpcopier", "com.hotels.bdp.circustrain.gcp", "com.hotels.bdp.circustrain.hive.view.transformation", "com.hotels.bdp.circustrain.housekeeping", "com.hotels.bdp.circustrain.metrics.conf", "com.hotels.bdp.circustrain.s3mapreducecpcopier", "com.hotels.bdp.circustrain.s3s3copier" })
public clreplaced CircusTrain {

    private static final Logger LOG = LoggerFactory.getLogger(CircusTrain.clreplaced);

    public static void main(String[] args) throws Exception {
        // below is output *before* logging is configured so will appear on console
        logVersionInfo();
        int exitCode = -1;
        try {
            String defaultModules = Joiner.on(",").join(Modules.REPLICATION, Modules.HOUSEKEEPING);
            exitCode = SpringApplication.exit(new SpringApplicationBuilder(CircusTrain.clreplaced).properties("spring.config.location:${config:null}").properties("spring.profiles.active:${modules:" + defaultModules + "}").properties("instance.home:${user.home}").properties("instance.name:${source-catalog.name}_${replica-catalog.name}").properties("jasypt.encryptor.preplacedword:${preplacedword:null}").properties("housekeeping.schema-name:circus_train").registerShutdownHook(true).initializers(new ExtensionInitializer()).listeners(new ConfigFileValidationApplicationListener()).build().run(args));
        } catch (ConfigFileValidationException e) {
            LOG.error(e.getMessage(), e);
            printCircusTrainHelp(e.getErrors());
        } catch (BeanCreationException e) {
            LOG.error(e.getMessage(), e);
            Throwable mostSpecificCause = e.getMostSpecificCause();
            if (mostSpecificCause instanceof BindException) {
                printCircusTrainHelp(((BindException) mostSpecificCause).getAllErrors());
            }
        }
        System.exit(exitCode);
    }

    private static void printCircusTrainHelp(List<ObjectError> allErrors) {
        System.out.println(new CircusTrainHelp(allErrors));
    }

    CircusTrain() {
        // below is output *after* logging is configured so will appear in log file
        logVersionInfo();
    }

    private static void logVersionInfo() {
        ManifestAttributes manifestAttributes = new ManifestAttributes(CircusTrain.clreplaced);
        LOG.info("{}", manifestAttributes);
    }

    @Bean
    LocomotiveListener locomotiveListener(List<LocomotiveListener> listeners) {
        if (listeners == null) {
            listeners = Collections.emptyList();
        }
        return new CompositeLocomotiveListener(listeners);
    }

    @Bean
    SourceCatalogListener sourceCatalogListener(List<SourceCatalogListener> listeners) {
        if (listeners == null) {
            listeners = Collections.emptyList();
        }
        return new CompositeSourceCatalogListener(listeners);
    }

    @Bean
    ReplicaCatalogListener replicaCatalogListener(List<ReplicaCatalogListener> listeners) {
        if (listeners == null) {
            listeners = Collections.emptyList();
        }
        return new CompositeReplicaCatalogListener(listeners);
    }

    @Bean
    TableReplicationListener tableReplicationListener(List<TableReplicationListener> listeners) {
        if (listeners == null) {
            listeners = Collections.emptyList();
        }
        return new CompositeTableReplicationListener(listeners);
    }

    @Bean
    CopierListener copierListener(List<CopierListener> listeners) {
        if (listeners == null) {
            listeners = Collections.emptyList();
        }
        return new CompositeCopierListener(listeners);
    }

    @Profile({ Modules.REPLICATION })
    @Bean
    TableTransformation tableTransformation(List<TableTransformation> transformations) {
        if (transformations == null) {
            transformations = Collections.emptyList();
        }
        return new CompositeTableTransformation(transformations);
    }

    @Profile({ Modules.REPLICATION })
    @Bean
    ParreplacedionTransformation parreplacedionTransformation(List<ParreplacedionTransformation> transformations) {
        if (transformations == null) {
            transformations = Collections.emptyList();
        }
        return new CompositeParreplacedionTransformation(transformations);
    }

    @Bean
    @ConditionalOnMissingBean(ColumnStatisticsTransformation.clreplaced)
    ColumnStatisticsTransformation columnStatisticsTransformation() {
        return ColumnStatisticsTransformation.IDENreplacedY;
    }

    @Bean
    @ConditionalOnMissingBean(MetricSender.clreplaced)
    MetricSender metricSender() {
        return MetricSender.DEFAULT_LOG_ONLY;
    }

    @Bean
    @ConditionalOnMissingBean(value = ScheduledReporterFactory.clreplaced)
    ScheduledReporterFactory runningScheduledReporterFactory(MetricRegistry runningMetricRegistry) {
        return new LoggingScheduledReporterFactory(runningMetricRegistry);
    }

    @Bean
    MetricRegistry runningMetricRegistry() {
        return new MetricRegistry();
    }

    @Bean
    @ConditionalOnMissingBean(name = "housekeepingListener")
    HousekeepingListener housekeepingListener() {
        return HousekeepingListener.NULL;
    }

    @Profile({ Modules.REPLICATION })
    @Bean
    ReplicationFactory replicationFactory(SourceFactory sourceFactory, ReplicaFactory replicaFactory, CopierFactoryManager copierFactoryManager, CopierListener copierListener, ParreplacedionPredicateFactory parreplacedionPredicateFactory, CopierOptions copierOptions, Supplier<CloseableMetaStoreClient> sourceMetaStoreClientSupplier, Supplier<CloseableMetaStoreClient> replicaMetaStoreClientSupplier, HousekeepingListener housekeepingListener, ReplicaCatalogListener replicaCatalogListener, DataManipulatorFactoryManager dataManipulatorFactoryManager) {
        ReplicationFactoryImpl upsertReplicationFactory = new ReplicationFactoryImpl(sourceFactory, replicaFactory, copierFactoryManager, copierListener, parreplacedionPredicateFactory, copierOptions, dataManipulatorFactoryManager);
        return new StrategyBasedReplicationFactory(upsertReplicationFactory, sourceMetaStoreClientSupplier, replicaMetaStoreClientSupplier, housekeepingListener, replicaCatalogListener);
    }

    @Profile({ Modules.REPLICATION })
    @Bean
    ParreplacedionPredicateFactory parreplacedionPredicateFactory(SourceFactory sourceFactory, ReplicaFactory replicaFactory, SpringExpressionParser expressionParser, @Value("#{checksumFunction}") Function<Path, String> checksumFunction) {
        return new ParreplacedionPredicateFactory(sourceFactory, replicaFactory, expressionParser, checksumFunction);
    }

    @Profile({ Modules.REPLICATION })
    @Bean
    Function<Path, String> checksumFunction(HiveConf sourceHiveConf) {
        return Functions.compose(new PathDigest(), new PathToPathMetadata(sourceHiveConf));
    }
}

15 View Source File : SchedulerConfiguration.java
License : Apache License 2.0
Project Creator : eventeum

@Configuration
@EnableScheduling
@EnableAsync
@EnableRetry
@Slf4j
public clreplaced SchedulerConfiguration implements SchedulingConfigurer {

    private ScheduledExecutorService scheduledExecutorService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(scheduledExecutorService);
    }

    @Bean(destroyMethod = "shutdown")
    public Executor taskScheduler(NodeSettings nodeSettings) {
        scheduledExecutorService = Executors.newScheduledThreadPool(nodeSettings.getNodes().size(), new CustomizableThreadFactory("eventeum-scheduler"));
        return scheduledExecutorService;
    }
}

15 View Source File : InvokerConfiguration.java
License : MIT License
Project Creator : attemper

@Import({ SecurityConfiguration.clreplaced, CustomQuartzAutoConfiguration.clreplaced })
@EnableAutoConfiguration(exclude = { QuartzAutoConfiguration.clreplaced })
@Configuration
@ComponentScan(basePackageClreplacedes = { RetryHttpHandler.clreplaced, JobCallingService.clreplaced })
@EnableRetry
public clreplaced InvokerConfiguration {

    @Autowired
    private AppProperties appProperties;

    /**
     * @param schedulerFactory
     * @return
     * @throws SchedulerException
     */
    @Bean
    public Scheduler scheduler(SchedulerFactory schedulerFactory) throws SchedulerException {
        Scheduler scheduler = schedulerFactory.getScheduler();
        if (appProperties.getWeb().isEnableScheduling()) {
            if (appProperties.getScheduler().getDelayedInSecond() > 0) {
                scheduler.startDelayed(appProperties.getScheduler().getDelayedInSecond());
            } else {
                scheduler.start();
            }
        }
        return scheduler;
    }
}

15 View Source File : PlatformGatewayApplication.java
License : GNU Lesser General Public License v2.1
Project Creator : abixen

@EnableRetry
@SpringBootApplication
@EnableRedisHttpSession
@EnableZuulProxy
@EnableEurekaClient
@EnableFeignClients(basePackages = { "com.abixen.platform" })
@EnableCircuitBreaker
@Configuration
public clreplaced PlatformGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(PlatformGatewayApplication.clreplaced, args);
    }
}

14 View Source File : AppInitializer.java
License : MIT License
Project Creator : valb3r

@EnableAsync
@EnableRetry
@EnableTransactionManagement
@EnableAspectJAutoProxy(proxyTargetClreplaced = true)
@EnreplacedyScan("com.gtc.opportunity.trader.domain")
@EnableJpaRepositories(basePackages = { "com.gtc.opportunity.trader.repository" })
@SpringBootApplication(scanBasePackages = { "com.gtc.opportunity.trader.aop", "com.gtc.opportunity.trader.service", "com.gtc.opportunity.trader.config" })
public clreplaced AppInitializer {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(AppInitializer.clreplaced);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);
    }
}

13 View Source File : LdapService.java
License : MIT License
Project Creator : sinnerschrader

/**
 * Service handling LDAP auth and data retrieval
 *
 * @author torree
 */
@Service
@EnableRetry
public clreplaced LdapService {

    private static final Logger logger = LoggerFactory.getLogger(LdapService.clreplaced);

    private static LDAPConnection ldapConnection;

    @Value("${ldapUrl}")
    private String ldapUrl;

    @Value("${ldapPort}")
    private int ldapPort;

    @Value("${ldapUserBaseDN}")
    private String ldapUserBaseDN;

    @Value("${ldapUserBaseOUs}")
    private String ldapUserBaseOUs;

    @Value("${ldapLookupBaseDN}")
    private String ldapLookupBaseDN;

    @Value("${ldapAdminGroupDN}")
    private String ldapAdminGroupDN;

    @Value("${ldapEmbedded}")
    private boolean ldapEmbedded;

    @Value("${ldapSsl}")
    private boolean ldapSsl;

    @Value("${ldapLookupUser}")
    private String ldapLookupUser;

    @Value("${ldapLookupPreplacedword}")
    private String ldapLookupPreplacedword;

    private final UserRepository userRepo;

    private final EmbeddedLdap embeddedLdap;

    private final UserLdapDetailsFactory userLdapDetailsFactory;

    @Autowired
    public LdapService(UserRepository userRepo, EmbeddedLdap embeddedLdap, UserLdapDetailsFactory userLdapDetailsFactory) {
        this.userRepo = userRepo;
        this.embeddedLdap = embeddedLdap;
        this.userLdapDetailsFactory = userLdapDetailsFactory;
    }

    private void tryStartEmbeddedLdap() {
        if (!ldapEmbedded) {
            return;
        }
        try {
            embeddedLdap.startup();
        } catch (LDAPException e) {
            logger.error("Failed to start embedded LDAP");
        }
    }

    @EventListener(ContextStartedEvent.clreplaced)
    public void openConnection() {
        tryStartEmbeddedLdap();
        try {
            if (ldapSsl) {
                var sreplacedil = new Sreplacedil(new TrustAllTrustManager());
                var sslSocketFactory = sreplacedil.createSSLSocketFactory();
                ldapConnection = new LDAPConnection(sslSocketFactory);
            } else {
                ldapConnection = new LDAPConnection();
            }
            ldapConnection.connect(ldapUrl, ldapPort);
            logger.info("Successfully connected to LDAP");
        } catch (LDAPException | GeneralSecurityException e) {
            logger.error("Failed to connect to LDAP", e);
        }
    }

    @EventListener(ContextStoppedEvent.clreplaced)
    public void closeConnection() {
        if (ldapConnection == null || !ldapConnection.isConnected()) {
            logger.debug("Failed to disconnect LDAP: No open connection");
        }
        ldapConnection.close();
    }

    private void ensureConnection() {
        if (ldapConnection == null || !ldapConnection.isConnected()) {
            openConnection();
        }
    }

    private void bindAsTechnicalUser() throws LDAPException {
        ldapConnection.bind(new SimpleBindRequest("cn=" + ldapLookupUser + "," + ldapLookupBaseDN, ldapLookupPreplacedword));
    }

    private List<String> allOUs() {
        return Arrays.stream(ldapUserBaseOUs.split("\\|")).map(pair -> pair.split(",")[0]).collect(Collectors.toList());
    }

    private SearchResultEntry getEntry(String filter) {
        try {
            for (String ou : allOUs()) {
                var dn = ldapUserBaseDN.replace("{}", ou);
                var ldapRequest = new SearchRequest(dn, SearchScope.SUB, filter);
                var ldapResult = ldapConnection.search(ldapRequest);
                if (ldapResult.getEntryCount() > 0) {
                    return ldapResult.getSearchEntries().get(0);
                }
            }
            return null;
        } catch (LDAPException e) {
            return null;
        }
    }

    private SearchResultEntry getEntryByMail(String mail) {
        return getEntry("(mail=" + mail + ")");
    }

    private SearchResultEntry getEntryById(String id) {
        return getEntry("(uid=" + id + ")");
    }

    public User createUserByMail(String mail) {
        ensureConnection();
        try {
            bindAsTechnicalUser();
        } catch (LDAPException e) {
            logger.error("Failed to bind ldap as tech user", e);
        }
        var ldapEntry = getEntryByMail(mail);
        if (ldapEntry == null) {
            logger.warn("Failed to sync user {} with LDAP: no result", mail);
            return null;
        }
        String dn = null;
        try {
            dn = ldapEntry.getParentDNString();
        } catch (LDAPException e) {
            e.printStackTrace();
        }
        var id = ldapEntry.getAttributeValue("uid");
        var role = getAdminIds().contains(id) ? Role.ADMIN : Role.USER;
        var ldapDetails = userLdapDetailsFactory.create(ldapEntry, role);
        var newUser = new User(id);
        newUser.setLdapDN(dn);
        newUser.setLdapDetails(ldapDetails);
        return newUser;
    }

    private Set<String> getAdminIds() {
        ensureConnection();
        try {
            bindAsTechnicalUser();
            var ldapRequest = new SearchRequest(ldapAdminGroupDN, SearchScope.SUB, "(memberUid=*)");
            var adminGroupResult = ldapConnection.search(ldapRequest).getSearchEntries();
            if (adminGroupResult.size() != 1) {
                throw new IllegalStateException("Failed to find unique admin ldap group");
            }
            return Set.of(adminGroupResult.get(0).getAttributeValues("memberUid"));
        } catch (LDAPException e) {
            return Collections.emptySet();
        }
    }

    @Retryable(include = OptimisticLockingFailureException.clreplaced, maxAttempts = 10)
    public User syncUser(User user) {
        return syncUsers(List.of(user), false).get(0);
    }

    public List<User> syncUsers(List<User> users, boolean forceUpdate) {
        ensureConnection();
        try {
            bindAsTechnicalUser();
        } catch (LDAPException e) {
            logger.error("Failed to sync users, LDAP error");
            return users;
        }
        var updated = new ArrayList<User>();
        var adminIds = getAdminIds();
        for (User user : users) {
            SearchRequest ldapRequest;
            SearchResultEntry ldapEntry;
            var isRemoved = false;
            try {
                // user does not need to update, irgnore
                if (!forceUpdate && user.getLdapDetails() != null) {
                    updated.add(user);
                    continue;
                }
                if (StringUtils.isEmpty(user.getLdapDN())) {
                    ldapEntry = getEntryById(user.getId());
                    if (ldapEntry != null) {
                        user.setLdapDN(ldapEntry.getParentDNString());
                    }
                } else {
                    ldapRequest = new SearchRequest(user.getLdapDN(), SearchScope.SUB, "(uid=" + user.getId() + ")");
                    var entries = ldapConnection.search(ldapRequest).getSearchEntries();
                    ldapEntry = entries.size() < 1 ? null : entries.get(0);
                }
                if (ldapEntry == null) {
                    logger.warn("Failed to sync user {}: Not found in LDAP, will remove", user.getId());
                    userRepo.delete(user);
                    isRemoved = true;
                } else {
                    var role = adminIds.contains(user.getId()) ? Role.ADMIN : Role.USER;
                    user.setLdapDetails(userLdapDetailsFactory.create(ldapEntry, role));
                }
            } catch (LDAPException e) {
                logger.error("Failed to sync user {}: LDAP error", user.getId());
            }
            if (!isRemoved) {
                updated.add(user);
            }
        }
        userRepo.saveAll(updated);
        logger.info("Successfully synced {} users with LDAP", updated.size());
        return updated;
    }
}

11 View Source File : Application.java
License : MIT License
Project Creator : jonathanlermitage

@SpringBootApplication
@EnableAsync
@EnableBatchProcessing
@EnableJpaRepositories(basePackages = "manon.repository")
@EnreplacedyScan(basePackages = "manon.doreplacedent")
@EnableScheduling
@EnableRetry
@RequiredArgsConstructor
@Slf4j
public clreplaced Application extends SpringBootServletInitializer {

    private final Cfg cfg;

    private final RegistrationService registrationService;

    public static void main(String[] args) {
        SpringApplicationBuilder app = new SpringApplicationBuilder(Application.clreplaced);
        app.build().addListeners(new ApplicationPidFileWriter());
        ConfigurableApplicationContext ctx = app.run(args);
        if (log.isDebugEnabled()) {
            Stream.of(ctx.getBeanDefinitionNames()).filter(s -> s.startsWith("org.springframework") && s.contains(".autoconfigure.")).sorted().forEach(s -> log.debug("Loaded autoconfig: " + s));
        }
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.web(WebApplicationType.SERVLET).sources(Application.clreplaced);
    }

    @PostConstruct
    public void startupHook() {
        log.info("jvm: [{} {} {} {}], os: [{}], file encoding: [{}], admin username: [{}], actuator username: [{}], Cfg: [{}]", System.getProperty("java.version"), System.getProperty("java.vm.name"), System.getProperty("java.vm.version"), System.getProperty("java.vm.vendor"), System.getProperty("os.name"), System.getProperty("file.encoding"), registrationService.ensureAdmin().getUsername(), registrationService.ensureActuator().getUsername(), cfg);
    }
}