diff --git a/CHANGELOG.md b/CHANGELOG.md index bdf84099..dac2b659 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,29 @@ =========================== +## [2.3.3](https://github.com/buession/buession-springboot/releases/tag/v2.3.3) (2024-05-06) + +### 🔨依赖升级 + +- [依赖库版本升级和安全漏洞修复](https://github.com/buession/buession-parent/releases/tag/v2.3.3) + + +### ⭐ 新特性 + +- **buession-springboot-boot:** 新增线程池自动配置类 ThreadPoolConfiguration +- **buession-springboot-mybatis:** ConfiguredMapperScannerRegistrar,增加 spring.mybatis.scanner.enabled 开关配置 + + +### ⏪ 优化 + +- **buession-springboot-pac4j:** 优化 Pac4jFilter 类 +- **buession-springboot-shiro:** 优化 Shiro Filter 初始化及处理流程 +- **buession-springboot-mybatis:** SqlSessionFactoryBean 初始化速度优化 + + +--- + + ## [2.3.2](https://github.com/buession/buession-springboot/releases/tag/v2.3.2) (2023-12-27) ### 🔨依赖升级 diff --git a/buession-springboot-boot/pom.xml b/buession-springboot-boot/pom.xml index 6aa32358..1357def9 100644 --- a/buession-springboot-boot/pom.xml +++ b/buession-springboot-boot/pom.xml @@ -7,7 +7,7 @@ com.buession.springboot buession-springboot-parent ../buession-springboot-parent - 2.3.2 + 2.3.3 buession-springboot-boot https://springboot.buession.com/ diff --git a/buession-springboot-boot/src/main/java/com/buession/springboot/boot/autoconfigure/ThreadPoolConfiguration.java b/buession-springboot-boot/src/main/java/com/buession/springboot/boot/autoconfigure/ThreadPoolConfiguration.java new file mode 100644 index 00000000..a1952dbd --- /dev/null +++ b/buession-springboot-boot/src/main/java/com/buession/springboot/boot/autoconfigure/ThreadPoolConfiguration.java @@ -0,0 +1,122 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2024 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.springboot.boot.autoconfigure; + +import com.buession.core.concurrent.DefaultThreadFactory; +import com.buession.core.concurrent.DefaultThreadPoolExecutor; +import com.buession.core.converter.mapper.PropertyMapper; +import com.buession.core.validator.Validate; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.Optional; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.RejectedExecutionHandler; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * 线程池自动配置 + * + * @author Yong.Teng + * @since 2.3.3 + */ +@Configuration(proxyBeanMethods = false) +@EnableConfigurationProperties(ThreadPoolProperties.class) +@ConditionalOnProperty(prefix = ThreadPoolProperties.PREFIX, name = "enabled", havingValue = "true") +public class ThreadPoolConfiguration { + + private final ThreadPoolProperties threadPoolProperties; + + public ThreadPoolConfiguration(ThreadPoolProperties threadPoolProperties) { + this.threadPoolProperties = threadPoolProperties; + } + + @Bean(name = "threadPoolWorkQueue") + @ConditionalOnMissingBean(name = "threadPoolWorkQueue") + public BlockingQueue workQueue() { + return new LinkedBlockingDeque<>(); + } + + @Bean(name = "threadPoolThreadFactory") + @ConditionalOnMissingBean(name = "threadPoolThreadFactory") + public ThreadFactory threadPoolFactory() { + final DefaultThreadFactory threadFactory = Validate.hasText( + threadPoolProperties.getNamePrefix()) ? new DefaultThreadFactory( + threadPoolProperties.getNamePrefix()) : new DefaultThreadFactory(); + final PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull(); + + propertyMapper.from(threadPoolProperties.getPriority()).to(threadFactory::setPriority); + propertyMapper.from(threadPoolProperties.getDaemon()).to(threadFactory::setDaemon); + + return threadFactory; + } + + @Bean(name = "threadPoolRejectedHandler") + @ConditionalOnMissingBean(name = "threadPoolRejectedHandler") + public RejectedExecutionHandler rejectedHandler() { + return new ThreadPoolExecutor.AbortPolicy(); + } + + @Bean(name = "threadPoolExecutor") + @ConditionalOnMissingBean(name = "threadPoolExecutor") + public ThreadPoolExecutor threadPoolExecutor( + @Qualifier("threadPoolWorkQueue") ObjectProvider> workQueue, + @Qualifier("threadPoolThreadFactory") ObjectProvider threadFactory, + @Qualifier("threadPoolRejectedHandler") ObjectProvider rejectedHandler) { + final com.buession.core.concurrent.ThreadPoolConfiguration threadPoolConfiguration = + new com.buession.core.concurrent.ThreadPoolConfiguration(); + final PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull(); + + propertyMapper.from(threadPoolProperties.getNamePrefix()).to(threadPoolConfiguration::setNamePrefix); + propertyMapper.from(threadPoolProperties.getAllowCoreThreadTimeOut()) + .to(threadPoolConfiguration::setAllowCoreThreadTimeOut); + propertyMapper.from(threadPoolProperties.getDaemon()).to(threadPoolConfiguration::setDaemon); + propertyMapper.from(threadPoolProperties.getPriority()).to(threadPoolConfiguration::setPriority); + + threadPoolConfiguration.setCorePoolSize(Optional.ofNullable(threadPoolProperties.getCorePoolSize()).orElse(-1)); + threadPoolConfiguration.setMaximumPoolSize( + Optional.ofNullable(threadPoolProperties.getMaximumPoolSize()).orElse(-1)); + + if(threadPoolProperties.getKeepAliveTime() != null){ + threadPoolConfiguration.setKeepAliveTime(threadPoolProperties.getKeepAliveTime().toMillis()); + threadPoolConfiguration.setKeepAliveTimeTimeUnit(TimeUnit.MILLISECONDS); + } + + workQueue.ifAvailable(threadPoolConfiguration::setWorkQueue); + threadFactory.ifAvailable(threadPoolConfiguration::setThreadFactory); + rejectedHandler.ifAvailable(threadPoolConfiguration::setRejectedHandler); + + return new DefaultThreadPoolExecutor(threadPoolConfiguration); + } + +} diff --git a/buession-springboot-boot/src/main/java/com/buession/springboot/boot/autoconfigure/ThreadPoolProperties.java b/buession-springboot-boot/src/main/java/com/buession/springboot/boot/autoconfigure/ThreadPoolProperties.java new file mode 100644 index 00000000..6d384145 --- /dev/null +++ b/buession-springboot-boot/src/main/java/com/buession/springboot/boot/autoconfigure/ThreadPoolProperties.java @@ -0,0 +1,224 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2024 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.springboot.boot.autoconfigure; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.time.Duration; + +/** + * 线程池配置 + * + * @author Yong.Teng + * @since 2.3.3 + */ +@ConfigurationProperties(prefix = ThreadPoolProperties.PREFIX) +public class ThreadPoolProperties { + + public final static String PREFIX = "spring.thread-pool"; + + /** + * 线程名称前缀 + */ + private String namePrefix; + + /** + * 线程池核心线程大小 + */ + private Integer corePoolSize; + + /** + * 线程池最大线程数量 + */ + private Integer maximumPoolSize; + + /** + * 空闲线程存活时间 + */ + private Duration keepAliveTime = Duration.ofSeconds(60); + + /** + * 空闲线程超过 keepAliveTime 后是否直接停掉 + */ + private Boolean allowCoreThreadTimeOut; + + /** + * 是否后台运行 + */ + private Boolean daemon; + + /** + * 优先级 + */ + private Integer priority; + + /** + * 返回线程名称前缀 + * + * @return 线程名称前缀 + */ + public String getNamePrefix() { + return namePrefix; + } + + /** + * 返回线程名称前缀 + * + * @param namePrefix + * 线程名称前缀 + */ + public void setNamePrefix(String namePrefix) { + this.namePrefix = namePrefix; + } + + /** + * 返回线程池核心线程大小; + *

线程池中会维护一个最小的线程数量,即使这些线程处理空闲状态,他们也不会被销毁。

+ * + * @return 线程池核心线程大小 + */ + public Integer getCorePoolSize() { + return corePoolSize; + } + + /** + * 设置线程池核心线程大小 + *

线程池中会维护一个最小的线程数量,即使这些线程处理空闲状态,他们也不会被销毁。

+ * + * @param corePoolSize + * 线程池核心线程大小 + */ + public void setCorePoolSize(Integer corePoolSize) { + this.corePoolSize = corePoolSize; + } + + /** + * 线程池最大线程数量 + *

一个任务被提交到线程池以后,首先会找有没有空闲存活线程,如果有则直接将任务交给这个空闲线程来执行, + * 如果没有则会缓存到工作队列中,如果工作队列满了,才会创建一个新线程, + * 然后从工作队列的头部取出一个任务交由新线程来处理,而将刚提交的任务放入工作队列尾部。 + * 线程池不会无限制的去创建新线程,它会有一个最大线程数量的限制,这个数量即由 maximunPoolSize 指定。

+ * + * @return 线程池最大线程数量 + */ + public Integer getMaximumPoolSize() { + return maximumPoolSize; + } + + /** + * 线程池最大线程数量 + *

一个任务被提交到线程池以后,首先会找有没有空闲存活线程,如果有则直接将任务交给这个空闲线程来执行, + * 如果没有则会缓存到工作队列中,如果工作队列满了,才会创建一个新线程, + * 然后从工作队列的头部取出一个任务交由新线程来处理,而将刚提交的任务放入工作队列尾部。 + * 线程池不会无限制的去创建新线程,它会有一个最大线程数量的限制,这个数量即由 maximunPoolSize 指定。

+ * + * @param maximumPoolSize + * 线程池最大线程数量 + */ + public void setMaximumPoolSize(Integer maximumPoolSize) { + this.maximumPoolSize = maximumPoolSize; + } + + /** + * 返回空闲线程存活时间 + *

一个线程如果处于空闲状态,并且当前的线程数量大于 corePoolSize,那么在指定时间后,这个空闲线程会被销毁, + * 这里的指定时间由 keepAliveTime 来设定。

+ * + * @return 空闲线程存活时间 + */ + public Duration getKeepAliveTime() { + return keepAliveTime; + } + + /** + * 设置空闲线程存活时间 + *

一个线程如果处于空闲状态,并且当前的线程数量大于 corePoolSize,那么在指定时间后,这个空闲线程会被销毁, + * 这里的指定时间由 keepAliveTime 来设定。

+ * + * @param keepAliveTime + * 空闲线程存活时间 + */ + public void setKeepAliveTime(Duration keepAliveTime) { + this.keepAliveTime = keepAliveTime; + } + + /** + * 返回空闲线程超过 keepAliveTime 后是否直接停掉 + * + * @return 空闲线程超过 keepAliveTime 后是否直接停掉 + */ + public Boolean getAllowCoreThreadTimeOut() { + return allowCoreThreadTimeOut; + } + + /** + * 设置空闲线程超过 keepAliveTime 后是否直接停掉 + * + * @param allowCoreThreadTimeOut + * 空闲线程超过 keepAliveTime 后是否直接停掉 + */ + public void setAllowCoreThreadTimeOut(Boolean allowCoreThreadTimeOut) { + this.allowCoreThreadTimeOut = allowCoreThreadTimeOut; + } + + /** + * 返回是否后台运行 + * + * @return 是否后台运行 + */ + public Boolean getDaemon() { + return daemon; + } + + /** + * 设置是否后台运行 + * + * @param daemon + * 是否后台运行 + */ + public void setDaemon(Boolean daemon) { + this.daemon = daemon; + } + + /** + * 返回优先级 + * + * @return 优先级 + */ + public Integer getPriority() { + return priority; + } + + /** + * 设置优先级 + * + * @param priority + * 优先级 + */ + public void setPriority(Integer priority) { + this.priority = priority; + } + +} diff --git a/buession-springboot-boot/src/main/resources/META-INF/spring.factories b/buession-springboot-boot/src/main/resources/META-INF/spring.factories index 432977ea..21130364 100644 --- a/buession-springboot-boot/src/main/resources/META-INF/spring.factories +++ b/buession-springboot-boot/src/main/resources/META-INF/spring.factories @@ -1,2 +1,3 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - com.buession.springboot.boot.autoconfigure.MessagePropertyConfiguration \ No newline at end of file + com.buession.springboot.boot.autoconfigure.MessagePropertyConfiguration, \ + com.buession.springboot.boot.autoconfigure.ThreadPoolConfiguration \ No newline at end of file diff --git a/buession-springboot-cache/pom.xml b/buession-springboot-cache/pom.xml index c874bf9a..dbdaedf8 100644 --- a/buession-springboot-cache/pom.xml +++ b/buession-springboot-cache/pom.xml @@ -7,7 +7,7 @@ com.buession.springboot buession-springboot-parent ../buession-springboot-parent - 2.3.2 + 2.3.3 buession-springboot-cache https://springboot.buession.com/ diff --git a/buession-springboot-cache/src/main/java/com/buession/springboot/cache/redis/autoconfigure/AbstractDataSourceFactoryBean.java b/buession-springboot-cache/src/main/java/com/buession/springboot/cache/redis/autoconfigure/AbstractDataSourceFactoryBean.java index aedb1202..b5b92bd8 100644 --- a/buession-springboot-cache/src/main/java/com/buession/springboot/cache/redis/autoconfigure/AbstractDataSourceFactoryBean.java +++ b/buession-springboot-cache/src/main/java/com/buession/springboot/cache/redis/autoconfigure/AbstractDataSourceFactoryBean.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.cache.redis.autoconfigure; @@ -69,7 +69,7 @@ public Class getObjectType() { @Override public void afterPropertiesSet() throws Exception { if(dataSource == null){ - PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull(); + final PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull(); dataSource = createDataSource(); propertyMapper.alwaysApplyingWhenHasText().from(properties.getClientName()).to(dataSource::setClientName); diff --git a/buession-springboot-canal/pom.xml b/buession-springboot-canal/pom.xml index d4202e16..bad4653a 100644 --- a/buession-springboot-canal/pom.xml +++ b/buession-springboot-canal/pom.xml @@ -7,7 +7,7 @@ com.buession.springboot buession-springboot-parent ../buession-springboot-parent - 2.3.2 + 2.3.3 buession-springboot-canal https://springboot.buession.com/ @@ -52,47 +52,24 @@ - 0.0.2 + 1.0.0 - - com.buession.springboot - buession-springboot-boot - ${project.version} - - com.buession.canal - buession-canal-client + buession-canal-springboot ${buession.canal.version} - + + + + com.buession.canal - buession-canal-spring + buession-canal-springboot ${buession.canal.version} - - - - org.springframework - spring-test - - - - org.springframework.boot - spring-boot-test - - - - org.slf4j - slf4j-api - - - - junit - junit - - + + buession-springboot-canal diff --git a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/ThreadConfig.java b/buession-springboot-canal/src/main/java/com/buession/springboot/canal/ThreadConfig.java deleted file mode 100644 index ab977835..00000000 --- a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/ThreadConfig.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. - * See the NOTICE file distributed with this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - * - * ========================================================================================================= - * - * This software consists of voluntary contributions made by many individuals on behalf of the - * Apache Software Foundation. For more information on the Apache Software Foundation, please see - * . - * - * +-------------------------------------------------------------------------------------------------------+ - * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | - * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | - * +-------------------------------------------------------------------------------------------------------+ - */ -package com.buession.springboot.canal; - -import com.buession.core.concurrent.ThreadPolicy; - -import java.time.Duration; - -/** - * 线程池配置 - * - * @author Yong.Teng - * @since 2.3.1 - */ -public class ThreadConfig { - - /** - * 线程名称前缀 - */ - private String namePrefix = "canal-execute"; - - /** - * 线程池核心线程大小 - */ - private Integer corePoolSize; - - /** - * 线程池最大线程数量 - */ - private Integer maximumPoolSize; - - /** - * 空闲线程存活时间 - */ - private Duration keepAliveTime = Duration.ZERO; - - /** - * 饱和策略 - */ - private ThreadPolicy policy = ThreadPolicy.DISCARD; - - /** - * 返回线程名称前缀 - * - * @return 线程名称前缀 - */ - public String getNamePrefix() { - return namePrefix; - } - - /** - * 设置线程名称前缀 - * - * @param namePrefix - * 线程名称前缀 - */ - public void setNamePrefix(String namePrefix) { - this.namePrefix = namePrefix; - } - - /** - * 返回线程池核心线程大小 - * - * @return 线程池核心线程大小 - */ - public Integer getCorePoolSize() { - return corePoolSize; - } - - /** - * 设置线程池核心线程大小 - * - * @param corePoolSize - * 线程池核心线程大小 - */ - public void setCorePoolSize(Integer corePoolSize) { - this.corePoolSize = corePoolSize; - } - - /** - * 返回线程池最大线程数量 - * - * @return 线程池最大线程数量 - */ - public Integer getMaximumPoolSize() { - return maximumPoolSize; - } - - /** - * 设置线程池最大线程数量 - * - * @param maximumPoolSize - * 线程池最大线程数量 - */ - public void setMaximumPoolSize(Integer maximumPoolSize) { - this.maximumPoolSize = maximumPoolSize; - } - - /** - * 返回空闲线程存活时间 - * - * @return 空闲线程存活时间 - */ - public Duration getKeepAliveTime() { - return keepAliveTime; - } - - /** - * 设置空闲线程存活时间 - * - * @param keepAliveTime - * 空闲线程存活时间 - */ - public void setKeepAliveTime(Duration keepAliveTime) { - this.keepAliveTime = keepAliveTime; - } - - /** - * 返回饱和策略 - * - * @return 饱和策略 - */ - public ThreadPolicy getPolicy() { - return policy; - } - - /** - * 设置饱和策略 - * - * @param policy - * 饱和策略 - */ - public void setPolicy(ThreadPolicy policy) { - this.policy = policy; - } - -} diff --git a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/AdapterClientConfiguration.java b/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/AdapterClientConfiguration.java index 4025f1c0..4e9df43a 100644 --- a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/AdapterClientConfiguration.java +++ b/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/AdapterClientConfiguration.java @@ -24,176 +24,18 @@ */ package com.buession.springboot.canal.autoconfigure; -import com.buession.canal.client.adapter.AdapterClient; -import com.buession.canal.client.adapter.KafkaAdapterClient; -import com.buession.canal.client.adapter.PulsarMQAdapterClient; -import com.buession.canal.client.adapter.RabbitMQAdapterClient; -import com.buession.canal.client.adapter.RocketMQAdapterClient; -import com.buession.canal.client.adapter.TcpAdapterClient; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; -import java.util.Set; -import java.util.stream.Collectors; - /** * @author Yong.Teng * @since 2.3.1 */ @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(CanalProperties.class) -public class AdapterClientConfiguration { - - @FunctionalInterface - interface CanalAdapterClientBuilder { - - C newInstance(final String destination, final IC instance); - - } - - interface IAdapterClientConfiguration { - - /** - * 初始化 {@link AdapterClient} 列表 bean - * - * @return {@link AdapterClient} 列表 bean - */ - Set createAdapterClients(); - - } - - static abstract class AbstractAdapterClientConfiguration implements IAdapterClientConfiguration { - - protected CanalProperties canalProperties; - - AbstractAdapterClientConfiguration(final CanalProperties canalProperties) { - this.canalProperties = canalProperties; - } - - protected Set createCanalAdapterClients( - final AdapterProperties properties, final CanalAdapterClientBuilder builder) { - return properties.getInstances().entrySet().stream().map((e)->builder.newInstance(e.getKey(), e.getValue())) - .collect(Collectors.toSet()); - } - - } - - @Configuration(proxyBeanMethods = false) - @EnableConfigurationProperties(CanalProperties.class) - @Conditional(AdapterClientConfiguredCondition.KafkaCanalAdapterClientConfiguredCondition.class) - @ConditionalOnMissingBean(IAdapterClientConfiguration.class) - @ConfigurationProperties(prefix = CanalProperties.PREFIX + ".kafka") - static class KafkaAdapterClientConfiguration extends AbstractAdapterClientConfiguration { - - public KafkaAdapterClientConfiguration(final CanalProperties canalProperties) { - super(canalProperties); - } - - @Bean - @Override - public Set createAdapterClients() { - final KafkaProperties kafka = canalProperties.getKafka(); - return createCanalAdapterClients(kafka, (topic, instance)->new KafkaAdapterClient(kafka.getServers(), topic, - instance.getGroupId(), instance.getPartition(), instance, instance.isFlatMessage())); - } - - } - - @Configuration(proxyBeanMethods = false) - @EnableConfigurationProperties(CanalProperties.class) - @Conditional(AdapterClientConfiguredCondition.PulsarCanalAdapterClientConfiguredCondition.class) - @ConditionalOnMissingBean(IAdapterClientConfiguration.class) - @ConfigurationProperties(prefix = CanalProperties.PREFIX + ".pulsar") - static class PulsarAdapterClientConfiguration extends AbstractAdapterClientConfiguration { - - public PulsarAdapterClientConfiguration(final CanalProperties canalProperties) { - super(canalProperties); - } - - @Bean - @Override - public Set createAdapterClients() { - final PulsarProperties pulsar = canalProperties.getPulsar(); - return createCanalAdapterClients(pulsar, (topic, instance)->new PulsarMQAdapterClient( - pulsar.getServiceUrl(), pulsar.getRoleToken(), topic, instance.getSubscriptName(), - pulsar.getGetBatchTimeout(), pulsar.getBatchProcessTimeout(), pulsar.getRedeliveryDelay(), - pulsar.getAckTimeout(), pulsar.isRetry(), pulsar.isRetryDLQUpperCase(), - pulsar.getMaxRedeliveryCount(), instance, instance.isFlatMessage())); - } - - } - - @Configuration(proxyBeanMethods = false) - @EnableConfigurationProperties(CanalProperties.class) - @Conditional(AdapterClientConfiguredCondition.RabbitCanalAdapterClientConfiguredCondition.class) - @ConditionalOnMissingBean(IAdapterClientConfiguration.class) - @ConfigurationProperties(prefix = CanalProperties.PREFIX + ".rabbit") - static class RabbitAdapterClientConfiguration extends AbstractAdapterClientConfiguration { - - public RabbitAdapterClientConfiguration(final CanalProperties canalProperties) { - super(canalProperties); - } - - @Bean - @Override - public Set createAdapterClients() { - final RabbitProperties rabbit = canalProperties.getRabbit(); - return createCanalAdapterClients(rabbit, - (queueName, instance)->new RabbitMQAdapterClient(rabbit.getServer(), - rabbit.getVirtualHost(), rabbit.getUsername(), rabbit.getPassword(), queueName, - instance, instance.isFlatMessage())); - } - - } - - @Configuration(proxyBeanMethods = false) - @EnableConfigurationProperties(CanalProperties.class) - @Conditional(AdapterClientConfiguredCondition.RocketCanalAdapterClientConfiguredCondition.class) - @ConditionalOnMissingBean(IAdapterClientConfiguration.class) - @ConfigurationProperties(prefix = CanalProperties.PREFIX + ".rocket") - static class RocketAdapterClientConfiguration extends AbstractAdapterClientConfiguration { - - public RocketAdapterClientConfiguration(final CanalProperties canalProperties) { - super(canalProperties); - } - - @Bean - @Override - public Set createAdapterClients() { - final RocketProperties rocket = canalProperties.getRocket(); - return createCanalAdapterClients(rocket, (topic, instance)->new RocketMQAdapterClient( - rocket.getNameServer(), topic, instance.getGroupId(), rocket.getEnableMessageTrace(), - rocket.getCustomizedTraceTopic(), rocket.getAccessChannel(), instance, - instance.isFlatMessage())); - } - - } - - @Configuration(proxyBeanMethods = false) - @EnableConfigurationProperties(CanalProperties.class) - @Conditional(AdapterClientConfiguredCondition.TcpCanalAdapterClientConfiguredCondition.class) - @ConditionalOnMissingBean(IAdapterClientConfiguration.class) - @ConfigurationProperties(prefix = CanalProperties.PREFIX + ".tcp") - static class TcpAdapterClientConfiguration extends AbstractAdapterClientConfiguration { - - public TcpAdapterClientConfiguration(final CanalProperties canalProperties) { - super(canalProperties); - } - - @Bean - @Override - public Set createAdapterClients() { - final TcpProperties tcp = canalProperties.getTcp(); - return createCanalAdapterClients(tcp, - (destination, instance)->new TcpAdapterClient(tcp.getServer(), - tcp.getZkServers(), destination, tcp.getUsername(), tcp.getPassword(), instance)); - } - - } +@ConditionalOnMissingBean(com.buession.canal.springboot.autoconfigure.AdapterClientConfiguration.class) +@Deprecated +public class AdapterClientConfiguration extends com.buession.canal.springboot.autoconfigure.AdapterClientConfiguration { } diff --git a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/AdapterClientConfiguredCondition.java b/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/AdapterClientConfiguredCondition.java deleted file mode 100644 index 558a79b6..00000000 --- a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/AdapterClientConfiguredCondition.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. - * See the NOTICE file distributed with this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - * - * ========================================================================================================= - * - * This software consists of voluntary contributions made by many individuals on behalf of the - * Apache Software Foundation. For more information on the Apache Software Foundation, please see - * . - * - * +-------------------------------------------------------------------------------------------------------+ - * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | - * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | - * +-------------------------------------------------------------------------------------------------------+ - */ -package com.buession.springboot.canal.autoconfigure; - -import com.buession.canal.core.CanalMode; -import com.buession.springboot.boot.autoconfigure.condition.BaseOnPropertyExistCondition; -import org.springframework.boot.context.properties.bind.Bindable; - -/** - * @author Yong.Teng - * @since 0.0.1 - */ -interface AdapterClientConfiguredCondition { - - abstract class AbstractCanalAdapterClientConfiguredCondition

> - extends BaseOnPropertyExistCondition

implements AdapterClientConfiguredCondition { - - public AbstractCanalAdapterClientConfiguredCondition(final Bindable

registration, final CanalMode mode) { - super(CanalProperties.PREFIX + '.' + mode.getName(), "registered canal adapter clients", registration, - "Canal " + mode.getName() + "adapter client configured condition"); - } - - } - - class KafkaCanalAdapterClientConfiguredCondition - extends AbstractCanalAdapterClientConfiguredCondition { - - private final static Bindable REGISTRATION = Bindable.of(KafkaProperties.class); - - KafkaCanalAdapterClientConfiguredCondition() { - super(REGISTRATION, CanalMode.KAFKA); - } - - } - - class RabbitCanalAdapterClientConfiguredCondition - extends AbstractCanalAdapterClientConfiguredCondition { - - private final static Bindable REGISTRATION = Bindable.of(RabbitProperties.class); - - RabbitCanalAdapterClientConfiguredCondition() { - super(REGISTRATION, CanalMode.RABBIT_MQ); - } - - } - - class PulsarCanalAdapterClientConfiguredCondition - extends AbstractCanalAdapterClientConfiguredCondition { - - private final static Bindable REGISTRATION = Bindable.of(PulsarProperties.class); - - PulsarCanalAdapterClientConfiguredCondition() { - super(REGISTRATION, CanalMode.PULSAR_MQ); - } - - } - - class RocketCanalAdapterClientConfiguredCondition - extends AbstractCanalAdapterClientConfiguredCondition { - - private final static Bindable REGISTRATION = Bindable.of(RocketProperties.class); - - RocketCanalAdapterClientConfiguredCondition() { - super(REGISTRATION, CanalMode.ROCKET_MQ); - } - - } - - class TcpCanalAdapterClientConfiguredCondition - extends AbstractCanalAdapterClientConfiguredCondition { - - private final static Bindable REGISTRATION = Bindable.of(TcpProperties.class); - - TcpCanalAdapterClientConfiguredCondition() { - super(REGISTRATION, CanalMode.TCP); - } - - } - -} diff --git a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/CanalConfiguration.java b/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/CanalConfiguration.java index 1463149b..c28ea83f 100644 --- a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/CanalConfiguration.java +++ b/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/CanalConfiguration.java @@ -24,21 +24,11 @@ */ package com.buession.springboot.canal.autoconfigure; -import com.buession.canal.client.CanalContext; -import com.buession.canal.client.DefaultCanalContext; -import com.buession.canal.client.adapter.AdapterClient; -import com.buession.canal.client.dispatcher.Dispatcher; -import com.buession.canal.spring.client.factory.CanalClientFactoryBean; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import java.util.Set; -import java.util.concurrent.ExecutorService; - /** * @author Yong.Teng * @since 2.3.1 @@ -46,20 +36,8 @@ @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(CanalProperties.class) @Import({ThreadPoolConfiguration.class, AdapterClientConfiguration.class}) -public class CanalConfiguration { - - @Bean(destroyMethod = "destroy") - public CanalClientFactoryBean createCanalClientFactoryBean( - ObjectProvider> canalAdapterClients, ObjectProvider dispatcher, - @Qualifier("canalExecutorService") ObjectProvider executorService) { - final CanalClientFactoryBean canalClientFactoryBean = new CanalClientFactoryBean(); - - CanalContext context = new DefaultCanalContext(canalAdapterClients.getIfAvailable()); - canalClientFactoryBean.setContext(context); - canalClientFactoryBean.setDispatcher(dispatcher.getIfAvailable()); - canalClientFactoryBean.setExecutor(executorService.getIfAvailable()); - - return canalClientFactoryBean; - } +@ConditionalOnMissingBean(com.buession.canal.springboot.autoconfigure.CanalConfiguration.class) +@Deprecated +public class CanalConfiguration extends com.buession.canal.springboot.autoconfigure.CanalConfiguration { } diff --git a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/CanalProperties.java b/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/CanalProperties.java index 70b520bb..770ea619 100644 --- a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/CanalProperties.java +++ b/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/CanalProperties.java @@ -24,7 +24,6 @@ */ package com.buession.springboot.canal.autoconfigure; -import com.buession.springboot.canal.ThreadConfig; import org.springframework.boot.context.properties.ConfigurationProperties; /** @@ -34,152 +33,7 @@ * @since 2.3.1 */ @ConfigurationProperties(CanalProperties.PREFIX) -public class CanalProperties { - - public final static String PREFIX = "spring.canal"; - - /** - * 线程池配置 - */ - private ThreadConfig thread = new ThreadConfig(); - - /** - * Kafka 实例配置 - */ - private KafkaProperties kafka; - - /** - * RabbitMQ 实例配置 - */ - private RabbitProperties rabbit; - - /** - * RocketMQ 实例配置 - */ - private RocketProperties rocket; - - /** - * PulsarMQ 实例配置 - */ - private PulsarProperties pulsar; - - /** - * TCP 实例配置 - */ - private TcpProperties tcp; - - /** - * 返回线程池配置 - * - * @return 线程池配置 - */ - public ThreadConfig getThread() { - return thread; - } - - /** - * 设置线程池配置 - * - * @param thread - * 线程池配置 - */ - public void setThread(ThreadConfig thread) { - this.thread = thread; - } - - /** - * 返回 Kafka 实例配置 - * - * @return Kafka 实例配置 - */ - public KafkaProperties getKafka() { - return kafka; - } - - /** - * 设置 Kafka 实例配置 - * - * @param kafka - * Kafka 实例配置 - */ - public void setKafka(KafkaProperties kafka) { - this.kafka = kafka; - } - - /** - * 返回 RabbitMQ 实例配置 - * - * @return RabbitMQ 实例配置 - */ - public RabbitProperties getRabbit() { - return rabbit; - } - - /** - * 设置 RabbitMQ 实例配置 - * - * @param rabbit - * RabbitMQ 实例配置 - */ - public void setRabbit(RabbitProperties rabbit) { - this.rabbit = rabbit; - } - - /** - * 返回 RocketMQ 实例配置 - * - * @return RocketMQ 实例配置 - */ - public RocketProperties getRocket() { - return rocket; - } - - /** - * 设置 RocketMQ 实例配置 - * - * @param rocket - * RocketMQ 实例配置 - */ - public void setRocket(RocketProperties rocket) { - this.rocket = rocket; - } - - /** - * 返回 PulsarMQ 实例配置 - * - * @return PulsarMQ 实例配置 - */ - public PulsarProperties getPulsar() { - return pulsar; - } - - /** - * 设置 PulsarMQ 实例配置 - * - * @param pulsar - * PulsarMQ 实例配置 - */ - public void setPulsar(PulsarProperties pulsar) { - this.pulsar = pulsar; - } - - /** - * 返回 TCP 实例配置 - * - * @return TCP 实例配置 - */ - public TcpProperties getTcp() { - return tcp; - } - - /** - * 设置 TCP 实例配置 - * - * @param tcp - * TCP 实例配置 - */ - public void setTcp(TcpProperties tcp) { - this.tcp = tcp; - } +@Deprecated +public class CanalProperties extends com.buession.canal.springboot.autoconfigure.CanalProperties { } diff --git a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/PulsarProperties.java b/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/PulsarProperties.java deleted file mode 100644 index 7fbfc0f2..00000000 --- a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/PulsarProperties.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. - * See the NOTICE file distributed with this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - * - * ========================================================================================================= - * - * This software consists of voluntary contributions made by many individuals on behalf of the - * Apache Software Foundation. For more information on the Apache Software Foundation, please see - * . - * - * +-------------------------------------------------------------------------------------------------------+ - * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | - * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | - * +-------------------------------------------------------------------------------------------------------+ - */ -package com.buession.springboot.canal.autoconfigure; - -import com.buession.canal.client.adapter.PulsarMQAdapterClient; - -/** - * PulsarMQ 适配器配置 - * - * @author Yong.Teng - * @since 2.3.1 - */ -public class PulsarProperties extends AbstractMqAdapterProperties { - - /** - * PulsarMQ 服务地址 - */ - private String serviceUrl; - - /** - * Role Token - */ - private String roleToken; - - /** - * - - */ - private int getBatchTimeout = PulsarMQAdapterClient.DEFAULT_GET_BATCH_TIMEOUT; - - /** - * - - */ - private int batchProcessTimeout = PulsarMQAdapterClient.DEFAULT_BATCH_PROCESS_TIMEOUT; - - /** - * - - */ - private int redeliveryDelay = PulsarMQAdapterClient.DEFAULT_REDELIVERY_DELAY; - - /** - * - - */ - private int ackTimeout = PulsarMQAdapterClient.DEFAULT_ACK_TIMEOUT; - - /** - * 是否重试 - */ - private boolean retry = true; - - /** - * - - */ - private boolean retryDLQUpperCase = true; - - /** - * - - */ - private Integer maxRedeliveryCount; - - /** - * 返回 PulsarMQ 服务地址 - * - * @return PulsarMQ 服务地址 - */ - public String getServiceUrl() { - return serviceUrl; - } - - /** - * 设置 PulsarMQ 服务地址 - * - * @param serviceUrl - * PulsarMQ 服务地址 - */ - public void setServiceUrl(String serviceUrl) { - this.serviceUrl = serviceUrl; - } - - /** - * 返回 Role Token - * - * @return Role Token - */ - public String getRoleToken() { - return roleToken; - } - - /** - * 设置 Role Token - * - * @param roleToken - * Role Token - */ - public void setRoleToken(String roleToken) { - this.roleToken = roleToken; - } - - public int getGetBatchTimeout() { - return getBatchTimeout; - } - - public void setGetBatchTimeout(int getBatchTimeout) { - this.getBatchTimeout = getBatchTimeout; - } - - public int getBatchProcessTimeout() { - return batchProcessTimeout; - } - - public void setBatchProcessTimeout(int batchProcessTimeout) { - this.batchProcessTimeout = batchProcessTimeout; - } - - public int getRedeliveryDelay() { - return redeliveryDelay; - } - - public void setRedeliveryDelay(int redeliveryDelay) { - this.redeliveryDelay = redeliveryDelay; - } - - public int getAckTimeout() { - return ackTimeout; - } - - public void setAckTimeout(int ackTimeout) { - this.ackTimeout = ackTimeout; - } - - /** - * 返回是否重试 - * - * @return true / false - */ - public boolean isRetry() { - return retry; - } - - /** - * 设置是否重试 - * - * @param retry - * true / false - */ - public void setRetry(boolean retry) { - this.retry = retry; - } - - public boolean isRetryDLQUpperCase() { - return retryDLQUpperCase; - } - - public void setRetryDLQUpperCase(boolean retryDLQUpperCase) { - this.retryDLQUpperCase = retryDLQUpperCase; - } - - public Integer getMaxRedeliveryCount() { - return maxRedeliveryCount; - } - - public void setMaxRedeliveryCount(Integer maxRedeliveryCount) { - this.maxRedeliveryCount = maxRedeliveryCount; - } - - public final static class Instance extends AbstractMqAdapterProperties.MqBaseInstanceConfiguration { - - /** - * 订阅名称 - */ - private String subscriptName; - - public Instance() { - super(); - } - - /** - * 返回订阅名称 - * - * @return 订阅名称 - */ - public String getSubscriptName() { - return subscriptName; - } - - /** - * 设置订阅名称 - * - * @param subscriptName - * 订阅名称 - */ - public void setSubscriptName(String subscriptName) { - this.subscriptName = subscriptName; - } - - } - -} diff --git a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/RabbitProperties.java b/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/RabbitProperties.java deleted file mode 100644 index 1d8c87e8..00000000 --- a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/RabbitProperties.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. - * See the NOTICE file distributed with this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - * - * ========================================================================================================= - * - * This software consists of voluntary contributions made by many individuals on behalf of the - * Apache Software Foundation. For more information on the Apache Software Foundation, please see - * . - * - * +-------------------------------------------------------------------------------------------------------+ - * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | - * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | - * +-------------------------------------------------------------------------------------------------------+ - */ -package com.buession.springboot.canal.autoconfigure; - -/** - * RabbitMQ 适配器配置 - * - * @author Yong.Teng - * @since 2.3.1 - */ -public class RabbitProperties extends AbstractMqAdapterProperties { - - /** - * RabbitMQ 主机地址 - */ - private String server; - - /** - * Virtual Host - */ - private String virtualHost; - - /** - * 用户名 - */ - private String username; - - /** - * 密码 - */ - private String password; - - /** - * 返回 RabbitMQ 主机地址 - * - * @return RabbitMQ 主机地址 - */ - public String getServer() { - return server; - } - - /** - * 设置 RabbitMQ 主机地址 - * - * @param server - * RabbitMQ 主机地址 - */ - public void setServer(String server) { - this.server = server; - } - - /** - * 返回 Virtual Host - * - * @return Virtual Host - */ - public String getVirtualHost() { - return virtualHost; - } - - /** - * 设置 Virtual Host - * - * @param virtualHost - * Virtual Host - */ - public void setVirtualHost(String virtualHost) { - this.virtualHost = virtualHost; - } - - /** - * 返回用户名 - * - * @return 用户名 - */ - public String getUsername() { - return username; - } - - /** - * 设置用户名 - * - * @param username - * 用户名 - */ - public void setUsername(String username) { - this.username = username; - } - - /** - * 返回密码 - * - * @return 密码 - */ - public String getPassword() { - return password; - } - - /** - * 设置密码 - * - * @param password - * 密码 - */ - public void setPassword(String password) { - this.password = password; - } - - public final static class Instance extends AbstractMqAdapterProperties.MqBaseInstanceConfiguration { - - public Instance() { - super(); - } - - } - -} diff --git a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/RocketProperties.java b/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/RocketProperties.java deleted file mode 100644 index 99d794eb..00000000 --- a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/RocketProperties.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. - * See the NOTICE file distributed with this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - * - * ========================================================================================================= - * - * This software consists of voluntary contributions made by many individuals on behalf of the - * Apache Software Foundation. For more information on the Apache Software Foundation, please see - * . - * - * +-------------------------------------------------------------------------------------------------------+ - * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | - * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | - * +-------------------------------------------------------------------------------------------------------+ - */ -package com.buession.springboot.canal.autoconfigure; - -/** - * RocketMQ 适配器配置 - * - * @author Yong.Teng - * @since 2.3.1 - */ -public class RocketProperties extends AbstractMqAdapterProperties { - - /** - * RocketMQ NameServer 地址 - */ - private String nameServer; - - /** - * 是否启用消息跟踪 - */ - private Boolean enableMessageTrace; - - /** - * 消息轨迹数据 Topic - */ - private String customizedTraceTopic; - - /** - * - - */ - private String accessChannel; - - /** - * 返回 RocketMQ NameServer 地址 - * - * @return RocketMQ NameServer 地址 - */ - public String getNameServer() { - return nameServer; - } - - /** - * 设置 RocketMQ NameServer 地址 - * - * @param nameServer - * RocketMQ NameServer 地址 - */ - public void setNameServer(String nameServer) { - this.nameServer = nameServer; - } - - /** - * 返回是否启用消息跟踪 - * - * @return true / false - */ - public Boolean getEnableMessageTrace() { - return enableMessageTrace; - } - - /** - * 设置是否启用消息跟踪 - * - * @param enableMessageTrace - * true / false - */ - public void setEnableMessageTrace(Boolean enableMessageTrace) { - this.enableMessageTrace = enableMessageTrace; - } - - /** - * 返回消息轨迹数据 Topic - * - * @return 消息轨迹数据 Topic - */ - public String getCustomizedTraceTopic() { - return customizedTraceTopic; - } - - /** - * 设置消息轨迹数据 Topic - * - * @param customizedTraceTopic - * 消息轨迹数据 Topic - */ - public void setCustomizedTraceTopic(String customizedTraceTopic) { - this.customizedTraceTopic = customizedTraceTopic; - } - - public String getAccessChannel() { - return accessChannel; - } - - public void setAccessChannel(String accessChannel) { - this.accessChannel = accessChannel; - } - - public final static class Instance extends AbstractMqAdapterProperties.MqBaseInstanceConfiguration { - - /** - * Group ID - */ - private String groupId; - - /** - * 名称空间 - */ - private String namespace; - - public Instance() { - super(); - } - - /** - * 返回 Group ID - * - * @return Group ID - */ - public String getGroupId() { - return groupId; - } - - /** - * 设置 Group ID - * - * @param groupId - * Group ID - */ - public void setGroupId(String groupId) { - this.groupId = groupId; - } - - /** - * 返回名称空间 - * - * @return 名称空间 - */ - public String getNamespace() { - return namespace; - } - - /** - * 设置名称空间 - * - * @param namespace - * 名称空间 - */ - public void setNamespace(String namespace) { - this.namespace = namespace; - } - - } - -} diff --git a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/TcpProperties.java b/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/TcpProperties.java deleted file mode 100644 index 3610fc3a..00000000 --- a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/TcpProperties.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. - * See the NOTICE file distributed with this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - * - * ========================================================================================================= - * - * This software consists of voluntary contributions made by many individuals on behalf of the - * Apache Software Foundation. For more information on the Apache Software Foundation, please see - * . - * - * +-------------------------------------------------------------------------------------------------------+ - * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | - * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | - * +-------------------------------------------------------------------------------------------------------+ - */ -package com.buession.springboot.canal.autoconfigure; - -/** - * Kafka 适配器配置 - * - * @author Yong.Teng - * @since 2.3.1 - */ -public class TcpProperties extends AbstractAdapterProperties { - - /** - * 主机地址 - */ - private String server; - - /** - * Zookeeper 主机地址 - */ - private String zkServers; - - /** - * 用户名 - */ - private String username; - - /** - * 密码 - */ - private String password; - - /** - * 返回主机地址 - * - * @return 主机地址 - */ - public String getServer() { - return server; - } - - /** - * 设置主机地址 - * - * @param server - * 主机地址 - */ - public void setServer(String server) { - this.server = server; - } - - /** - * 返回 Zookeeper 主机地址 - * - * @return Zookeeper 主机地址 - */ - public String getZkServers() { - return zkServers; - } - - /** - * 设置 Zookeeper 主机地址 - * - * @param zkServers - * Zookeeper 主机地址 - */ - public void setZkServers(String zkServers) { - this.zkServers = zkServers; - } - - /** - * 返回用户名 - * - * @return 用户名 - */ - public String getUsername() { - return username; - } - - /** - * 设置用户名 - * - * @param username - * 用户名 - */ - public void setUsername(String username) { - this.username = username; - } - - /** - * 返回密码 - * - * @return 密码 - */ - public String getPassword() { - return password; - } - - /** - * 设置密码 - * - * @param password - * 密码 - */ - public void setPassword(String password) { - this.password = password; - } - - public final static class Instance extends AbstractAdapterProperties.BaseInstanceConfiguration { - - public Instance() { - } - - } - -} diff --git a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/ThreadPoolConfiguration.java b/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/ThreadPoolConfiguration.java index 6b2efa04..6872f260 100644 --- a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/ThreadPoolConfiguration.java +++ b/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/ThreadPoolConfiguration.java @@ -24,67 +24,22 @@ */ package com.buession.springboot.canal.autoconfigure; -import com.buession.canal.core.concurrent.DefaultCanalThreadPoolExecutor; -import com.buession.springboot.canal.ThreadConfig; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.RejectedExecutionHandler; -import java.util.concurrent.ThreadPoolExecutor; - /** * @author Yong.Teng * @since 2.3.1 */ @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties({CanalProperties.class}) -public class ThreadPoolConfiguration { - - private final ThreadConfig thread; +@ConditionalOnMissingBean(com.buession.canal.springboot.autoconfigure.ThreadPoolConfiguration.class) +@Deprecated +public class ThreadPoolConfiguration extends com.buession.canal.springboot.autoconfigure.ThreadPoolConfiguration { public ThreadPoolConfiguration(CanalProperties canalProperties) { - this.thread = canalProperties.getThread(); - } - - @Bean(name = "canalExecutorService", destroyMethod = "shutdown") - public ExecutorService executorService() { - RejectedExecutionHandler rejectedExecutionHandler; - - switch(thread.getPolicy()){ - case ABORT: - rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy(); - break; - case CALLER_RUNS: - rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy(); - break; - case DISCARD: - rejectedExecutionHandler = new ThreadPoolExecutor.DiscardPolicy(); - break; - case DISCARD_OLDEST: - rejectedExecutionHandler = new ThreadPoolExecutor.DiscardOldestPolicy(); - break; - default: - rejectedExecutionHandler = new ThreadPoolExecutor.DiscardPolicy(); - break; - } - - Integer corePoolSize = thread.getCorePoolSize(); - Integer maximumPoolSize = thread.getMaximumPoolSize(); - - if(corePoolSize == null || maximumPoolSize == null){ - int coreSize = Runtime.getRuntime().availableProcessors(); - if(corePoolSize == null){ - corePoolSize = coreSize << 1; - } - if(maximumPoolSize == null){ - maximumPoolSize = coreSize << 1; - } - } - - return new DefaultCanalThreadPoolExecutor(thread.getNamePrefix(), corePoolSize, maximumPoolSize, - thread.getKeepAliveTime().toMillis(), rejectedExecutionHandler); + super(canalProperties); } } diff --git a/buession-springboot-captcha/pom.xml b/buession-springboot-captcha/pom.xml index 525b3037..fe4c6d32 100644 --- a/buession-springboot-captcha/pom.xml +++ b/buession-springboot-captcha/pom.xml @@ -7,7 +7,7 @@ com.buession.springboot buession-springboot-parent ../buession-springboot-parent - 2.3.2 + 2.3.3 buession-springboot-captcha https://springboot.buession.com/ diff --git a/buession-springboot-captcha/src/main/java/com/buession/springboot/captcha/autoconfigure/CaptchaWebConfiguration.java b/buession-springboot-captcha/src/main/java/com/buession/springboot/captcha/autoconfigure/CaptchaWebConfiguration.java index 509d3272..062675ae 100644 --- a/buession-springboot-captcha/src/main/java/com/buession/springboot/captcha/autoconfigure/CaptchaWebConfiguration.java +++ b/buession-springboot-captcha/src/main/java/com/buession/springboot/captcha/autoconfigure/CaptchaWebConfiguration.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.captcha.autoconfigure; @@ -65,6 +65,11 @@ public AbstractCaptchaWebConfiguration(CaptchaProperties properties) { this.properties = properties; } + protected GeetestParameter getGeetestParameter(final GeetestCaptchaClient geetestCaptchaClient) { + return geetestCaptchaClient.isV3() ? properties.getGeetest().getV3() + .getParameter() : properties.getGeetest().getV4().getParameter(); + } + } @Configuration(proxyBeanMethods = false) @@ -91,9 +96,8 @@ public ServletAliYunCaptchaValidator aliYunCaptchaValidator( @ConditionalOnBean({GeetestCaptchaClient.class}) public ServletGeetestCaptchaValidator geetestCaptchaValidator( ObjectProvider geetestCaptchaClient) { - GeetestParameter parameter = geetestCaptchaClient.getIfAvailable().isV3() ? properties.getGeetest().getV3() - .getParameter() : properties.getGeetest().getV4().getParameter(); - return new ServletGeetestCaptchaValidator(geetestCaptchaClient.getIfAvailable(), parameter); + return new ServletGeetestCaptchaValidator(geetestCaptchaClient.getIfAvailable(), + getGeetestParameter(geetestCaptchaClient.getIfAvailable())); } @Bean @@ -131,9 +135,8 @@ public ReactiveAliYunCaptchaValidator aliYunCaptchaValidator( @ConditionalOnBean({GeetestCaptchaClient.class}) public ReactiveGeetestCaptchaValidator geetestCaptchaValidator( ObjectProvider geetestCaptchaClient) { - GeetestParameter parameter = geetestCaptchaClient.getIfAvailable().isV3() ? properties.getGeetest().getV3() - .getParameter() : properties.getGeetest().getV4().getParameter(); - return new ReactiveGeetestCaptchaValidator(geetestCaptchaClient.getIfAvailable(), parameter); + return new ReactiveGeetestCaptchaValidator(geetestCaptchaClient.getIfAvailable(), + getGeetestParameter(geetestCaptchaClient.getIfAvailable())); } @Bean diff --git a/buession-springboot-cli/pom.xml b/buession-springboot-cli/pom.xml index 64e7c814..cd07312f 100644 --- a/buession-springboot-cli/pom.xml +++ b/buession-springboot-cli/pom.xml @@ -7,7 +7,7 @@ com.buession.springboot buession-springboot-parent ../buession-springboot-parent - 2.3.2 + 2.3.3 buession-springboot-cli https://springboot.buession.com/ diff --git a/buession-springboot-datasource/pom.xml b/buession-springboot-datasource/pom.xml index 86f9ee21..6c51fe9c 100644 --- a/buession-springboot-datasource/pom.xml +++ b/buession-springboot-datasource/pom.xml @@ -7,7 +7,7 @@ com.buession.springboot buession-springboot-parent ../buession-springboot-parent - 2.3.2 + 2.3.3 buession-springboot-datasource https://springboot.buession.com/ diff --git a/buession-springboot-datasource/src/main/java/com/buession/springboot/datasource/autoconfigure/DataSourceInitializer.java b/buession-springboot-datasource/src/main/java/com/buession/springboot/datasource/autoconfigure/DataSourceInitializer.java index 788f7ea8..555f0b7b 100644 --- a/buession-springboot-datasource/src/main/java/com/buession/springboot/datasource/autoconfigure/DataSourceInitializer.java +++ b/buession-springboot-datasource/src/main/java/com/buession/springboot/datasource/autoconfigure/DataSourceInitializer.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.datasource.autoconfigure; @@ -72,7 +72,7 @@ public DataSource createDataSource() { if(logger.isInfoEnabled()){ logger.info("Create master datasource: by driver {}, type {}", properties.getDriverClassName(), - this.type.getName()); + type.getName()); } if(Validate.isEmpty(properties.getSlaves())){ @@ -84,7 +84,7 @@ public DataSource createDataSource() { if(logger.isInfoEnabled()){ logger.info("Create {} size slave datasource: by driver {}, type {}", dataSource.getSlaves().size(), - properties.getDriverClassName(), this.type.getName()); + properties.getDriverClassName(), type.getName()); } return dataSource; diff --git a/buession-springboot-datasource/src/main/java/com/buession/springboot/datasource/autoconfigure/DataSourcePoolMetadataProvidersConfiguration.java b/buession-springboot-datasource/src/main/java/com/buession/springboot/datasource/autoconfigure/DataSourcePoolMetadataProvidersConfiguration.java index b7d91093..3c58618d 100644 --- a/buession-springboot-datasource/src/main/java/com/buession/springboot/datasource/autoconfigure/DataSourcePoolMetadataProvidersConfiguration.java +++ b/buession-springboot-datasource/src/main/java/com/buession/springboot/datasource/autoconfigure/DataSourcePoolMetadataProvidersConfiguration.java @@ -19,13 +19,12 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.datasource.autoconfigure; import com.alibaba.druid.pool.DruidDataSourceMBean; -import com.buession.core.utils.ObjectUtils; import com.buession.core.validator.Validate; import com.buession.jdbc.datasource.Dbcp2DataSource; import com.buession.jdbc.datasource.DruidDataSource; @@ -46,6 +45,7 @@ import org.springframework.context.annotation.Configuration; import java.util.ArrayList; +import java.util.Optional; /** * DataSource Pool Metadata Providers {@link DataSourcePoolMetadataProvider} Auto Configuration @@ -75,8 +75,8 @@ public DataSourcePoolMetadataProvider.HikariDataSourcePoolMetadataProvider poolD com.zaxxer.hikari.HikariDataSource hikariDataSource = DataSourceUnwrapper.unwrap(dataSource.getMaster(), HikariConfigMXBean.class, com.zaxxer.hikari.HikariDataSource.class); - ObjectUtils.invokeIfAvailable(hikariDataSource, - (ds)->dataSourcePoolMetadata.setMaster(new HikariDataSourcePoolMetadata(ds))); + Optional.ofNullable(hikariDataSource) + .ifPresent((ds)->dataSourcePoolMetadata.setMaster(new HikariDataSourcePoolMetadata(ds))); if(Validate.isNotEmpty(dataSource.getSlaves())){ dataSourcePoolMetadata.setSlaves(new ArrayList<>(dataSource.getSlaves().size())); @@ -84,7 +84,7 @@ public DataSourcePoolMetadataProvider.HikariDataSourcePoolMetadataProvider poolD for(javax.sql.DataSource datasource : dataSource.getSlaves()){ hikariDataSource = DataSourceUnwrapper.unwrap(datasource, HikariConfigMXBean.class, com.zaxxer.hikari.HikariDataSource.class); - ObjectUtils.invokeIfAvailable(hikariDataSource, + Optional.ofNullable(hikariDataSource).ifPresent( (ds)->dataSourcePoolMetadata.getSlaves().add(new HikariDataSourcePoolMetadata(ds))); } } @@ -109,8 +109,8 @@ public DataSourcePoolMetadataProvider.Dbcp2DataSourcePoolMetadataProvider poolDa dataSource.getMaster(), BasicDataSourceMXBean.class, org.apache.commons.dbcp2.BasicDataSource.class); - ObjectUtils.invokeIfAvailable(dbcp2DataSource, - (ds)->dataSourcePoolMetadata.setMaster(new CommonsDbcp2DataSourcePoolMetadata(ds))); + Optional.ofNullable(dbcp2DataSource) + .ifPresent((ds)->dataSourcePoolMetadata.setMaster(new CommonsDbcp2DataSourcePoolMetadata(ds))); if(Validate.isNotEmpty(dataSource.getSlaves())){ dataSourcePoolMetadata.setSlaves(new ArrayList<>(dataSource.getSlaves().size())); @@ -118,9 +118,8 @@ public DataSourcePoolMetadataProvider.Dbcp2DataSourcePoolMetadataProvider poolDa for(javax.sql.DataSource datasource : dataSource.getSlaves()){ dbcp2DataSource = DataSourceUnwrapper.unwrap(datasource, BasicDataSourceMXBean.class, org.apache.commons.dbcp2.BasicDataSource.class); - ObjectUtils.invokeIfAvailable(dbcp2DataSource, - (ds)->dataSourcePoolMetadata.getSlaves() - .add(new CommonsDbcp2DataSourcePoolMetadata(ds))); + Optional.ofNullable(dbcp2DataSource).ifPresent((ds)->dataSourcePoolMetadata.getSlaves() + .add(new CommonsDbcp2DataSourcePoolMetadata(ds))); } } @@ -144,8 +143,8 @@ public DataSourcePoolMetadataProvider.DruidDataSourcePoolMetadataProvider poolDa dataSource.getMaster(), DruidDataSourceMBean.class, com.alibaba.druid.pool.DruidDataSource.class); - ObjectUtils.invokeIfAvailable(druidDataSource, - (ds)->dataSourcePoolMetadata.setMaster(new DruidDataSourcePoolMetadata(ds))); + Optional.ofNullable(druidDataSource) + .ifPresent((ds)->dataSourcePoolMetadata.setMaster(new DruidDataSourcePoolMetadata(ds))); if(Validate.isNotEmpty(dataSource.getSlaves())){ dataSourcePoolMetadata.setSlaves(new ArrayList<>(dataSource.getSlaves().size())); @@ -153,7 +152,7 @@ public DataSourcePoolMetadataProvider.DruidDataSourcePoolMetadataProvider poolDa for(javax.sql.DataSource datasource : dataSource.getSlaves()){ druidDataSource = DataSourceUnwrapper.unwrap(datasource, DruidDataSourceMBean.class, com.alibaba.druid.pool.DruidDataSource.class); - ObjectUtils.invokeIfAvailable(druidDataSource, + Optional.ofNullable(druidDataSource).ifPresent( (ds)->dataSourcePoolMetadata.getSlaves().add(new DruidDataSourcePoolMetadata(ds))); } } @@ -178,8 +177,8 @@ public DataSourcePoolMetadataProvider.TomcatDataSourcePoolMetadataProvider poolD dataSource.getMaster(), ConnectionPoolMBean.class, org.apache.tomcat.jdbc.pool.DataSource.class); - ObjectUtils.invokeIfAvailable(tomcatDataSource, - (ds)->dataSourcePoolMetadata.setMaster(new TomcatDataSourcePoolMetadata(ds))); + Optional.ofNullable(tomcatDataSource) + .ifPresent((ds)->dataSourcePoolMetadata.setMaster(new TomcatDataSourcePoolMetadata(ds))); if(Validate.isNotEmpty(dataSource.getSlaves())){ dataSourcePoolMetadata.setSlaves(new ArrayList<>(dataSource.getSlaves().size())); @@ -187,7 +186,7 @@ public DataSourcePoolMetadataProvider.TomcatDataSourcePoolMetadataProvider poolD for(javax.sql.DataSource datasource : dataSource.getSlaves()){ tomcatDataSource = DataSourceUnwrapper.unwrap(datasource, ConnectionPoolMBean.class, org.apache.tomcat.jdbc.pool.DataSource.class); - ObjectUtils.invokeIfAvailable(tomcatDataSource, + Optional.ofNullable(tomcatDataSource).ifPresent( (ds)->dataSourcePoolMetadata.getSlaves().add(new TomcatDataSourcePoolMetadata(ds))); } } diff --git a/buession-springboot-geoip/pom.xml b/buession-springboot-geoip/pom.xml index 49a023bd..9e97ab6d 100644 --- a/buession-springboot-geoip/pom.xml +++ b/buession-springboot-geoip/pom.xml @@ -7,7 +7,7 @@ com.buession.springboot buession-springboot-parent ../buession-springboot-parent - 2.3.2 + 2.3.3 buession-springboot-geoip https://springboot.buession.com/ diff --git a/buession-springboot-httpclient/pom.xml b/buession-springboot-httpclient/pom.xml index 57d3aa00..b93e350f 100644 --- a/buession-springboot-httpclient/pom.xml +++ b/buession-springboot-httpclient/pom.xml @@ -7,7 +7,7 @@ com.buession.springboot buession-springboot-parent ../buession-springboot-parent - 2.3.2 + 2.3.3 buession-springboot-httpclient https://springboot.buession.com/ diff --git a/buession-springboot-httpclient/src/main/java/com/buession/springboot/httpclient/autoconfigure/ApacheHttpClientConfiguration.java b/buession-springboot-httpclient/src/main/java/com/buession/springboot/httpclient/autoconfigure/ApacheHttpClientConfiguration.java index ae1faa9c..ac9cfda1 100644 --- a/buession-springboot-httpclient/src/main/java/com/buession/springboot/httpclient/autoconfigure/ApacheHttpClientConfiguration.java +++ b/buession-springboot-httpclient/src/main/java/com/buession/springboot/httpclient/autoconfigure/ApacheHttpClientConfiguration.java @@ -19,12 +19,11 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.httpclient.autoconfigure; -import com.buession.core.utils.ObjectUtils; import com.buession.httpclient.ApacheHttpAsyncClient; import com.buession.httpclient.ApacheHttpClient; import com.buession.httpclient.conn.ApacheClientConnectionManager; @@ -38,6 +37,8 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import java.util.Optional; + /** * Apache HttpClient Auto Configuration * @@ -99,10 +100,10 @@ public ApacheNioClientConnectionManager clientConnectionManager() { new ApacheNioClientConnectionManager(properties); if(properties.getApacheClient() != null){ - ObjectUtils.invokeIfAvailable(properties.getApacheClient().getIoReactor(), - clientConnectionManager::setIoReactorConfig); - ObjectUtils.invokeIfAvailable(properties.getApacheClient().getThreadFactory(), - (threadFactory)->clientConnectionManager.setThreadFactory( + Optional.ofNullable(properties.getApacheClient().getIoReactor()) + .ifPresent(clientConnectionManager::setIoReactorConfig); + Optional.ofNullable(properties.getApacheClient().getThreadFactory()) + .ifPresent((threadFactory)->clientConnectionManager.setThreadFactory( BeanUtils.instantiateClass(threadFactory))); } diff --git a/buession-springboot-mongodb/pom.xml b/buession-springboot-mongodb/pom.xml index 839356af..fabda635 100644 --- a/buession-springboot-mongodb/pom.xml +++ b/buession-springboot-mongodb/pom.xml @@ -7,7 +7,7 @@ com.buession.springboot buession-springboot-parent ../buession-springboot-parent - 2.3.2 + 2.3.3 buession-springboot-mongodb https://springboot.buession.com/ diff --git a/buession-springboot-mongodb/src/main/java/com/buession/springboot/mongodb/autoconfigure/MongoDBConfiguration.java b/buession-springboot-mongodb/src/main/java/com/buession/springboot/mongodb/autoconfigure/MongoDBConfiguration.java index 78ed9dd7..3d3949b7 100644 --- a/buession-springboot-mongodb/src/main/java/com/buession/springboot/mongodb/autoconfigure/MongoDBConfiguration.java +++ b/buession-springboot-mongodb/src/main/java/com/buession/springboot/mongodb/autoconfigure/MongoDBConfiguration.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.mongodb.autoconfigure; @@ -47,7 +47,7 @@ public class MongoDBConfiguration { public MongoDBConfiguration(MongoDBProperties properties, ObjectProvider mongoMappingContext, - ObjectProvider mappingMongoConverter){ + ObjectProvider mappingMongoConverter) { MongoMappingContext mappingContext = mongoMappingContext.getIfAvailable(); MongoTypeMapper mongoTypeMapper; @@ -55,11 +55,10 @@ public MongoDBConfiguration(MongoDBProperties properties, ObjectProvidermongoConverter.setTypeMapper(mongoTypeMapper)); + mappingMongoConverter.ifAvailable((mongoConverter)->mongoConverter.setTypeMapper(mongoTypeMapper)); } } diff --git a/buession-springboot-mongodb/src/main/java/com/buession/springboot/mongodb/autoconfigure/MongoDBProperties.java b/buession-springboot-mongodb/src/main/java/com/buession/springboot/mongodb/autoconfigure/MongoDBProperties.java index 2458d88e..8a2d3127 100644 --- a/buession-springboot-mongodb/src/main/java/com/buession/springboot/mongodb/autoconfigure/MongoDBProperties.java +++ b/buession-springboot-mongodb/src/main/java/com/buession/springboot/mongodb/autoconfigure/MongoDBProperties.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.mongodb.autoconfigure; @@ -54,31 +54,31 @@ public class MongoDBProperties { @Deprecated private Class readPreference; - public Class getTypeMapper(){ + public Class getTypeMapper() { return typeMapper; } - public void setTypeMapper(Class typeMapper){ + public void setTypeMapper(Class typeMapper) { this.typeMapper = typeMapper; } - public String getTypeKey(){ + public String getTypeKey() { return typeKey; } - public void setTypeKey(String typeKey){ + public void setTypeKey(String typeKey) { this.typeKey = typeKey; } @Deprecated @DeprecatedConfigurationProperty - public Class getReadPreference(){ + public Class getReadPreference() { return readPreference; } @Deprecated @DeprecatedConfigurationProperty - public void setReadPreference(Class readPreference){ + public void setReadPreference(Class readPreference) { this.readPreference = readPreference; } diff --git a/buession-springboot-mongodb/src/main/java/com/buession/springboot/mongodb/autoconfigure/package-info.java b/buession-springboot-mongodb/src/main/java/com/buession/springboot/mongodb/autoconfigure/package-info.java index 77917f37..40735a12 100644 --- a/buession-springboot-mongodb/src/main/java/com/buession/springboot/mongodb/autoconfigure/package-info.java +++ b/buession-springboot-mongodb/src/main/java/com/buession/springboot/mongodb/autoconfigure/package-info.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2018 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ /** diff --git a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/AdapterProperties.java b/buession-springboot-mongodb/src/main/java/com/buession/springboot/mongodb/package-info.java similarity index 78% rename from buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/AdapterProperties.java rename to buession-springboot-mongodb/src/main/java/com/buession/springboot/mongodb/package-info.java index ac2ccf21..013eeb46 100644 --- a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/AdapterProperties.java +++ b/buession-springboot-mongodb/src/main/java/com/buession/springboot/mongodb/package-info.java @@ -19,29 +19,10 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ -package com.buession.springboot.canal.autoconfigure; - -import com.buession.canal.core.Configuration; - -import java.util.Map; - /** - * Canal 适配器配置 - * * @author Yong.Teng - * @since 2.3.1 */ -@FunctionalInterface -interface AdapterProperties { - - /** - * 返回实例清单 - * - * @return 实例清单 - */ - Map getInstances(); - -} +package com.buession.springboot.mongodb; \ No newline at end of file diff --git a/buession-springboot-mybatis/pom.xml b/buession-springboot-mybatis/pom.xml index b36ca36d..4d4e1bd6 100644 --- a/buession-springboot-mybatis/pom.xml +++ b/buession-springboot-mybatis/pom.xml @@ -7,7 +7,7 @@ com.buession.springboot buession-springboot-parent ../buession-springboot-parent - 2.3.2 + 2.3.3 buession-springboot-mybatis https://springboot.buession.com/ @@ -89,6 +89,14 @@ mybatis-typehandlers-threeten-extra + + org.mybatis.scripting mybatis-freemarker diff --git a/buession-springboot-mybatis/src/main/java/com/buession/springboot/mybatis/ConfiguredMapperScannerRegistrar.java b/buession-springboot-mybatis/src/main/java/com/buession/springboot/mybatis/ConfiguredMapperScannerRegistrar.java index 436d6916..ecbc8332 100644 --- a/buession-springboot-mybatis/src/main/java/com/buession/springboot/mybatis/ConfiguredMapperScannerRegistrar.java +++ b/buession-springboot-mybatis/src/main/java/com/buession/springboot/mybatis/ConfiguredMapperScannerRegistrar.java @@ -26,6 +26,7 @@ import com.buession.core.utils.StringUtils; import com.buession.core.validator.Validate; +import com.buession.lang.Constants; import com.buession.springboot.mybatis.autoconfigure.MybatisProperties; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.slf4j.Logger; @@ -49,6 +50,7 @@ import java.util.Arrays; import java.util.List; +import java.util.Optional; import java.util.stream.Stream; /** @@ -67,12 +69,12 @@ public class ConfiguredMapperScannerRegistrar implements EnvironmentAware, BeanF private final static Logger logger = LoggerFactory.getLogger(ConfiguredMapperScannerRegistrar.class); @Override - public void setEnvironment(Environment environment) { + public void setEnvironment(@NonNull Environment environment) { this.environment = environment; } @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + public void setBeanFactory(@NonNull BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } @@ -87,18 +89,10 @@ public void registerBeanDefinitions(@NonNull AnnotationMetadata annotationMetada } public void registerBeanDefinition(@NonNull BeanDefinitionRegistry registry) { - String basePackage = getProperty("base-package", "basePackage", String.class); - List basePackages = Validate.isBlank(basePackage) ? AutoConfigurationPackages.get( - beanFactory) : Arrays.asList(com.buession.core.utils.StringUtils.split(basePackage, ',')); + final BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition( + MapperScannerConfigurer.class); - if(logger.isDebugEnabled()){ - basePackages.forEach((pkg)->logger.debug("Using auto-configuration base package '{}'", pkg)); - } - - BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class); - builder.addPropertyValue("processPropertyPlaceHolders", true); - - String annotationClassName = getProperty("annotation-class", "annotationClass", String.class); + String annotationClassName = getProperty("annotation-class", "annotationClass"); try{ Class annotationClass = annotationClassName == null ? @@ -107,27 +101,41 @@ public void registerBeanDefinition(@NonNull BeanDefinitionRegistry registry) { builder.addPropertyValue("annotationClass", annotationClass); if(logger.isDebugEnabled()){ - logger.debug("Searching for mappers annotated with @{}", annotationClass.getSimpleName()); + logger.debug("Searching for mappers annotated with @{}", annotationClass.getName()); } }catch(ClassNotFoundException e){ throw new BeanInitializationException(e.getMessage()); } + String basePackage = getProperty("base-package", "basePackage"); + List basePackages = Validate.isBlank(basePackage) ? AutoConfigurationPackages.get( + beanFactory) : Arrays.asList(com.buession.core.utils.StringUtils.split(basePackage, ',')); + + if(logger.isDebugEnabled()){ + basePackages.forEach((pkg)->logger.debug("Using auto-configuration base package '{}'", pkg)); + } + + builder.addPropertyValue("processPropertyPlaceHolders", true); builder.addPropertyValue("basePackage", StringUtils.join(basePackages, ',')); BeanWrapper beanWrapper = new BeanWrapperImpl(MapperScannerConfigurer.class); Stream.of(beanWrapper.getPropertyDescriptors()).filter((x)->"lazyInitialization".equals(x.getName())).findAny() .ifPresent((x)->builder.addPropertyValue("lazyInitialization", - "${" + PREFIX + ".lazy-initialization:false}")); + getProperty("lazy-initialization", "lazyInitialization", Boolean.class, false))); Stream.of(beanWrapper.getPropertyDescriptors()).filter((x)->"defaultScope".equals(x.getName())).findAny() - .ifPresent((x)->builder.addPropertyValue("defaultScope", "${" + PREFIX + ".mapper-default-scope:}")); + .ifPresent((x)->builder.addPropertyValue("defaultScope", getProperty("mapper-default-scope", + "mapperDefaultScope", Constants.EMPTY_STRING))); builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(MapperScannerConfigurer.class.getName(), builder.getBeanDefinition()); } + private String getProperty(final String key, final String humpKey) { + return getProperty(key, humpKey, String.class); + } + private T getProperty(final String key, final String humpKey, final Class targetType) { T value = environment.getProperty(PREFIX + '.' + key, targetType); @@ -138,4 +146,13 @@ private T getProperty(final String key, final String humpKey, final Class return value; } + private String getProperty(final String key, final String humpKey, final String defaultValue) { + return getProperty(key, humpKey, String.class, defaultValue); + } + + private T getProperty(final String key, final String humpKey, final Class targetType, final T defaultValue) { + T value = getProperty(key, humpKey, targetType); + return Optional.ofNullable(value).orElse(defaultValue); + } + } diff --git a/buession-springboot-mybatis/src/main/java/com/buession/springboot/mybatis/autoconfigure/MybatisConfiguration.java b/buession-springboot-mybatis/src/main/java/com/buession/springboot/mybatis/autoconfigure/MybatisConfiguration.java index 04fdcf4d..75271fbc 100644 --- a/buession-springboot-mybatis/src/main/java/com/buession/springboot/mybatis/autoconfigure/MybatisConfiguration.java +++ b/buession-springboot-mybatis/src/main/java/com/buession/springboot/mybatis/autoconfigure/MybatisConfiguration.java @@ -21,7 +21,7 @@ * +------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.mybatis.autoconfigure; @@ -29,6 +29,7 @@ import com.buession.core.collect.Arrays; import com.buession.core.converter.mapper.PropertyMapper; import com.buession.core.utils.Assert; +import com.buession.core.utils.FieldUtils; import com.buession.core.validator.Validate; import com.buession.springboot.datasource.autoconfigure.DataSourceConfiguration; import com.buession.springboot.datasource.core.DataSource; @@ -47,13 +48,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanInstantiationException; -import org.springframework.beans.BeanWrapperImpl; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -62,12 +63,9 @@ import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import java.beans.PropertyDescriptor; import java.io.IOException; import java.util.List; -import java.util.Set; import java.util.stream.Collectors; -import java.util.stream.Stream; /** * @author Yong.Teng @@ -76,7 +74,7 @@ @EnableConfigurationProperties(MybatisProperties.class) @ConditionalOnBean({DataSource.class}) @ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class}) -@AutoConfigureAfter({DataSourceConfiguration.class}) +@AutoConfigureAfter({DataSourceConfiguration.class, MybatisLanguageDriverConfiguration.class}) public class MybatisConfiguration { private final MybatisProperties properties; @@ -87,12 +85,16 @@ public class MybatisConfiguration { private final ResourceLoader resourceLoader; + private Resource configLocationResource = null; + private final DatabaseIdProvider databaseIdProvider; private final List configurationCustomizers; private final LanguageDriver[] languageDrivers; + private final Resource[] mapperLocations; + private final static Logger logger = LoggerFactory.getLogger(MybatisConfiguration.class); public MybatisConfiguration(MybatisProperties properties, ObjectProvider dataSource, @@ -109,6 +111,12 @@ public MybatisConfiguration(MybatisProperties properties, ObjectProvider slaveSqlSessionTemplates(List slaveSqlSessionFactories) { - if(Validate.isEmpty(slaveSqlSessionFactories)){ + public List slaveSqlSessionTemplates( + ObjectProvider> slaveSqlSessionFactories) { + return slaveSqlSessionFactories.getIfAvailable(()->{ throw new BeanInstantiationException(SqlSessionTemplate.class, "slave sqlSessionFactory is null or empty"); - } - - return slaveSqlSessionFactories.stream().map(this::createSqlSessionTemplate).collect(Collectors.toList()); + }).stream().map(this::createSqlSessionTemplate).collect(Collectors.toList()); } @Bean @ConditionalOnMissingBean public List slaveSqlSessionFactories() { - if(Validate.isEmpty(dataSource.getSlaves())){ - throw new BeanInstantiationException(SqlSessionFactory.class, "slave dataSource is null or empty"); - } - + Assert.isEmpty(dataSource.getSlaves(), ()-> + new BeanInstantiationException(SqlSessionFactory.class, "slave dataSource is null or empty")); return dataSource.getSlaves().parallelStream().map(this::createSqlSessionFactory).collect(Collectors.toList()); } @@ -151,8 +156,7 @@ private SqlSessionFactoryBean createSqlSessionFactory(javax.sql.DataSource dataS sessionFactoryBean.setVfs(SpringBootVFS.class); sessionFactoryBean.setFailFast(properties.getFailFast()); - mapper.from(properties::getConfigLocation).as(resourceLoader::getResource) - .to(sessionFactoryBean::setConfigLocation); + mapper.from(this.configLocationResource).to(sessionFactoryBean::setConfigLocation); applyConfiguration(sessionFactoryBean); @@ -164,13 +168,12 @@ private SqlSessionFactoryBean createSqlSessionFactory(javax.sql.DataSource dataS sessionFactoryBean.setPlugins(interceptors); } - mapper.from(properties.getTypeAliasesPackage()).to(sessionFactoryBean::setTypeAliasesPackage); - mapper.from(properties.getTypeAliasesSuperType()).to(sessionFactoryBean::setTypeAliasesSuperType); - mapper.from(properties.getTypeHandlersPackage()).to(sessionFactoryBean::setTypeHandlersPackage); - if(Validate.isNotEmpty(properties.getTypeAliases())){ sessionFactoryBean.setTypeAliases(properties.getTypeAliases()); } + mapper.from(properties.getTypeAliasesPackage()).to(sessionFactoryBean::setTypeAliasesPackage); + mapper.from(properties.getTypeAliasesSuperType()).to(sessionFactoryBean::setTypeAliasesSuperType); + mapper.from(properties.getTypeHandlersPackage()).to(sessionFactoryBean::setTypeHandlersPackage); if(Validate.isNotEmpty(properties.getTypeHandlers())){ sessionFactoryBean.setTypeHandlers(properties.getTypeHandlers()); @@ -179,28 +182,34 @@ private SqlSessionFactoryBean createSqlSessionFactory(javax.sql.DataSource dataS mapper.alwaysApplyingWhenNonNull().from(properties.getDefaultEnumTypeHandler()) .to(sessionFactoryBean::setDefaultEnumTypeHandler); - Resource[] resolveMapperLocations = resolveMapperLocations(); - if(Validate.isNotEmpty(resolveMapperLocations)){ - sessionFactoryBean.setMapperLocations(resolveMapperLocations); + if(Validate.isNotEmpty(this.mapperLocations)){ + sessionFactoryBean.setMapperLocations(this.mapperLocations); } - Set factoryPropertyNames = Stream - .of(new BeanWrapperImpl(SqlSessionFactoryBean.class).getPropertyDescriptors()) - .map(PropertyDescriptor::getName) - .collect(Collectors.toSet()); - Class defaultLanguageDriver = properties.getDefaultScriptingLanguageDriver(); - if(factoryPropertyNames.contains("scriptingLanguageDrivers") && Validate.isNotEmpty(languageDrivers)){ - // Need to mybatis-spring 2.0.2+ - sessionFactoryBean.setScriptingLanguageDrivers(languageDrivers); + if(Validate.isNotEmpty(languageDrivers)){ + try{ + FieldUtils.writeField(sessionFactoryBean, "scriptingLanguageDrivers", languageDrivers); + }catch(IllegalAccessException e){ + if(logger.isWarnEnabled()){ + logger.warn("Set field 'scriptingLanguageDrivers' for {} error: {}", + SqlSessionFactoryBean.class.getName(), e.getMessage()); + } + } + if(defaultLanguageDriver == null && languageDrivers.length == 1){ defaultLanguageDriver = languageDrivers[0].getClass(); } } - if(factoryPropertyNames.contains("defaultScriptingLanguageDriver")){ - // Need to mybatis-spring 2.0.2+ - sessionFactoryBean.setDefaultScriptingLanguageDriver(defaultLanguageDriver); + try{ + FieldUtils.writeDeclaredField(sessionFactoryBean, "defaultScriptingLanguageDriver", defaultLanguageDriver, + true); + }catch(IllegalAccessException e){ + if(logger.isWarnEnabled()){ + logger.warn("Set field 'defaultScriptingLanguageDriver' for {} error: {}", + SqlSessionFactoryBean.class.getName(), e.getMessage()); + } } return sessionFactoryBean; @@ -243,8 +252,7 @@ private Resource[] resolveMapperLocations() { for(String mapperLocation : properties.getMapperLocations()){ try{ - Resource[] mappers = resourceResolver.getResources(mapperLocation); - resources = Arrays.addAll(resources, mappers); + resources = Arrays.addAll(resources, resourceResolver.getResources(mapperLocation)); }catch(IOException e){ if(logger.isErrorEnabled()){ logger.error("Load mapper resource error: {}.", e.getMessage()); @@ -261,6 +269,7 @@ private Resource[] resolveMapperLocations() { @Configuration(proxyBeanMethods = false) @Import(ConfiguredMapperScannerRegistrar.class) @ConditionalOnMissingBean({MapperFactoryBean.class, MapperScannerConfigurer.class}) + @ConditionalOnProperty(prefix = MybatisProperties.PREFIX, name = "scanner.enabled", havingValue = "true", matchIfMissing = true) static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean { @Override diff --git a/buession-springboot-pac4j/pom.xml b/buession-springboot-pac4j/pom.xml index 3f508a56..be61187e 100644 --- a/buession-springboot-pac4j/pom.xml +++ b/buession-springboot-pac4j/pom.xml @@ -7,7 +7,7 @@ com.buession.springboot buession-springboot-parent ../buession-springboot-parent - 2.3.2 + 2.3.3 buession-springboot-pac4j https://springboot.buession.com/ @@ -67,6 +67,7 @@ buession-security-pac4j ${buession.security.version} + org.jasig.cas.client cas-client-core diff --git a/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/autoconfigure/Pac4jCasConfiguration.java b/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/autoconfigure/Pac4jCasConfiguration.java index 6d803db7..5077e7c6 100644 --- a/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/autoconfigure/Pac4jCasConfiguration.java +++ b/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/autoconfigure/Pac4jCasConfiguration.java @@ -19,13 +19,12 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.pac4j.autoconfigure; import com.buession.core.converter.mapper.PropertyMapper; -import com.buession.core.utils.ObjectUtils; import com.buession.core.validator.Validate; import com.buession.springboot.pac4j.config.Cas; import org.pac4j.cas.client.CasClient; @@ -50,6 +49,7 @@ import org.springframework.context.annotation.Configuration; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; /** @@ -137,7 +137,7 @@ protected void clientInit() { }; - ObjectUtils.invokeIfAvailable(config.getCallbackUrl(), casClient::setCallbackUrl); + Optional.ofNullable(config.getCallbackUrl()).ifPresent(casClient::setCallbackUrl); afterClientInitialized(casClient, config.getGeneral()); @@ -220,8 +220,8 @@ public CasRestBasicAuthClient casRestBasicAuthClient() { } protected void doClientInit(final BaseClient client) { - ObjectUtils.invokeIfAvailable(config.getProfileDefinition(), - (profileDefinition)->((CasAuthenticator) client.getAuthenticator()).setProfileDefinition( + Optional.of(config.getProfileDefinition()) + .ifPresent((profileDefinition)->((CasAuthenticator) client.getAuthenticator()).setProfileDefinition( BeanUtils.instantiateClass(profileDefinition))); if(Validate.isNotEmpty(config.getAuthorizationGenerator())){ diff --git a/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/autoconfigure/Pac4jConfiguration.java b/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/autoconfigure/Pac4jConfiguration.java index 43c50ffc..861f9537 100644 --- a/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/autoconfigure/Pac4jConfiguration.java +++ b/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/autoconfigure/Pac4jConfiguration.java @@ -21,20 +21,16 @@ * +------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.pac4j.autoconfigure; -import com.buession.core.utils.ObjectUtils; import com.buession.security.pac4j.spring.reactive.Pac4jWebFluxConfigurerAdapter; import com.buession.security.pac4j.spring.servlet.Pac4jWebMvcConfigurerAdapter; import org.pac4j.core.client.Client; import org.pac4j.core.client.Clients; import org.pac4j.core.config.Config; -import org.pac4j.core.context.WebContext; -import org.pac4j.core.http.adapter.HttpActionAdapter; -import org.pac4j.core.http.ajax.AjaxRequestResolver; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Qualifier; @@ -47,6 +43,7 @@ import org.springframework.core.ReactiveAdapterRegistry; import java.util.List; +import java.util.Optional; /** * Pac4j 基础配置自动加载类 @@ -78,7 +75,7 @@ public Pac4jConfiguration(Pac4jProperties properties) { public Clients clients(List clientList) { final Clients clients = new Clients(clientList); - ObjectUtils.invokeIfAvailable(properties.getAjaxRequestResolverClass(), + Optional.ofNullable(properties.getAjaxRequestResolverClass()).ifPresent( (ajaxRequestResolver)->clients.setAjaxRequestResolver(BeanUtils.instantiateClass(ajaxRequestResolver))); return clients; @@ -94,12 +91,12 @@ public Clients clients(List clientList) { */ @Bean @ConditionalOnMissingBean - public Config config(Clients clients) { + public Config config(ObjectProvider clients) { final Config config = Config.INSTANCE; - config.setClients(clients); + clients.ifAvailable(config::setClients); - ObjectUtils.invokeIfAvailable(properties.getHttpActionAdapterClass(), + Optional.ofNullable(properties.getHttpActionAdapterClass()).ifPresent( (httpActionAdapter)->config.setHttpActionAdapter(BeanUtils.instantiateClass(httpActionAdapter))); return config; diff --git a/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/autoconfigure/Pac4jJwtConfiguration.java b/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/autoconfigure/Pac4jJwtConfiguration.java index 27d5cc89..5104fcaa 100644 --- a/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/autoconfigure/Pac4jJwtConfiguration.java +++ b/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/autoconfigure/Pac4jJwtConfiguration.java @@ -21,16 +21,14 @@ * +------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.pac4j.autoconfigure; -import com.buession.core.utils.ObjectUtils; import com.buession.core.utils.StringUtils; import com.buession.springboot.pac4j.config.Jwt; import org.pac4j.core.profile.CommonProfile; -import org.pac4j.core.util.generator.ValueGenerator; import org.pac4j.http.client.direct.CookieClient; import org.pac4j.http.client.direct.HeaderClient; import org.pac4j.http.client.direct.ParameterClient; @@ -48,6 +46,8 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import java.util.Optional; + /** * Pac4j JWT 自动配置类 * @@ -103,8 +103,8 @@ public JwtAuthenticator jwtAuthenticator(ObjectProviderjwtAuthenticator.setIdentifierGenerator( + Optional.ofNullable(config.getIdentifierGenerator()) + .ifPresent((identifierGenerator)->jwtAuthenticator.setIdentifierGenerator( BeanUtils.instantiateClass(identifierGenerator))); return jwtAuthenticator; diff --git a/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/autoconfigure/Pac4jProperties.java b/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/autoconfigure/Pac4jProperties.java index 4ed4ef61..6405325c 100644 --- a/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/autoconfigure/Pac4jProperties.java +++ b/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/autoconfigure/Pac4jProperties.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.pac4j.autoconfigure; @@ -92,7 +92,7 @@ public class Pac4jProperties { * * @return 启用认证的客户端类型名称 */ - public Set getClients(){ + public Set getClients() { return clients; } @@ -102,7 +102,7 @@ public Set getClients(){ * @param clients * 启用认证的客户端类型名称 */ - public void setClients(Set clients){ + public void setClients(Set clients) { this.clients = clients; } @@ -111,7 +111,7 @@ public void setClients(Set clients){ * * @return 默认客户端类型名称 */ - public String getDefaultClient(){ + public String getDefaultClient() { return defaultClient; } @@ -121,7 +121,7 @@ public String getDefaultClient(){ * @param defaultClient * 默认客户端类型名称 */ - public void setDefaultClient(String defaultClient){ + public void setDefaultClient(String defaultClient) { this.defaultClient = defaultClient; } @@ -130,7 +130,7 @@ public void setDefaultClient(String defaultClient){ * * @return 客户端配置 */ - public Client getClient(){ + public Client getClient() { return client; } @@ -140,7 +140,7 @@ public Client getClient(){ * @param client * 客户端配置 */ - public void setClient(Client client){ + public void setClient(Client client) { this.client = client; } @@ -149,7 +149,7 @@ public void setClient(Client client){ * * @return Compute if a HTTP request is an AJAX one and the appropriate response. */ - public Class getAjaxRequestResolverClass(){ + public Class getAjaxRequestResolverClass() { return ajaxRequestResolverClass; } @@ -160,7 +160,7 @@ public Class getAjaxRequestResolverClass(){ * Compute if a HTTP request is an AJAX one and the appropriate response */ public void setAjaxRequestResolverClass( - Class ajaxRequestResolverClass){ + Class ajaxRequestResolverClass) { this.ajaxRequestResolverClass = ajaxRequestResolverClass; } @@ -169,7 +169,7 @@ public void setAjaxRequestResolverClass( * * @return The HTTP action adapter for the {@link JEEContext}. */ - public Class> getHttpActionAdapterClass(){ + public Class> getHttpActionAdapterClass() { return httpActionAdapterClass; } @@ -180,7 +180,7 @@ public void setAjaxRequestResolverClass( * The HTTP action adapter for the {@link JEEContext}. */ public void setHttpActionAdapterClass( - Class> httpActionAdapterClass){ + Class> httpActionAdapterClass) { this.httpActionAdapterClass = httpActionAdapterClass; } @@ -189,7 +189,7 @@ public void setHttpActionAdapterClass( * * @return 是否允许多个 Profile */ - public boolean isMultiProfile(){ + public boolean isMultiProfile() { return multiProfile; } @@ -199,7 +199,7 @@ public boolean isMultiProfile(){ * @param multiProfile * 是否允许多个 Profile */ - public void setMultiProfile(boolean multiProfile){ + public void setMultiProfile(boolean multiProfile) { this.multiProfile = multiProfile; } @@ -208,7 +208,7 @@ public void setMultiProfile(boolean multiProfile){ * * @return 是否保存到 SESSION 中 */ - public boolean isSaveInSession(){ + public boolean isSaveInSession() { return saveInSession; } @@ -218,7 +218,7 @@ public boolean isSaveInSession(){ * @param saveInSession * 是否保存到 SESSION 中 */ - public void setSaveInSession(boolean saveInSession){ + public void setSaveInSession(boolean saveInSession) { this.saveInSession = saveInSession; } @@ -227,7 +227,7 @@ public void setSaveInSession(boolean saveInSession){ * * @return 过滤器配置 */ - public Filter getFilter(){ + public Filter getFilter() { return filter; } @@ -237,7 +237,7 @@ public Filter getFilter(){ * @param filter * 过滤器配置 */ - public void setFilter(Filter filter){ + public void setFilter(Filter filter) { this.filter = filter; } @@ -266,7 +266,7 @@ public final static class Filter { * * @return {@link io.buji.pac4j.filter.SecurityFilter} 配置 */ - public Security getSecurity(){ + public Security getSecurity() { return security; } @@ -276,7 +276,7 @@ public Security getSecurity(){ * @param security * {@link io.buji.pac4j.filter.SecurityFilter} 配置 */ - public void setSecurity(Security security){ + public void setSecurity(Security security) { this.security = security; } @@ -285,7 +285,7 @@ public void setSecurity(Security security){ * * @return {@link io.buji.pac4j.filter.CallbackFilter} 配置 */ - public Callback getCallback(){ + public Callback getCallback() { return callback; } @@ -295,7 +295,7 @@ public Callback getCallback(){ * @param callback * {@link io.buji.pac4j.filter.CallbackFilter} 配置 */ - public void setCallback(Callback callback){ + public void setCallback(Callback callback) { this.callback = callback; } @@ -304,7 +304,7 @@ public void setCallback(Callback callback){ * * @return {@link io.buji.pac4j.filter.LogoutFilter} 配置 */ - public Logout getLogout(){ + public Logout getLogout() { return logout; } @@ -314,7 +314,7 @@ public Logout getLogout(){ * @param logout * {@link io.buji.pac4j.filter.LogoutFilter} 配置 */ - public void setLogout(Logout logout){ + public void setLogout(Logout logout) { this.logout = logout; } @@ -335,7 +335,7 @@ private static abstract class BaseFilter { * * @return 过滤器名称 */ - public String getName(){ + public String getName() { return name; } @@ -345,7 +345,7 @@ public String getName(){ * @param name * 过滤器名称 */ - public void setName(String name){ + public void setName(String name) { this.name = name; } @@ -356,10 +356,6 @@ public void setName(String name){ */ public final static class Security extends BaseFilter { - public Security(){ - setName("securityFilter"); - } - /** * 认证器名称列表 */ @@ -370,12 +366,16 @@ public Security(){ */ private Set matchers; + public Security() { + setName("securityFilter"); + } + /** * 返回认证器名称列表 * * @return 认证器名称列表 */ - public Set getAuthorizers(){ + public Set getAuthorizers() { return authorizers; } @@ -385,7 +385,7 @@ public Set getAuthorizers(){ * @param authorizers * 认证器名称列表 */ - public void setAuthorizers(Set authorizers){ + public void setAuthorizers(Set authorizers) { this.authorizers = authorizers; } @@ -394,7 +394,7 @@ public void setAuthorizers(Set authorizers){ * * @return 匹配器名称列表 */ - public Set getMatchers(){ + public Set getMatchers() { return matchers; } @@ -404,7 +404,7 @@ public Set getMatchers(){ * @param matchers * 匹配器名称列表 */ - public void setMatchers(Set matchers){ + public void setMatchers(Set matchers) { this.matchers = matchers; } @@ -415,21 +415,21 @@ public void setMatchers(Set matchers){ */ public final static class Callback extends BaseFilter { - public Callback(){ - setName("callbackFilter"); - } - /** * 默认跳转地址 */ private String defaultUrl; + public Callback() { + setName("callbackFilter"); + } + /** * 返回默认跳转地址 * * @return 默认跳转地址 */ - public String getDefaultUrl(){ + public String getDefaultUrl() { return defaultUrl; } @@ -439,7 +439,7 @@ public String getDefaultUrl(){ * @param defaultUrl * 默认跳转地址 */ - public void setDefaultUrl(String defaultUrl){ + public void setDefaultUrl(String defaultUrl) { this.defaultUrl = defaultUrl; } @@ -450,10 +450,6 @@ public void setDefaultUrl(String defaultUrl){ */ public final static class Logout extends BaseFilter { - public Logout(){ - setName("logoutFilter"); - } - /** * 登出成功默认跳转地址 */ @@ -474,12 +470,16 @@ public Logout(){ */ private boolean centralLogout = true; + public Logout() { + setName("logoutFilter"); + } + /** * 返回登出成功默认跳转地址 * * @return 登出成功默认跳转地址 */ - public String getDefaultUrl(){ + public String getDefaultUrl() { return defaultUrl; } @@ -489,7 +489,7 @@ public String getDefaultUrl(){ * @param defaultUrl * 登出成功默认跳转地址 */ - public void setDefaultUrl(String defaultUrl){ + public void setDefaultUrl(String defaultUrl) { this.defaultUrl = defaultUrl; } @@ -498,7 +498,7 @@ public void setDefaultUrl(String defaultUrl){ * * @return 登出地址模式 */ - public String getLogoutUrlPattern(){ + public String getLogoutUrlPattern() { return logoutUrlPattern; } @@ -508,7 +508,7 @@ public String getLogoutUrlPattern(){ * @param logoutUrlPattern * 登出地址模式 */ - public void setLogoutUrlPattern(String logoutUrlPattern){ + public void setLogoutUrlPattern(String logoutUrlPattern) { this.logoutUrlPattern = logoutUrlPattern; } @@ -517,7 +517,7 @@ public void setLogoutUrlPattern(String logoutUrlPattern){ * * @return 本地是否退出登录 */ - public boolean isLocalLogout(){ + public boolean isLocalLogout() { return localLogout; } @@ -527,7 +527,7 @@ public boolean isLocalLogout(){ * @param localLogout * 本地是否退出登录 */ - public void setLocalLogout(boolean localLogout){ + public void setLocalLogout(boolean localLogout) { this.localLogout = localLogout; } @@ -536,7 +536,7 @@ public void setLocalLogout(boolean localLogout){ * * @return 认证中心是否退出登录 */ - public boolean isCentralLogout(){ + public boolean isCentralLogout() { return centralLogout; } @@ -546,7 +546,7 @@ public boolean isCentralLogout(){ * @param centralLogout * 认证中心是否退出登录 */ - public void setCentralLogout(boolean centralLogout){ + public void setCentralLogout(boolean centralLogout) { this.centralLogout = centralLogout; } @@ -584,7 +584,7 @@ public final static class Client { * * @return CAS 配置 */ - public Cas getCas(){ + public Cas getCas() { return cas; } @@ -594,7 +594,7 @@ public Cas getCas(){ * @param cas * CAS 配置 */ - public void setCas(Cas cas){ + public void setCas(Cas cas) { this.cas = cas; } @@ -603,7 +603,7 @@ public void setCas(Cas cas){ * * @return HTTP 配置 */ - public Http getHttp(){ + public Http getHttp() { return http; } @@ -613,7 +613,7 @@ public Http getHttp(){ * @param http * HTTP 配置 */ - public void setHttp(Http http){ + public void setHttp(Http http) { this.http = http; } @@ -622,7 +622,7 @@ public void setHttp(Http http){ * * @return JWT 配置 */ - public Jwt getJwt(){ + public Jwt getJwt() { return jwt; } @@ -632,7 +632,7 @@ public Jwt getJwt(){ * @param jwt * JWT 配置 */ - public void setJwt(Jwt jwt){ + public void setJwt(Jwt jwt) { this.jwt = jwt; } @@ -641,7 +641,7 @@ public void setJwt(Jwt jwt){ * * @return OAuth 配置 */ - public OAuth getOAuth(){ + public OAuth getOAuth() { return oAuth; } @@ -651,7 +651,7 @@ public OAuth getOAuth(){ * @param oAuth * OAuth 配置 */ - public void setOAuth(OAuth oAuth){ + public void setOAuth(OAuth oAuth) { this.oAuth = oAuth; } diff --git a/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/filter/Pac4jFilter.java b/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/filter/Pac4jFilter.java index 0eb0ad45..1ccb9155 100644 --- a/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/filter/Pac4jFilter.java +++ b/buession-springboot-pac4j/src/main/java/com/buession/springboot/pac4j/filter/Pac4jFilter.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.pac4j.filter; @@ -38,12 +38,15 @@ * @author Yong.Teng * @since 2.1.0 */ -public class Pac4jFilter { +public class Pac4jFilter extends HashMap { + + private final static long serialVersionUID = 4022270505797878239L; /** - * pac4j 过滤器 + * 构造函数 */ - private final Map filters = new HashMap<>(3); + public Pac4jFilter() { + } /** * 添加 pac4j 过滤器 @@ -54,11 +57,31 @@ public class Pac4jFilter { * 过滤器 */ public void addFilter(final String name, final Filter filter) { + put(name, filter); + } + + /** + * 添加 pac4j 过滤器 + * + * @param name + * 过滤器名称,如果为 null 或者空字符串时,使用过滤器类名首字母小写后,作为过滤器名称 + * @param filter + * 过滤器 + * + * @since 2.3.3 + */ + @Override + public Filter put(final String name, final Filter filter) { Assert.isNull(filter, "Filter cloud not null."); + return doPut(name, filter); + } - final String filterName = Validate.hasText(name) ? name : StringUtils.uncapitalize( - filter.getClass().getSimpleName()); - filters.put(filterName, filter); + @Override + public void putAll(final Map m) { + for(Map.Entry e : m.entrySet()){ + Assert.isNull(e.getValue(), "Filter cloud not null."); + doPut(e.getKey(), e.getValue()); + } } /** @@ -66,15 +89,15 @@ public void addFilter(final String name, final Filter filter) { * * @return pac4j 过滤器 */ + @Deprecated public Map getFilters() { - return filters; + return this; } - /** - * 清除所有 pac4j 过滤器 - */ - public void clear() { - filters.clear(); + private Filter doPut(final String filterName, final Filter filter) { + final String key = Validate.hasText(filterName) ? filterName : StringUtils.uncapitalize( + filter.getClass().getSimpleName()); + return super.put(key, filter); } } diff --git a/buession-springboot-parent/pom.xml b/buession-springboot-parent/pom.xml index a53550c6..fada4186 100644 --- a/buession-springboot-parent/pom.xml +++ b/buession-springboot-parent/pom.xml @@ -7,13 +7,13 @@ com.buession parent - 2.3.2 + 2.3.3 com.buession.springboot buession-springboot-parent https://springboot.buession.com/ Buession Springboot Framework Parent - 2.3.2 + 2.3.3 pom @@ -72,8 +72,8 @@ - 2.3.2 - 2.3.2 + 2.3.3 + 2.3.3 diff --git a/buession-springboot-session/pom.xml b/buession-springboot-session/pom.xml index de882ab1..eb110dae 100644 --- a/buession-springboot-session/pom.xml +++ b/buession-springboot-session/pom.xml @@ -7,7 +7,7 @@ com.buession.springboot buession-springboot-parent ../buession-springboot-parent - 2.3.2 + 2.3.3 buession-springboot-session https://springboot.buession.com/ diff --git a/buession-springboot-shiro/pom.xml b/buession-springboot-shiro/pom.xml index ab33d7e9..1db9d320 100644 --- a/buession-springboot-shiro/pom.xml +++ b/buession-springboot-shiro/pom.xml @@ -7,7 +7,7 @@ com.buession.springboot buession-springboot-parent ../buession-springboot-parent - 2.3.2 + 2.3.3 buession-springboot-shiro https://springboot.buession.com/ diff --git a/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/Pac4jConfiguration.java b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/Pac4jConfiguration.java index c41ec23e..f21c1ea8 100644 --- a/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/Pac4jConfiguration.java +++ b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/Pac4jConfiguration.java @@ -19,11 +19,13 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.shiro.autoconfigure; +import com.buession.springboot.pac4j.filter.Pac4jFilter; +import com.buession.springboot.shiro.core.ShiroFilter; import io.buji.pac4j.realm.Pac4jRealm; import io.buji.pac4j.subject.Pac4jSubjectFactory; import org.apache.shiro.mgt.DefaultSecurityManager; @@ -37,7 +39,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Lazy; /** * Pac4j for shiro 自动加载类 @@ -52,28 +53,26 @@ public class Pac4jConfiguration { @Bean @ConditionalOnMissingBean - @Lazy - public Realm pac4jRealm(){ - return new Pac4jRealm(); + @ConditionalOnBean({Pac4jFilter.class}) + public ShiroFilter shiroFilter(ObjectProvider pac4jFilter) { + return new ShiroFilter(pac4jFilter.getIfAvailable()); } @Bean @ConditionalOnMissingBean - @Lazy - public SubjectFactory subjectFactory(){ - return new Pac4jSubjectFactory(); + public Realm pac4jRealm() { + return new Pac4jRealm(); } - @Configuration(proxyBeanMethods = false) - @ConditionalOnBean({SecurityManager.class, SubjectFactory.class}) - static class ShiroAutoConfiguration { + @Bean + @ConditionalOnMissingBean({SubjectFactory.class}) + public SubjectFactory subjectFactory(ObjectProvider securityManager) { + SubjectFactory subjectFactory = new Pac4jSubjectFactory(); - public ShiroAutoConfiguration(ObjectProvider securityManager, - ObjectProvider subjectFactory){ - ((DefaultSecurityManager) securityManager.getIfAvailable()).setSubjectFactory( - subjectFactory.getIfAvailable()); - } + securityManager.ifAvailable( + (securityMgr)->((DefaultSecurityManager) securityMgr).setSubjectFactory(subjectFactory)); + return subjectFactory; } } diff --git a/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/ShiroConfiguration.java b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/ShiroConfiguration.java index ffe723b2..f0a3f17a 100644 --- a/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/ShiroConfiguration.java +++ b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/ShiroConfiguration.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.shiro.autoconfigure; @@ -65,7 +65,7 @@ public class ShiroConfiguration extends AbstractShiroConfiguration { private final ShiroProperties properties; - public ShiroConfiguration(ShiroProperties properties){ + public ShiroConfiguration(ShiroProperties properties) { this.properties = properties; // Session info @@ -78,49 +78,49 @@ public ShiroConfiguration(ShiroProperties properties){ @Bean @ConditionalOnMissingBean @Override - protected SessionsSecurityManager securityManager(List realms){ + protected SessionsSecurityManager securityManager(List realms) { return super.securityManager(realms); } @Bean @ConditionalOnMissingBean @Override - protected SessionManager sessionManager(){ + protected SessionManager sessionManager() { return super.sessionManager(); } @Bean @ConditionalOnMissingBean @Override - protected SubjectDAO subjectDAO(){ + protected SubjectDAO subjectDAO() { return super.subjectDAO(); } @Bean @ConditionalOnMissingBean @Override - protected SessionStorageEvaluator sessionStorageEvaluator(){ + protected SessionStorageEvaluator sessionStorageEvaluator() { return super.sessionStorageEvaluator(); } @Bean - @ConditionalOnMissingBean + @ConditionalOnMissingBean({SubjectFactory.class}) @Override - protected SubjectFactory subjectFactory(){ + protected SubjectFactory subjectFactory() { return super.subjectFactory(); } @Bean @ConditionalOnMissingBean @Override - protected SessionFactory sessionFactory(){ + protected SessionFactory sessionFactory() { return super.sessionFactory(); } @Bean(name = "sessionDAO") @ConditionalOnBean({RedisManager.class}) @ConditionalOnMissingBean({SessionDAO.class}) - protected SessionDAO sessionDAO(ObjectProvider redisManager){ + protected SessionDAO sessionDAO(ObjectProvider redisManager) { ShiroProperties.Session session = properties.getSession(); return new RedisSessionDAO(redisManager.getIfAvailable(), session.getPrefix(), session.getExpire(), session.isSessionInMemoryEnabled(), session.getSessionInMemoryTimeout()); @@ -129,53 +129,53 @@ protected SessionDAO sessionDAO(ObjectProvider redisManager){ @Bean(name = "sessionDAO") @ConditionalOnMissingBean({SessionDAO.class}) @Override - protected SessionDAO sessionDAO(){ + protected SessionDAO sessionDAO() { return super.sessionDAO(); } @Bean @ConditionalOnMissingBean @Override - protected Authorizer authorizer(){ + protected Authorizer authorizer() { return super.authorizer(); } @Bean @ConditionalOnMissingBean @Override - protected AuthenticationStrategy authenticationStrategy(){ + protected AuthenticationStrategy authenticationStrategy() { return super.authenticationStrategy(); } @Bean @ConditionalOnMissingBean @Override - protected Authenticator authenticator(){ + protected Authenticator authenticator() { return super.authenticator(); } @Bean @ConditionalOnMissingBean @Override - protected RememberMeManager rememberMeManager(){ + protected RememberMeManager rememberMeManager() { return super.rememberMeManager(); } @Bean @ConditionalOnResource(resources = "classpath:shiro.ini") - protected Realm iniClasspathRealm(){ + protected Realm iniClasspathRealm() { return iniRealmFromLocation("classpath:shiro.ini"); } @Bean @ConditionalOnResource(resources = "classpath:META-INF/shiro.ini") - protected Realm iniMetaInfClasspathRealm(){ + protected Realm iniMetaInfClasspathRealm() { return iniRealmFromLocation("classpath:META-INF/shiro.ini"); } @Bean @ConditionalOnMissingBean(Realm.class) - protected Realm missingRealm(){ + protected Realm missingRealm() { throw new NoRealmBeanConfiguredException(); } diff --git a/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/ShiroProperties.java b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/ShiroProperties.java index 9dc646ba..84207eeb 100644 --- a/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/ShiroProperties.java +++ b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/ShiroProperties.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.shiro.autoconfigure; @@ -81,7 +81,7 @@ public class ShiroProperties { * * @return 登录地址 */ - public String getLoginUrl(){ + public String getLoginUrl() { return loginUrl; } @@ -91,7 +91,7 @@ public String getLoginUrl(){ * @param loginUrl * 登录地址 */ - public void setLoginUrl(String loginUrl){ + public void setLoginUrl(String loginUrl) { this.loginUrl = loginUrl; } @@ -100,7 +100,7 @@ public void setLoginUrl(String loginUrl){ * * @return 登录成功跳转地址 */ - public String getSuccessUrl(){ + public String getSuccessUrl() { return successUrl; } @@ -110,7 +110,7 @@ public String getSuccessUrl(){ * @param successUrl * 登录成功跳转地址 */ - public void setSuccessUrl(String successUrl){ + public void setSuccessUrl(String successUrl) { this.successUrl = successUrl; } @@ -119,7 +119,7 @@ public void setSuccessUrl(String successUrl){ * * @return 授权失败跳转地址 */ - public String getUnauthorizedUrl(){ + public String getUnauthorizedUrl() { return unauthorizedUrl; } @@ -129,7 +129,7 @@ public String getUnauthorizedUrl(){ * @param unauthorizedUrl * 授权失败跳转地址 */ - public void setUnauthorizedUrl(String unauthorizedUrl){ + public void setUnauthorizedUrl(String unauthorizedUrl) { this.unauthorizedUrl = unauthorizedUrl; } @@ -138,7 +138,7 @@ public void setUnauthorizedUrl(String unauthorizedUrl){ * * @return Session 配置 */ - public Session getSession(){ + public Session getSession() { return session; } @@ -148,7 +148,7 @@ public Session getSession(){ * @param session * Session 配置 */ - public void setSession(Session session){ + public void setSession(Session session) { this.session = session; } @@ -157,7 +157,7 @@ public void setSession(Session session){ * * @return 缓存配置 */ - public Cache getCache(){ + public Cache getCache() { return cache; } @@ -167,7 +167,7 @@ public Cache getCache(){ * @param cache * 缓存配置 */ - public void setCache(Cache cache){ + public void setCache(Cache cache) { this.cache = cache; } @@ -176,7 +176,7 @@ public void setCache(Cache cache){ * * @return 记住我配置 */ - public RememberMe getRememberMe(){ + public RememberMe getRememberMe() { return rememberMe; } @@ -186,7 +186,7 @@ public RememberMe getRememberMe(){ * @param rememberMe * 记住我配置 */ - public void setRememberMe(RememberMe rememberMe){ + public void setRememberMe(RememberMe rememberMe) { this.rememberMe = rememberMe; } @@ -249,7 +249,7 @@ public final static class Session { * * @return 是否使用原生 Session 管理器 */ - public boolean isUseNativeSessionManager(){ + public boolean isUseNativeSessionManager() { return getUseNativeSessionManager(); } @@ -258,7 +258,7 @@ public boolean isUseNativeSessionManager(){ * * @return 是否使用原生 Session 管理器 */ - public boolean getUseNativeSessionManager(){ + public boolean getUseNativeSessionManager() { return useNativeSessionManager; } @@ -268,7 +268,7 @@ public boolean getUseNativeSessionManager(){ * @param useNativeSessionManager * 是否使用原生 Session 管理器 */ - public void setUseNativeSessionManager(boolean useNativeSessionManager){ + public void setUseNativeSessionManager(boolean useNativeSessionManager) { this.useNativeSessionManager = useNativeSessionManager; } @@ -277,7 +277,7 @@ public void setUseNativeSessionManager(boolean useNativeSessionManager){ * * @return 是否开启 SESSION ID Cookie */ - public boolean isSessionIdCookieEnabled(){ + public boolean isSessionIdCookieEnabled() { return getSessionIdCookieEnabled(); } @@ -286,7 +286,7 @@ public boolean isSessionIdCookieEnabled(){ * * @return 是否开启 SESSION ID Cookie */ - public boolean getSessionIdCookieEnabled(){ + public boolean getSessionIdCookieEnabled() { return sessionIdCookieEnabled; } @@ -296,7 +296,7 @@ public boolean getSessionIdCookieEnabled(){ * @param sessionIdCookieEnabled * 是否开启 SESSION ID Cookie */ - public void setSessionIdCookieEnabled(boolean sessionIdCookieEnabled){ + public void setSessionIdCookieEnabled(boolean sessionIdCookieEnabled) { this.sessionIdCookieEnabled = sessionIdCookieEnabled; } @@ -305,7 +305,7 @@ public void setSessionIdCookieEnabled(boolean sessionIdCookieEnabled){ * * @return 是否开启 URL 重写 */ - public boolean isSessionIdUrlRewritingEnabled(){ + public boolean isSessionIdUrlRewritingEnabled() { return getSessionIdUrlRewritingEnabled(); } @@ -314,7 +314,7 @@ public boolean isSessionIdUrlRewritingEnabled(){ * * @return 是否开启 URL 重写 */ - public boolean getSessionIdUrlRewritingEnabled(){ + public boolean getSessionIdUrlRewritingEnabled() { return sessionIdUrlRewritingEnabled; } @@ -324,7 +324,7 @@ public boolean getSessionIdUrlRewritingEnabled(){ * @param sessionIdUrlRewritingEnabled * 是否开启 URL 重写 */ - public void setSessionIdUrlRewritingEnabled(boolean sessionIdUrlRewritingEnabled){ + public void setSessionIdUrlRewritingEnabled(boolean sessionIdUrlRewritingEnabled) { this.sessionIdUrlRewritingEnabled = sessionIdUrlRewritingEnabled; } @@ -333,7 +333,7 @@ public void setSessionIdUrlRewritingEnabled(boolean sessionIdUrlRewritingEnabled * * @return 是否开启 Session 在内存中保存 */ - public boolean isSessionInMemoryEnabled(){ + public boolean isSessionInMemoryEnabled() { return getSessionInMemoryEnabled(); } @@ -342,7 +342,7 @@ public boolean isSessionInMemoryEnabled(){ * * @return 是否开启 Session 在内存中保存 */ - public boolean getSessionInMemoryEnabled(){ + public boolean getSessionInMemoryEnabled() { return sessionInMemoryEnabled; } @@ -352,7 +352,7 @@ public boolean getSessionInMemoryEnabled(){ * @param sessionInMemoryEnabled * 是否开启 Session 在内存中保存 */ - public void setSessionInMemoryEnabled(boolean sessionInMemoryEnabled){ + public void setSessionInMemoryEnabled(boolean sessionInMemoryEnabled) { this.sessionInMemoryEnabled = sessionInMemoryEnabled; } @@ -361,7 +361,7 @@ public void setSessionInMemoryEnabled(boolean sessionInMemoryEnabled){ * * @return Session 在内存中保存超时时间 */ - public long getSessionInMemoryTimeout(){ + public long getSessionInMemoryTimeout() { return sessionInMemoryTimeout; } @@ -371,7 +371,7 @@ public long getSessionInMemoryTimeout(){ * @param sessionInMemoryTimeout * Session 在内存中保存超时时间 */ - public void setSessionInMemoryTimeout(long sessionInMemoryTimeout){ + public void setSessionInMemoryTimeout(long sessionInMemoryTimeout) { this.sessionInMemoryTimeout = sessionInMemoryTimeout; } @@ -380,7 +380,7 @@ public void setSessionInMemoryTimeout(long sessionInMemoryTimeout){ * * @return Session 名称前缀 */ - public String getPrefix(){ + public String getPrefix() { return prefix; } @@ -390,7 +390,7 @@ public String getPrefix(){ * @param prefix * Session 名称前缀 */ - public void setPrefix(String prefix){ + public void setPrefix(String prefix) { this.prefix = prefix; } @@ -399,7 +399,7 @@ public void setPrefix(String prefix){ * * @return Session 有效期 */ - public int getExpire(){ + public int getExpire() { return expire; } @@ -409,7 +409,7 @@ public int getExpire(){ * @param expire * Session 有效期 */ - public void setExpire(int expire){ + public void setExpire(int expire) { this.expire = expire; } @@ -418,7 +418,7 @@ public void setExpire(int expire){ * * @return 如果 Session 过期或者无效后,是否删除 */ - public boolean isSessionManagerDeleteInvalidSessions(){ + public boolean isSessionManagerDeleteInvalidSessions() { return getSessionManagerDeleteInvalidSessions(); } @@ -427,7 +427,7 @@ public boolean isSessionManagerDeleteInvalidSessions(){ * * @return 如果 Session 过期或者无效后,是否删除 */ - public boolean getSessionManagerDeleteInvalidSessions(){ + public boolean getSessionManagerDeleteInvalidSessions() { return sessionManagerDeleteInvalidSessions; } @@ -437,7 +437,7 @@ public boolean getSessionManagerDeleteInvalidSessions(){ * @param sessionManagerDeleteInvalidSessions * 如果 Session 过期或者无效后,是否删除 */ - public void setSessionManagerDeleteInvalidSessions(boolean sessionManagerDeleteInvalidSessions){ + public void setSessionManagerDeleteInvalidSessions(boolean sessionManagerDeleteInvalidSessions) { this.sessionManagerDeleteInvalidSessions = sessionManagerDeleteInvalidSessions; } @@ -446,7 +446,7 @@ public void setSessionManagerDeleteInvalidSessions(boolean sessionManagerDeleteI * * @return Session Cookie */ - public Cookie getCookie(){ + public Cookie getCookie() { return cookie; } @@ -456,7 +456,7 @@ public Cookie getCookie(){ * @param cookie * Session Cookie */ - public void setCookie(Cookie cookie){ + public void setCookie(Cookie cookie) { this.cookie = cookie; } @@ -490,7 +490,7 @@ public final static class Cache { * * @return 缓存 Key 前缀 */ - public String getPrefix(){ + public String getPrefix() { return prefix; } @@ -500,7 +500,7 @@ public String getPrefix(){ * @param prefix * 缓存 Key 前缀 */ - public void setPrefix(String prefix){ + public void setPrefix(String prefix) { this.prefix = prefix; } @@ -509,7 +509,7 @@ public void setPrefix(String prefix){ * * @return 缓存过期时间(单位:秒) */ - public int getExpire(){ + public int getExpire() { return expire; } @@ -519,7 +519,7 @@ public int getExpire(){ * @param expire * 缓存过期时间 */ - public void setExpire(int expire){ + public void setExpire(int expire) { this.expire = expire; } @@ -528,7 +528,7 @@ public void setExpire(int expire){ * * @return Principal Id */ - public String getPrincipalIdFieldName(){ + public String getPrincipalIdFieldName() { return principalIdFieldName; } @@ -538,7 +538,7 @@ public String getPrincipalIdFieldName(){ * @param principalIdFieldName * Principal Id */ - public void setPrincipalIdFieldName(String principalIdFieldName){ + public void setPrincipalIdFieldName(String principalIdFieldName) { this.principalIdFieldName = principalIdFieldName; } @@ -563,7 +563,7 @@ public final static class RememberMe { * * @return 记住我 Cookie */ - public Cookie getCookie(){ + public Cookie getCookie() { return cookie; } @@ -573,7 +573,7 @@ public Cookie getCookie(){ * @param cookie * 记住我 Cookie */ - public void setCookie(Cookie cookie){ + public void setCookie(Cookie cookie) { this.cookie = cookie; } diff --git a/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/ShiroWebConfiguration.java b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/ShiroWebConfiguration.java index 0ee0beab..6fd27415 100644 --- a/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/ShiroWebConfiguration.java +++ b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/ShiroWebConfiguration.java @@ -21,7 +21,7 @@ * +------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.shiro.autoconfigure; @@ -76,7 +76,7 @@ public class ShiroWebConfiguration extends AbstractShiroWebConfiguration { private final ShiroProperties properties; - public ShiroWebConfiguration(ShiroProperties properties){ + public ShiroWebConfiguration(ShiroProperties properties) { this.properties = properties; SameSiteConverter sameSiteConverter = new SameSiteConverter(); @@ -160,28 +160,28 @@ public ShiroWebConfiguration(ShiroProperties properties){ @Bean @ConditionalOnMissingBean @Override - protected SubjectDAO subjectDAO(){ + protected SubjectDAO subjectDAO() { return super.subjectDAO(); } @Bean @ConditionalOnMissingBean @Override - protected SessionStorageEvaluator sessionStorageEvaluator(){ + protected SessionStorageEvaluator sessionStorageEvaluator() { return super.sessionStorageEvaluator(); } @Bean @ConditionalOnMissingBean @Override - protected SessionFactory sessionFactory(){ + protected SessionFactory sessionFactory() { return super.sessionFactory(); } @Bean(name = "sessionDAO") @ConditionalOnBean({RedisManager.class}) @ConditionalOnMissingBean({SessionDAO.class}) - protected SessionDAO sessionDAO(ObjectProvider redisManager){ + protected SessionDAO sessionDAO(ObjectProvider redisManager) { ShiroProperties.Session session = properties.getSession(); return new RedisSessionDAO(redisManager.getIfAvailable(), session.getPrefix(), session.getExpire(), session.isSessionInMemoryEnabled(), session.getSessionInMemoryTimeout()); @@ -190,14 +190,14 @@ protected SessionDAO sessionDAO(ObjectProvider redisManager){ @Bean(name = "sessionDAO") @ConditionalOnMissingBean({SessionDAO.class}) @Override - protected SessionDAO sessionDAO(){ + protected SessionDAO sessionDAO() { return super.sessionDAO(); } @Bean(name = "sessionCookieTemplate") @ConditionalOnMissingBean(name = "sessionCookieTemplate") @Override - protected org.apache.shiro.web.servlet.Cookie sessionCookieTemplate(){ + protected org.apache.shiro.web.servlet.Cookie sessionCookieTemplate() { org.apache.shiro.web.servlet.Cookie cookie = super.sessionCookieTemplate(); final PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull(); @@ -211,7 +211,7 @@ protected org.apache.shiro.web.servlet.Cookie sessionCookieTemplate(){ @Bean(name = "rememberMeCookieTemplate") @ConditionalOnMissingBean(name = "rememberMeCookieTemplate") @Override - protected org.apache.shiro.web.servlet.Cookie rememberMeCookieTemplate(){ + protected org.apache.shiro.web.servlet.Cookie rememberMeCookieTemplate() { org.apache.shiro.web.servlet.Cookie cookie = super.rememberMeCookieTemplate(); final PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull(); @@ -225,55 +225,55 @@ protected org.apache.shiro.web.servlet.Cookie rememberMeCookieTemplate(){ @Bean @ConditionalOnMissingBean @Override - protected RememberMeManager rememberMeManager(){ + protected RememberMeManager rememberMeManager() { return super.rememberMeManager(); } @Bean - @ConditionalOnMissingBean + @ConditionalOnMissingBean({SubjectFactory.class}) @Override - protected SubjectFactory subjectFactory(){ + protected SubjectFactory subjectFactory() { return super.subjectFactory(); } @Bean @ConditionalOnMissingBean @Override - protected Authorizer authorizer(){ + protected Authorizer authorizer() { return super.authorizer(); } @Bean @Override - protected AuthenticationStrategy authenticationStrategy(){ + protected AuthenticationStrategy authenticationStrategy() { return super.authenticationStrategy(); } @Bean @ConditionalOnMissingBean @Override - protected Authenticator authenticator(){ + protected Authenticator authenticator() { return super.authenticator(); } @Bean @ConditionalOnMissingBean @Override - protected SessionManager sessionManager(){ + protected SessionManager sessionManager() { return super.sessionManager(); } @Bean @ConditionalOnMissingBean @Override - protected SessionsSecurityManager securityManager(List realms){ + protected SessionsSecurityManager securityManager(List realms) { return super.securityManager(realms); } @Bean @ConditionalOnMissingBean({ShiroFilterChainDefinition.class}) @ConditionalOnResource(resources = "classpath:chainDefinition.ini") - protected ShiroFilterChainDefinition iniShiroFilterChainDefinition(){ + protected ShiroFilterChainDefinition iniShiroFilterChainDefinition() { Ini ini = Ini.fromResourcePath("classpath:chainDefinition.ini"); if(Validate.isEmpty(ini)){ @@ -294,7 +294,7 @@ protected ShiroFilterChainDefinition iniShiroFilterChainDefinition(){ @Bean @ConditionalOnMissingBean({ShiroFilterChainDefinition.class}) @Override - protected ShiroFilterChainDefinition shiroFilterChainDefinition(){ + protected ShiroFilterChainDefinition shiroFilterChainDefinition() { return super.shiroFilterChainDefinition(); } diff --git a/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/ShiroWebFilterConfiguration.java b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/ShiroWebFilterConfiguration.java index ede5b55a..6c22f3a3 100644 --- a/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/ShiroWebFilterConfiguration.java +++ b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/autoconfigure/ShiroWebFilterConfiguration.java @@ -26,12 +26,13 @@ import com.buession.core.utils.SystemPropertyUtils; import com.buession.core.validator.Validate; -import com.buession.springboot.pac4j.filter.Pac4jFilter; +import com.buession.springboot.shiro.core.ShiroFilter; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.spring.web.config.AbstractShiroWebFilterConfiguration; import org.apache.shiro.web.servlet.AbstractShiroFilter; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfigureAfter; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; @@ -42,6 +43,7 @@ import javax.servlet.DispatcherType; import java.util.List; +import java.util.function.Consumer; /** * @author Yong.Teng @@ -54,11 +56,7 @@ @AutoConfigureAfter({ShiroWebConfiguration.class}) public class ShiroWebFilterConfiguration extends AbstractShiroWebFilterConfiguration { - private final Pac4jFilter pac4jFilter; - - public ShiroWebFilterConfiguration(ShiroProperties properties, ObjectProvider pac4jFilter) { - this.pac4jFilter = pac4jFilter.getIfAvailable(); - + public ShiroWebFilterConfiguration(ShiroProperties properties) { if(Validate.hasText(properties.getLoginUrl())){ SystemPropertyUtils.setProperty("shiro.loginUrl", properties.getLoginUrl()); } @@ -72,34 +70,50 @@ public ShiroWebFilterConfiguration(ShiroProperties properties, ObjectProvider filterShiroFilterRegistrationBean( + ObjectProvider shiroFilterProvider) throws Exception { + return filterShiroFilterRegistrationBean((shiroFilterFactoryBean)->{ + shiroFilterProvider.ifAvailable((shiroFilter)->{ + if(shiroFilterFactoryBean.getFilters() == null){ + shiroFilterFactoryBean.setFilters(shiroFilter.getFilters()); + }else{ + shiroFilterFactoryBean.getFilters().putAll(shiroFilter.getFilters()); + } + }); + }); } @Bean(name = "filterShiroFilterRegistrationBean") @ConditionalOnMissingBean(name = "filterShiroFilterRegistrationBean") protected FilterRegistrationBean filterShiroFilterRegistrationBean() throws Exception { + return filterShiroFilterRegistrationBean((shiroFilterFactoryBean)->{ + }); + } + + @Bean(name = "globalFilters") + @ConditionalOnMissingBean + @Override + protected List globalFilters() { + return super.globalFilters(); + } + + private FilterRegistrationBean filterShiroFilterRegistrationBean( + Consumer consumer) throws Exception { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean<>(); + ShiroFilterFactoryBean shiroFilterFactoryBean = super.shiroFilterFactoryBean(); + + consumer.accept(shiroFilterFactoryBean); filterRegistrationBean.setName("shiroFilter"); filterRegistrationBean.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ERROR); - filterRegistrationBean.setFilter(shiroFilterFactoryBean().getObject()); + filterRegistrationBean.setFilter(shiroFilterFactoryBean.getObject()); filterRegistrationBean.setOrder(1); return filterRegistrationBean; } - @Bean(name = "globalFilters") - @ConditionalOnMissingBean - @Override - protected List globalFilters() { - return super.globalFilters(); - } - } diff --git a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/AbstractMqAdapterProperties.java b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/core/ShiroFilter.java similarity index 68% rename from buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/AbstractMqAdapterProperties.java rename to buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/core/ShiroFilter.java index d04016d6..dba4b4bb 100644 --- a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/AbstractMqAdapterProperties.java +++ b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/core/ShiroFilter.java @@ -19,40 +19,34 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ -package com.buession.springboot.canal.autoconfigure; +package com.buession.springboot.shiro.core; + +import javax.servlet.Filter; +import java.util.Map; /** * @author Yong.Teng - * @since 2.3.1 + * @since 2.3.3 */ -abstract class AbstractMqAdapterProperties - extends AbstractAdapterProperties { - - /** - * MQ 实例基本配置 - * - * @author Yong.Teng - * @since 0.0.1 - */ - public static abstract class MqBaseInstanceConfiguration extends BaseInstanceConfiguration { - - private boolean flatMessage; +public class ShiroFilter { - public MqBaseInstanceConfiguration() { - super(); - } + private Map filters; - public boolean isFlatMessage() { - return flatMessage; - } + public ShiroFilter() { + } - public void setFlatMessage(boolean flatMessage) { - this.flatMessage = flatMessage; - } + public ShiroFilter(Map filters) { + this.filters = filters; + } + public Map getFilters() { + return filters; } + public void setFilters(Map filters) { + this.filters = filters; + } } diff --git a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/KafkaProperties.java b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/core/package-info.java similarity index 52% rename from buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/KafkaProperties.java rename to buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/core/package-info.java index b6ec9a97..712f076a 100644 --- a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/KafkaProperties.java +++ b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/core/package-info.java @@ -19,97 +19,10 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ -package com.buession.springboot.canal.autoconfigure; - /** - * Kafka 适配器配置 - * * @author Yong.Teng - * @since 2.3.1 */ -public class KafkaProperties extends AbstractMqAdapterProperties { - - /** - * Kafka 主机地址 - */ - private String servers; - - /** - * 返回 Kafka 主机地址 - * - * @return Kafka 主机地址 - */ - public String getServers() { - return servers; - } - - /** - * 设置 Kafka 主机地址 - * - * @param servers - * Kafka 主机地址 - */ - public void setServers(String servers) { - this.servers = servers; - } - - public final static class Instance extends AbstractMqAdapterProperties.MqBaseInstanceConfiguration { - - /** - * Group Id - */ - private String groupId; - - /** - * 分区 - */ - private Integer partition; - - public Instance() { - super(); - } - - /** - * 返回 Group Id - * - * @return Group Id - */ - public String getGroupId() { - return groupId; - } - - /** - * 设置 Group Id - * - * @param groupId - * Group Id - */ - public void setGroupId(String groupId) { - this.groupId = groupId; - } - - /** - * 返回分区 - * - * @return 分区 - */ - public Integer getPartition() { - return partition; - } - - /** - * 设置分区 - * - * @param partition - * 分区 - */ - public void setPartition(Integer partition) { - this.partition = partition; - } - - } - -} +package com.buession.springboot.shiro.core; \ No newline at end of file diff --git a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/AbstractAdapterProperties.java b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/env/ShiroEnvironmentPostProcessor.java similarity index 59% rename from buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/AbstractAdapterProperties.java rename to buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/env/ShiroEnvironmentPostProcessor.java index b0eebc87..e68ca6eb 100644 --- a/buession-springboot-canal/src/main/java/com/buession/springboot/canal/autoconfigure/AbstractAdapterProperties.java +++ b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/env/ShiroEnvironmentPostProcessor.java @@ -19,64 +19,28 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ -package com.buession.springboot.canal.autoconfigure; +package com.buession.springboot.shiro.env; -import com.buession.canal.core.Configuration; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.env.EnvironmentPostProcessor; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MapPropertySource; -import java.time.Duration; -import java.util.HashMap; -import java.util.Map; +import java.util.Collections; /** - * Canal 适配器配置基类 - * * @author Yong.Teng - * @since 0.0.1 + * @since 2.3.3 */ -abstract class AbstractAdapterProperties - implements AdapterProperties { - - /** - * 实例清单 - */ - private Map instances = new HashMap<>(); +public class ShiroEnvironmentPostProcessor implements EnvironmentPostProcessor { - /** - * 返回实例清单 - * - * @return 实例清单 - */ @Override - public Map getInstances() { - return instances; - } - - /** - * 设置实例清单 - * - * @param instances - * 实例清单 - */ - public void setInstances(Map instances) { - this.instances = instances; - } - - /** - * 实例基本配置 - * - * @author Yong.Teng - * @since 0.0.1 - */ - public static abstract class BaseInstanceConfiguration extends Configuration { - - public BaseInstanceConfiguration() { - setTimeout(Duration.ofSeconds(10)); - setBatchSize(10); - } - + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + environment.getPropertySources().addFirst(new MapPropertySource("shiro", + Collections.singletonMap("spring.mvc.pathmatch.matching-strategy", "ant_path_matcher"))); } } diff --git a/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/env/package-info.java b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/env/package-info.java new file mode 100644 index 00000000..910caf2a --- /dev/null +++ b/buession-springboot-shiro/src/main/java/com/buession/springboot/shiro/env/package-info.java @@ -0,0 +1,28 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2024 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +/** + * @author Yong.Teng + */ +package com.buession.springboot.shiro.env; \ No newline at end of file diff --git a/buession-springboot-shiro/src/main/resources/META-INF/spring.factories b/buession-springboot-shiro/src/main/resources/META-INF/spring.factories index c2eee02f..afb0277f 100644 --- a/buession-springboot-shiro/src/main/resources/META-INF/spring.factories +++ b/buession-springboot-shiro/src/main/resources/META-INF/spring.factories @@ -7,5 +7,7 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.buession.springboot.shiro.autoconfigure.ShiroBeanConfiguration, \ com.buession.springboot.shiro.autoconfigure.ShiroConfiguration, \ com.buession.springboot.shiro.autoconfigure.ShiroAnnotationProcessorAutoConfiguration +org.springframework.boot.env.EnvironmentPostProcessor=\ + com.buession.springboot.shiro.env.ShiroEnvironmentPostProcessor org.springframework.boot.diagnostics.FailureAnalyzer=\ com.buession.springboot.shiro.ShiroNoRealmConfiguredFailureAnalyzer \ No newline at end of file diff --git a/buession-springboot-velocity/pom.xml b/buession-springboot-velocity/pom.xml index 82c70730..28510dab 100644 --- a/buession-springboot-velocity/pom.xml +++ b/buession-springboot-velocity/pom.xml @@ -7,7 +7,7 @@ com.buession.springboot buession-springboot-parent ../buession-springboot-parent - 2.3.2 + 2.3.3 buession-springboot-velocity https://springboot.buession.com/ diff --git a/buession-springboot-velocity/src/main/java/com/buession/springboot/velocity/autoconfigure/VelocityConfiguration.java b/buession-springboot-velocity/src/main/java/com/buession/springboot/velocity/autoconfigure/VelocityConfiguration.java index b7cbb9d3..24744ae9 100644 --- a/buession-springboot-velocity/src/main/java/com/buession/springboot/velocity/autoconfigure/VelocityConfiguration.java +++ b/buession-springboot-velocity/src/main/java/com/buession/springboot/velocity/autoconfigure/VelocityConfiguration.java @@ -21,7 +21,7 @@ * +------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.velocity.autoconfigure; @@ -73,19 +73,18 @@ public class VelocityConfiguration { private final static Logger logger = LoggerFactory.getLogger(VelocityConfiguration.class); - public VelocityConfiguration(VelocityProperties properties, ObjectProvider applicationContext){ + public VelocityConfiguration(VelocityProperties properties, ObjectProvider applicationContext) { this.properties = properties; this.applicationContext = applicationContext.getIfAvailable(); } @PostConstruct - public void checkTemplateLocationExists(){ + public void checkTemplateLocationExists() { if(properties.isCheckTemplateLocation()){ TemplateLocation location = new TemplateLocation(properties.getResourceLoaderPath()); if(location.exists(applicationContext) == false){ logger.warn("Cannot find template location: {} (please add some templates, check your Velocity " + - "configuration, or set {}.checkTemplateLocation=false)", location, - VelocityProperties.class.getName()); + "configuration, or set spring.velocity.checkTemplateLocation=false)", location); } } } @@ -94,17 +93,17 @@ static abstract class AbstractVelocityConfiguration { protected final VelocityProperties properties; - public AbstractVelocityConfiguration(VelocityProperties properties){ + public AbstractVelocityConfiguration(VelocityProperties properties) { this.properties = properties; } - protected VelocityConfigurer velocityConfigurer(){ + protected VelocityConfigurer velocityConfigurer() { VelocityConfigurer configurer = new VelocityConfigurer(); applyProperties(configurer); return configurer; } - protected void applyProperties(VelocityEngineFactory factory){ + protected void applyProperties(VelocityEngineFactory factory) { Properties velocityProperties = new Properties(); velocityProperties.setProperty(RuntimeConstants.INPUT_ENCODING, @@ -127,20 +126,20 @@ protected void applyProperties(VelocityEngineFactory factory){ @AutoConfigureAfter(WebMvcAutoConfiguration.class) static class VelocityServletWebConfiguration extends AbstractVelocityConfiguration { - public VelocityServletWebConfiguration(VelocityProperties properties){ + public VelocityServletWebConfiguration(VelocityProperties properties) { super(properties); } @Bean @ConditionalOnMissingBean @Override - public VelocityConfigurer velocityConfigurer(){ + public VelocityConfigurer velocityConfigurer() { return super.velocityConfigurer(); } @Bean @ConditionalOnMissingBean(name = "velocityViewResolver") - public com.buession.velocity.servlet.VelocityViewResolver velocityViewResolver(){ + public com.buession.velocity.servlet.VelocityViewResolver velocityViewResolver() { com.buession.velocity.servlet.VelocityViewResolver resolver = new com.buession.velocity.servlet.VelocityViewResolver(); resolver.setEncoding(properties.getCharset().name()); @@ -156,7 +155,7 @@ public com.buession.velocity.servlet.VelocityViewResolver velocityViewResolver() @Bean @ConditionalOnEnabledResourceChain @ConditionalOnMissingFilterBean(ResourceUrlEncodingFilter.class) - public FilterRegistrationBean resourceUrlEncodingFilter(){ + public FilterRegistrationBean resourceUrlEncodingFilter() { FilterRegistrationBean registration = new FilterRegistrationBean<>( new ResourceUrlEncodingFilter()); registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ERROR); @@ -172,12 +171,12 @@ public FilterRegistrationBean resourceUrlEncodingFilt @AutoConfigureAfter(WebFluxAutoConfiguration.class) static class VelocityReactiveWebConfiguration extends AbstractVelocityConfiguration { - public VelocityReactiveWebConfiguration(VelocityProperties properties){ + public VelocityReactiveWebConfiguration(VelocityProperties properties) { super(properties); } @PostConstruct - public void initialize(){ + public void initialize() { if(logger.isErrorEnabled()){ logger.error("{} cloud not support on {}", VelocityEngine.class.getName(), ConditionalOnWebApplication.Type.REACTIVE.name()); @@ -191,13 +190,13 @@ public void initialize(){ @ConditionalOnNotWebApplication static class VelocityNonWebConfiguration extends AbstractVelocityConfiguration { - public VelocityNonWebConfiguration(VelocityProperties properties){ + public VelocityNonWebConfiguration(VelocityProperties properties) { super(properties); } @Bean @ConditionalOnMissingBean - public VelocityEngineFactoryBean velocityConfiguration(){ + public VelocityEngineFactoryBean velocityConfiguration() { final VelocityEngineFactoryBean velocityEngineFactoryBean = new VelocityEngineFactoryBean(); applyProperties(velocityEngineFactoryBean); diff --git a/buession-springboot-web/pom.xml b/buession-springboot-web/pom.xml index 3aa93ec9..b801df65 100644 --- a/buession-springboot-web/pom.xml +++ b/buession-springboot-web/pom.xml @@ -7,7 +7,7 @@ com.buession.springboot buession-springboot-parent ../buession-springboot-parent - 2.3.2 + 2.3.3 buession-springboot-web https://springboot.buession.com/ diff --git a/buession-springboot-web/src/main/java/com/buession/springboot/web/reactive/autoconfigure/ReactiveWebSecurityConfiguration.java b/buession-springboot-web/src/main/java/com/buession/springboot/web/reactive/autoconfigure/ReactiveWebSecurityConfiguration.java index 8ce90679..6dcdd3dc 100644 --- a/buession-springboot-web/src/main/java/com/buession/springboot/web/reactive/autoconfigure/ReactiveWebSecurityConfiguration.java +++ b/buession-springboot-web/src/main/java/com/buession/springboot/web/reactive/autoconfigure/ReactiveWebSecurityConfiguration.java @@ -19,20 +19,18 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.web.reactive.autoconfigure; -import com.buession.core.validator.Validate; import com.buession.security.web.config.Configurer; +import com.buession.security.web.config.Xss; import com.buession.security.web.reactive.config.ReactiveWebSecurityConfigurerAdapterConfiguration; -import com.buession.security.web.utils.PolicyUtils; +import com.buession.security.web.xss.Options; import com.buession.security.web.xss.reactive.XssFilter; import com.buession.springboot.web.autoconfigure.AbstractWebSecurityConfiguration; import com.buession.springboot.web.security.WebSecurityProperties; -import org.owasp.validator.html.Policy; -import org.owasp.validator.html.PolicyException; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -43,8 +41,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.security.config.web.server.ServerHttpSecurity; -import java.io.IOException; - /** * @author Yong.Teng * @since 2.0.0 @@ -56,22 +52,29 @@ @ConditionalOnProperty(prefix = WebSecurityProperties.PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true) public class ReactiveWebSecurityConfiguration extends AbstractWebSecurityConfiguration { - public ReactiveWebSecurityConfiguration(WebSecurityProperties properties){ + public ReactiveWebSecurityConfiguration(WebSecurityProperties properties) { super(properties); } @Bean - @ConditionalOnClass({Policy.class}) @ConditionalOnProperty(prefix = WebSecurityProperties.PREFIX, name = "xss.enabled", havingValue = "true") - public XssFilter xssFilter() throws PolicyException, IOException{ - XssFilter xssFilter = new XssFilter(); - String policyConfigLocation = properties.getXss().getPolicyConfigLocation(); + public XssFilter xssFilter() { + final Xss xss = properties.getXss(); + final Options.Builder optionsBuilder = Options.Builder.getInstance(); + + optionsBuilder.policy(xss.getPolicy()); + + if(xss.getPolicy() == Options.Policy.ESCAPE){ + optionsBuilder.escape(new Options.Escape()); + }else{ + final Options.Clean clean = new Options.Clean(); + + clean.setPolicyConfigLocation(xss.getPolicyConfigLocation()); - if(Validate.hasText(policyConfigLocation)){ - xssFilter.setPolicy(PolicyUtils.createFromConfigFile(policyConfigLocation)); + optionsBuilder.clean(clean); } - return xssFilter; + return new XssFilter(optionsBuilder.build()); } @Configuration(proxyBeanMethods = false) @@ -81,7 +84,7 @@ static class DefaultWebSecurityConfigurerAdapterConfiguration extends ReactiveWebSecurityConfigurerAdapterConfiguration { public DefaultWebSecurityConfigurerAdapterConfiguration(WebSecurityProperties properties, - ObjectProvider serverHttpSecurity){ + ObjectProvider serverHttpSecurity) { super(new Configurer(properties.getHttpBasic(), properties.getCsrf(), properties.getCors(), properties.getFrameOptions(), properties.getHsts(), properties.getHpkp(), properties.getContentSecurityPolicy(), properties.getReferrerPolicy(), properties.getXss(), diff --git a/buession-springboot-web/src/main/java/com/buession/springboot/web/servlet/autoconfigure/ServletWebSecurityConfiguration.java b/buession-springboot-web/src/main/java/com/buession/springboot/web/servlet/autoconfigure/ServletWebSecurityConfiguration.java index 2b9e12c0..d961f87c 100644 --- a/buession-springboot-web/src/main/java/com/buession/springboot/web/servlet/autoconfigure/ServletWebSecurityConfiguration.java +++ b/buession-springboot-web/src/main/java/com/buession/springboot/web/servlet/autoconfigure/ServletWebSecurityConfiguration.java @@ -21,21 +21,19 @@ * +------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2023 Buession.com Inc. | + * | Copyright @ 2013-2024 Buession.com Inc. | * +------------------------------------------------------------------------------------------------+ */ package com.buession.springboot.web.servlet.autoconfigure; -import com.buession.core.validator.Validate; import com.buession.security.web.config.Configurer; +import com.buession.security.web.config.Xss; import com.buession.security.web.servlet.config.ServletWebSecurityConfigurerAdapterConfiguration; -import com.buession.security.web.utils.PolicyUtils; +import com.buession.security.web.xss.Options; import com.buession.security.web.xss.servlet.WebMvcXssConfigurer; import com.buession.security.web.xss.servlet.XssFilter; import com.buession.springboot.web.autoconfigure.AbstractWebSecurityConfiguration; import com.buession.springboot.web.security.WebSecurityProperties; -import org.owasp.validator.html.Policy; -import org.owasp.validator.html.PolicyException; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; @@ -44,8 +42,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import java.io.IOException; - /** * Spring Security Configuration * @@ -59,22 +55,29 @@ @ConditionalOnProperty(prefix = WebSecurityProperties.PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true) public class ServletWebSecurityConfiguration extends AbstractWebSecurityConfiguration { - public ServletWebSecurityConfiguration(WebSecurityProperties properties){ + public ServletWebSecurityConfiguration(WebSecurityProperties properties) { super(properties); } @Bean - @ConditionalOnClass({Policy.class}) @ConditionalOnProperty(prefix = WebSecurityProperties.PREFIX, name = "xss.enabled", havingValue = "true") - public XssFilter xssFilter() throws PolicyException, IOException{ - XssFilter xssFilter = new XssFilter(); - String policyConfigLocation = properties.getXss().getPolicyConfigLocation(); + public XssFilter xssFilter() { + final Xss xss = properties.getXss(); + final Options.Builder optionsBuilder = Options.Builder.getInstance(); + + optionsBuilder.policy(xss.getPolicy()); + + if(xss.getPolicy() == Options.Policy.ESCAPE){ + optionsBuilder.escape(new Options.Escape()); + }else{ + final Options.Clean clean = new Options.Clean(); + + clean.setPolicyConfigLocation(xss.getPolicyConfigLocation()); - if(Validate.hasText(policyConfigLocation)){ - xssFilter.setPolicy(PolicyUtils.createFromConfigFile(policyConfigLocation)); + optionsBuilder.clean(clean); } - return xssFilter; + return new XssFilter(optionsBuilder.build()); } @Configuration(proxyBeanMethods = false) @@ -83,7 +86,7 @@ public XssFilter xssFilter() throws PolicyException, IOException{ static class DefaultWebSecurityConfigurerAdapterConfiguration extends ServletWebSecurityConfigurerAdapterConfiguration { - public DefaultWebSecurityConfigurerAdapterConfiguration(WebSecurityProperties properties){ + public DefaultWebSecurityConfigurerAdapterConfiguration(WebSecurityProperties properties) { super(new Configurer(properties.getHttpBasic(), properties.getCsrf(), properties.getCors(), properties.getFrameOptions(), properties.getHsts(), properties.getHpkp(), properties.getContentSecurityPolicy(), properties.getReferrerPolicy(), properties.getXss(), @@ -93,7 +96,6 @@ public DefaultWebSecurityConfigurerAdapterConfiguration(WebSecurityProperties pr } @Configuration(proxyBeanMethods = false) - @ConditionalOnClass({Policy.class}) @ConditionalOnProperty(prefix = WebSecurityProperties.PREFIX, name = "xss.enabled", havingValue = "true") static class WebMvcXssConfigurerConfiguration extends WebMvcXssConfigurer {