无依赖升级springboot3

pull/1561/head
在小菜 1 year ago
parent 832fd4c21e
commit db9c22c102

@ -31,60 +31,60 @@
<build>
<finalName>hippo4j-threadpool-agent</finalName>
<plugins>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>false</shadedArtifactAttached>
<createDependencyReducedPom>true</createDependencyReducedPom>
<createSourcesJar>true</createSourcesJar>
<shadeSourcesContent>true</shadeSourcesContent>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<manifestEntries>
<Premain-Class>${premain.class}</Premain-Class>
<Can-Redefine-Classes>${can.redefine.classes}</Can-Redefine-Classes>
<Can-Retransform-Classes>${can.retransform.classes}</Can-Retransform-Classes>
</manifestEntries>
</transformer>
</transformers>
<artifactSet>
<excludes>
<exclude>*:gson</exclude>
<exclude>io.grpc:*</exclude>
<exclude>io.netty:*</exclude>
<exclude>io.opencensus:*</exclude>
<exclude>com.google.*:*</exclude>
<exclude>com.google.guava:guava</exclude>
<exclude>org.checkerframework:checker-compat-qual</exclude>
<exclude>org.codehaus.mojo:animal-sniffer-annotations</exclude>
<exclude>io.perfmark:*</exclude>
<exclude>org.slf4j:*</exclude>
</excludes>
</artifactSet>
<relocations>
<relocation>
<pattern>${shade.net.bytebuddy.source}</pattern>
<shadedPattern>${shade.net.bytebuddy.target}</shadedPattern>
</relocation>
</relocations>
<filters>
<filter>
<artifact>net.bytebuddy:byte-buddy</artifact>
<excludes>
<exclude>META-INF/versions/9/module-info.class</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
<!-- <plugin>-->
<!-- <artifactId>maven-shade-plugin</artifactId>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <phase>package</phase>-->
<!-- <goals>-->
<!-- <goal>shade</goal>-->
<!-- </goals>-->
<!-- <configuration>-->
<!-- <shadedArtifactAttached>false</shadedArtifactAttached>-->
<!-- <createDependencyReducedPom>true</createDependencyReducedPom>-->
<!-- <createSourcesJar>true</createSourcesJar>-->
<!-- <shadeSourcesContent>true</shadeSourcesContent>-->
<!-- <transformers>-->
<!-- <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">-->
<!-- <manifestEntries>-->
<!-- <Premain-Class>${premain.class}</Premain-Class>-->
<!-- <Can-Redefine-Classes>${can.redefine.classes}</Can-Redefine-Classes>-->
<!-- <Can-Retransform-Classes>${can.retransform.classes}</Can-Retransform-Classes>-->
<!-- </manifestEntries>-->
<!-- </transformer>-->
<!-- </transformers>-->
<!-- <artifactSet>-->
<!-- <excludes>-->
<!-- <exclude>*:gson</exclude>-->
<!-- <exclude>io.grpc:*</exclude>-->
<!-- <exclude>io.netty:*</exclude>-->
<!-- <exclude>io.opencensus:*</exclude>-->
<!-- <exclude>com.google.*:*</exclude>-->
<!-- <exclude>com.google.guava:guava</exclude>-->
<!-- <exclude>org.checkerframework:checker-compat-qual</exclude>-->
<!-- <exclude>org.codehaus.mojo:animal-sniffer-annotations</exclude>-->
<!-- <exclude>io.perfmark:*</exclude>-->
<!-- <exclude>org.slf4j:*</exclude>-->
<!-- </excludes>-->
<!-- </artifactSet>-->
<!-- <relocations>-->
<!-- <relocation>-->
<!-- <pattern>${shade.net.bytebuddy.source}</pattern>-->
<!-- <shadedPattern>${shade.net.bytebuddy.target}</shadedPattern>-->
<!-- </relocation>-->
<!-- </relocations>-->
<!-- <filters>-->
<!-- <filter>-->
<!-- <artifact>net.bytebuddy:byte-buddy</artifact>-->
<!-- <excludes>-->
<!-- <exclude>META-INF/versions/9/module-info.class</exclude>-->
<!-- </excludes>-->
<!-- </filter>-->
<!-- </filters>-->
<!-- </configuration>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- </plugin>-->
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>

@ -105,68 +105,68 @@
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<excludes>
<exclude>net.bytebuddy:byte-buddy:jar:</exclude>
<exclude>com.google.errorprone:error_prone_annotations:jar:</exclude>
<exclude>com.google.code.findbugs:jsr305:jar:</exclude>
<exclude>com.google.android:annotations:jar:</exclude>
<exclude>com.google.api.grpc:proto-google-common-protos:jar:</exclude>
<exclude>org.checkerframework:checker-compat-qual:jar:</exclude>
<exclude>org.codehaus.mojo:animal-sniffer-annotations:jar:</exclude>
</excludes>
</artifactSet>
<relocations>
<relocation>
<pattern>${shade.com.google.source}</pattern>
<shadedPattern>${shade.com.google.target}</shadedPattern>
</relocation>
<relocation>
<pattern>${shade.io.grpc.source}</pattern>
<shadedPattern>${shade.io.grpc.target}</shadedPattern>
</relocation>
<relocation>
<pattern>${shade.io.netty.source}</pattern>
<shadedPattern>${shade.io.netty.target}</shadedPattern>
</relocation>
<relocation>
<pattern>${shade.io.opencensus.source}</pattern>
<shadedPattern>${shade.io.opencensus.target}</shadedPattern>
</relocation>
<relocation>
<pattern>${shade.io.perfmark.source}</pattern>
<shadedPattern>${shade.io.perfmark.target}</shadedPattern>
</relocation>
<relocation>
<pattern>${shade.org.slf4j.source}</pattern>
<shadedPattern>${shade.org.slf4j.target}</shadedPattern>
</relocation>
</relocations>
<filters>
<filter>
<artifact>com.google.protobuf:protobuf-java</artifact>
<excludes>
<exclude>google/protobuf/*.proto</exclude>
<exclude>google/protobuf/compiler/*.proto</exclude>
</excludes>
</filter>
</filters>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<!-- <plugin>-->
<!-- <artifactId>maven-shade-plugin</artifactId>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <phase>package</phase>-->
<!-- <goals>-->
<!-- <goal>shade</goal>-->
<!-- </goals>-->
<!-- <configuration>-->
<!-- <artifactSet>-->
<!-- <excludes>-->
<!-- <exclude>net.bytebuddy:byte-buddy:jar:</exclude>-->
<!-- <exclude>com.google.errorprone:error_prone_annotations:jar:</exclude>-->
<!-- <exclude>com.google.code.findbugs:jsr305:jar:</exclude>-->
<!-- <exclude>com.google.android:annotations:jar:</exclude>-->
<!-- <exclude>com.google.api.grpc:proto-google-common-protos:jar:</exclude>-->
<!-- <exclude>org.checkerframework:checker-compat-qual:jar:</exclude>-->
<!-- <exclude>org.codehaus.mojo:animal-sniffer-annotations:jar:</exclude>-->
<!-- </excludes>-->
<!-- </artifactSet>-->
<!-- <relocations>-->
<!-- <relocation>-->
<!-- <pattern>${shade.com.google.source}</pattern>-->
<!-- <shadedPattern>${shade.com.google.target}</shadedPattern>-->
<!-- </relocation>-->
<!-- <relocation>-->
<!-- <pattern>${shade.io.grpc.source}</pattern>-->
<!-- <shadedPattern>${shade.io.grpc.target}</shadedPattern>-->
<!-- </relocation>-->
<!-- <relocation>-->
<!-- <pattern>${shade.io.netty.source}</pattern>-->
<!-- <shadedPattern>${shade.io.netty.target}</shadedPattern>-->
<!-- </relocation>-->
<!-- <relocation>-->
<!-- <pattern>${shade.io.opencensus.source}</pattern>-->
<!-- <shadedPattern>${shade.io.opencensus.target}</shadedPattern>-->
<!-- </relocation>-->
<!-- <relocation>-->
<!-- <pattern>${shade.io.perfmark.source}</pattern>-->
<!-- <shadedPattern>${shade.io.perfmark.target}</shadedPattern>-->
<!-- </relocation>-->
<!-- <relocation>-->
<!-- <pattern>${shade.org.slf4j.source}</pattern>-->
<!-- <shadedPattern>${shade.org.slf4j.target}</shadedPattern>-->
<!-- </relocation>-->
<!-- </relocations>-->
<!-- <filters>-->
<!-- <filter>-->
<!-- <artifact>com.google.protobuf:protobuf-java</artifact>-->
<!-- <excludes>-->
<!-- <exclude>google/protobuf/*.proto</exclude>-->
<!-- <exclude>google/protobuf/compiler/*.proto</exclude>-->
<!-- </excludes>-->
<!-- </filter>-->
<!-- </filters>-->
<!-- <transformers>-->
<!-- <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />-->
<!-- </transformers>-->
<!-- </configuration>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- </plugin>-->
</plugins>
</build>
</project>

@ -48,29 +48,29 @@
<build>
<plugins>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>false</shadedArtifactAttached>
<createDependencyReducedPom>true</createDependencyReducedPom>
<createSourcesJar>true</createSourcesJar>
<shadeSourcesContent>true</shadeSourcesContent>
<relocations>
<relocation>
<pattern>${shade.net.bytebuddy.source}</pattern>
<shadedPattern>${shade.net.bytebuddy.target}</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
<!-- <plugin>-->
<!-- <artifactId>maven-shade-plugin</artifactId>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <phase>package</phase>-->
<!-- <goals>-->
<!-- <goal>shade</goal>-->
<!-- </goals>-->
<!-- <configuration>-->
<!-- <shadedArtifactAttached>false</shadedArtifactAttached>-->
<!-- <createDependencyReducedPom>true</createDependencyReducedPom>-->
<!-- <createSourcesJar>true</createSourcesJar>-->
<!-- <shadeSourcesContent>true</shadeSourcesContent>-->
<!-- <relocations>-->
<!-- <relocation>-->
<!-- <pattern>${shade.net.bytebuddy.source}</pattern>-->
<!-- <shadedPattern>${shade.net.bytebuddy.target}</shadedPattern>-->
<!-- </relocation>-->
<!-- </relocations>-->
<!-- </configuration>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- </plugin>-->
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>

@ -13,7 +13,7 @@
<packaging>pom</packaging>
<modules>
<module>spring-boot-1x-plugin</module>
<!-- <module>spring-boot-1x-plugin</module>-->
<module>spring-boot-2x-plugin</module>
<module>spring-plugin-common</module>
</modules>

@ -20,11 +20,11 @@
<mockito.version>3.12.4</mockito.version>
<dubbo.version>3.0.5</dubbo.version>
<alibaba-dubbo.version>2.6.12</alibaba-dubbo.version>
<slf4j-api.version>1.7.7</slf4j-api.version>
<micrometer-core.version>1.8.4</micrometer-core.version>
<slf4j-api.version>2.0.9</slf4j-api.version>
<micrometer-core.version>1.10.13</micrometer-core.version>
<nacos-client.version>2.0.4</nacos-client.version>
<mybatis-plus.version>3.4.2</mybatis-plus.version>
<spring-boot.version>2.3.2.RELEASE</spring-boot.version>
<spring-boot.version>3.0.13</spring-boot.version>
<apollo.version>1.9.1</apollo.version>
<consul.version>2.2.4.RELEASE</consul.version>
<jetcd.version>0.7.3</jetcd.version>
@ -32,7 +32,7 @@
<rocketmq.version>2.2.2</rocketmq.version>
<netty.version>4.1.56.Final</netty.version>
<elasticsearch.version>6.8.17</elasticsearch.version>
<tomcat-embed-core.version>9.0.55</tomcat-embed-core.version>
<tomcat-embed-core.version>10.1.16</tomcat-embed-core.version>
<curator-framework.version>5.1.0</curator-framework.version>
<spring-cloud-starter-stream-rocketmq.version>2.2.6.RELEASE</spring-cloud-starter-stream-rocketmq.version>
<spring-cloud-starter-stream-rabbitmq.version>3.1.0</spring-cloud-starter-stream-rabbitmq.version>

@ -21,7 +21,7 @@
<module>config-zookeeper</module>
<module>config-consul-spring-boot</module>
<module>config-etcd</module>
<module>config-nacos-spring-boot-1x</module>
<module>config-apollo-spring-boot-1x</module>
<!-- <module>config-nacos-spring-boot-1x</module>-->
<!-- <module>config-apollo-spring-boot-1x</module>-->
</modules>
</project>

@ -17,12 +17,12 @@
package cn.hippo4j.example.core.inittest;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.SynchronousQueue;

@ -17,6 +17,7 @@
package cn.hippo4j.springboot.starter.adapter.kafka.example;
import jakarta.annotation.PostConstruct;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
@ -24,7 +25,6 @@ import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.PostConstruct;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@ -14,6 +14,7 @@
</properties>
<dependencies>
<dependency>
<groupId>cn.hippo4j</groupId>
<artifactId>hippo4j-example-core</artifactId>
@ -47,10 +48,10 @@
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.apache.tomcat.embed</groupId>-->
<!-- <artifactId>tomcat-embed-core</artifactId>-->
<!-- </dependency>-->
<!--<dependency>
<groupId>org.springframework.boot</groupId>

@ -2,7 +2,7 @@ server.port=8088
server.servlet.context-path=/example
management.metrics.export.prometheus.enabled=true
management.prometheus.metrics.export.enabled=true
management.server.port=29901
management.endpoints.web.exposure.include=*
@ -24,3 +24,4 @@ spring.dynamic.thread-pool.monitor.collect-types=server,micrometer
spring.dynamic.thread-pool.monitor.thread-pool-types=dynamic,web
spring.dynamic.thread-pool.monitor.initial-delay=10000
spring.dynamic.thread-pool.monitor.collect-interval=5000
debug=true

@ -1,46 +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.
*/
package cn.hippo4j.common;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class MockitoTests {
@Mock
List<String> list;
@Test
public void mockTests() {
Mockito.when(list.get(1)).thenReturn("mock success.");
Assertions.assertEquals("mock success.", list.get(1));
try (final MockedStatic<StringUtils> mockStatic = Mockito.mockStatic(StringUtils.class)) {
mockStatic.when(() -> StringUtils.trim("")).thenReturn("测试");
Assertions.assertEquals("测试", StringUtils.trim(""));
}
}
}

@ -1,89 +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.
*/
package cn.hippo4j.common.executor;
import cn.hippo4j.common.toolkit.MapUtil;
import cn.hippo4j.common.toolkit.ReflectUtil;
import org.junit.Assert;
import org.junit.Test;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.stream.IntStream;
public final class ExecutorFactoryTest {
ThreadFactory threadFactory = new ThreadFactoryBuilder().prefix("test").build();
/**
* data range min
*/
Integer rangeMin = 1;
/**
* data range max
*/
Integer rangeMax = 10;
/**
* default test index
*/
Integer defaultIndex = 0;
@Test
public void assertNewSingleScheduledExecutorService() {
// init data snapshot
ThreadPoolManager poolManager = (ThreadPoolManager) ReflectUtil.getFieldValue(ExecutorFactory.Managed.class, "THREAD_POOL_MANAGER");
String poolName = (String) ReflectUtil.getFieldValue(ExecutorFactory.Managed.class, "DEFAULT_NAMESPACE");
Map<String, Map<String, Set<ExecutorService>>> manager = (Map<String, Map<String, Set<ExecutorService>>>) ReflectUtil.getFieldValue(poolManager, "resourcesManager");
Map<String, Set<ExecutorService>> initRelationMap = manager.get(poolName);
int defaultManagerSize = manager.size();
int defaultRelationSize = MapUtil.isEmpty(initRelationMap) ? 0 : initRelationMap.size();
// test begin
ScheduledExecutorService executorService = ExecutorFactory.Managed.newSingleScheduledExecutorService(String.format("test-group-%s", defaultIndex), threadFactory);
Assert.assertNotNull(executorService);
// check default init
Assert.assertEquals(1, manager.size() - defaultManagerSize);
// check multiple registrations and check to see if it is still an instance
IntStream.rangeClosed(rangeMin, rangeMax).forEach(index -> ExecutorFactory.Managed.newSingleScheduledExecutorService(String.format("test-group-%s", index), threadFactory));
Assert.assertEquals(1, manager.size() - defaultManagerSize);
// check group size
Map<String, Set<ExecutorService>> relationMap = manager.get(poolName);
Assert.assertEquals(11, relationMap.size() - defaultRelationSize);
// check the number of threads between the group and the thread pool
IntStream.rangeClosed(rangeMin, rangeMax).forEach(index -> {
String relationKey = String.format("test-group-%s", index);
Assert.assertNotNull(relationMap.get(relationKey));
Assert.assertEquals(1, relationMap.get(relationKey).size());
});
// instantiate the same group a second time and check the corresponding quantitative relationship
IntStream.rangeClosed(defaultIndex, rangeMax).forEach(index -> ExecutorFactory.Managed.newSingleScheduledExecutorService(String.format("test-group-%s", index), threadFactory));
// chek group size
Assert.assertEquals(11, manager.get(poolName).size() - defaultRelationSize);
// check the number of threads between the group and the thread pool
IntStream.rangeClosed(rangeMin, rangeMax).forEach(index -> Assert.assertEquals(2, relationMap.get(String.format("test-group-%s", index)).size()));
}
}

@ -1,81 +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.
*/
package cn.hippo4j.common.design.builder;
import cn.hippo4j.common.design.builder.ThreadFactoryBuilder;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.ThreadFactory;
import java.lang.Thread.UncaughtExceptionHandler;
public class ThreadFactoryBuilderTest {
ThreadFactoryBuilder builder;
TestUncaughtExceptionHandler uncaughtExceptionHandler;
Thread thread;
@Before
public void buildThread() {
builder = ThreadFactoryBuilder.builder();
uncaughtExceptionHandler = new TestUncaughtExceptionHandler();
builder.uncaughtExceptionHandler(uncaughtExceptionHandler);
builder.prefix("my-thread-factory");
builder.daemon(true);
builder.priority(Thread.MAX_PRIORITY);
ThreadFactory threadFactory = builder.build();
thread = threadFactory.newThread(() -> {
System.out.println("Create a new thread.");
});
thread.start();
}
@Test
public void testName() {
Assert.assertEquals("my-thread-factory_0", thread.getName());
}
@Test
public void testIsDaemon() {
Assert.assertTrue(thread.isDaemon());
}
@Test
public void testExceptionHandler() {
Assert.assertEquals(uncaughtExceptionHandler, thread.getUncaughtExceptionHandler());
}
@Test
public void testPriority() {
Assert.assertEquals(Thread.MAX_PRIORITY, thread.getPriority());
}
}
class TestUncaughtExceptionHandler implements UncaughtExceptionHandler {
private volatile boolean exceptionCaught = false;
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("Exception caught by " + t.getName());
exceptionCaught = true;
}
public boolean isExceptionCaught() {
return exceptionCaught;
}
}

@ -1,89 +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.
*/
package cn.hippo4j.common.executor;
import cn.hippo4j.common.toolkit.ThreadPoolExecutorUtil;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolExecutorUtilTest {
private ThreadPoolExecutor executor;
private int corePoolSize;
private int maxPoolSize;
@Before
public void testSafeSetPoolSize() {
corePoolSize = 2;
maxPoolSize = 4;
executor = new ThreadPoolExecutor(
corePoolSize,
maxPoolSize,
1L,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10)
);
}
@Test
public void testEquals(){
// Test when the new core pool size equals the original maximum pool size.
int newCorePoolSize1 = maxPoolSize;
int newMaxPoolSize1 = 6;
ThreadPoolExecutorUtil.safeSetPoolSize(executor, newCorePoolSize1, newMaxPoolSize1);
Assert.assertEquals(newCorePoolSize1, executor.getCorePoolSize());
Assert.assertEquals(newMaxPoolSize1, executor.getMaximumPoolSize());
}
@Test
public void testGreater(){
// Test when the new core pool size is greater than the original maximum pool size.
int newCorePoolSize2 = 8;
int newMaxPoolSize2 = 10;
ThreadPoolExecutorUtil.safeSetPoolSize(executor, newCorePoolSize2, newMaxPoolSize2);
Assert.assertEquals(newCorePoolSize2, executor.getCorePoolSize());
Assert.assertEquals(newMaxPoolSize2, executor.getMaximumPoolSize());
}
@Test
public void testLess(){
// Test when the new core pool size is less than the original maximum pool size.
int newCorePoolSize3 = 3;
int newMaxPoolSize3 = 5;
ThreadPoolExecutorUtil.safeSetPoolSize(executor, newCorePoolSize3, newMaxPoolSize3);
Assert.assertEquals(newCorePoolSize3, executor.getCorePoolSize());
Assert.assertEquals(newMaxPoolSize3, executor.getMaximumPoolSize());
}
@Test
public void testException(){
// Test when the new core pool size is greater than the new maximum pool size, which should throw an IllegalArgumentException.
int newCorePoolSize4 = 6;
int newMaxPoolSize4 = 4;
try {
ThreadPoolExecutorUtil.safeSetPoolSize(executor, newCorePoolSize4, newMaxPoolSize4);
} catch (IllegalArgumentException e) {
// Expected to throw an exception.
Assert.assertEquals("newCorePoolSize must be smaller than newMaximumPoolSize", e.getMessage());
}
}
}

@ -1,74 +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.
*/
package cn.hippo4j.common.executor;
import cn.hippo4j.common.toolkit.ReflectUtil;
import org.junit.Assert;
import org.junit.Test;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
public class ThreadPoolManagerTest {
// tenantId = schedulegroup = schedule
ScheduledExecutorService executorService1 = Executors.newScheduledThreadPool(1);
// tenantId = schedulegroup = schedule
ScheduledExecutorService executorService2 = Executors.newScheduledThreadPool(10);
// tenantId = executorgroup = executor
ExecutorService executorService3 = Executors.newFixedThreadPool(8);
// tenantId = executorgroup = executor
ExecutorService executorService4 = Executors.newFixedThreadPool(16);
static final String schedule = "schedule";
static final String executor = "executor";
@Test
public void getInstance() {
ThreadPoolManager poolManager = ThreadPoolManager.getInstance();
Assert.assertNotNull(poolManager);
}
@Test
public void register() {
ThreadPoolManager poolManager = ThreadPoolManager.getInstance();
poolManager.register(schedule, schedule, executorService1);
poolManager.register(schedule, schedule, executorService2);
poolManager.register(executor, executor, executorService3);
poolManager.register(executor, executor, executorService4);
Map<String, Map<String, Set<ExecutorService>>> manager = (Map<String, Map<String, Set<ExecutorService>>>) ReflectUtil.getFieldValue(poolManager, "resourcesManager");
Map<String, Set<ExecutorService>> scheduleMap = manager.get(schedule);
Assert.assertEquals(1, scheduleMap.size());
Set<ExecutorService> scheduleSet = scheduleMap.get(schedule);
Assert.assertEquals(2, scheduleSet.size());
Map<String, Set<ExecutorService>> executorMap = manager.get(executor);
Assert.assertEquals(1, executorMap.size());
Set<ExecutorService> executorSet = executorMap.get(executor);
Assert.assertEquals(2, executorSet.size());
}
}

@ -1,134 +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.
*/
package cn.hippo4j.common.executor.support;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.stream.Collectors;
/**
* BlockingQueueTypeEnum test class
*/
public final class BlockingQueueTypeEnumTest {
// get all blocking queue names
private static final List<String> BLOCKING_QUEUE_NAMES = Arrays.stream(BlockingQueueTypeEnum.values()).map(BlockingQueueTypeEnum::getName).collect(Collectors.toList());
@Test
public void testAssertCreateBlockingQueueNormal() {
// check legal param: name and capacity
for (String name : BLOCKING_QUEUE_NAMES) {
BlockingQueue<Object> blockingQueueByName = BlockingQueueTypeEnum.createBlockingQueue(name, 10);
Assert.assertNotNull(blockingQueueByName);
}
}
@Test
public void testAssertCreateBlockingQueueWithIllegalName() {
// check illegal null name
Assert.assertNotNull(BlockingQueueTypeEnum.createBlockingQueue(null, 10));
// check unexistent name
Assert.assertNotNull(BlockingQueueTypeEnum.createBlockingQueue("ABC", 10));
}
@Test
public void testAssertCreateBlockingQueueWithIllegalCapacity() {
// check illegal null capacity
for (String name : BLOCKING_QUEUE_NAMES) {
BlockingQueue<Object> blockingQueueWithNullCapacity = BlockingQueueTypeEnum.createBlockingQueue(name, null);
Assert.assertNotNull(blockingQueueWithNullCapacity);
}
// check illegal negatives capacity
final String arrayBlockingQueueName = BlockingQueueTypeEnum.ARRAY_BLOCKING_QUEUE.getName();
Assert.assertThrows(IllegalArgumentException.class, () -> BlockingQueueTypeEnum.createBlockingQueue(arrayBlockingQueueName, -100));
final String linkedBlockingQueueName = BlockingQueueTypeEnum.LINKED_BLOCKING_QUEUE.getName();
Assert.assertThrows(IllegalArgumentException.class, () -> BlockingQueueTypeEnum.createBlockingQueue(linkedBlockingQueueName, -100));
final String linkedBlockingDequeName = BlockingQueueTypeEnum.LINKED_BLOCKING_DEQUE.getName();
Assert.assertThrows(IllegalArgumentException.class, () -> BlockingQueueTypeEnum.createBlockingQueue(linkedBlockingDequeName, -100));
final String synchronousQueueName = BlockingQueueTypeEnum.SYNCHRONOUS_QUEUE.getName();
Assert.assertNotNull(BlockingQueueTypeEnum.createBlockingQueue(synchronousQueueName, -99));
final String linkedTransferQueueName = BlockingQueueTypeEnum.LINKED_TRANSFER_QUEUE.getName();
Assert.assertNotNull(BlockingQueueTypeEnum.createBlockingQueue(linkedTransferQueueName, -0));
final String priorityBlockingQueueName = BlockingQueueTypeEnum.PRIORITY_BLOCKING_QUEUE.getName();
Assert.assertThrows(IllegalArgumentException.class, () -> BlockingQueueTypeEnum.createBlockingQueue(priorityBlockingQueueName, -100));
final String resizableLinkedBlockingQueueName = BlockingQueueTypeEnum.RESIZABLE_LINKED_BLOCKING_QUEUE.getName();
Assert.assertThrows(IllegalArgumentException.class, () -> BlockingQueueTypeEnum.createBlockingQueue(resizableLinkedBlockingQueueName, -100));
}
@Test
public void testAssertCreateBlockingQueueWithIllegalParams() {
// check illegal name and capacity
Assert.assertNotNull(BlockingQueueTypeEnum.createBlockingQueue("HelloWorld", null));
Assert.assertNotNull(BlockingQueueTypeEnum.createBlockingQueue(null, null));
}
@Test
public void testAssertCreateBlockingQueueWithType() {
Assert.assertNotNull(BlockingQueueTypeEnum.createBlockingQueue(1, null));
Assert.assertNotNull(BlockingQueueTypeEnum.createBlockingQueue(2, null));
Assert.assertNotNull(BlockingQueueTypeEnum.createBlockingQueue(3, null));
Assert.assertNotNull(BlockingQueueTypeEnum.createBlockingQueue(4, null));
Assert.assertNotNull(BlockingQueueTypeEnum.createBlockingQueue(5, null));
Assert.assertNotNull(BlockingQueueTypeEnum.createBlockingQueue(6, null));
Assert.assertNotNull(BlockingQueueTypeEnum.createBlockingQueue(9, null));
Assert.assertNotNull(BlockingQueueTypeEnum.createBlockingQueue(100, null));
Assert.assertNotNull(BlockingQueueTypeEnum.createBlockingQueue(-1, null));
Assert.assertNotNull(BlockingQueueTypeEnum.createBlockingQueue(0, null));
}
@Test
public void testAssertGetBlockingQueueNameByType() {
// check legal range of type
Assert.assertEquals("ArrayBlockingQueue", BlockingQueueTypeEnum.getBlockingQueueNameByType(1));
Assert.assertEquals("LinkedBlockingQueue", BlockingQueueTypeEnum.getBlockingQueueNameByType(2));
Assert.assertEquals("LinkedBlockingDeque", BlockingQueueTypeEnum.getBlockingQueueNameByType(3));
Assert.assertEquals("SynchronousQueue", BlockingQueueTypeEnum.getBlockingQueueNameByType(4));
Assert.assertEquals("LinkedTransferQueue", BlockingQueueTypeEnum.getBlockingQueueNameByType(5));
Assert.assertEquals("PriorityBlockingQueue", BlockingQueueTypeEnum.getBlockingQueueNameByType(6));
Assert.assertEquals("ResizableCapacityLinkedBlockingQueue", BlockingQueueTypeEnum.getBlockingQueueNameByType(9));
// check illegal range of type
Assert.assertEquals("", BlockingQueueTypeEnum.getBlockingQueueNameByType(0));
Assert.assertEquals("", BlockingQueueTypeEnum.getBlockingQueueNameByType(-1));
Assert.assertEquals("", BlockingQueueTypeEnum.getBlockingQueueNameByType(100));
}
@Test
public void testAssertGetBlockingQueueTypeEnumByName() {
// check legal range of name
Assert.assertEquals(BlockingQueueTypeEnum.ARRAY_BLOCKING_QUEUE, BlockingQueueTypeEnum.getBlockingQueueTypeEnumByName("ArrayBlockingQueue"));
Assert.assertEquals(BlockingQueueTypeEnum.LINKED_BLOCKING_QUEUE, BlockingQueueTypeEnum.getBlockingQueueTypeEnumByName("LinkedBlockingQueue"));
Assert.assertEquals(BlockingQueueTypeEnum.LINKED_BLOCKING_DEQUE, BlockingQueueTypeEnum.getBlockingQueueTypeEnumByName("LinkedBlockingDeque"));
Assert.assertEquals(BlockingQueueTypeEnum.SYNCHRONOUS_QUEUE, BlockingQueueTypeEnum.getBlockingQueueTypeEnumByName("SynchronousQueue"));
Assert.assertEquals(BlockingQueueTypeEnum.LINKED_TRANSFER_QUEUE, BlockingQueueTypeEnum.getBlockingQueueTypeEnumByName("LinkedTransferQueue"));
Assert.assertEquals(BlockingQueueTypeEnum.PRIORITY_BLOCKING_QUEUE, BlockingQueueTypeEnum.getBlockingQueueTypeEnumByName("PriorityBlockingQueue"));
Assert.assertEquals(BlockingQueueTypeEnum.RESIZABLE_LINKED_BLOCKING_QUEUE, BlockingQueueTypeEnum.getBlockingQueueTypeEnumByName("ResizableCapacityLinkedBlockingQueue"));
// check illegal range of name
Assert.assertEquals(BlockingQueueTypeEnum.LINKED_BLOCKING_QUEUE, BlockingQueueTypeEnum.getBlockingQueueTypeEnumByName("Hello"));
Assert.assertEquals(BlockingQueueTypeEnum.LINKED_BLOCKING_QUEUE, BlockingQueueTypeEnum.getBlockingQueueTypeEnumByName(null));
}
}

@ -1,96 +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.
*/
package cn.hippo4j.common.executor.support;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import java.util.Arrays;
/**
* test for {@link RejectedPolicyTypeEnum}
*/
public class RejectedPolicyTypeEnumTest {
@Test
public void testGetType() {
Assertions.assertEquals(1, RejectedPolicyTypeEnum.CALLER_RUNS_POLICY.getType());
Assertions.assertEquals(2, RejectedPolicyTypeEnum.ABORT_POLICY.getType());
Assertions.assertEquals(3, RejectedPolicyTypeEnum.DISCARD_POLICY.getType());
Assertions.assertEquals(4, RejectedPolicyTypeEnum.DISCARD_OLDEST_POLICY.getType());
Assertions.assertEquals(5, RejectedPolicyTypeEnum.RUNS_OLDEST_TASK_POLICY.getType());
Assertions.assertEquals(6, RejectedPolicyTypeEnum.SYNC_PUT_QUEUE_POLICY.getType());
}
@Test
public void testGetName() {
Assertions.assertEquals("CallerRunsPolicy", RejectedPolicyTypeEnum.CALLER_RUNS_POLICY.getName());
Assertions.assertEquals("AbortPolicy", RejectedPolicyTypeEnum.ABORT_POLICY.getName());
Assertions.assertEquals("DiscardPolicy", RejectedPolicyTypeEnum.DISCARD_POLICY.getName());
Assertions.assertEquals("DiscardOldestPolicy", RejectedPolicyTypeEnum.DISCARD_OLDEST_POLICY.getName());
Assertions.assertEquals("RunsOldestTaskPolicy", RejectedPolicyTypeEnum.RUNS_OLDEST_TASK_POLICY.getName());
Assertions.assertEquals("SyncPutQueuePolicy", RejectedPolicyTypeEnum.SYNC_PUT_QUEUE_POLICY.getName());
}
@Test
public void testValues() {
Assertions.assertNotNull(RejectedPolicyTypeEnum.values());
}
@Test
public void testValueOf() {
Assertions.assertEquals(RejectedPolicyTypeEnum.CALLER_RUNS_POLICY, RejectedPolicyTypeEnum.valueOf("CALLER_RUNS_POLICY"));
Assertions.assertEquals(RejectedPolicyTypeEnum.ABORT_POLICY, RejectedPolicyTypeEnum.valueOf("ABORT_POLICY"));
Assertions.assertEquals(RejectedPolicyTypeEnum.DISCARD_POLICY, RejectedPolicyTypeEnum.valueOf("DISCARD_POLICY"));
Assertions.assertEquals(RejectedPolicyTypeEnum.DISCARD_OLDEST_POLICY, RejectedPolicyTypeEnum.valueOf("DISCARD_OLDEST_POLICY"));
Assertions.assertEquals(RejectedPolicyTypeEnum.RUNS_OLDEST_TASK_POLICY, RejectedPolicyTypeEnum.valueOf("RUNS_OLDEST_TASK_POLICY"));
Assertions.assertEquals(RejectedPolicyTypeEnum.SYNC_PUT_QUEUE_POLICY, RejectedPolicyTypeEnum.valueOf("SYNC_PUT_QUEUE_POLICY"));
}
@Test
public void testCreatePolicy() {
// check legal param: name and type
Arrays.stream(RejectedPolicyTypeEnum.values()).forEach(each -> {
Assertions.assertNotNull(RejectedPolicyTypeEnum.createPolicy(each.getName()));
Assertions.assertNotNull(RejectedPolicyTypeEnum.createPolicy(each.getType()));
});
// check illegal null name
Assertions.assertNotNull(RejectedPolicyTypeEnum.createPolicy(null));
// check nonexistent name
Assertions.assertNotNull(RejectedPolicyTypeEnum.createPolicy("ABC"));
// check nonexistent type
Assertions.assertNotNull(RejectedPolicyTypeEnum.createPolicy(-1));
}
@Test
public void testGetRejectedNameByType() {
// check legal range of type
Arrays.stream(RejectedPolicyTypeEnum.values()).forEach(each -> Assertions.assertEquals(each.getName(), RejectedPolicyTypeEnum.getRejectedNameByType(each.getType())));
// check illegal range of type
Assertions.assertEquals("AbortPolicy", RejectedPolicyTypeEnum.getRejectedNameByType(-1));
}
@Test
public void testGetRejectedPolicyTypeEnumByName() {
// check legal range of name
Arrays.stream(RejectedPolicyTypeEnum.values()).forEach(each -> Assertions.assertEquals(each, RejectedPolicyTypeEnum.getRejectedPolicyTypeEnumByName(each.getName())));
// check illegal name
Assertions.assertEquals(RejectedPolicyTypeEnum.ABORT_POLICY,
RejectedPolicyTypeEnum.getRejectedPolicyTypeEnumByName("XXX"));
}
}

@ -1,107 +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.
*/
package cn.hippo4j.common.executor.support;
import cn.hippo4j.common.toolkit.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
@Slf4j
public class ResizableCapacityLinkedBlockingQueueTest {
@Test
public void testResizableCapacityLinkedBlockingQueueSize() throws InterruptedException {
ResizableCapacityLinkedBlockingQueue<Integer> queue1 = new ResizableCapacityLinkedBlockingQueue(10);
queue1.setCapacity(20);
Assert.assertEquals(20, queue1.remainingCapacity());
queue1.add(1);
Assert.assertEquals(19, queue1.remainingCapacity());
ResizableCapacityLinkedBlockingQueue<Integer> queue2 = new ResizableCapacityLinkedBlockingQueue(Arrays.asList(1, 2, 3, 4));
queue2.setCapacity(5);
Assert.assertEquals(1, queue2.remainingCapacity());
}
@Test
public void testIncreaseResizableCapacityLinkedBlockingQueue() throws InterruptedException {
MyRejectedExecutionHandler myRejectedExecutionHandler = new MyRejectedExecutionHandler();
ResizableCapacityLinkedBlockingQueue<Runnable> queue = new ResizableCapacityLinkedBlockingQueue();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1,
60, TimeUnit.SECONDS, queue, myRejectedExecutionHandler);
Assert.assertSame(queue, threadPoolExecutor.getQueue());
threadPoolExecutor.prestartAllCoreThreads();
queue.setCapacity(6);
IntStream.range(0, 4).forEach(s -> {
threadPoolExecutor.execute(() -> ThreadUtil.sleep(0L));
});
threadPoolExecutor.shutdown();
while (!threadPoolExecutor.isTerminated()) {
}
Assert.assertEquals(4, threadPoolExecutor.getCompletedTaskCount());
Assert.assertEquals(0, myRejectedExecutionHandler.getCount());
}
@Test
public void testDecreaseResizableCapacityLinkedBlockingQueue() throws InterruptedException {
MyRejectedExecutionHandler myRejectedExecutionHandler = new MyRejectedExecutionHandler();
ResizableCapacityLinkedBlockingQueue<Runnable> queue = new ResizableCapacityLinkedBlockingQueue<>(4);
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1,
60, TimeUnit.SECONDS, queue, myRejectedExecutionHandler);
Assert.assertSame(queue, threadPoolExecutor.getQueue());
threadPoolExecutor.prestartAllCoreThreads();
queue.setCapacity(0);
IntStream.range(0, 4).forEach(s -> {
threadPoolExecutor.execute(() -> ThreadUtil.sleep(0L));
});
threadPoolExecutor.shutdown();
while (!threadPoolExecutor.isTerminated()) {
}
Assert.assertEquals(0, threadPoolExecutor.getCompletedTaskCount());
Assert.assertEquals(4, myRejectedExecutionHandler.getCount());
}
}
class MyRejectedExecutionHandler implements RejectedExecutionHandler {
public AtomicInteger count = new AtomicInteger(0);
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (executor.isShutdown()) {
return;
}
if (!executor.getQueue().offer(r)) {
count.incrementAndGet();
}
}
public int getCount() {
return count.get();
}
}

@ -1,100 +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.
*/
package cn.hippo4j.common.executor.support;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class RunsOldestTaskPolicyTest {
private final RunsOldestTaskPolicy runsOldestTaskPolicy = new RunsOldestTaskPolicy();
@Mock
private Runnable runnable;
@Mock
private Runnable runnableInTheQueue;
@Mock
private ThreadPoolExecutor threadPoolExecutor;
@Mock
private BlockingQueue<Runnable> workQueue;
@Test
public void testRejectedExecutionWhenExecutorIsShutDown() {
when(threadPoolExecutor.isShutdown()).thenReturn(true);
runsOldestTaskPolicy.rejectedExecution(runnable, threadPoolExecutor);
verify(threadPoolExecutor, never()).execute(runnable);
verify(runnable, never()).run();
}
@Test
public void testRejectedExecutionWhenATaskIsInTheQueueTheExecutorShouldNotExecute() {
when(threadPoolExecutor.isShutdown()).thenReturn(false);
when(threadPoolExecutor.getQueue()).thenReturn(workQueue);
when(workQueue.poll()).thenReturn(runnableInTheQueue);
when(workQueue.offer(runnable)).thenReturn(true);
runsOldestTaskPolicy.rejectedExecution(runnable, threadPoolExecutor);
verify(runnableInTheQueue).run();
verify(threadPoolExecutor, never()).execute(runnable);
verify(runnable, never()).run();
}
@Test
public void testRejectedExecutionWhenATaskIsInTheQueueTheExecutorShouldExecute() {
when(threadPoolExecutor.isShutdown()).thenReturn(false);
when(threadPoolExecutor.getQueue()).thenReturn(workQueue);
when(workQueue.poll()).thenReturn(runnableInTheQueue);
when(workQueue.offer(runnable)).thenReturn(false);
runsOldestTaskPolicy.rejectedExecution(runnable, threadPoolExecutor);
verify(runnableInTheQueue).run();
verify(threadPoolExecutor).execute(runnable);
verify(runnable, never()).run();
}
@Test
public void testRejectedExecutionWhenATaskIsInTheQueueAndThePollReturnANullValue() {
when(threadPoolExecutor.isShutdown()).thenReturn(false);
when(threadPoolExecutor.getQueue()).thenReturn(workQueue);
when(workQueue.poll()).thenReturn(null);
when(workQueue.offer(runnable)).thenReturn(false);
runsOldestTaskPolicy.rejectedExecution(runnable, threadPoolExecutor);
verify(runnableInTheQueue, never()).run();
verify(threadPoolExecutor).execute(runnable);
verify(runnable, never()).run();
}
}

@ -1,53 +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.
*/
package cn.hippo4j.common.executor.support;
import cn.hippo4j.common.toolkit.ThreadUtil;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
/**
* Synchronous placement queue policy implementation test
*/
public class SyncPutQueuePolicyTest {
/**
* test thread pool rejected execution
*/
@Test
public void testRejectedExecution() {
SyncPutQueuePolicy syncPutQueuePolicy = new SyncPutQueuePolicy();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 2,
60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1), syncPutQueuePolicy);
threadPoolExecutor.prestartAllCoreThreads();
Assert.assertSame(syncPutQueuePolicy, threadPoolExecutor.getRejectedExecutionHandler());
IntStream.range(0, 4).forEach(s -> {
threadPoolExecutor.execute(() -> ThreadUtil.sleep(200L));
});
threadPoolExecutor.shutdown();
while (!threadPoolExecutor.isTerminated()) {
}
Assert.assertEquals(4, threadPoolExecutor.getCompletedTaskCount());
}
}

@ -1,94 +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.
*/
package cn.hippo4j.common.executor.support;
import cn.hippo4j.common.toolkit.ThreadPoolExecutorUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Thread pool executor util test
*/
@Slf4j
public class ThreadPoolExecutorUtilTest {
private ThreadPoolExecutor executor;
private int corePoolSize;
private int maxPoolSize;
@Before
public void testSafeSetPoolSize() {
corePoolSize = 2;
maxPoolSize = 4;
executor = new ThreadPoolExecutor(
corePoolSize,
maxPoolSize,
1L,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10));
}
@Test
public void testEquals() {
// Test when the new core pool size equals the original maximum pool size.
int newCorePoolSize1 = maxPoolSize;
int newMaxPoolSize1 = 6;
ThreadPoolExecutorUtil.safeSetPoolSize(executor, newCorePoolSize1, newMaxPoolSize1);
Assert.assertEquals(newCorePoolSize1, executor.getCorePoolSize());
Assert.assertEquals(newMaxPoolSize1, executor.getMaximumPoolSize());
}
@Test
public void testGreater() {
// Test when the new core pool size is greater than the original maximum pool size.
int newCorePoolSize2 = 8;
int newMaxPoolSize2 = 10;
ThreadPoolExecutorUtil.safeSetPoolSize(executor, newCorePoolSize2, newMaxPoolSize2);
Assert.assertEquals(newCorePoolSize2, executor.getCorePoolSize());
Assert.assertEquals(newMaxPoolSize2, executor.getMaximumPoolSize());
}
@Test
public void testLess() {
// Test when the new core pool size is less than the original maximum pool size.
int newCorePoolSize3 = 3;
int newMaxPoolSize3 = 5;
ThreadPoolExecutorUtil.safeSetPoolSize(executor, newCorePoolSize3, newMaxPoolSize3);
Assert.assertEquals(newCorePoolSize3, executor.getCorePoolSize());
Assert.assertEquals(newMaxPoolSize3, executor.getMaximumPoolSize());
}
@Test
public void testException() {
// Test when the new core pool size is greater than the new maximum pool size, which should throw an IllegalArgumentException.
int newCorePoolSize4 = 6;
int newMaxPoolSize4 = 4;
try {
ThreadPoolExecutorUtil.safeSetPoolSize(executor, newCorePoolSize4, newMaxPoolSize4);
} catch (IllegalArgumentException e) {
// Expected to throw an exception.
Assert.assertEquals("newCorePoolSize must be smaller than newMaximumPoolSize", e.getMessage());
log.error("newCorePoolSize must be smaller than newMaximumPoolSize;{}", e.getMessage());
}
}
}

@ -1,163 +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.
*/
package cn.hippo4j.common.extension.design;
import lombok.Getter;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class AbstractSubjectCenterTest {
private Map<String, List<Observer>> OBSERVERS_MAP;
private SubjectNotifyListener subjectNotifyListener;
@Before
public void setUp() throws NoSuchFieldException, IllegalAccessException {
subjectNotifyListener = new SubjectNotifyListener();
Field field = AbstractSubjectCenter.class.getDeclaredField("OBSERVERS_MAP");
field.setAccessible(true);
OBSERVERS_MAP = (Map<String, List<Observer>>) field.get(AbstractSubjectCenter.class);
}
/**
* test register listener
*/
@Test
public void testDefaultRegister() {
AbstractSubjectCenter.register(subjectNotifyListener);
List<Observer> list = OBSERVERS_MAP.get(AbstractSubjectCenter.SubjectType.SPRING_CONTENT_REFRESHED.name());
Assert.assertNotNull(list);
Assert.assertEquals(1, list.size());
Assert.assertSame(subjectNotifyListener, list.get(0));
OBSERVERS_MAP.clear();
}
/**
* test register listener
*/
@Test
public void testSubjectTypeEnumRegister() {
AbstractSubjectCenter.register(AbstractSubjectCenter.SubjectType.THREAD_POOL_DYNAMIC_REFRESH, subjectNotifyListener);
List<Observer> list = OBSERVERS_MAP.get(AbstractSubjectCenter.SubjectType.THREAD_POOL_DYNAMIC_REFRESH.name());
Assert.assertNotNull(list);
Assert.assertEquals(1, list.size());
Assert.assertSame(subjectNotifyListener, list.get(0));
OBSERVERS_MAP.clear();
}
/**
* test register listener
*/
@Test
public void testSubjectTypeNameRegister() {
AbstractSubjectCenter.register(AbstractSubjectCenter.SubjectType.THREAD_POOL_DYNAMIC_REFRESH.name(), subjectNotifyListener);
List<Observer> list = OBSERVERS_MAP.get(AbstractSubjectCenter.SubjectType.THREAD_POOL_DYNAMIC_REFRESH.name());
Assert.assertNotNull(list);
Assert.assertEquals(1, list.size());
Assert.assertSame(subjectNotifyListener, list.get(0));
OBSERVERS_MAP.clear();
}
/**
* test remove listener
*/
@Test
public void testDefaultRemoveListener() {
AbstractSubjectCenter.register(subjectNotifyListener);
List<Observer> list = OBSERVERS_MAP.get(AbstractSubjectCenter.SubjectType.SPRING_CONTENT_REFRESHED.name());
Assert.assertNotNull(list);
Assert.assertEquals(1, list.size());
Assert.assertSame(subjectNotifyListener, list.get(0));
AbstractSubjectCenter.remove(subjectNotifyListener);
Assert.assertEquals(0, list.size());
}
/**
* test remove listener
*/
@Test
public void testRemoveSubjectTypeNameListener() {
AbstractSubjectCenter.register(AbstractSubjectCenter.SubjectType.THREAD_POOL_DYNAMIC_REFRESH, subjectNotifyListener);
List<Observer> list = OBSERVERS_MAP.get(AbstractSubjectCenter.SubjectType.THREAD_POOL_DYNAMIC_REFRESH.name());
Assert.assertNotNull(list);
Assert.assertEquals(1, list.size());
Assert.assertSame(subjectNotifyListener, list.get(0));
AbstractSubjectCenter.remove(AbstractSubjectCenter.SubjectType.THREAD_POOL_DYNAMIC_REFRESH.name(), subjectNotifyListener);
Assert.assertEquals(0, list.size());
}
/**
* test notify
*/
@Test
public void testNotifyBySubjectType() {
AbstractSubjectCenter.register(subjectNotifyListener);
List<Observer> list = OBSERVERS_MAP.get(AbstractSubjectCenter.SubjectType.SPRING_CONTENT_REFRESHED.name());
Assert.assertNotNull(list);
NotifyMessage notifyMessage = new NotifyMessage();
Assert.assertEquals(0, notifyMessage.getCount().get());
AbstractSubjectCenter.notify(AbstractSubjectCenter.SubjectType.SPRING_CONTENT_REFRESHED, () -> notifyMessage);
Assert.assertEquals(1, notifyMessage.getCount().get());
OBSERVERS_MAP.clear();
}
/**
* test notify
*/
@Test
public void testNotifyBySubjectTypeName() {
AbstractSubjectCenter.register(subjectNotifyListener);
List<Observer> list = OBSERVERS_MAP.get(AbstractSubjectCenter.SubjectType.SPRING_CONTENT_REFRESHED.name());
Assert.assertNotNull(list);
NotifyMessage notifyMessage = new NotifyMessage();
Assert.assertEquals(0, notifyMessage.getCount().get());
AbstractSubjectCenter.notify(AbstractSubjectCenter.SubjectType.SPRING_CONTENT_REFRESHED.name(), () -> notifyMessage);
Assert.assertEquals(1, notifyMessage.getCount().get());
OBSERVERS_MAP.clear();
}
@Getter
private static final class NotifyMessage {
private final AtomicInteger count = new AtomicInteger(0);
}
/**
* Subject Response Listener
*/
private static final class SubjectNotifyListener implements Observer<NotifyMessage> {
@Override
public void accept(ObserverMessage<NotifyMessage> observerMessage) {
observerMessage.message().getCount().incrementAndGet();
}
}
}

@ -1,37 +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.
*/
package cn.hippo4j.common.function;
import cn.hippo4j.common.extension.function.Matcher;
import cn.hippo4j.common.toolkit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
public final class MatcherFunctionTest {
public static <T> boolean matchTest(Matcher<T> matcher, T value) {
return matcher.match(value);
}
@Test
public void assertMatch() {
Assert.isTrue(matchTest(Boolean.TRUE::equals, true));
Assert.isTrue(matchTest(BigDecimal.ZERO::equals, BigDecimal.ZERO));
}
}

@ -1,35 +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.
*/
package cn.hippo4j.common.function;
import cn.hippo4j.common.extension.function.NoArgsConsumer;
import cn.hippo4j.common.toolkit.Assert;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicBoolean;
public final class NoArgsConsumerTest {
@Test
public void accept() {
AtomicBoolean checkValue = new AtomicBoolean(false);
NoArgsConsumer noArgsConsumer = () -> checkValue.set(true);
noArgsConsumer.accept();
Assert.isTrue(checkValue.get());
}
}

@ -1,67 +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.
*/
package cn.hippo4j.common.toolkit;
import cn.hippo4j.common.extension.function.Matcher;
import org.junit.Test;
import org.springframework.util.StringUtils;
/**
* test {@link ArrayUtil}
*/
public class ArrayUtilTest {
@Test
public void assertIsEmpty() {
String[] array = new String[0];
Assert.isTrue(ArrayUtil.isEmpty(array));
}
@Test
public void assertIsNotEmpty() {
String[] array = new String[0];
Assert.isTrue(!ArrayUtil.isNotEmpty(array));
}
@Test
public void assertFirstMatch() {
Matcher<String> matcher = (str) -> "1".equalsIgnoreCase(str);
String[] array = new String[0];
Assert.isTrue(StringUtils.isEmpty(ArrayUtil.firstMatch(matcher, array)));
array = new String[]{"0"};
Assert.isTrue(StringUtils.isEmpty(ArrayUtil.firstMatch(matcher, array)));
array = new String[]{"1"};
Assert.isTrue(!StringUtils.isEmpty(ArrayUtil.firstMatch(matcher, array)));
}
@Test
public void assertAddAll() {
String[] array = new String[]{"1"};
Assert.isTrue(ArrayUtil.addAll(array, null).length == 1);
Assert.isTrue(ArrayUtil.addAll(null, array).length == 1);
Assert.isTrue(ArrayUtil.addAll(array, new String[]{"1"}).length == 2);
}
@Test
public void assertClone() {
Assert.isNull(ArrayUtil.clone(null));
String[] array = new String[0];
Assert.isTrue(array != ArrayUtil.clone(array));
Assert.isTrue(array.length == ArrayUtil.clone(array).length);
}
}

@ -1,109 +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.
*/
package cn.hippo4j.common.toolkit;
import java.util.Collections;
import org.junit.Test;
/**
* test {@link Assert}
*/
public final class AssertTest {
@Test(expected = IllegalArgumentException.class)
public void assertIsTrue() {
Assert.isTrue(false, "test message");
}
@Test(expected = IllegalArgumentException.class)
public void assertIsTrueAndMessageIsNull() {
Assert.isTrue(false);
}
@Test(expected = IllegalArgumentException.class)
public void assertIsNullAndMessageIsNull() {
Assert.isNull("");
}
@Test(expected = IllegalArgumentException.class)
public void assertIsNull() {
Assert.isNull("", "object is null");
}
@Test(expected = IllegalArgumentException.class)
public void assertNotNull() {
Assert.notNull(null, "object is null");
}
@Test(expected = IllegalArgumentException.class)
public void assertNotNullAndMessageIsNull() {
Assert.notNull(null);
}
@Test(expected = IllegalArgumentException.class)
public void assertNotEmptyByList() {
Assert.notEmpty(Collections.emptyList(), "object is null");
}
@Test(expected = IllegalArgumentException.class)
public void assertNotEmptyByListAndMessageIsNull() {
Assert.notEmpty(Collections.emptyList());
}
@Test(expected = IllegalArgumentException.class)
public void assertNotEmptyByMap() {
Assert.notEmpty(Collections.emptyMap(), "map is null");
}
@Test(expected = IllegalArgumentException.class)
public void assertNotEmptyByMapAndMessageIsNull() {
Assert.notEmpty(Collections.emptyMap());
}
@Test(expected = IllegalArgumentException.class)
public void assertNotEmptyByString() {
Assert.notEmpty("", "string is null");
}
@Test(expected = IllegalArgumentException.class)
public void assertNotEmptyByStringAndMessageIsNull() {
Assert.notEmpty("");
}
@Test(expected = IllegalArgumentException.class)
public void assertNotBlankByString() {
Assert.notBlank(" ", "string is null");
}
@Test(expected = IllegalArgumentException.class)
public void assertNotBlankByStringAndMessageIsNull() {
Assert.notBlank(" ");
}
@Test(expected = IllegalArgumentException.class)
public void assertHasText() {
Assert.hasText(" ", "text is null");
}
@Test(expected = IllegalArgumentException.class)
public void assertHasTextAndMessageIsNull() {
Assert.hasText(" ");
}
}

@ -1,174 +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.
*/
package cn.hippo4j.common.toolkit;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.junit.Assert;
import org.junit.Test;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class BeanUtilTest {
@Test
public void beanToMapConvertTest() {
// 测试BeanToMap
final Person person = new Person();
person.setName("Hippo4j");
person.setAge(1);
person.setAddress("hippo4j.cn");
person.setSize(999);
final Map<?, ?> convert = BeanUtil.convert(person, Map.class);
Assert.assertEquals("Hippo4j", convert.get("name"));
Assert.assertEquals(1, convert.get("age"));
Assert.assertEquals("hippo4j.cn", convert.get("address"));
Assert.assertEquals(999, convert.get("size"));
}
@Test
public void mapToBeanConvertTest() {
// 测试MapToBean
final HashMap<String, Object> map = new HashMap<>();
map.put("name", "Hippo4j");
map.put("age", 1);
map.put("address", "hippo4j.cn");
map.put("size", 999);
final Person person = BeanUtil.convert(map, Person.class);
Assert.assertEquals("Hippo4j", person.getName());
Assert.assertEquals(1, person.getAge());
Assert.assertEquals("hippo4j.cn", person.getAddress());
Assert.assertEquals(999, (int) person.getSize());
}
@Test
public void ListToListConvertTest() {
final List<Person> list = new ArrayList<>();
list.add(Person.builder().name("one").age(1).build());
list.add(Person.builder().name("two").age(2).build());
list.add(Person.builder().name("three").age(3).build());
final List<PersonVo> persons = BeanUtil.convert(list, PersonVo.class);
Assert.assertEquals(list.size(), persons.size());
}
@Test
public void SetToSetConvertTest() {
final Set<Person> sets = new HashSet<>();
sets.add(Person.builder().name("one").age(1).build());
sets.add(Person.builder().name("two").age(2).build());
sets.add(Person.builder().name("three").age(3).build());
final Set<PersonVo> persons = BeanUtil.convert(sets, PersonVo.class);
Assert.assertEquals(sets.size(), persons.size());
}
@Test
public void copyPropertiesBeanToMapTest() {
// 测试BeanToMap
final Person person = new Person();
person.setName("Hippo4j");
final Map<?, ?> convert = BeanUtil.convert(person, Map.class);
Assert.assertEquals("Hippo4j", convert.get("name"));
// static属性应被忽略
Assert.assertFalse(convert.containsKey("STATIC_NAME"));
}
/**
*
*/
// @Test(expected = ConversionException.class)
public void mapToBeanWinErrorTest() {
final Map<String, String> map = new HashMap<>();
map.put("age", "Hippo4j");
BeanUtil.convert(map, Person.class);
}
// -----------------------------------------------------------------------------------------------------------------
@Test
public void testMapToBean() {
Map<String, Object> map = new HashMap<>();
map.put("name", "Test");
map.put("status_code", 12);
Customer customer = BeanUtil.mapToBean(map, Customer.class, true);
Assert.assertEquals("Test", customer.getName());
Assert.assertEquals(Integer.valueOf(12), customer.getStatusCode());
}
@Test
public void testGetter() {
Method name = BeanUtil.getter(Customer.class, "name");
Assert.assertEquals("getName", name.getName());
}
@Test
public void testSetter() {
Method name = BeanUtil.setter(Customer.class, "name");
Assert.assertEquals("setName", name.getName());
}
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public static class Person {
public static final String STATIC_NAME = "STATIC_NAME";
private String name;
private int age;
private String address;
private Integer size;
}
@Setter
public static class PersonVo {
private String name;
private int age;
}
@Getter
@Setter
static class Customer {
String name;
Integer statusCode;
}
@Getter
@Setter
static class PreCustomer {
String name;
Integer statusCode;
}
}

@ -1,36 +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.
*/
package cn.hippo4j.common.toolkit;
import org.junit.Assert;
import org.junit.Test;
public class BooleanUtilTest {
@Test
public void assertToBoolean() {
Assert.assertTrue(BooleanUtil.toBoolean("true"));
Assert.assertTrue(BooleanUtil.toBoolean("yes"));
Assert.assertTrue(BooleanUtil.toBoolean("1"));
}
@Test
public void assertIsTrue() {
Assert.assertTrue(BooleanUtil.isTrue(true));
}
}

@ -1,33 +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.
*/
package cn.hippo4j.common.toolkit;
import org.junit.Test;
import java.util.Objects;
public class ByteConvertUtilTest {
@Test
public void assertGetPrintSize() {
Assert.isTrue(Objects.equals(ByteConvertUtil.getPrintSize(220), "220B"));
Assert.isTrue(Objects.equals(ByteConvertUtil.getPrintSize(2200), "2.15KB"));
Assert.isTrue(Objects.equals(ByteConvertUtil.getPrintSize(2200000), "2.10MB"));
Assert.isTrue(Objects.equals(ByteConvertUtil.getPrintSize(2200000000L), "2.05GB"));
}
}

@ -1,30 +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.
*/
package cn.hippo4j.common.toolkit;
import org.junit.Test;
public class CalculateUtilTest {
@Test
public void assertDivide() {
Assert.isTrue(CalculateUtil.divide(200, 100) == 200);
Assert.isTrue(CalculateUtil.divide(100, 200) == 50);
Assert.isTrue(CalculateUtil.divide(100, 100) == 100);
}
}

@ -1,43 +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.
*/
package cn.hippo4j.common.toolkit;
import org.junit.Assert;
import org.junit.Test;
/**
* test for {@link ClassUtil}
*/
public class ClassUtilTest {
@Test
public void testGetClassLoader() {
ClassLoader expectedClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader actualClassLoader = ClassUtil.getClassLoader(ClassUtilTest.class);
Assert.assertEquals(expectedClassLoader, actualClassLoader);
expectedClassLoader = ClassUtilTest.class.getClassLoader();
actualClassLoader = ClassUtil.getClassLoader(null);
Assert.assertEquals(expectedClassLoader, actualClassLoader);
expectedClassLoader = ClassLoader.getSystemClassLoader();
actualClassLoader = ClassUtil.getClassLoader(String.class);
Assert.assertEquals(expectedClassLoader, actualClassLoader);
}
}

@ -1,80 +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.
*/
package cn.hippo4j.common.toolkit;
import org.assertj.core.util.Lists;
import org.junit.Test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class CollectionUtilTest {
@Test
public void assertGetFirst() {
Assert.isNull(CollectionUtil.getFirst(null));
String first = CollectionUtil.getFirst(Lists.newArrayList("1", "2"));
Assert.notEmpty(first);
}
@Test
public void assertIsEmpty() {
List list = null;
Assert.isTrue(CollectionUtil.isEmpty(list));
list = Lists.newArrayList();
Assert.isTrue(CollectionUtil.isEmpty(list));
list = Lists.newArrayList("1");
Assert.isTrue(!CollectionUtil.isEmpty(list));
Map map = null;
Assert.isTrue(CollectionUtil.isEmpty(map));
map = new HashMap<>();
Assert.isTrue(CollectionUtil.isEmpty(map));
map.put("key", "value");
Assert.isTrue(!CollectionUtil.isEmpty(map));
Iterator iterator = null;
Assert.isTrue(CollectionUtil.isEmpty(iterator));
iterator = Lists.emptyList().iterator();
Assert.isTrue(CollectionUtil.isEmpty(iterator));
iterator = Lists.newArrayList("1").iterator();
Assert.isTrue(!CollectionUtil.isEmpty(iterator));
}
@Test
public void assertIsNotEmpty() {
List list = null;
Assert.isTrue(!CollectionUtil.isNotEmpty(list));
list = Lists.newArrayList();
Assert.isTrue(!CollectionUtil.isNotEmpty(list));
list = Lists.newArrayList("1");
Assert.isTrue(CollectionUtil.isNotEmpty(list));
Map map = null;
Assert.isTrue(!CollectionUtil.isNotEmpty(map));
map = new HashMap<>();
Assert.isTrue(!CollectionUtil.isNotEmpty(map));
map.put("key", "value");
Assert.isTrue(CollectionUtil.isNotEmpty(map));
Iterator iterator = null;
Assert.isTrue(!CollectionUtil.isNotEmpty(iterator));
iterator = Lists.emptyList().iterator();
Assert.isTrue(!CollectionUtil.isNotEmpty(iterator));
iterator = Lists.newArrayList("1").iterator();
Assert.isTrue(CollectionUtil.isNotEmpty(iterator));
}
}

@ -1,40 +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.
*/
package cn.hippo4j.common.toolkit;
import cn.hippo4j.common.extension.function.NoArgsConsumer;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicBoolean;
public class ConditionUtilTest {
@Test
public void assertCondition() {
// init consumer
AtomicBoolean checkValue = new AtomicBoolean(false);
NoArgsConsumer trueConsumer = () -> checkValue.set(true);
NoArgsConsumer falseConsumer = () -> checkValue.set(false);
// test trueConsumer run
ConditionUtil.condition(true, trueConsumer, falseConsumer);
Assert.isTrue(checkValue.get());
// test falseConsumer run
ConditionUtil.condition(false, trueConsumer, falseConsumer);
Assert.isTrue(!checkValue.get());
}
}

@ -1,51 +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.
*/
package cn.hippo4j.common.toolkit;
import cn.hippo4j.common.model.ThreadPoolParameterInfo;
import org.junit.Test;
public class ContentUtilTest {
@Test
public void assertGetPoolContent() {
String testText = "{\"tenantId\":\"prescription\",\"itemId\":\"dynamic-threadpool-example\",\"tpId\":" +
"\"message-consume\",\"queueType\":1,\"capacity\":4,\"keepAliveTime\":513,\"rejectedType\":4,\"isAlarm\"" +
":1,\"capacityAlarm\":80,\"livenessAlarm\":80,\"allowCoreThreadTimeOut\":1}";
ThreadPoolParameterInfo threadPoolParameterInfo = ThreadPoolParameterInfo.builder().tenantId("prescription")
.itemId("dynamic-threadpool-example").tpId("message-consume").content("描述信息").corePoolSize(1)
.maximumPoolSize(2).queueType(1).capacity(4).keepAliveTime(513L).executeTimeOut(null).rejectedType(4)
.isAlarm(1).capacityAlarm(80).livenessAlarm(80).allowCoreThreadTimeOut(1).build();
Assert.isTrue(testText.equals(ContentUtil.getPoolContent(threadPoolParameterInfo)));
}
@Test
public void assertGetGroupKey() {
String testText = "message-consume+dynamic-threadpool-example+prescription";
ThreadPoolParameterInfo parameter = ThreadPoolParameterInfo.builder()
.tenantId("prescription").itemId("dynamic-threadpool-example").tpId("message-consume").build();
Assert.isTrue(testText.equals(ContentUtil.getGroupKey(parameter)));
}
@Test
public void assertGetGroupKeys() {
String testText = "message-consume+dynamic-threadpool-example+prescription";
String groupKey = ContentUtil.getGroupKey("message-consume", "dynamic-threadpool-example", "prescription");
Assert.isTrue(testText.equals(groupKey));
}
}

@ -1,77 +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.
*/
package cn.hippo4j.common.toolkit;
import org.junit.Test;
public class GroupKeyTest {
@Test
public void getKey() {
String dataId = "dataId";
String group = "group";
String datumStr = "datumStr";
String expected = "dataId+group+datumStr";
String key = GroupKey.getKey(dataId, group, datumStr);
Assert.isTrue(key.equals(expected));
}
@Test
public void testGetKey() {
String dataId = "dataId";
String group = "group";
String expected = "dataId+group";
String key = GroupKey.getKey(dataId, group);
Assert.isTrue(key.equals(expected));
}
@Test
public void testGetKey1() {
String[] strings = {"dataId", "group", "datumStr"};
String expected = "dataId+group+datumStr";
String key = GroupKey.getKey(strings);
Assert.isTrue(key.equals(expected));
}
@Test
public void getKeyTenant() {
String dataId = "dataId";
String group = "group";
String datumStr = "datumStr";
String expected = "dataId+group+datumStr";
String keyTenant = GroupKey.getKeyTenant(dataId, group, datumStr);
Assert.isTrue(keyTenant.equals(expected));
}
@Test
public void parseKey() {
String groupKey = "prescription+dynamic-threadpool-example+message-consume+12";
String[] strings = GroupKey.parseKey(groupKey);
Assert.isTrue(strings.length == 4);
}
@Test
public void urlEncode() {
String str = "hello+World%";
String expected = "hello%2BWorld%25";
StringBuilder stringBuilder = new StringBuilder();
GroupKey.urlEncode(str, stringBuilder);
Assert.isTrue(stringBuilder.toString().contains(expected));
}
}

@ -1,37 +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.
*/
package cn.hippo4j.common.toolkit;
import org.junit.Assert;
import org.junit.Test;
public class IdUtilTest {
@Test
public void randomUUIDTest() {
String randomUUID = IdUtil.randomUUID();
Assert.assertNotNull(randomUUID);
}
@Test
public void simpleUUIDTest() {
String simpleUUID = IdUtil.simpleUUID();
Assert.assertNotNull(simpleUUID);
Assert.assertFalse(simpleUUID.contains("-"));
}
}

@ -1,261 +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.
*/
package cn.hippo4j.common.toolkit;
import org.apache.commons.io.input.BrokenInputStream;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Closeable;
import java.io.FileReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* test for {@link IoUtil}
*/
public class IoUtilTest {
private Path tempDir;
private File sourceFile;
@Before
public void setUp() throws IOException {
tempDir = Files.createTempDirectory("test");
sourceFile = new File(tempDir.toFile(), "source.txt");
try (FileOutputStream fos = new FileOutputStream(sourceFile)) {
fos.write("Hello, World!".getBytes());
}
}
@After
public void tearDown() throws IOException {
Files.walk(tempDir)
.sorted((a, b) -> -a.compareTo(b))
.forEach(path -> {
try {
Files.deleteIfExists(path);
} catch (IOException e) {
e.printStackTrace();
}
});
}
@Test
public void testTryDecompressInputStream() throws IOException {
byte[] inputBytes = "This is a test string.".getBytes("UTF-8");
ByteArrayOutputStream compressedOutput = new ByteArrayOutputStream();
try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(compressedOutput)) {
gzipOutputStream.write(inputBytes);
}
byte[] compressedBytes = compressedOutput.toByteArray();
ByteArrayInputStream compressedInput = new ByteArrayInputStream(compressedBytes);
byte[] decompressedBytes = IoUtil.tryDecompress(compressedInput);
Assert.assertNotNull(decompressedBytes);
Assert.assertTrue(decompressedBytes.length > 0);
Assert.assertArrayEquals(inputBytes, decompressedBytes);
}
@Test
public void testTryDecompressByteArray() throws Exception {
byte[] inputBytes = "This is a test string.".getBytes("UTF-8");
ByteArrayOutputStream compressedOutput = new ByteArrayOutputStream();
try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(compressedOutput)) {
gzipOutputStream.write(inputBytes);
}
byte[] compressedBytes = compressedOutput.toByteArray();
byte[] decompressedBytes = IoUtil.tryDecompress(compressedBytes);
Assert.assertNotNull(decompressedBytes);
Assert.assertTrue(decompressedBytes.length > 0);
Assert.assertArrayEquals(inputBytes, decompressedBytes);
}
@Test
public void testTryCompress() throws IOException {
String inputString = "This is a test string.";
String encoding = "UTF-8";
byte[] compressedBytes = IoUtil.tryCompress(inputString, encoding);
Assert.assertNotNull(compressedBytes);
Assert.assertTrue(compressedBytes.length > 0);
try (
GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(compressedBytes))) {
byte[] decompressedBytes = new byte[1024];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int readBytes;
while ((readBytes = gzipInputStream.read(decompressedBytes)) > 0) {
outputStream.write(decompressedBytes, 0, readBytes);
}
String decompressedString = outputStream.toString(encoding);
Assert.assertEquals(inputString, decompressedString);
}
}
@Test
public void testWriteStringToFile() throws IOException {
File tempFile = new File(tempDir.toFile(), "testWriteStringToFile.txt");
String testString = "test string";
IoUtil.writeStringToFile(tempFile, testString, "UTF-8");
BufferedReader reader = new BufferedReader(new FileReader(tempFile));
String fileContent = reader.readLine();
reader.close();
Assert.assertEquals(testString, fileContent);
}
@Test
public void testReadLines() throws IOException {
File tempFile = new File(tempDir.toFile(), "testReadLines.txt");
try (
PrintWriter writer = new PrintWriter(tempFile)) {
writer.println("test string 1");
writer.println("test string 2");
writer.println("test string 3");
}
FileReader fileReader = new FileReader(tempFile);
List<String> lines = IoUtil.readLines(fileReader);
fileReader.close();
Assert.assertEquals(3, lines.size());
Assert.assertEquals("test string 1", lines.get(0));
Assert.assertEquals("test string 2", lines.get(1));
Assert.assertEquals("test string 3", lines.get(2));
}
@Test
public void testToStringInputStream() {
String testString = "test string";
InputStream inputStream = new ByteArrayInputStream(testString.getBytes());
String result = IoUtil.toString(inputStream, "UTF-8");
Assert.assertEquals(testString, result);
}
@Test
public void testToStringReader() throws IOException {
String testString = "test string";
Reader reader = new StringReader(testString);
String result = IoUtil.toString(reader);
Assert.assertEquals(testString, result);
}
@Test
public void testCopyReaderWriter() throws IOException {
String inputString = "testCopyReaderWriter";
Reader reader = new StringReader(inputString);
Writer writer = new StringWriter();
IoUtil.copy(reader, writer);
Assert.assertEquals(inputString, writer.toString());
}
@Test
public void testCopyInputStreamOutputStream() throws IOException {
String inputString = "testCopyInputStreamOutputStream";
InputStream inputStream = new ByteArrayInputStream(inputString.getBytes());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
IoUtil.copy(inputStream, outputStream);
Assert.assertEquals(inputString, outputStream.toString());
}
@Test
public void testDelete() throws IOException {
File deleteFile = new File(tempDir.toFile(), "delete.txt");
deleteFile.createNewFile();
Assert.assertTrue(deleteFile.exists());
IoUtil.delete(deleteFile);
Assert.assertFalse(deleteFile.exists());
File deleteDir = new File(tempDir.toFile(), "delete");
deleteDir.mkdirs();
Assert.assertTrue(deleteDir.exists());
File deleteDirFile = new File(deleteDir, "delete.txt");
deleteDirFile.createNewFile();
Assert.assertTrue(deleteDirFile.exists());
IoUtil.delete(deleteDir);
Assert.assertTrue(deleteDir.exists());
Assert.assertFalse(deleteDirFile.exists());
}
@Test
public void testCleanDirectory() throws IOException {
File cleanDir = new File(tempDir.toFile(), "clean");
cleanDir.mkdirs();
File cleanFile1 = new File(cleanDir, "clean1.txt");
File cleanFile2 = new File(cleanDir, "clean2.txt");
Assert.assertTrue(cleanDir.exists());
Assert.assertTrue(cleanFile1.createNewFile());
Assert.assertTrue(cleanFile2.createNewFile());
IoUtil.cleanDirectory(cleanDir);
Assert.assertFalse(cleanFile1.exists());
Assert.assertFalse(cleanFile2.exists());
}
@Test
public void testCopyFile() throws Exception {
String sourcePath = sourceFile.getAbsolutePath();
String targetPath = sourceFile.getParent() + File.separator + "copy" + File.separator + "target.txt";
IoUtil.copyFile(sourcePath, targetPath);
File targetFile = new File(targetPath);
Assert.assertTrue(targetFile.exists());
Assert.assertEquals(sourceFile.length(), targetFile.length());
byte[] sourceBytes = Files.readAllBytes(sourceFile.toPath());
byte[] targetBytes = Files.readAllBytes(targetFile.toPath());
Assert.assertArrayEquals(sourceBytes, targetBytes);
}
@Test
public void testIsGzipStream() {
byte[] gzipBytes = new byte[2];
gzipBytes[0] = (byte) GZIPInputStream.GZIP_MAGIC;
gzipBytes[1] = (byte) (GZIPInputStream.GZIP_MAGIC >> 8);
byte[] invalidGzipBytes = new byte[2];
invalidGzipBytes[0] = (byte) (GZIPInputStream.GZIP_MAGIC + 1);
invalidGzipBytes[1] = (byte) ((GZIPInputStream.GZIP_MAGIC >> 8) + 1);
byte[] invalidGzipBytes2 = new byte[1];
byte[] normalBytes = new byte[2];
Assert.assertTrue(IoUtil.isGzipStream(gzipBytes));
Assert.assertFalse(IoUtil.isGzipStream(invalidGzipBytes));
Assert.assertFalse(IoUtil.isGzipStream(invalidGzipBytes2));
Assert.assertFalse(IoUtil.isGzipStream(null));
Assert.assertFalse(IoUtil.isGzipStream(normalBytes));
}
@Test
public void testCloseQuietly() throws IOException {
Closeable closeable = new BrokenInputStream();
URL url = new URL("https://www.baidu.com");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
Assertions.assertDoesNotThrow(() -> IoUtil.closeQuietly(closeable));
Assertions.assertDoesNotThrow(() -> IoUtil.closeQuietly(closeable, closeable, closeable));
Assertions.assertDoesNotThrow(() -> IoUtil.closeQuietly(httpURLConnection));
}
}

@ -1,94 +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.
*/
package cn.hippo4j.common.toolkit;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.junit.Assert;
import org.junit.Test;
import org.json.JSONException;
import org.skyscreamer.jsonassert.JSONAssert;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class JSONUtilTest {
private static final Foo EXPECTED_FOO = new Foo(1, "foo1", new Foo(2, "foo2", null));
private static final List<Foo> EXPECTED_FOO_ARRAY = Arrays.asList(EXPECTED_FOO, EXPECTED_FOO);
private static final String EXPECTED_FOO_JSON = "{\"id\":1,\"name\":\"foo1\",\"foo\":{\"id\":2,\"name\":\"foo2\"}}";
private static final String EXPECTED_FOO_JSON_ARRAY = "[" + EXPECTED_FOO_JSON + "," + EXPECTED_FOO_JSON + "]";
@Test
public void assertToJSONString() {
Assert.assertNull(JSONUtil.toJSONString(null));
try {
JSONAssert.assertEquals(EXPECTED_FOO_JSON, JSONUtil.toJSONString(EXPECTED_FOO), false);
} catch (JSONException jse) {
throw new RuntimeException(jse);
}
}
@Test
public void assertParseObject() {
Assert.assertNull(JSONUtil.parseObject(null, Foo.class));
Assert.assertNull(JSONUtil.parseObject(" ", Foo.class));
Assert.assertEquals(EXPECTED_FOO, JSONUtil.parseObject(EXPECTED_FOO_JSON, Foo.class));
}
@Test
public void assertParseObjectTypeReference() {
Assert.assertNull(JSONUtil.parseObject(null, new TypeReference<List<Foo>>() {
}));
Assert.assertNull(JSONUtil.parseObject(" ", new TypeReference<List<Foo>>() {
}));
Assert.assertEquals(
EXPECTED_FOO_ARRAY,
JSONUtil.parseObject(EXPECTED_FOO_JSON_ARRAY, new TypeReference<List<Foo>>() {
}));
}
@Test
public void assertParseArray() {
Assert.assertEquals(Collections.emptyList(), JSONUtil.parseArray(null, Foo.class));
Assert.assertEquals(Collections.emptyList(), JSONUtil.parseArray(" ", Foo.class));
Assert.assertEquals(
EXPECTED_FOO_ARRAY,
JSONUtil.parseArray(EXPECTED_FOO_JSON_ARRAY, Foo.class));
}
@EqualsAndHashCode
@AllArgsConstructor
@NoArgsConstructor
@Data
private static class Foo {
private Integer id;
private String name;
private Foo foo;
}
}

@ -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.
*/
package cn.hippo4j.common.toolkit;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* test for {@link JacksonHandler}
*/
public class JacksonHandlerTest {
private final static JacksonHandler JACKSON_HANDLER = new JacksonHandler();
private static final Entity EXPECTED_ENTITY =
new Entity(1, "entity1", new Entity(2, "entity2", null));
private static final List<Entity> EXPECTED_ENTITY_ARRAY = Arrays.asList(EXPECTED_ENTITY, EXPECTED_ENTITY);
private static final String EXPECTED_ENTITY_JSON = "{" +
"\"id\":1," +
"\"name\":\"entity1\"," +
"\"entity\":{" +
"\"id\":2," +
"\"name\":\"entity2\"" +
"}}";
private static final String EXPECTED_ENTITY_ARRAY_JSON = "[" +
EXPECTED_ENTITY_JSON + "," +
EXPECTED_ENTITY_JSON +
"]";
@Test
public void testToJSONString() {
// boolean to json
Assertions.assertEquals("true", JACKSON_HANDLER.toJSONString(true));
// double to json
Assertions.assertEquals("0.01", JACKSON_HANDLER.toJSONString(0.01));
// integer to json
Assertions.assertEquals("1", JACKSON_HANDLER.toJSONString(1));
// string to json
Assertions.assertEquals("\"hello world\"", JACKSON_HANDLER.toJSONString("hello world"));
// array to json
Assertions.assertEquals("[0,1,2,3,4]", JACKSON_HANDLER.toJSONString(new int[]{0, 1, 2, 3, 4}));
// object to json
Assertions.assertEquals(EXPECTED_ENTITY_JSON, JACKSON_HANDLER.toJSONString(EXPECTED_ENTITY));
}
@Test
public void testParseObject() {
// normal json to boolean
Assertions.assertEquals(true, JACKSON_HANDLER.parseObject("true", Boolean.class));
// normal json to double
Assertions.assertEquals(0.01, JACKSON_HANDLER.parseObject("0.01", Double.class));
// normal json to integer
Assertions.assertEquals(1, JACKSON_HANDLER.parseObject("1", Integer.class));
// normal json to string
Assertions.assertEquals("hello world",
JACKSON_HANDLER.parseObject("\"hello world\"", String.class));
// normal json to object
Assertions.assertEquals(EXPECTED_ENTITY, JACKSON_HANDLER.parseObject(EXPECTED_ENTITY_JSON, Entity.class));
Assertions.assertEquals(
EXPECTED_ENTITY,
JACKSON_HANDLER.parseObject(EXPECTED_ENTITY_JSON, new TypeReference<Entity>() {
}));
// illegal json
Assertions.assertThrows(MismatchedInputException.class,
() -> JACKSON_HANDLER.parseObject(" ", Entity.class));
// null json
Assertions.assertThrows(IllegalArgumentException.class,
() -> JACKSON_HANDLER.parseObject(null, Entity.class));
// illegal type
Assertions.assertThrows(MismatchedInputException.class,
() -> JACKSON_HANDLER.parseObject(EXPECTED_ENTITY_JSON, String.class));
}
@Test
public void testParseArray() {
// normal json to array
Assertions.assertEquals(EXPECTED_ENTITY_ARRAY, JSONUtil.parseArray(EXPECTED_ENTITY_ARRAY_JSON, Entity.class));
// null json
Assertions.assertEquals(Collections.emptyList(), JSONUtil.parseArray(null, Entity.class));
// illegal json
Assertions.assertEquals(Collections.emptyList(), JSONUtil.parseArray(" ", Entity.class));
}
@Test
public void testIsJson() {
// normal json
Assertions.assertTrue(JACKSON_HANDLER.isJson(EXPECTED_ENTITY_JSON));
Assertions.assertTrue(JACKSON_HANDLER.isJson(EXPECTED_ENTITY_ARRAY_JSON));
Assertions.assertTrue(JACKSON_HANDLER.isJson(" "));
// illegal json
Assertions.assertFalse(JACKSON_HANDLER.isJson("{" +
"\"id\":1," +
"\"name\":\"entity1\"," +
"\"entity\":{\"id\":2,\"name\":\"entity2\"}"));
// null json
Assertions.assertThrows(IllegalArgumentException.class, () -> JACKSON_HANDLER.isJson(null));
}
@EqualsAndHashCode
@AllArgsConstructor
@NoArgsConstructor
@Data
private static class Entity {
private Integer id;
private String name;
private Entity entity;
}
}

@ -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.
*/
package cn.hippo4j.common.toolkit;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiFunction;
/**
* MapUtil Test
*/
public class MapUtilTest {
@Test
public void parseMapForFilterRetIsEmptyTest() {
HashMap<String, Object> map = new HashMap<>();
map.put("abc", "123");
map.put("bcd", "456");
map.put("cde", "789");
List<String> ret = MapUtil.parseMapForFilter(map, "x");
Assert.isTrue(CollectionUtil.isEmpty(ret));
}
@Test
public void parseMapForFilterRetIsNotEmptyTest() {
HashMap<String, Object> map = new HashMap<>();
map.put("abc", "123");
map.put("bcd", "456");
map.put("cde", "789");
List<String> ret = MapUtil.parseMapForFilter(map, "b");
Assert.isTrue(CollectionUtil.isNotEmpty(ret));
}
@Test
public void computeIfAbsentNotExistTargetTest() {
BiFunction<String, String, String> mappingFunction = (a, b) -> a + b;
try {
MapUtil.computeIfAbsent(null, "key", mappingFunction, "param1", "param2");
} catch (Exception e) {
if (e instanceof NullPointerException) {
Assert.isTrue(Objects.equals("target", e.getMessage()));
}
}
}
@Test
public void computeIfAbsentNotExistKeyTest() {
Map<String, Object> map = new HashMap<>();
map.put("abc", "123");
BiFunction<String, String, Object> mappingFunction = (a, b) -> a + b;
try {
MapUtil.computeIfAbsent(map, null, mappingFunction, "param1", "param2");
} catch (Exception e) {
if (e instanceof NullPointerException) {
Assert.isTrue(Objects.equals("key", e.getMessage()));
}
}
}
@Test
public void computeIfAbsentNotExistMappingFunctionTest() {
Map<Object, Object> map = new HashMap<>();
map.put("abc", "123");
try {
MapUtil.computeIfAbsent(map, "abc", null, "param1", "param2");
} catch (Exception e) {
if (e instanceof NullPointerException) {
Assert.isTrue(Objects.equals("mappingFunction", e.getMessage()));
}
}
}
@Test
public void computeIfAbsentNotExistParam1Test() {
Map<String, Object> map = new HashMap<>();
map.put("abc", "123");
BiFunction<String, String, Object> mappingFunction = (a, b) -> a + b;
try {
MapUtil.computeIfAbsent(map, "abc", mappingFunction, null, "param2");
} catch (Exception e) {
if (e instanceof NullPointerException) {
Assert.isTrue(Objects.equals("param1", e.getMessage()));
}
}
}
@Test
public void computeIfAbsentNotExistParam2Test() {
Map<String, Object> map = new HashMap<>();
map.put("abc", "123");
BiFunction<String, String, Object> mappingFunction = (a, b) -> a + b;
try {
MapUtil.computeIfAbsent(map, "abc", mappingFunction, "param1", null);
} catch (Exception e) {
if (e instanceof NullPointerException) {
Assert.isTrue(Objects.equals("param2", e.getMessage()));
}
}
}
@Test
public void computeIfAbsentValNotNullTest() {
Map<String, Object> map = new HashMap<>();
map.put("abc", "123");
BiFunction<String, String, Object> mappingFunction = (a, b) -> a + b;
Object ret = MapUtil.computeIfAbsent(map, "abc", mappingFunction, "param1", "param2");
Assert.isTrue(Objects.equals("123", String.valueOf(ret)));
}
@Test
public void computeIfAbsentValIsNullTest() {
Map<String, Object> map = new HashMap<>();
map.put("abc", "123");
BiFunction<String, String, Object> mappingFunction = (a, b) -> a + b;
Object ret = MapUtil.computeIfAbsent(map, "xyz", mappingFunction, "param1", "param2");
Assert.isTrue(Objects.equals("param1param2", String.valueOf(ret)));
}
}

@ -1,78 +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.
*/
package cn.hippo4j.common.toolkit;
import cn.hippo4j.common.model.ThreadPoolParameterInfo;
import org.junit.Test;
import org.mockito.MockedStatic;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.mockStatic;
public class Md5UtilTest {
@Test
public void assertMd5Hex() throws NoSuchAlgorithmException {
String md5 = "3cdefff74dcf7a5d60893865b84b62c8";
String message = "message-consume";
Assert.isTrue(md5.equals(Md5Util.md5Hex(message.getBytes())));
}
@Test
public void assertMd5Hex2() {
String md5 = "503840dc3af3cdb39749cd099e4dfeff";
String message = "dynamic-threadpool-example";
Assert.isTrue(md5.equals(Md5Util.md5Hex(message, "UTF-8")));
}
@Test
public void assetEncodeHexString() {
String encodeHexString = "00010f107f80203040506070";
byte[] bytes = {0, 1, 15, 16, 127, -128, 32, 48, 64, 80, 96, 112};
Assert.isTrue(encodeHexString.equals(Md5Util.encodeHexString(bytes)));
}
@Test
public void assetGetTpContentMd5() {
final ThreadPoolParameterInfo threadPoolParameterInfo = new ThreadPoolParameterInfo();
final String mockContent = "mockContent";
final String mockContentMd5 = "34cf17bc632ece6e4c81a4ce8aa97d5e";
try (final MockedStatic<ContentUtil> mockedContentUtil = mockStatic(ContentUtil.class)) {
mockedContentUtil.when(() -> ContentUtil.getPoolContent(threadPoolParameterInfo)).thenReturn(mockContent);
final String result = Md5Util.getTpContentMd5(threadPoolParameterInfo);
Assert.isTrue(result.equals(mockContentMd5));
mockedContentUtil.verify(() -> ContentUtil.getPoolContent(threadPoolParameterInfo), times(1));
}
}
@Test
public void assetCompareMd5ResultString() throws IOException {
Assert.isTrue("".equals(Md5Util.compareMd5ResultString(null)));
String result = "prescription%02dynamic-threadpool-example%02message-consume%01" +
"prescription%02dynamic-threadpool-example%02message-produce%01";
List<String> changedGroupKeys = new ArrayList<>(2);
changedGroupKeys.add("prescription+dynamic-threadpool-example+message-consume+12");
changedGroupKeys.add("prescription+dynamic-threadpool-example+message-produce+11");
Assert.isTrue(result.equals(Md5Util.compareMd5ResultString(changedGroupKeys)));
}
}

@ -1,60 +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.
*/
package cn.hippo4j.common.toolkit;
import org.junit.Assert;
import org.junit.Test;
public class MemoryUtilTest {
@Test
public void heapMemoryUsed() {
long memoryUsed = MemoryUtil.heapMemoryUsed();
Assert.assertNotEquals(0, memoryUsed);
}
@Test
public void heapMemoryMax() {
long memoryUsed = MemoryUtil.heapMemoryMax();
Assert.assertNotEquals(0, memoryUsed);
}
@Test
public void heapMemoryFree() {
long memoryUsed = MemoryUtil.heapMemoryFree();
Assert.assertNotEquals(0, memoryUsed);
}
@Test
public void noHeapMemoryUsed() {
long memoryUsed = MemoryUtil.noHeapMemoryUsed();
Assert.assertNotEquals(0, memoryUsed);
}
@Test
public void noHeapMemoryMax() {
long memoryUsed = MemoryUtil.noHeapMemoryMax();
Assert.assertNotEquals(0, memoryUsed);
}
@Test
public void noHeapMemoryFree() {
long memoryUsed = MemoryUtil.noHeapMemoryFree();
Assert.assertNotEquals(0, memoryUsed);
}
}

@ -1,110 +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.
*/
package cn.hippo4j.common.toolkit;
import cn.hippo4j.common.model.ThreadPoolRunStateInfo;
import cn.hippo4j.common.monitor.*;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
/***
* @description : Todo
* @author : DDDreame
* @date : 2023/5/27 23:24
*/
public class MessageConvertTest {
@Test
public void testConvert() {
AbstractMessage message = new RuntimeMessage();
List<Message> runtimeMessages = new ArrayList<>();
ThreadPoolRunStateInfo poolRunState = ThreadPoolRunStateInfo.builder()
.tpId("testTPid")
.activeSize(4)
.poolSize(12)
.completedTaskCount(8L)
.largestPoolSize(12)
.currentLoad("6")
.clientLastRefreshTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
.peakLoad("20")
.queueSize(0)
.queueRemainingCapacity(512)
.rejectCount(0L)
.timestamp(System.currentTimeMillis())
.build();
RuntimeMessage runtimeMessage = BeanUtil.convert(poolRunState, RuntimeMessage.class);
runtimeMessage.setGroupKey("test-groupKeys");
runtimeMessages.add(runtimeMessage);
message.setMessageType(MessageTypeEnum.RUNTIME);
message.setMessages(runtimeMessages);
MessageWrapper messageWrapper = MessageConvert.convert(message);
Assertions.assertNotNull(messageWrapper);
}
@Test
public void testMessageWrapperConvert() {
AbstractMessage message = new RuntimeMessage();
List<Message> runtimeMessages = new ArrayList<>();
ThreadPoolRunStateInfo poolRunState = ThreadPoolRunStateInfo.builder()
.tpId("testTPid")
.activeSize(4)
.poolSize(12)
.completedTaskCount(8L)
.largestPoolSize(12)
.currentLoad("6")
.clientLastRefreshTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
.peakLoad("20")
.queueSize(0)
.queueRemainingCapacity(512)
.rejectCount(0L)
.timestamp(System.currentTimeMillis())
.build();
RuntimeMessage runtimeMessage = BeanUtil.convert(poolRunState, RuntimeMessage.class);
runtimeMessage.setGroupKey("test-groupKeys");
runtimeMessages.add(runtimeMessage);
message.setMessageType(MessageTypeEnum.RUNTIME);
message.setMessages(runtimeMessages);
MessageWrapper messageWrapper = MessageConvert.convert(message);
Message messageResult = MessageConvert.convert(messageWrapper);
Assertions.assertNotNull(messageResult);
Assertions.assertEquals(message, messageResult);
}
@Test
public void testMessageWrapperConvertException() {
Assertions.assertThrows(Exception.class, () -> {
Map<String, Object> data1 = new HashMap<>();
data1.put("key1", "value1");
data1.put("key2", 123);
Map<String, Object> data2 = new HashMap<>();
data2.put("key3", true);
data2.put("key4", 3.14);
List<Map<String, Object>> contentParams = Arrays.asList(data1, data2);
Class responseClass = String.class;
MessageTypeEnum messageType = MessageTypeEnum.DEFAULT;
MessageWrapper messageWrapper = new MessageWrapper(contentParams, responseClass, messageType);
MessageConvert.convert(messageWrapper);
});
}
}

@ -1,80 +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.
*/
package cn.hippo4j.common.monitor;
import cn.hippo4j.common.monitor.MessageTypeEnum;
import cn.hippo4j.common.monitor.MessageWrapper;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
import java.util.List;
import java.util.Collections;
public class MessageWrapperTest {
private static List<Map<String, Object>> contentParams;
private static Class responseClass;
private static MessageTypeEnum messageType;
private static MessageWrapper messageWrapper;
@BeforeAll
static void setUp() {
// init data
Map<String, Object> data1 = new HashMap<>();
data1.put("key1", "value1");
data1.put("key2", 123);
Map<String, Object> data2 = new HashMap<>();
data2.put("key3", true);
data2.put("key4", 3.14);
contentParams = Arrays.asList(data1, data2);
responseClass = String.class;
messageType = MessageTypeEnum.DEFAULT;
messageWrapper = new MessageWrapper(contentParams, responseClass, messageType);
}
@Test
void testGetContentParams() {
Assert.assertEquals(contentParams, messageWrapper.getContentParams());
}
@Test
void testGetResponseClass() {
Assert.assertEquals(responseClass, messageWrapper.getResponseClass());
}
@Test
void testGetMessageType() {
Assert.assertEquals(messageType, messageWrapper.getMessageType());
}
@Test
void testSettersAndGetters() {
List<Map<String, Object>> newContentParams = Collections.singletonList(Collections.emptyMap());
Class newResponseClass = Integer.class;
MessageTypeEnum newMessageType = MessageTypeEnum.DEFAULT;
messageWrapper.setContentParams(newContentParams);
messageWrapper.setResponseClass(newResponseClass);
messageWrapper.setMessageType(newMessageType);
Assert.assertEquals(newContentParams, messageWrapper.getContentParams());
Assert.assertEquals(newResponseClass, messageWrapper.getResponseClass());
Assert.assertEquals(newMessageType, messageWrapper.getMessageType());
}
}

@ -1,164 +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.
*/
package cn.hippo4j.common.toolkit;
import lombok.Getter;
import lombok.Setter;
import org.junit.Test;
import org.junit.Assert;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.concurrent.ThreadPoolExecutor;
public class ReflectUtilTest {
@Test
public void getFieldValueTest() {
TestSubClass testSubClass = new TestSubClass();
Object privateField = ReflectUtil.getFieldValue(testSubClass, "privateField");
Assert.assertEquals("privateField", privateField);
Object field = ReflectUtil.getFieldValue(testSubClass, "field");
Assert.assertEquals("field", field);
}
@Test
public void getFieldValueByFiledTest() {
TestSubClass testSubClass = new TestSubClass();
Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField");
Object privateFieldVal = ReflectUtil.getFieldValue(testSubClass, privateField);
Assert.assertEquals("privateField", privateFieldVal);
}
@Test
public void getFieldTest() {
Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField");
Assert.assertNotNull(privateField);
Field field = ReflectUtil.getField(TestSubClass.class, "field");
Assert.assertNotNull(field);
}
// @Test
public void getFieldsTest() {
Field[] fields = ReflectUtil.getFields(TestSubClass.class);
Assert.assertEquals(4, fields.length);
}
// @Test
public void getFieldsDirectlyTest() {
Field[] fields = ReflectUtil.getFieldsDirectly(TestSubClass.class, false);
Assert.assertEquals(2, fields.length);
fields = ReflectUtil.getFieldsDirectly(TestSubClass.class, true);
Assert.assertEquals(4, fields.length);
}
@Test
public void getFieldNameTest() {
Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField");
String fieldName = ReflectUtil.getFieldName(privateField);
Assert.assertNotNull(fieldName);
Field subField = ReflectUtil.getField(TestSubClass.class, "subField");
String subfieldName = ReflectUtil.getFieldName(subField);
Assert.assertNotNull(subfieldName);
}
@Test
public void setFieldValueTest() {
TestClass testClass = new TestClass();
ReflectUtil.setFieldValue(testClass, "field", "fieldVal");
Assert.assertEquals("fieldVal", testClass.getField());
Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField");
ReflectUtil.setFieldValue(testClass, privateField, "privateFieldVal");
Assert.assertEquals("privateFieldVal", testClass.getPrivateField());
}
@Test
public void castTest() {
TestClass testClass = new TestSubClass();
Object cast = ReflectUtil.cast(TestSubClass.class, testClass);
Assert.assertTrue(cast instanceof TestSubClass);
}
@Test
public void getDefaultValueTest() {
Object defaultValue = ReflectUtil.getDefaultValue(Long.class);
Assert.assertNull(defaultValue);
Object primitiveValueLong = ReflectUtil.getDefaultValue(long.class);
Assert.assertEquals(0L, primitiveValueLong);
Object primitiveValueInt = ReflectUtil.getDefaultValue(int.class);
Assert.assertEquals(0, primitiveValueInt);
Object primitiveValueFloat = ReflectUtil.getDefaultValue(float.class);
Assert.assertEquals(0f, primitiveValueFloat);
Object primitiveValueShort = ReflectUtil.getDefaultValue(short.class);
Assert.assertEquals((short) 0, primitiveValueShort);
Object primitiveValueChar = ReflectUtil.getDefaultValue(char.class);
Assert.assertEquals((char) 0, primitiveValueChar);
Object primitiveValueDouble = ReflectUtil.getDefaultValue(double.class);
Assert.assertEquals(0D, primitiveValueDouble);
Object primitiveValueBoolean = ReflectUtil.getDefaultValue(boolean.class);
Assert.assertEquals(false, primitiveValueBoolean);
}
@Test
public void getMethodByNameTest() {
// private method
Method runStateLessThan = ReflectUtil.getMethodByName(ThreadPoolExecutor.class, "runStateLessThan");
Assert.assertNotNull(runStateLessThan);
// public method
Method field = ReflectUtil.getMethodByName(TestClass.class, "setPrivateField");
Assert.assertNotNull(field);
// parameters
Method privateField = ReflectUtil.getMethodByName(TestClass.class, "setPrivateField", String.class);
Assert.assertNotNull(privateField);
}
@Test
public void invokeTest() {
TestClass testClass = new TestClass();
Method method = ReflectUtil.getMethodByName(TestClass.class, "getPrivateField");
String invoke = ReflectUtil.invoke(testClass, method);
Assert.assertEquals(invoke, "privateField");
}
@Getter
@Setter
static class TestClass {
private String privateField;
protected String field;
public TestClass() {
this.privateField = "privateField";
this.field = "field";
}
}
class TestSubClass extends TestClass {
private String subField;
}
}

@ -1,46 +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.
*/
package cn.hippo4j.common.toolkit;
import cn.hippo4j.common.model.ThreadPoolParameterInfo;
import org.junit.Assert;
import org.junit.Test;
public class SingletonTest {
@Test
public void assertSingletonGet() {
Assert.assertNull(Singleton.get("userName"));
Singleton.put("userName", "hippo4j");
Assert.assertEquals("hippo4j", Singleton.get("userName"));
ThreadPoolParameterInfo threadPoolParameterInfo = ThreadPoolParameterInfo.builder().tenantId("prescription")
.itemId("dynamic-threadpool-example").tpId("message-consume").content("描述信息").corePoolSize(1)
.maximumPoolSize(2).queueType(1).capacity(4).keepAliveTime(513L).executeTimeOut(null).rejectedType(4)
.isAlarm(1).capacityAlarm(80).livenessAlarm(80).allowCoreThreadTimeOut(1).build();
Singleton.put(threadPoolParameterInfo);
Assert.assertEquals(threadPoolParameterInfo, Singleton.get(ThreadPoolParameterInfo.class.getName()));
}
@Test
public void assertSingletonGet2() {
Assert.assertNull(Singleton.get("userName1", () -> null));
Assert.assertEquals("hippo4j", Singleton.get("userName1", () -> "hippo4j"));
Assert.assertEquals("123456", Singleton.get("pw", () -> "123456") + "");
Assert.assertNotEquals("135790", Singleton.get("pw", () -> "135790") + "");
}
}

@ -1,172 +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.
*/
package cn.hippo4j.common.toolkit;
import org.junit.Test;
import org.junit.Assert;
public class StringUtilTest {
@Test
public void replace() {
String url = "http://localhost:8088/hippo4j_manager?";
String replace = StringUtil.replace(url, "/hippo4j_manager?", "?");
Assert.assertEquals(replace, "http://localhost:8088?");
}
/**
* <p>Splits the provided text into an array, separators specified.
*
* <pre>
* StringUtils.split(null, *) = null
* StringUtils.split("", *) = []
* StringUtils.split("abc def", null) = ["abc", "def"]
* StringUtils.split("abc def", " ") = ["abc", "def"]
* StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* </pre>
*/
@Test
public void split() {
String str1 = null;
String separator1 = "*";
String[] res1 = StringUtil.split(str1, separator1);
assert res1 == null;
String str2 = "";
String separator2 = "*";
String[] res2 = StringUtil.split(str2, separator2);
Assert.assertArrayEquals(res2, new String[0]);
String str3 = "abc def";
String separator3 = null;
String[] res3 = StringUtil.split(str3, separator3);
Assert.assertArrayEquals(res3, new String[]{"abc", "def"});
String str4 = "abc def";
String separator4 = " ";
String[] res4 = StringUtil.split(str4, separator4);
Assert.assertArrayEquals(res4, new String[]{"abc", "def"});
String str5 = "ab:cd:ef";
String separator5 = ":";
String[] res5 = StringUtil.split(str5, separator5);
Assert.assertArrayEquals(res5, new String[]{"ab", "cd", "ef"});
}
@Test
public void assertIsEmpty() {
String string = "";
Assert.assertTrue(StringUtil.isEmpty(string));
}
@Test
public void assertIsNotEmpty() {
String string = "string";
Assert.assertTrue(StringUtil.isNotEmpty(string));
}
@Test
public void emptyToNull() {
String string = "";
Assert.assertNull(StringUtil.emptyToNull(string));
}
@Test
public void nullToEmpty() {
String string = "null";
Assert.assertEquals("null", StringUtil.nullToEmpty(string));
}
@Test
public void isNullOrEmpty() {
String string = "null";
Assert.assertFalse(StringUtil.isEmpty(string));
}
@Test
public void isBlank() {
String string = "";
Assert.assertTrue(StringUtil.isBlank(string));
}
@Test
public void isNotBlank() {
String string = "null";
Assert.assertTrue(StringUtil.isNotBlank(string));
}
@Test
public void isAllNotEmpty() {
String strings = "str";
Assert.assertTrue(StringUtil.isAllNotEmpty(strings));
}
@Test
public void hasEmpty() {
String strings = "";
Assert.assertTrue(StringUtil.hasEmpty(strings));
}
@Test
public void toUnderlineCase() {
String string = "str";
String s = StringUtil.toUnderlineCase(string);
Assert.assertEquals("str", s);
}
@Test
public void toSymbolCase() {
String string = "str";
String s = StringUtil.toSymbolCase(string, StringUtil.UNDERLINE);
Assert.assertEquals("str", s);
}
@Test
public void toCamelCase() {
String string = "str_str";
String s = StringUtil.toCamelCase(string, StringUtil.UNDERLINE);
Assert.assertEquals("strStr", s);
}
@Test
public void newBuilder() {
String s1 = StringUtil.newBuilder(null);
Assert.assertEquals("", s1);
String s2 = StringUtil.newBuilder("H", "ippo", "4j");
Assert.assertEquals("Hippo4j", s2);
}
@Test
public void createBuilder() {
StringBuilder s1 = StringUtil.createBuilder(null);
Assert.assertEquals("", s1.toString());
StringBuilder s2 = StringUtil.createBuilder("H", "ippo", "4j");
Assert.assertEquals("Hippo4j", s2.toString());
}
@Test
public void appends() {
StringBuilder sb1 = StringUtil.appends(null, "H", "ippo", "4j");
Assert.assertEquals("Hippo4j", sb1.toString());
StringBuilder sb2 = StringUtil.appends(StringUtil.createBuilder("To "), null);
Assert.assertEquals("To ", sb2.toString());
StringBuilder sb3 = StringUtil.appends(StringUtil.createBuilder("To "), "H", "ippo", "4j");
Assert.assertEquals("To Hippo4j", sb3.toString());
}
}

@ -1,41 +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.
*/
package cn.hippo4j.common.toolkit;
import org.junit.Test;
import org.junit.Assert;
public class ThreadUtilTest {
@Test
public void testNewThread() {
// Setup
final Runnable runnable = null;
// Run the test
final Thread result = ThreadUtil.newThread(runnable, "name", false);
// Verify the results
Assert.assertNotNull(result);
}
@Test
public void testSleep() {
Assert.assertTrue(ThreadUtil.sleep(0L));
}
}

@ -1,58 +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.
*/
package cn.hippo4j.common.toolkit;
import org.junit.Test;
public class UserContextTest {
private static final String USERNAME = "test";
private static final String USER_ROLE = "role1";
@Test
public void testSetUserInfo() {
UserContext.setUserInfo(USERNAME, USER_ROLE);
ThreadLocal<UserContext.User> userThreadLocal = (ThreadLocal<UserContext.User>) ReflectUtil.getFieldValue(UserContext.class, "USER_THREAD_LOCAL");
Assert.notNull(userThreadLocal.get());
}
@Test
public void testGetUserName() {
UserContext.setUserInfo(USERNAME, USER_ROLE);
String userName = UserContext.getUserName();
Assert.isTrue(USERNAME.equals(userName));
}
@Test
public void testGetUserRole() {
UserContext.setUserInfo(USERNAME, USER_ROLE);
String userRole = UserContext.getUserRole();
Assert.isTrue(USER_ROLE.equals(userRole));
}
@Test
public void testClear() {
UserContext.setUserInfo(USERNAME, USER_ROLE);
ThreadLocal<UserContext.User> userThreadLocal = (ThreadLocal<UserContext.User>) ReflectUtil.getFieldValue(UserContext.class, "USER_THREAD_LOCAL");
Assert.notNull(userThreadLocal.get());
UserContext.clear();
Assert.isNull(userThreadLocal.get());
}
}

@ -1,42 +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.
*/
package cn.hippo4j.common.toolkit.http;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Implement HttpServlet and receive post and get requests<br>
* This HttpServlet represents the home page
*/
public class HomeServlet extends HttpServlet {
int status = 200;
String result = "success";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setStatus(status);
PrintWriter writer = resp.getWriter();
writer.println(result);
}
}

@ -1,207 +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.
*/
package cn.hippo4j.common.toolkit.http;
import cn.hippo4j.common.toolkit.JSONUtil;
import lombok.Getter;
import lombok.Setter;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.LinkedHashMap;
import java.util.Map;
public class HttpUtilsTest {
static int PORT = 8080;
static Tomcat tomcat;
static final String PROTOCOL = "org.apache.coyote.http11.Http11NioProtocol";
static final String HOME_PAGE_URL = "/home";
static final String HOME_PAGE_NAME = "homeServlet";
static final String LOGIN_URL = "/login";
static final String LOGIN_NAME = "loginServlet";
static final String CONTEXT_PATH = "/";
static final String USER_DIR = "user.dir";
static final String BASE_DIR = System.getProperty(USER_DIR) + "/target/tomcat";
@BeforeClass
public static void startWeb() throws IOException, LifecycleException {
tomcat = new Tomcat();
// clear historical files that may be left behind
deleteBaseDir();
// set base dir
tomcat.setBaseDir(BASE_DIR);
// get a random port
ServerSocket socket = new ServerSocket(0);
PORT = socket.getLocalPort();
socket.close();
tomcat.setPort(PORT);
// set a connector
Connector connector = new Connector(PROTOCOL);
connector.setThrowOnFailure(true);
connector.setPort(PORT);
tomcat.setConnector(connector);
// set a context
Context context = tomcat.addContext(CONTEXT_PATH, BASE_DIR);
Tomcat.addServlet(context, HOME_PAGE_NAME, new HomeServlet()).setAsyncSupported(true);
context.addServletMappingDecoded(HOME_PAGE_URL, HOME_PAGE_NAME);
Tomcat.addServlet(context, LOGIN_NAME, new LoginServlet()).setAsyncSupported(true);
context.addServletMappingDecoded(LOGIN_URL, LOGIN_NAME);
// start tomcat
tomcat.start();
}
@AfterClass
public static void stopWeb() throws LifecycleException, IOException {
// stop tomcat
tomcat.stop();
// del dir
deleteBaseDir();
}
/**
* forcibly delete the tomcat's base dir and its sub files
*/
private static void deleteBaseDir() throws IOException {
File file = new File(BASE_DIR);
// fail fast
if (!file.exists()) {
return;
}
Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
/**
* test url
*/
String url = "http://localhost:";
String passwordValue = "hippo4jtest";
String usernameValue = "hippo4j";
String password = "password";
String username = "username";
String suffix = "?password=hippo4jtest&username=hippo4j";
@Test
public void get() {
String s = HttpUtil.get(url + PORT + HOME_PAGE_URL);
Assert.assertNotNull(s);
}
@Test
public void restApiPost() {
String loginUrl = url + PORT + LOGIN_URL;
LoginInfo loginInfo = new LoginInfo();
loginInfo.setPassword(passwordValue);
loginInfo.setUsername(usernameValue);
loginInfo.setRememberMe(1);
String s = HttpUtil.post(loginUrl, loginInfo);
Result result = JSONUtil.parseObject(s, Result.class);
Assert.assertNotNull(result);
String data = result.getData().getData();
Assert.assertNotNull(data);
}
@Test
public void testRestApiPost() {
String loginUrl = url + PORT + LOGIN_URL;
LoginInfo loginInfo = new LoginInfo();
loginInfo.setPassword(passwordValue);
loginInfo.setUsername(usernameValue);
loginInfo.setRememberMe(1);
Result result = HttpUtil.post(loginUrl, loginInfo, Result.class);
Assert.assertNotNull(result);
String data = result.getData().getData();
Assert.assertNotNull(data);
}
// @Test(expected = SocketTimeoutException.class)
public void testRestApiPostTimeout() {
String loginUrl = url + PORT + LOGIN_URL;
LoginInfo loginInfo = new LoginInfo();
loginInfo.setPassword(passwordValue);
loginInfo.setUsername(usernameValue);
loginInfo.setRememberMe(1);
HttpUtil.post(loginUrl, loginInfo, 1, Result.class);
}
@Test
public void buildUrl() {
Map<String, String> map = new LinkedHashMap<>();
map.put(password, passwordValue);
map.put(username, usernameValue);
String s = HttpUtil.buildUrl(url + PORT, map);
Assert.assertEquals(url + PORT + suffix, s);
}
@Getter
@Setter
protected static class LoginInfo {
private String username;
private String password;
private Integer rememberMe;
}
@Getter
@Setter
protected static class Result {
private String code;
private ResultData data;
}
@Getter
@Setter
protected static class ResultData {
private String data;
private String[] roles;
}
}

@ -1,50 +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.
*/
package cn.hippo4j.common.toolkit.http;
import cn.hippo4j.common.toolkit.JSONUtil;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* his HttpServlet represents the login request
*/
public class LoginServlet extends HttpServlet {
String passwordAttr = "password";
String usernameAttr = "username";
String status = "200";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String password = (String) req.getAttribute(passwordAttr);
String username = (String) req.getAttribute(usernameAttr);
HttpUtilsTest.ResultData resultData = new HttpUtilsTest.ResultData();
resultData.setData(username + password);
HttpUtilsTest.Result result = new HttpUtilsTest.Result();
result.setCode(status);
result.setData(resultData);
String s = JSONUtil.toJSONString(result);
PrintWriter writer = resp.getWriter();
writer.println(s);
}
}

@ -1,94 +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.
*/
package cn.hippo4j.common.toolkit.logtracing;
import org.apache.logging.log4j.util.Strings;
import org.junit.Before;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class LogMessageTest {
private final static String MESSAGE = "message";
private final static String THROWABLE_MESSAGE = "throwable message";
private LogMessage logMessage;
@Before
public void init() {
logMessage = LogMessage.getInstance();
}
@Test
public void testGetInstanceShouldReturnANewLogMessageInstance() {
final LogMessage newInstance = LogMessage.getInstance();
assertNotNull(newInstance);
assertNotSame(logMessage, newInstance);
}
@Test
public void testToStringShouldHaveAnEmptyMessage() {
assertEquals(Strings.EMPTY, logMessage.toString());
}
@Test
public void testSetMsgShouldSetAnewMessageInLogMessage() {
logMessage.setMsg(MESSAGE);
assertEquals(MESSAGE, logMessage.toString());
}
@Test
public void testMsgShouldContainsMessageAndThrowableMessage() {
final String message = logMessage.msg(MESSAGE, new Throwable(THROWABLE_MESSAGE));
assertNotNull(message);
assertTrue(message.contains(MESSAGE));
assertTrue(message.contains(THROWABLE_MESSAGE));
}
@Test
public void testKvShouldPutKeyAndValue() {
logMessage.kv("key", "value");
assertEquals("key=value", logMessage.toString());
}
@Test
public void testKvShouldPutAllKeyAndValuePairs() {
logMessage.kv("key1", "value1");
logMessage.kv("key2", "value2");
String output = logMessage.toString();
assertTrue(output.equals("key1=value1||key2=value2") || output.equals("key2=value2||key1=value1"));
}
@Test
public void testToStringShouldPrintMessageAndAllKeyAndValuePairs() {
logMessage.setMsg(MESSAGE);
logMessage.kv("key1", "value1");
logMessage.kv("key2", "value2");
String output = logMessage.toString();
assertTrue(output.equals("messagekey1=value1||key2=value2") || output.equals("messagekey2=value2||key1=value1"));
}
@Test
public void testKv2StringShouldPrintMessageAndAllKeyAndValuePairs() {
String result = logMessage.kv2String("key", "value");
assertEquals("key=value", result);
}
}

@ -34,6 +34,7 @@ import java.util.List;
* Json config parser.
*/
public class JsonConfigParser extends AbstractConfigParser {
private static final ObjectMapper MAPPER;
private static final String DOT = ".";
private static final String LEFT_BRACE = "{";

@ -1,42 +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.
*/
package cn.hippo4j.message.service;
import cn.hippo4j.threadpool.message.api.AlarmControlDTO;
import cn.hippo4j.threadpool.message.api.NotifyTypeEnum;
import cn.hippo4j.threadpool.message.core.service.AlarmControlHandler;
import org.junit.Assert;
import org.junit.Test;
public final class AlarmControlHandlerTest {
@Test
public void assertIsNotSendAlarm() {
AlarmControlHandler alarmControlHandler = new AlarmControlHandler();
AlarmControlDTO alarmControlDTO = new AlarmControlDTO("1", "Wechat", NotifyTypeEnum.ACTIVITY);
Assert.assertFalse(alarmControlHandler.isSendAlarm(alarmControlDTO));
}
@Test
public void assertIsSendAlarm() {
AlarmControlHandler alarmControlHandler = new AlarmControlHandler();
AlarmControlDTO alarmControlDTO = new AlarmControlDTO("1", "Wechat", NotifyTypeEnum.ACTIVITY);
alarmControlHandler.initCacheAndLock("1", "Wechat", 1);
Assert.assertTrue(alarmControlHandler.isSendAlarm(alarmControlDTO));
}
}

@ -125,6 +125,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven.jar.plugin.version}</version>
<configuration>
<archive>
<manifestEntries>
@ -206,22 +207,22 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>${maven-source-plugin.version}</version>
<configuration>
<attach>true</attach>
</configuration>
<executions>
<execution>
<goals>
<goal>jar-no-fork</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
</plugin>
<!-- <plugin>-->
<!-- <groupId>org.apache.maven.plugins</groupId>-->
<!-- <artifactId>maven-source-plugin</artifactId>-->
<!-- <version>${maven-source-plugin.version}</version>-->
<!-- <configuration>-->
<!-- <attach>true</attach>-->
<!-- </configuration>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <goals>-->
<!-- <goal>jar-no-fork</goal>-->
<!-- </goals>-->
<!-- <phase>package</phase>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- </plugin>-->
<plugin>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>

@ -17,14 +17,15 @@
package cn.hippo4j.springboot.starter.adapter.web;
import cn.hippo4j.adapter.web.WebThreadPoolRunStateHandler;
import cn.hippo4j.adapter.web.jetty.DefaultJettyWebThreadPoolHandler;
import cn.hippo4j.adapter.web.jetty.JettyWebThreadPoolHandlerAdapt;
import cn.hippo4j.adapter.web.tomcat.DefaultTomcatWebThreadPoolHandler;
import cn.hippo4j.adapter.web.tomcat.TomcatWebThreadPoolHandlerAdapt;
import cn.hippo4j.adapter.web.undertow.DefaultUndertowWebThreadPoolHandler;
import cn.hippo4j.adapter.web.WebThreadPoolRunStateHandler;
import cn.hippo4j.adapter.web.undertow.UndertowWebThreadPoolHandlerAdapt;
import io.undertow.Undertow;
import jakarta.servlet.Servlet;
import org.apache.catalina.startup.Tomcat;
import org.apache.coyote.UpgradeProtocol;
import org.eclipse.jetty.server.Server;
@ -42,8 +43,6 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.xnio.SslClientAuthMode;
import javax.servlet.Servlet;
/**
* Web Thread Pool Handler Configuration
**/

@ -15,6 +15,6 @@
<module>server</module>
<module>adapter</module>
<module>monitor</module>
<module>config-spring-boot-1x</module>
<!-- <module>config-spring-boot-1x</module>-->
</modules>
</project>

@ -18,11 +18,11 @@
package cn.hippo4j.springboot.starter.event;
import cn.hippo4j.springboot.starter.core.ClientWorker;
import jakarta.annotation.Resource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicBoolean;
/**

@ -1,177 +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.
*/
package cn.hippo4j.core.executor;
import cn.hippo4j.common.toolkit.ThreadUtil;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.core.task.TaskDecorator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* test for {@link DynamicThreadPoolExecutor}
*/
public class DynamicThreadPoolExecutorTest {
@Test
public void testRedundancyHandler() {
RejectedExecutionHandler handler = new ThreadPoolExecutor.DiscardOldestPolicy();
DynamicThreadPoolExecutor executor = new DynamicThreadPoolExecutor(
1, 1, 1000L, TimeUnit.MILLISECONDS,
1000L, true, 1000L,
new ArrayBlockingQueue<>(1), "test", Thread::new, handler);
Assert.assertEquals(handler, executor.getRedundancyHandler());
handler = new ThreadPoolExecutor.AbortPolicy();
executor.setRedundancyHandler(handler);
Assert.assertEquals(handler, executor.getRedundancyHandler());
}
@Test
public void testTaskDecorator() {
DynamicThreadPoolExecutor executor = new DynamicThreadPoolExecutor(
1, 1, 1000L, TimeUnit.MILLISECONDS,
1000L, true, 1000L,
new ArrayBlockingQueue<>(1), "test", Thread::new, new ThreadPoolExecutor.DiscardOldestPolicy());
Assert.assertNull(executor.getTaskDecorator());
TaskDecorator decorator = runnable -> runnable;
executor.setTaskDecorator(decorator);
Assert.assertEquals(decorator, executor.getTaskDecorator());
decorator = runnable -> runnable;
executor.setTaskDecorator(decorator);
Assert.assertEquals(decorator, executor.getTaskDecorator());
}
@Test
public void testExecuteTimeOut() {
DynamicThreadPoolExecutor executor = new DynamicThreadPoolExecutor(
1, 1, 1000L, TimeUnit.MILLISECONDS,
1000L, true, 1000L,
new ArrayBlockingQueue<>(1), "test", Thread::new, new ThreadPoolExecutor.DiscardOldestPolicy());
Assert.assertEquals(1000L, executor.getExecuteTimeOut().longValue());
executor.setExecuteTimeOut(500L);
Assert.assertEquals(500L, executor.getExecuteTimeOut().longValue());
}
@Test
public void testDestroyWhenWaitForTask() {
DynamicThreadPoolExecutor executor = new DynamicThreadPoolExecutor(
1, 1, 1000L, TimeUnit.MILLISECONDS,
1000L, true, 1000L,
new ArrayBlockingQueue<>(1), "test", Thread::new, new ThreadPoolExecutor.DiscardOldestPolicy());
AtomicInteger count = new AtomicInteger(0);
executor.execute(() -> {
ThreadUtil.sleep(500L);
count.incrementAndGet();
});
executor.execute(() -> {
ThreadUtil.sleep(500L);
count.incrementAndGet();
});
executor.destroy();
// waiting for terminated
while (!executor.isTerminated()) {
} ;
Assert.assertEquals(2, count.get());
}
@Test
public void testDestroyWhenNotWaitForTask() {
DynamicThreadPoolExecutor executor = new DynamicThreadPoolExecutor(
1, 1, 1000L, TimeUnit.MILLISECONDS,
1000L, false, 1000L,
new ArrayBlockingQueue<>(1), "test", Thread::new, new ThreadPoolExecutor.DiscardOldestPolicy());
AtomicInteger count = new AtomicInteger(0);
executor.execute(() -> {
ThreadUtil.sleep(500L);
count.incrementAndGet();
});
executor.execute(() -> {
ThreadUtil.sleep(500L);
count.incrementAndGet();
});
executor.destroy();
// waiting for terminated
while (!executor.isTerminated()) {
}
Assert.assertEquals(1, count.get());
}
@Test
public void testRejectCount() {
DynamicThreadPoolExecutor executor = new DynamicThreadPoolExecutor(
1, 1, 1000L, TimeUnit.MILLISECONDS,
1000L, true, 1000L,
new ArrayBlockingQueue<>(1), "test", Thread::new, new ThreadPoolExecutor.DiscardOldestPolicy());
Assert.assertEquals(0L, executor.getRejectCountNum().longValue());
Assert.assertEquals(0L, executor.getRejectCount().get());
executor.submit(() -> ThreadUtil.sleep(100L));
executor.submit(() -> ThreadUtil.sleep(100L));
executor.submit(() -> ThreadUtil.sleep(100L));
ThreadUtil.sleep(200L);
Assert.assertEquals(1L, executor.getRejectCountNum().longValue());
Assert.assertEquals(1L, executor.getRejectCount().get());
}
@Test
public void testSupportParam() {
DynamicThreadPoolExecutor executor = new DynamicThreadPoolExecutor(
1, 1, 1000L, TimeUnit.MILLISECONDS,
1000L, true, 1000L,
new ArrayBlockingQueue<>(1), "test", Thread::new, new ThreadPoolExecutor.DiscardOldestPolicy());
Assert.assertEquals(1000L, executor.getAwaitTerminationMillis());
Assert.assertTrue(executor.isWaitForTasksToCompleteOnShutdown());
executor.setSupportParam(500L, false);
Assert.assertEquals(500L, executor.getAwaitTerminationMillis());
Assert.assertFalse(executor.isWaitForTasksToCompleteOnShutdown());
}
@Test
public void testIsActive() {
DynamicThreadPoolExecutor executor = new DynamicThreadPoolExecutor(
1, 1, 1000L, TimeUnit.MILLISECONDS,
1000L, true, 1000L,
new ArrayBlockingQueue<>(1), "test", Thread::new, new ThreadPoolExecutor.DiscardOldestPolicy());
Assert.assertTrue(executor.isActive());
// waiting for terminated
executor.destroy();
while (!executor.isTerminated()) {
}
Assert.assertFalse(executor.isActive());
executor.destroy();
Assert.assertFalse(executor.isActive());
}
}

@ -1,240 +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.
*/
package cn.hippo4j.core.executor;
import cn.hippo4j.common.toolkit.ThreadUtil;
import cn.hippo4j.core.executor.plugin.ExecuteAwarePlugin;
import cn.hippo4j.core.executor.plugin.RejectedAwarePlugin;
import cn.hippo4j.core.executor.plugin.ShutdownAwarePlugin;
import cn.hippo4j.core.executor.plugin.TaskAwarePlugin;
import cn.hippo4j.core.executor.plugin.manager.DefaultThreadPoolPluginManager;
import cn.hippo4j.core.executor.plugin.manager.ThreadPoolPluginManager;
import lombok.Getter;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* test for {@link ExtensibleThreadPoolExecutor}
*/
public class ExtensibleThreadPoolExecutorTest {
private final RejectedExecutionHandler originalHandler = new ThreadPoolExecutor.DiscardPolicy();
private ExtensibleThreadPoolExecutor executor;
private ThreadPoolPluginManager manager;
@Before
public void initExecutor() {
manager = new DefaultThreadPoolPluginManager();
executor = new ExtensibleThreadPoolExecutor(
"test", manager,
5, 5, 1000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1), Thread::new, originalHandler);
}
@Test
public void testGetThreadPoolId() {
Assert.assertEquals("test", executor.getThreadPoolId());
}
@Test
public void testGetThreadPoolExecutor() {
Assert.assertSame(executor, executor.getThreadPoolExecutor());
}
@Test
public void testGetThreadPoolPluginManager() {
Assert.assertSame(manager, executor.getThreadPoolPluginManager());
}
@Test
public void testGetOrSetRejectedHandler() {
RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
executor.setRejectedExecutionHandler(handler);
Assert.assertSame(handler, executor.getRejectedExecutionHandler());
}
@Test
public void testInvokeTaskAwarePlugin() {
TestTaskAwarePlugin plugin = new TestTaskAwarePlugin();
executor.register(plugin);
executor.submit(() -> {
});
executor.submit(() -> true);
executor.submit(() -> {
}, false);
executor.execute(() -> {
});
Assert.assertEquals(7, plugin.getInvokeCount().get());
}
@Test
public void testInvokeExecuteAwarePlugin() {
TestExecuteAwarePlugin plugin = new TestExecuteAwarePlugin();
executor.register(plugin);
executor.execute(() -> {
});
ThreadUtil.sleep(500L);
Assert.assertEquals(2, plugin.getInvokeCount().get());
// no task will be executed because it has been replaced with null
executor.register(new TestTaskToNullAwarePlugin());
executor.execute(() -> {
});
ThreadUtil.sleep(500L);
Assert.assertEquals(2, plugin.getInvokeCount().get());
}
@Test
public void testInvokeRejectedAwarePlugin() {
executor.setCorePoolSize(1);
executor.setMaximumPoolSize(1);
TestRejectedAwarePlugin plugin = new TestRejectedAwarePlugin();
executor.register(plugin);
// blocking pool and queue
executor.submit(() -> ThreadUtil.sleep(500L));
executor.submit(() -> ThreadUtil.sleep(500L));
// reject 3 tasks
executor.submit(() -> {
});
executor.submit(() -> {
});
executor.submit(() -> {
});
ThreadUtil.sleep(500L);
Assert.assertEquals(3, plugin.getInvokeCount().get());
}
@Test
public void testInvokeTestShutdownAwarePluginWhenShutdown() throws InterruptedException {
TestShutdownAwarePlugin plugin = new TestShutdownAwarePlugin();
executor.register(plugin);
executor.shutdown();
executor.submit(() -> {
throw new IllegalArgumentException("???");
});
if (executor.awaitTermination(500L, TimeUnit.MILLISECONDS)) {
Assert.assertEquals(3, plugin.getInvokeCount().get());
}
}
@Test
public void testInvokeTestShutdownAwarePluginWhenShutdownNow() throws InterruptedException {
TestShutdownAwarePlugin plugin = new TestShutdownAwarePlugin();
executor.register(plugin);
executor.shutdownNow();
if (executor.awaitTermination(500L, TimeUnit.MILLISECONDS)) {
Assert.assertEquals(3, plugin.getInvokeCount().get());
}
}
private final static class TestTaskToNullAwarePlugin implements TaskAwarePlugin {
@Override
public @Nullable Runnable beforeTaskExecute(@NonNull Runnable runnable) {
return null;
}
}
@Getter
private final static class TestTaskAwarePlugin implements TaskAwarePlugin {
private final AtomicInteger invokeCount = new AtomicInteger(0);
private final String id = "TestTaskAwarePlugin";
@Override
public <V> Runnable beforeTaskCreate(ThreadPoolExecutor executor, Runnable runnable, V value) {
invokeCount.incrementAndGet();
return TaskAwarePlugin.super.beforeTaskCreate(executor, runnable, value);
}
@Override
public <V> Callable<V> beforeTaskCreate(ThreadPoolExecutor executor, Callable<V> future) {
invokeCount.incrementAndGet();
return TaskAwarePlugin.super.beforeTaskCreate(executor, future);
}
@Override
public Runnable beforeTaskExecute(@NonNull Runnable runnable) {
invokeCount.incrementAndGet();
return TaskAwarePlugin.super.beforeTaskExecute(runnable);
}
}
@Getter
private final static class TestExecuteAwarePlugin implements ExecuteAwarePlugin {
private final AtomicInteger invokeCount = new AtomicInteger(0);
private final String id = "TestExecuteAwarePlugin";
@Override
public void beforeExecute(Thread thread, Runnable runnable) {
invokeCount.incrementAndGet();
ExecuteAwarePlugin.super.beforeExecute(thread, runnable);
}
@Override
public void afterExecute(Runnable runnable, Throwable throwable) {
invokeCount.incrementAndGet();
ExecuteAwarePlugin.super.afterExecute(runnable, throwable);
}
}
@Getter
private final static class TestRejectedAwarePlugin implements RejectedAwarePlugin {
private final AtomicInteger invokeCount = new AtomicInteger(0);
private final String id = "TestRejectedAwarePlugin";
@Override
public void beforeRejectedExecution(Runnable runnable, ThreadPoolExecutor executor) {
invokeCount.incrementAndGet();
}
}
@Getter
private final static class TestShutdownAwarePlugin implements ShutdownAwarePlugin {
private final AtomicInteger invokeCount = new AtomicInteger(0);
private final String id = "TestShutdownAwarePlugin";
@Override
public void beforeShutdown(ThreadPoolExecutor executor) {
invokeCount.incrementAndGet();
ShutdownAwarePlugin.super.beforeShutdown(executor);
}
@Override
public void afterShutdown(ThreadPoolExecutor executor, List<Runnable> remainingTasks) {
invokeCount.incrementAndGet();
ShutdownAwarePlugin.super.afterShutdown(executor, remainingTasks);
}
@Override
public void afterTerminated(ThreadPoolExecutor executor) {
invokeCount.incrementAndGet();
ShutdownAwarePlugin.super.afterTerminated(executor);
}
}
}

@ -1,28 +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.
*/
package cn.hippo4j.core.executor.handler;
import org.junit.Test;
public final class DynamicThreadPoolBannerHandlerTest {
@Test
public void assertGetVersion() {
// Assert.assertTrue(StringUtil.isEmpty(DynamicThreadPoolBannerHandler.getVersion()));
}
}

@ -1,41 +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.
*/
package cn.hippo4j.core.executor.plugin;
import cn.hippo4j.core.executor.plugin.PluginRuntime;
import org.junit.Assert;
import org.junit.Test;
/**
* test for {@link PluginRuntime}
*/
public class PluginRuntimeTest {
@Test
public void test() {
PluginRuntime runtime = new PluginRuntime("test");
Assert.assertEquals("test", runtime.getPluginId());
Assert.assertTrue(runtime.getInfoList().isEmpty());
runtime.addInfo("item", "item");
PluginRuntime.Info info = runtime.getInfoList().get(0);
Assert.assertEquals("item", info.getName());
Assert.assertEquals("item", info.getValue());
}
}

@ -1,93 +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.
*/
package cn.hippo4j.core.executor.plugin;
import cn.hippo4j.common.toolkit.ThreadUtil;
import cn.hippo4j.core.executor.ExtensibleThreadPoolExecutor;
import cn.hippo4j.core.executor.plugin.*;
import cn.hippo4j.core.executor.plugin.manager.DefaultThreadPoolPluginManager;
import lombok.Getter;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* test for default method of {@link ThreadPoolPlugin} and it's subclass
*/
public class ThreadPoolPluginTest {
@Test
public void testDefaultMethod() {
ExtensibleThreadPoolExecutor executor = new ExtensibleThreadPoolExecutor(
"test", new DefaultThreadPoolPluginManager(),
1, 1, 1000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1), Thread::new, new ThreadPoolExecutor.DiscardPolicy());
executor.register(new TestTaskAwarePlugin());
executor.register(new TestExecuteAwarePlugin());
executor.register(new TestRejectedAwarePlugin());
executor.register(new TestShutdownAwarePlugin());
AtomicInteger count = new AtomicInteger(0);
executor.submit(() -> {
ThreadUtil.sleep(100L);
return count.incrementAndGet();
});
executor.submit(() -> {
ThreadUtil.sleep(100L);
count.incrementAndGet();
});
executor.submit(count::incrementAndGet, 2);
// waiting for shutdown
executor.shutdown();
while (!executor.isTerminated()) {
}
Assert.assertEquals(2, count.get());
}
@Getter
private final static class TestTaskAwarePlugin implements TaskAwarePlugin {
private final String id = this.getClass().getSimpleName();
}
@Getter
private final static class TestExecuteAwarePlugin implements ExecuteAwarePlugin {
private final String id = this.getClass().getSimpleName();
}
@Getter
private final static class TestRejectedAwarePlugin implements RejectedAwarePlugin {
private final String id = this.getClass().getSimpleName();
}
@Getter
private final static class TestShutdownAwarePlugin implements ShutdownAwarePlugin {
private final String id = this.getClass().getSimpleName();
}
}

@ -1,104 +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.
*/
package cn.hippo4j.core.executor.plugin.impl;
import cn.hippo4j.common.toolkit.ThreadUtil;
import cn.hippo4j.core.executor.ExtensibleThreadPoolExecutor;
import cn.hippo4j.core.executor.plugin.PluginRuntime;
import cn.hippo4j.core.executor.plugin.ThreadPoolPlugin;
import cn.hippo4j.core.executor.plugin.impl.TaskDecoratorPlugin;
import cn.hippo4j.core.executor.plugin.manager.DefaultThreadPoolPluginManager;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.core.task.TaskDecorator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* test for {@link TaskDecoratorPlugin}
*/
public class TaskDecoratorPluginTest {
private final AtomicInteger taskExecuteCount = new AtomicInteger(0);
@Test
public void testGetId() {
Assert.assertEquals(TaskDecoratorPlugin.PLUGIN_NAME, new TaskDecoratorPlugin().getId());
}
@Test
public void testGetRuntime() {
ThreadPoolPlugin plugin = new TaskDecoratorPlugin();
PluginRuntime runtime = new TaskDecoratorPlugin().getPluginRuntime();
Assert.assertNotNull(runtime);
Assert.assertEquals(plugin.getId(), runtime.getPluginId());
}
@Test
public void testAddDecorator() {
TaskDecoratorPlugin plugin = new TaskDecoratorPlugin();
plugin.addDecorator(runnable -> runnable);
plugin.addDecorator(runnable -> runnable);
Assert.assertEquals(2, plugin.getDecorators().size());
}
@Test
public void testRemoveDecorator() {
TaskDecoratorPlugin plugin = new TaskDecoratorPlugin();
TaskDecorator decorator = runnable -> runnable;
plugin.addDecorator(decorator);
plugin.removeDecorator(decorator);
Assert.assertTrue(plugin.getDecorators().isEmpty());
}
@Test
public void testClear() {
TaskDecoratorPlugin plugin = new TaskDecoratorPlugin();
TaskDecorator decorator = runnable -> runnable;
plugin.addDecorator(decorator);
plugin.addDecorator(decorator);
plugin.clearDecorators();
Assert.assertTrue(plugin.getDecorators().isEmpty());
}
@Test
public void testBeforeTaskExecute() {
ExtensibleThreadPoolExecutor executor = new ExtensibleThreadPoolExecutor(
"test", new DefaultThreadPoolPluginManager(),
5, 5, 1000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1), Thread::new, new ThreadPoolExecutor.DiscardPolicy());
TaskDecoratorPlugin plugin = new TaskDecoratorPlugin();
plugin.addDecorator(runnable -> () -> {
taskExecuteCount.incrementAndGet();
runnable.run();
});
plugin.addDecorator(runnable -> () -> {
taskExecuteCount.incrementAndGet();
runnable.run();
});
executor.register(plugin);
executor.execute(() -> {
});
ThreadUtil.sleep(500L);
Assert.assertEquals(2, taskExecuteCount.get());
}
}

@ -1,84 +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.
*/
package cn.hippo4j.core.executor.plugin.impl;
import cn.hippo4j.common.toolkit.ThreadUtil;
import cn.hippo4j.core.executor.ExtensibleThreadPoolExecutor;
import cn.hippo4j.core.executor.plugin.impl.TaskRejectCountRecordPlugin;
import cn.hippo4j.core.executor.plugin.manager.DefaultThreadPoolPluginManager;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* test for {@link TaskRejectCountRecordPlugin}
*/
public class TaskRejectCountRecordPluginTest {
@Test
public void testGetId() {
Assert.assertEquals(TaskRejectCountRecordPlugin.PLUGIN_NAME, new TaskRejectCountRecordPlugin().getId());
}
@Test
public void testGetRuntime() {
Assert.assertNotNull(new TaskRejectCountRecordPlugin().getPluginRuntime());
}
@Test
public void testGetRejectCountNum() {
TaskRejectCountRecordPlugin plugin = new TaskRejectCountRecordPlugin();
Assert.assertEquals((Long) 0L, plugin.getRejectCountNum());
}
@Test
public void testGetRejectCount() {
TaskRejectCountRecordPlugin plugin = new TaskRejectCountRecordPlugin();
Assert.assertEquals(0L, plugin.getRejectCount().get());
}
@Test
public void testSetRejectCount() {
TaskRejectCountRecordPlugin plugin = new TaskRejectCountRecordPlugin();
AtomicLong atomicLong = new AtomicLong(0);
plugin.setRejectCount(atomicLong);
Assert.assertSame(atomicLong, plugin.getRejectCount());
}
@Test
public void testBeforeRejectedExecution() {
ExtensibleThreadPoolExecutor executor = new ExtensibleThreadPoolExecutor(
"test", new DefaultThreadPoolPluginManager(),
1, 1, 1000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1), Thread::new, new ThreadPoolExecutor.DiscardPolicy());
TaskRejectCountRecordPlugin plugin = new TaskRejectCountRecordPlugin();
executor.register(plugin);
executor.submit(() -> ThreadUtil.sleep(500L));
executor.submit(() -> ThreadUtil.sleep(500L));
executor.submit(() -> ThreadUtil.sleep(500L));
ThreadUtil.sleep(500L);
Assert.assertEquals((Long) 1L, plugin.getRejectCountNum());
}
}

@ -1,94 +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.
*/
package cn.hippo4j.core.executor.plugin.impl;
import cn.hippo4j.common.toolkit.ThreadUtil;
import cn.hippo4j.core.executor.ExtensibleThreadPoolExecutor;
import cn.hippo4j.core.executor.plugin.manager.DefaultThreadPoolPluginManager;
import cn.hippo4j.threadpool.alarm.api.ThreadPoolCheckAlarm;
import lombok.Getter;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* test for {@link TaskRejectNotifyAlarmPlugin}
*/
public class TaskRejectNotifyAlarmPluginTest {
@Test
public void testGetId() {
Assert.assertEquals(TaskRejectNotifyAlarmPlugin.PLUGIN_NAME, new TaskRejectNotifyAlarmPlugin().getId());
}
@Test
public void testGetRuntime() {
Assert.assertNotNull(new TaskRejectNotifyAlarmPlugin().getPluginRuntime());
}
@Test
public void testBeforeRejectedExecution() {
ExtensibleThreadPoolExecutor executor = new ExtensibleThreadPoolExecutor(
"test", new DefaultThreadPoolPluginManager(),
1, 1, 1000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1), Thread::new, new ThreadPoolExecutor.DiscardPolicy());
TestAlarm alarm = new TestAlarm();
executor.register(new TaskRejectNotifyAlarmPlugin(alarm));
executor.submit(() -> ThreadUtil.sleep(200L));
executor.submit(() -> ThreadUtil.sleep(200L));
executor.submit(() -> ThreadUtil.sleep(200L));
// waiting for shutdown
executor.shutdown();
while (!executor.isTerminated()) {
}
Assert.assertEquals(1, alarm.getNumberOfAlarms().get());
}
private static class TestAlarm implements ThreadPoolCheckAlarm {
@Getter
private final AtomicInteger numberOfAlarms = new AtomicInteger(0);
@Override
public void checkPoolCapacityAlarm(String threadPoolId, ThreadPoolExecutor threadPoolExecutor) {
// do noting
}
@Override
public void checkPoolActivityAlarm(String threadPoolId, ThreadPoolExecutor threadPoolExecutor) {
// do noting
}
@Override
public void asyncSendRejectedAlarm(String threadPoolId) {
numberOfAlarms.incrementAndGet();
}
@Override
public void asyncSendExecuteTimeOutAlarm(String threadPoolId, long executeTime, long executeTimeOut, ThreadPoolExecutor threadPoolExecutor) {
// do noting
}
}
}

@ -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.
*/
package cn.hippo4j.core.executor.plugin.impl;
import cn.hippo4j.common.toolkit.ThreadUtil;
import cn.hippo4j.core.executor.ExtensibleThreadPoolExecutor;
import cn.hippo4j.core.executor.plugin.manager.DefaultThreadPoolPluginManager;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* test for {@link TaskTimeRecordPlugin}
*/
@Slf4j
public class TaskTimeRecordPluginTest {
@Test
public void testGetId() {
Assert.assertEquals(TaskTimeRecordPlugin.PLUGIN_NAME, new TaskTimeRecordPlugin().getId());
}
@Test
public void testGetRuntime() {
Assert.assertNotNull(new TaskTimeRecordPlugin().getPluginRuntime());
}
@Test
public void testSummarize() {
ExtensibleThreadPoolExecutor executor = new ExtensibleThreadPoolExecutor(
"test", new DefaultThreadPoolPluginManager(),
3, 3, 1000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1), Thread::new, new ThreadPoolExecutor.DiscardPolicy());
TaskTimeRecordPlugin plugin = new TaskTimeRecordPlugin(3);
executor.register(plugin);
executor.submit(() -> ThreadUtil.sleep(1000L));
executor.submit(() -> ThreadUtil.sleep(3000L));
executor.submit(() -> ThreadUtil.sleep(2000L));
executor.submit(() -> ThreadUtil.sleep(2000L));
// waiting for shutdown
executor.shutdown();
while (!executor.isTerminated()) {
}
TaskTimeRecordPlugin.Summary summary = plugin.summarize();
Assert.assertTrue(summary.getMinTaskTimeMillis() > 0L);
Assert.assertTrue(summary.getMaxTaskTimeMillis() > 0L);
Assert.assertTrue(summary.getAvgTaskTimeMillis() > 0L);
Assert.assertTrue(summary.getTotalTaskTimeMillis() > 0L);
// Assert.assertTrue(testInDeviation(summary.getMinTaskTimeMillis(), 1000L, 300L));
// Assert.assertTrue(testInDeviation(summary.getMaxTaskTimeMillis(), 3000L, 300L));
// Assert.assertTrue(testInDeviation(summary.getAvgTaskTimeMillis(), 2000L, 300L));
// Assert.assertTrue(testInDeviation(summary.getTotalTaskTimeMillis(), 8000L, 300L));
}
private boolean testInDeviation(long except, long actual, long offer) {
long exceptLower = except - offer;
long exceptUpper = except + offer;
log.info("test {} < [{}] < {}", exceptLower, actual, exceptUpper);
return exceptLower < actual && actual < exceptUpper;
}
@Test
public void testTableSizeFor() {
int maxCap = 1 << 30;
for (int i = 0; i <= maxCap; i++) {
int tabSize1 = tabSizeFor_JDK8(i);
int tabSize2 = TaskTimeRecordPlugin.tableSizeFor(i);
Assert.assertTrue(tabSize1 == tabSize2);
}
}
private static int tabSizeFor_JDK8(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= 1073741824) ? 1073741824 : n + 1;
}
}

@ -1,113 +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.
*/
package cn.hippo4j.core.executor.plugin.impl;
import cn.hippo4j.common.toolkit.ThreadUtil;
import cn.hippo4j.core.executor.ExtensibleThreadPoolExecutor;
import cn.hippo4j.core.executor.plugin.manager.DefaultThreadPoolPluginManager;
import cn.hippo4j.threadpool.alarm.api.ThreadPoolCheckAlarm;
import lombok.Getter;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* test for {@link TaskTimeoutNotifyAlarmPlugin}
*/
public class TaskTimeoutNotifyAlarmPluginTest {
private final ExtensibleThreadPoolExecutor executor = new ExtensibleThreadPoolExecutor(
"test", new DefaultThreadPoolPluginManager(),
5, 5, 1000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1), Thread::new, new ThreadPoolExecutor.AbortPolicy());
private final TestAlarm testAlarm = new TestAlarm();
private final TaskTimeoutNotifyAlarmPlugin plugin = new TaskTimeoutNotifyAlarmPlugin(
executor.getThreadPoolId(), 1L, executor, testAlarm);
@Test
public void testGetId() {
Assert.assertEquals(TaskTimeoutNotifyAlarmPlugin.PLUGIN_NAME, plugin.getId());
}
@Test
public void testGetRuntime() {
Assert.assertNotNull(plugin.getPluginRuntime());
}
@Test
public void testGetExecuteTimeOut() {
Assert.assertEquals(1L, plugin.getExecuteTimeOut().longValue());
}
@Test
public void testSetExecuteTimeOut() {
plugin.setExecuteTimeOut(2L);
Assert.assertEquals(2L, plugin.getExecuteTimeOut().longValue());
}
@Test
public void testProcessTaskTime() {
executor.register(plugin);
executor.submit(() -> {
ThreadUtil.sleep(100L);
});
executor.submit(() -> {
ThreadUtil.sleep(300L);
});
// waiting for shutdown
executor.shutdown();
while (!executor.isTerminated()) {
}
Assert.assertEquals(2, testAlarm.getNumberOfAlarms().get());
}
private static class TestAlarm implements ThreadPoolCheckAlarm {
@Getter
private final AtomicInteger numberOfAlarms = new AtomicInteger(0);
@Override
public void checkPoolCapacityAlarm(String threadPoolId, ThreadPoolExecutor threadPoolExecutor) {
// do noting
}
@Override
public void checkPoolActivityAlarm(String threadPoolId, ThreadPoolExecutor threadPoolExecutor) {
// do noting
}
@Override
public void asyncSendRejectedAlarm(String threadPoolId) {
// do noting
}
@Override
public void asyncSendExecuteTimeOutAlarm(String threadPoolId, long executeTime, long executeTimeOut, ThreadPoolExecutor threadPoolExecutor) {
numberOfAlarms.incrementAndGet();
}
}
}

@ -1,92 +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.
*/
package cn.hippo4j.core.executor.plugin.impl;
import cn.hippo4j.common.toolkit.ThreadUtil;
import cn.hippo4j.core.executor.ExtensibleThreadPoolExecutor;
import cn.hippo4j.core.executor.plugin.ThreadPoolPlugin;
import cn.hippo4j.core.executor.plugin.impl.ThreadPoolExecutorShutdownPlugin;
import cn.hippo4j.core.executor.plugin.manager.DefaultThreadPoolPluginManager;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* test for {@link ThreadPoolExecutorShutdownPlugin}
*/
public class ThreadPoolExecutorShutdownPluginTest {
@Test
public void testGetId() {
Assert.assertEquals(ThreadPoolExecutorShutdownPlugin.PLUGIN_NAME, new ThreadPoolExecutorShutdownPlugin(1000L).getId());
}
@Test
public void testGetRuntime() {
Assert.assertNotNull(new ThreadPoolExecutorShutdownPlugin(1000L).getPluginRuntime());
}
@Test
public void testGetAwaitTerminationMillis() {
ThreadPoolExecutorShutdownPlugin plugin = new ThreadPoolExecutorShutdownPlugin(1000L);
Assert.assertEquals(1000L, plugin.getAwaitTerminationMillis());
}
@Test
public void testSetAwaitTerminationMillis() {
ThreadPoolExecutorShutdownPlugin plugin = new ThreadPoolExecutorShutdownPlugin(1000L);
plugin.setAwaitTerminationMillis(5000L);
Assert.assertEquals(5000L, plugin.getAwaitTerminationMillis());
}
public ExtensibleThreadPoolExecutor getExecutor(ThreadPoolPlugin plugin) {
ExtensibleThreadPoolExecutor executor = new ExtensibleThreadPoolExecutor(
"test", new DefaultThreadPoolPluginManager(),
2, 2, 1000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1), Thread::new, new ThreadPoolExecutor.DiscardPolicy());
executor.register(plugin);
return executor;
}
private static Callable<Integer> getCallable(AtomicInteger completedCount) {
return () -> {
ThreadUtil.sleep(1000L);
return completedCount.incrementAndGet();
};
}
@Test
public void testShutdown() {
ExtensibleThreadPoolExecutor executor = getExecutor(
new ThreadPoolExecutorShutdownPlugin(2000L));
AtomicInteger completedCount = new AtomicInteger(0);
executor.submit(getCallable(completedCount));
executor.submit(getCallable(completedCount));
executor.submit(getCallable(completedCount));
executor.shutdownNow();
Assert.assertEquals(2, completedCount.get());
}
}

@ -1,238 +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.
*/
package cn.hippo4j.core.executor.plugin.manager;
import cn.hippo4j.core.executor.plugin.ThreadPoolPlugin;
import cn.hippo4j.core.executor.plugin.manager.*;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* test for {@link DefaultGlobalThreadPoolPluginManager}
*/
public class DefaultGlobalThreadPoolPluginManagerTest {
@Test
public void testDoRegister() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
manager.enableThreadPoolPlugin(new TestPlugin("1"));
manager.enableThreadPoolPlugin(new TestPlugin("2"));
manager.enableThreadPoolPluginRegistrar(new TestRegistrar("1"));
TestSupport support = new TestSupport("1");
manager.doRegister(support);
Assert.assertEquals(3, support.getAllPlugins().size());
}
@Test
public void testRegisterThreadPoolPluginSupport() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
Assert.assertTrue(manager.enableThreadPoolPlugin(new TestPlugin("1")));
TestSupport support = new TestSupport("1");
Assert.assertTrue(manager.registerThreadPoolPluginSupport(support));
Assert.assertFalse(manager.registerThreadPoolPluginSupport(support));
Assert.assertEquals(1, support.getAllPlugins().size());
// incremental update
manager.enableThreadPoolPlugin(new TestPlugin("2"));
manager.enableThreadPoolPluginRegistrar(new TestRegistrar("1"));
Assert.assertEquals(3, support.getAllPlugins().size());
}
@Test
public void testCancelManagement() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
manager.enableThreadPoolPlugin(new TestPlugin("1"));
TestSupport support = new TestSupport("1");
manager.registerThreadPoolPluginSupport(support);
Assert.assertEquals(1, support.getAllPlugins().size());
manager.cancelManagement(support.getThreadPoolId());
manager.enableThreadPoolPlugin(new TestPlugin("2"));
Assert.assertEquals(1, support.getAllPlugins().size());
}
@Test
public void testGetManagedThreadPoolPluginSupport() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
TestSupport support = new TestSupport("1");
manager.registerThreadPoolPluginSupport(support);
Assert.assertSame(support, manager.getManagedThreadPoolPluginSupport(support.getThreadPoolId()));
support = new TestSupport("2");
manager.registerThreadPoolPluginSupport(support);
Assert.assertSame(support, manager.getManagedThreadPoolPluginSupport(support.getThreadPoolId()));
}
@Test
public void testGetAllManagedThreadPoolPluginSupports() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
manager.registerThreadPoolPluginSupport(new TestSupport("1"));
manager.registerThreadPoolPluginSupport(new TestSupport("2"));
Assert.assertEquals(2, manager.getAllManagedThreadPoolPluginSupports().size());
}
@Test
public void testEnableThreadPoolPlugin() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
TestSupport support1 = new TestSupport("1");
manager.registerThreadPoolPluginSupport(support1);
TestSupport support2 = new TestSupport("2");
manager.registerThreadPoolPluginSupport(support2);
Assert.assertTrue(manager.enableThreadPoolPlugin(new TestPlugin("1")));
Assert.assertFalse(manager.enableThreadPoolPlugin(new TestPlugin("1")));
Assert.assertEquals(1, support1.getAllPlugins().size());
}
@Test
public void testGetAllEnableThreadPoolPlugins() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
manager.enableThreadPoolPlugin(new TestPlugin("1"));
manager.enableThreadPoolPlugin(new TestPlugin("2"));
Assert.assertEquals(2, manager.getAllEnableThreadPoolPlugins().size());
}
@Test
public void testDisableThreadPoolPlugin() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
manager.enableThreadPoolPlugin(new TestPlugin("1"));
manager.enableThreadPoolPlugin(new TestPlugin("2"));
manager.disableThreadPoolPlugin("2");
Assert.assertEquals(1, manager.getAllEnableThreadPoolPlugins().size());
}
@Test
public void testEnableThreadPoolPluginRegistrar() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
Assert.assertTrue(manager.enableThreadPoolPluginRegistrar(new TestRegistrar("1")));
Assert.assertFalse(manager.enableThreadPoolPluginRegistrar(new TestRegistrar("1")));
Assert.assertEquals(1, manager.getAllEnableThreadPoolPluginRegistrar().size());
}
@Test
public void testGetAllEnableThreadPoolPluginRegistrar() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
manager.enableThreadPoolPluginRegistrar(new TestRegistrar("1"));
manager.enableThreadPoolPluginRegistrar(new TestRegistrar("2"));
Assert.assertEquals(2, manager.getAllEnableThreadPoolPluginRegistrar().size());
}
@Test
public void testDisableThreadPoolPluginRegistrar() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
manager.enableThreadPoolPluginRegistrar(new TestRegistrar("1"));
manager.enableThreadPoolPluginRegistrar(new TestRegistrar("2"));
manager.disableThreadPoolPluginRegistrar("2");
Assert.assertEquals(1, manager.getAllEnableThreadPoolPluginRegistrar().size());
}
@Test
public void testGetAllPluginsFromManagers() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
manager.enableThreadPoolPluginRegistrar(new TestRegistrar("1"));
manager.enableThreadPoolPlugin(new TestPlugin("1"));
TestSupport support1 = new TestSupport("1");
manager.registerThreadPoolPluginSupport(support1);
TestSupport support2 = new TestSupport("2");
manager.registerThreadPoolPluginSupport(support2);
Assert.assertEquals(4, manager.getAllPluginsFromManagers().size());
}
@Test
public void testGetPluginsOfTypeFromManagers() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
manager.enableThreadPoolPluginRegistrar(new TestRegistrar("1"));
manager.enableThreadPoolPlugin(new TestPlugin("1"));
TestSupport support1 = new TestSupport("1");
manager.registerThreadPoolPluginSupport(support1);
TestSupport support2 = new TestSupport("2");
manager.registerThreadPoolPluginSupport(support2);
Assert.assertEquals(4, manager.getPluginsOfTypeFromManagers(TestPlugin.class).size());
}
@Test
public void testGetPluginsFromManagers() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
manager.enableThreadPoolPluginRegistrar(new TestRegistrar("1"));
manager.enableThreadPoolPlugin(new TestPlugin("1"));
TestSupport support1 = new TestSupport("1");
manager.registerThreadPoolPluginSupport(support1);
TestSupport support2 = new TestSupport("2");
manager.registerThreadPoolPluginSupport(support2);
Assert.assertEquals(2, manager.getPluginsFromManagers("1").size());
}
@Test
public void testUnregisterForAllManagers() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
manager.enableThreadPoolPluginRegistrar(new TestRegistrar("1"));
manager.enableThreadPoolPlugin(new TestPlugin("1"));
TestSupport support1 = new TestSupport("1");
manager.registerThreadPoolPluginSupport(support1);
TestSupport support2 = new TestSupport("2");
manager.registerThreadPoolPluginSupport(support2);
manager.unregisterForAllManagers("1");
Assert.assertEquals(2, manager.getAllPluginsFromManagers().size());
}
@RequiredArgsConstructor
@Getter
private static class TestSupport implements ThreadPoolPluginSupport {
private final String threadPoolId;
private final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
private final ThreadPoolPluginManager threadPoolPluginManager = new DefaultThreadPoolPluginManager();
}
@Getter
@RequiredArgsConstructor
private static class TestRegistrar implements ThreadPoolPluginRegistrar {
private final String id;
@Override
public void doRegister(ThreadPoolPluginSupport support) {
support.register(new TestPlugin("TestRegistrar"));
}
}
@Getter
@RequiredArgsConstructor
private static class TestPlugin implements ThreadPoolPlugin {
private final String id;
}
}

@ -1,250 +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.
*/
package cn.hippo4j.core.executor.plugin.manager;
import cn.hippo4j.core.executor.plugin.ExecuteAwarePlugin;
import cn.hippo4j.core.executor.plugin.RejectedAwarePlugin;
import cn.hippo4j.core.executor.plugin.ShutdownAwarePlugin;
import cn.hippo4j.core.executor.plugin.TaskAwarePlugin;
import cn.hippo4j.core.executor.plugin.ThreadPoolPlugin;
import cn.hippo4j.core.executor.plugin.manager.DefaultThreadPoolPluginManager;
import lombok.Getter;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.annotation.Order;
import java.util.Iterator;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* test for {@link DefaultThreadPoolPluginManager}
*/
public class DefaultThreadPoolPluginManagerTest {
private DefaultThreadPoolPluginManager manager;
@Before
public void initRegistry() {
manager = new DefaultThreadPoolPluginManager(new ReentrantReadWriteLock(), null);
}
@Test
public void testRegister() {
manager.register(new TestShutdownAwarePlugin());
Assert.assertEquals(1, manager.getAllPlugins().size());
}
@Test
public void testGetAllPlugins() {
manager.register(new TestExecuteAwarePlugin());
manager.register(new TestRejectedAwarePlugin());
Assert.assertEquals(2, manager.getAllPlugins().size());
}
@Test
public void testClear() {
manager.register(new TestExecuteAwarePlugin());
manager.clear();
Assert.assertTrue(manager.getAllPlugins().isEmpty());
}
@Test
public void testTryRegister() {
Assert.assertTrue(manager.tryRegister(new TestExecuteAwarePlugin()));
Assert.assertFalse(manager.tryRegister(new TestExecuteAwarePlugin()));
}
@Test
public void testIsRegistered() {
Assert.assertFalse(manager.isRegistered(TestExecuteAwarePlugin.class.getSimpleName()));
manager.register(new TestExecuteAwarePlugin());
Assert.assertTrue(manager.isRegistered(TestExecuteAwarePlugin.class.getSimpleName()));
}
@Test
public void testUnregister() {
manager.register(new TestTaskAwarePlugin());
manager.unregister(TestTaskAwarePlugin.class.getSimpleName());
Assert.assertFalse(manager.isRegistered(TestTaskAwarePlugin.class.getSimpleName()));
manager.register(new TestRejectedAwarePlugin());
manager.unregister(TestRejectedAwarePlugin.class.getSimpleName());
Assert.assertFalse(manager.isRegistered(TestRejectedAwarePlugin.class.getSimpleName()));
manager.register(new TestShutdownAwarePlugin());
manager.unregister(TestShutdownAwarePlugin.class.getSimpleName());
Assert.assertFalse(manager.isRegistered(TestShutdownAwarePlugin.class.getSimpleName()));
manager.register(new TestExecuteAwarePlugin());
manager.unregister(TestExecuteAwarePlugin.class.getSimpleName());
Assert.assertFalse(manager.isRegistered(TestExecuteAwarePlugin.class.getSimpleName()));
}
@Test
public void testGetPlugin() {
ThreadPoolPlugin plugin = new TestExecuteAwarePlugin();
manager.register(plugin);
Assert.assertSame(plugin, manager.getPlugin(plugin.getId()).orElse(null));
}
@Test
public void testGetRejectedAwarePluginList() {
manager.register(new TestRejectedAwarePlugin());
Assert.assertEquals(1, manager.getRejectedAwarePluginList().size());
}
@Test
public void testGetShutdownAwarePluginList() {
manager.register(new TestShutdownAwarePlugin());
Assert.assertEquals(1, manager.getShutdownAwarePluginList().size());
}
@Test
public void testGetTaskAwarePluginList() {
manager.register(new TestTaskAwarePlugin());
Assert.assertEquals(1, manager.getTaskAwarePluginList().size());
}
@Test
public void testGetExecuteAwarePluginList() {
manager.register(new TestExecuteAwarePlugin());
Assert.assertEquals(1, manager.getExecuteAwarePluginList().size());
}
@Test
public void testGetAllPluginsOfType() {
manager.register(new TestExecuteAwarePlugin());
manager.register(new TestRejectedAwarePlugin());
Assert.assertEquals(1, manager.getAllPluginsOfType(TestExecuteAwarePlugin.class).size());
Assert.assertEquals(1, manager.getAllPluginsOfType(TestRejectedAwarePlugin.class).size());
Assert.assertEquals(2, manager.getAllPluginsOfType(ThreadPoolPlugin.class).size());
}
@Test
public void testGetAllPluginRuntimes() {
manager.register(new TestExecuteAwarePlugin());
manager.register(new TestRejectedAwarePlugin());
Assert.assertEquals(2, manager.getAllPluginRuntimes().size());
}
@Test
public void testGetPluginRuntime() {
manager.register(new TestExecuteAwarePlugin());
Assert.assertTrue(manager.getRuntime(TestExecuteAwarePlugin.class.getSimpleName()).isPresent());
}
@Test
public void testGetPluginOfType() {
manager.register(new TestExecuteAwarePlugin());
Assert.assertTrue(manager.getPluginOfType(TestExecuteAwarePlugin.class.getSimpleName(), TestExecuteAwarePlugin.class).isPresent());
Assert.assertTrue(manager.getPluginOfType(TestExecuteAwarePlugin.class.getSimpleName(), ThreadPoolPlugin.class).isPresent());
Assert.assertFalse(manager.getPluginOfType(TestExecuteAwarePlugin.class.getSimpleName(), RejectedAwarePlugin.class).isPresent());
}
@Test
public void testEnable() {
ThreadPoolPlugin plugin = new TestExecuteAwarePlugin();
Assert.assertFalse(manager.enable(plugin.getId()));
manager.register(plugin);
Assert.assertFalse(manager.enable(plugin.getId()));
manager.disable(plugin.getId());
Assert.assertTrue(manager.enable(plugin.getId()));
}
@Test
public void testDisable() {
ThreadPoolPlugin plugin = new TestExecuteAwarePlugin();
Assert.assertFalse(manager.disable(plugin.getId()));
manager.register(plugin);
Assert.assertTrue(manager.disable(plugin.getId()));
Assert.assertFalse(manager.disable(plugin.getId()));
Assert.assertTrue(manager.getExecuteAwarePluginList().isEmpty());
Assert.assertEquals(1, manager.getAllPlugins().size());
}
@Test
public void testIsDisable() {
ThreadPoolPlugin plugin = new TestExecuteAwarePlugin();
Assert.assertFalse(manager.isDisabled(plugin.getId()));
manager.register(plugin);
Assert.assertTrue(manager.disable(plugin.getId()));
Assert.assertTrue(manager.isDisabled(plugin.getId()));
}
@Test
public void testGetDisabledPluginIds() {
ThreadPoolPlugin plugin = new TestExecuteAwarePlugin();
Assert.assertTrue(manager.getAllDisabledPluginIds().isEmpty());
manager.register(plugin);
Assert.assertTrue(manager.disable(plugin.getId()));
Assert.assertEquals(1, manager.getAllDisabledPluginIds().size());
}
@Test
public void testSetPluginComparator() {
Assert.assertFalse(manager.isEnableSort());
manager.register(new TestExecuteAwarePlugin());
manager.register(new TestTaskAwarePlugin());
manager.setPluginComparator(AnnotationAwareOrderComparator.INSTANCE);
manager.register(new TestRejectedAwarePlugin());
manager.register(new TestShutdownAwarePlugin());
Assert.assertTrue(manager.isEnableSort());
Iterator<ThreadPoolPlugin> iterator = manager.getAllPlugins().iterator();
Assert.assertEquals(TestTaskAwarePlugin.class, iterator.next().getClass());
Assert.assertEquals(TestRejectedAwarePlugin.class, iterator.next().getClass());
Assert.assertEquals(TestExecuteAwarePlugin.class, iterator.next().getClass());
Assert.assertEquals(TestShutdownAwarePlugin.class, iterator.next().getClass());
}
@Order(0)
@Getter
private final static class TestTaskAwarePlugin implements TaskAwarePlugin {
private final String id = this.getClass().getSimpleName();
}
@Order(2)
@Getter
private final static class TestExecuteAwarePlugin implements ExecuteAwarePlugin {
private final String id = this.getClass().getSimpleName();
}
@Order(1)
@Getter
private final static class TestRejectedAwarePlugin implements RejectedAwarePlugin {
private final String id = this.getClass().getSimpleName();
}
@Order(3)
@Getter
private final static class TestShutdownAwarePlugin implements ShutdownAwarePlugin {
private final String id = this.getClass().getSimpleName();
}
}

@ -1,65 +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.
*/
package cn.hippo4j.core.executor.plugin.manager;
import cn.hippo4j.core.executor.ExtensibleThreadPoolExecutor;
import cn.hippo4j.core.executor.plugin.impl.TaskDecoratorPlugin;
import cn.hippo4j.core.executor.plugin.impl.TaskRejectCountRecordPlugin;
import cn.hippo4j.core.executor.plugin.impl.TaskRejectNotifyAlarmPlugin;
import cn.hippo4j.core.executor.plugin.impl.TaskTimeoutNotifyAlarmPlugin;
import cn.hippo4j.core.executor.plugin.impl.ThreadPoolExecutorShutdownPlugin;
import cn.hippo4j.core.executor.plugin.manager.DefaultThreadPoolPluginManager;
import cn.hippo4j.core.executor.plugin.manager.DefaultThreadPoolPluginRegistrar;
import cn.hippo4j.core.executor.plugin.manager.ThreadPoolPluginManager;
import cn.hippo4j.core.executor.plugin.manager.ThreadPoolPluginRegistrar;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* test for {@link DefaultThreadPoolPluginRegistrar}
*/
public class DefaultThreadPoolPluginRegistrarTest {
@Test
public void testGetId() {
ThreadPoolPluginRegistrar registrar = new DefaultThreadPoolPluginRegistrar();
Assert.assertEquals(registrar.getClass().getSimpleName(), registrar.getId());
}
@Test
public void testDoRegister() {
ThreadPoolPluginRegistrar registrar = new DefaultThreadPoolPluginRegistrar(100L, 100L);
ThreadPoolPluginManager manager = new DefaultThreadPoolPluginManager();
ExtensibleThreadPoolExecutor executor = new ExtensibleThreadPoolExecutor(
"test", manager,
5, 5, 1000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1), Thread::new, new ThreadPoolExecutor.AbortPolicy());
registrar.doRegister(executor);
Assert.assertTrue(manager.getPlugin(TaskDecoratorPlugin.PLUGIN_NAME).isPresent());
Assert.assertTrue(manager.getPlugin(TaskTimeoutNotifyAlarmPlugin.PLUGIN_NAME).isPresent());
Assert.assertTrue(manager.getPlugin(TaskRejectCountRecordPlugin.PLUGIN_NAME).isPresent());
Assert.assertTrue(manager.getPlugin(TaskRejectNotifyAlarmPlugin.PLUGIN_NAME).isPresent());
Assert.assertTrue(manager.getPlugin(ThreadPoolExecutorShutdownPlugin.PLUGIN_NAME).isPresent());
}
}

@ -1,155 +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.
*/
package cn.hippo4j.core.executor.plugin.manager;
import cn.hippo4j.core.executor.plugin.manager.EmptyThreadPoolPluginManager;
import cn.hippo4j.core.executor.plugin.ThreadPoolPlugin;
import cn.hippo4j.core.executor.plugin.manager.ThreadPoolPluginManager;
import lombok.Getter;
import org.junit.Assert;
import org.junit.Test;
import java.util.Collections;
import java.util.Optional;
/**
* test for {@link EmptyThreadPoolPluginManager}
*/
public class EmptyThreadPoolPluginManagerTest {
private final ThreadPoolPluginManager manager = EmptyThreadPoolPluginManager.INSTANCE;
@Test
public void testEmpty() {
Assert.assertSame(manager, ThreadPoolPluginManager.empty());
}
@Test
public void testGetAllPlugins() {
Assert.assertEquals(Collections.emptyList(), manager.getAllPluginRuntimes());
}
@Test
public void testClear() {
manager.clear();
Assert.assertTrue(isEmpty(manager));
}
@Test
public void testRegister() {
manager.register(new TestPlugin());
Assert.assertTrue(isEmpty(manager));
}
@Test
public void testTryRegister() {
Assert.assertFalse(manager.tryRegister(new TestPlugin()));
}
@Test
public void testIsRegistered() {
manager.register(new TestPlugin());
Assert.assertFalse(manager.isRegistered(TestPlugin.class.getSimpleName()));
}
@Test
public void testUnregister() {
manager.register(new TestPlugin());
manager.unregister(TestPlugin.class.getSimpleName());
Assert.assertTrue(isEmpty(manager));
}
@Test
public void testGetPlugin() {
Assert.assertSame(Optional.empty(), manager.getPlugin(""));
}
@Test
public void testGetRejectedAwarePluginList() {
Assert.assertEquals(Collections.emptyList(), manager.getRejectedAwarePluginList());
}
@Test
public void testGetShutdownAwarePluginList() {
Assert.assertEquals(Collections.emptyList(), manager.getShutdownAwarePluginList());
}
@Test
public void testGetTaskAwarePluginList() {
Assert.assertEquals(Collections.emptyList(), manager.getTaskAwarePluginList());
}
@Test
public void testGetExecuteAwarePluginList() {
Assert.assertEquals(Collections.emptyList(), manager.getExecuteAwarePluginList());
}
@Test
public void testEnable() {
ThreadPoolPlugin plugin = new TestPlugin();
Assert.assertFalse(manager.enable(plugin.getId()));
manager.register(plugin);
Assert.assertFalse(manager.enable(plugin.getId()));
manager.disable(plugin.getId());
Assert.assertFalse(manager.enable(plugin.getId()));
}
@Test
public void testDisable() {
ThreadPoolPlugin plugin = new TestPlugin();
Assert.assertFalse(manager.disable(plugin.getId()));
manager.register(plugin);
Assert.assertFalse(manager.disable(plugin.getId()));
Assert.assertFalse(manager.disable(plugin.getId()));
Assert.assertTrue(manager.getExecuteAwarePluginList().isEmpty());
Assert.assertTrue(manager.getAllPlugins().isEmpty());
}
@Test
public void testIsDisable() {
ThreadPoolPlugin plugin = new TestPlugin();
Assert.assertTrue(manager.isDisabled(plugin.getId()));
manager.register(plugin);
Assert.assertFalse(manager.disable(plugin.getId()));
Assert.assertTrue(manager.isDisabled(plugin.getId()));
}
@Test
public void testGetDisabledPluginIds() {
ThreadPoolPlugin plugin = new TestPlugin();
Assert.assertTrue(manager.getAllDisabledPluginIds().isEmpty());
manager.register(plugin);
Assert.assertFalse(manager.disable(plugin.getId()));
Assert.assertTrue(manager.getAllDisabledPluginIds().isEmpty());
}
private static boolean isEmpty(ThreadPoolPluginManager manager) {
return manager.getAllPlugins().isEmpty();
}
@Getter
private static class TestPlugin implements ThreadPoolPlugin {
private final String id = TestPlugin.class.getSimpleName();
}
}

@ -1,239 +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.
*/
package cn.hippo4j.core.executor.plugin.manager;
import cn.hippo4j.core.executor.ExtensibleThreadPoolExecutor;
import cn.hippo4j.core.executor.plugin.ExecuteAwarePlugin;
import cn.hippo4j.core.executor.plugin.RejectedAwarePlugin;
import cn.hippo4j.core.executor.plugin.ShutdownAwarePlugin;
import cn.hippo4j.core.executor.plugin.TaskAwarePlugin;
import cn.hippo4j.core.executor.plugin.ThreadPoolPlugin;
import cn.hippo4j.core.executor.plugin.manager.DefaultThreadPoolPluginManager;
import cn.hippo4j.core.executor.plugin.manager.ThreadPoolPluginManager;
import cn.hippo4j.core.executor.plugin.manager.ThreadPoolPluginSupport;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* test for default method of {@link ThreadPoolPluginSupport}
*/
public class ThreadPoolPluginSupportTest {
private final ThreadPoolPluginManager manager = new DefaultThreadPoolPluginManager();
private final ExtensibleThreadPoolExecutor executor = new ExtensibleThreadPoolExecutor(
"test", manager,
5, 5, 1000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1), Thread::new, new ThreadPoolExecutor.AbortPolicy());
private final ThreadPoolPluginSupport support = new TestSupport(executor.getThreadPoolId(), executor, manager);
@Test
public void testGetThreadPoolId() {
Assert.assertEquals(executor.getThreadPoolId(), support.getThreadPoolId());
}
@Test
public void testGetThreadPoolPluginManager() {
Assert.assertEquals(manager, support.getThreadPoolPluginManager());
}
@Getter
@RequiredArgsConstructor
private static class TestSupport implements ThreadPoolPluginSupport {
private final String threadPoolId;
private final ExtensibleThreadPoolExecutor threadPoolExecutor;
private final ThreadPoolPluginManager threadPoolPluginManager;
}
// ================ default delegate method ================
@Test
public void testRegister() {
support.register(new TestShutdownAwarePlugin());
Assert.assertEquals(1, support.getAllPlugins().size());
}
@Test
public void testGetAllPlugins() {
support.register(new TestExecuteAwarePlugin());
support.register(new TestRejectedAwarePlugin());
Assert.assertEquals(2, support.getAllPlugins().size());
}
@Test
public void testClear() {
support.register(new TestExecuteAwarePlugin());
support.clear();
Assert.assertTrue(support.getAllPlugins().isEmpty());
}
@Test
public void testTryRegister() {
Assert.assertTrue(support.tryRegister(new TestExecuteAwarePlugin()));
Assert.assertFalse(support.tryRegister(new TestExecuteAwarePlugin()));
}
@Test
public void testIsRegistered() {
Assert.assertFalse(support.isRegistered(TestExecuteAwarePlugin.class.getSimpleName()));
support.register(new TestExecuteAwarePlugin());
Assert.assertTrue(support.isRegistered(TestExecuteAwarePlugin.class.getSimpleName()));
}
@Test
public void testUnregister() {
support.register(new TestExecuteAwarePlugin());
support.unregister(TestExecuteAwarePlugin.class.getSimpleName());
Assert.assertFalse(support.isRegistered(TestExecuteAwarePlugin.class.getSimpleName()));
}
@Test
public void testGetPlugin() {
ThreadPoolPlugin plugin = new TestExecuteAwarePlugin();
support.register(plugin);
Assert.assertSame(plugin, support.getPlugin(plugin.getId()).orElse(null));
}
@Test
public void testGetRejectedAwarePluginList() {
support.register(new TestRejectedAwarePlugin());
Assert.assertEquals(1, support.getRejectedAwarePluginList().size());
}
@Test
public void testGetShutdownAwarePluginList() {
support.register(new TestShutdownAwarePlugin());
Assert.assertEquals(1, support.getShutdownAwarePluginList().size());
}
@Test
public void testGetTaskAwarePluginList() {
support.register(new TestTaskAwarePlugin());
Assert.assertEquals(1, support.getTaskAwarePluginList().size());
}
@Test
public void testGetExecuteAwarePluginList() {
support.register(new TestExecuteAwarePlugin());
Assert.assertEquals(1, support.getExecuteAwarePluginList().size());
}
@Test
public void testGetAllPluginsOfType() {
support.register(new TestExecuteAwarePlugin());
support.register(new TestRejectedAwarePlugin());
Assert.assertEquals(1, support.getAllPluginsOfType(TestExecuteAwarePlugin.class).size());
Assert.assertEquals(1, support.getAllPluginsOfType(TestRejectedAwarePlugin.class).size());
Assert.assertEquals(2, support.getAllPluginsOfType(ThreadPoolPlugin.class).size());
}
@Test
public void testGetAllPluginRuntimes() {
support.register(new TestExecuteAwarePlugin());
support.register(new TestRejectedAwarePlugin());
Assert.assertEquals(2, support.getAllPluginRuntimes().size());
}
@Test
public void testGetPluginRuntime() {
support.register(new TestExecuteAwarePlugin());
Assert.assertTrue(support.getRuntime(TestExecuteAwarePlugin.class.getSimpleName()).isPresent());
}
@Test
public void testGetPluginOfType() {
support.register(new TestExecuteAwarePlugin());
Assert.assertTrue(support.getPluginOfType(TestExecuteAwarePlugin.class.getSimpleName(), TestExecuteAwarePlugin.class).isPresent());
Assert.assertTrue(support.getPluginOfType(TestExecuteAwarePlugin.class.getSimpleName(), ThreadPoolPlugin.class).isPresent());
Assert.assertFalse(support.getPluginOfType(TestExecuteAwarePlugin.class.getSimpleName(), RejectedAwarePlugin.class).isPresent());
}
@Test
public void testEnable() {
ThreadPoolPlugin plugin = new TestExecuteAwarePlugin();
Assert.assertFalse(support.enable(plugin.getId()));
support.register(plugin);
Assert.assertFalse(support.enable(plugin.getId()));
support.disable(plugin.getId());
Assert.assertTrue(support.enable(plugin.getId()));
}
@Test
public void testDisable() {
ThreadPoolPlugin plugin = new TestExecuteAwarePlugin();
Assert.assertFalse(support.disable(plugin.getId()));
support.register(plugin);
Assert.assertTrue(support.disable(plugin.getId()));
Assert.assertFalse(support.disable(plugin.getId()));
Assert.assertTrue(support.getExecuteAwarePluginList().isEmpty());
Assert.assertEquals(1, support.getAllPlugins().size());
}
@Test
public void testIsDisable() {
ThreadPoolPlugin plugin = new TestExecuteAwarePlugin();
Assert.assertFalse(support.isDisabled(plugin.getId()));
support.register(plugin);
Assert.assertTrue(support.disable(plugin.getId()));
Assert.assertTrue(support.isDisabled(plugin.getId()));
}
@Test
public void testGetDisabledPluginIds() {
ThreadPoolPlugin plugin = new TestExecuteAwarePlugin();
Assert.assertTrue(support.getAllDisabledPluginIds().isEmpty());
support.register(plugin);
Assert.assertTrue(support.disable(plugin.getId()));
Assert.assertEquals(1, support.getAllDisabledPluginIds().size());
}
@Getter
private final static class TestTaskAwarePlugin implements TaskAwarePlugin {
private final String id = this.getClass().getSimpleName();
}
@Getter
private final static class TestExecuteAwarePlugin implements ExecuteAwarePlugin {
private final String id = this.getClass().getSimpleName();
}
@Getter
private final static class TestRejectedAwarePlugin implements RejectedAwarePlugin {
private final String id = this.getClass().getSimpleName();
}
@Getter
private final static class TestShutdownAwarePlugin implements ShutdownAwarePlugin {
private final String id = this.getClass().getSimpleName();
}
}

@ -1,74 +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.
*/
package cn.hippo4j.core.executor.proxy;
import cn.hippo4j.core.config.ApplicationContextHolder;
import cn.hippo4j.threadpool.alarm.api.ThreadPoolCheckAlarm;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.context.ApplicationContext;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicLong;
@RunWith(MockitoJUnitRunner.class)
public class RejectedProxyInvocationHandlerTest {
@Mock
private ThreadPoolCheckAlarm mockAlarmHandler;
@Mock
private ApplicationContext applicationContext;
@Mock
private Object target;
@Mock
private Method mockMethod;
private RejectedProxyInvocationHandler handler;
private AtomicLong rejectCount;
@Before
public void setUp() {
String threadPoolId = "test-pool";
rejectCount = new AtomicLong(0);
handler = new RejectedProxyInvocationHandler(target, threadPoolId, rejectCount);
}
@Test
public void testInvoke() throws Throwable {
Object[] mockArgs = new Object[]{"arg1", "arg2"};
MockedStatic<ApplicationContextHolder> mockedStatic = Mockito.mockStatic(ApplicationContextHolder.class);
mockedStatic.when(ApplicationContextHolder::getInstance).thenReturn(applicationContext);
mockedStatic.when(() -> ApplicationContextHolder.getBean(ThreadPoolCheckAlarm.class)).thenReturn(mockAlarmHandler);
Mockito.doNothing().when(mockAlarmHandler).asyncSendRejectedAlarm("test-pool");
handler.invoke(null, mockMethod, mockArgs);
Mockito.doThrow(new InvocationTargetException(new Throwable())).when(mockMethod).invoke(target, mockArgs);
Assertions.assertThrows(Throwable.class, () -> handler.invoke(null, mockMethod, mockArgs));
Assertions.assertSame(rejectCount.get(), 2L);
}
}

@ -1,56 +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.
*/
package cn.hippo4j.core.executor.state;
import cn.hippo4j.common.executor.ThreadPoolExecutorRegistry;
import cn.hippo4j.common.model.ThreadPoolRunStateInfo;
import cn.hippo4j.common.support.AbstractThreadPoolRuntime;
import cn.hippo4j.core.executor.DynamicThreadPoolExecutor;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@RunWith(MockitoJUnitRunner.class)
public class AbstractThreadPoolRuntimeTest {
@Test
public void testPoolRunState() {
AbstractThreadPoolRuntime threadPoolRuntime = new AbstractThreadPoolRuntime() {
@Override
public ThreadPoolRunStateInfo supplement(ThreadPoolRunStateInfo threadPoolRunStateInfo) {
return threadPoolRunStateInfo;
}
};
final String threadPoolId = "test";
DynamicThreadPoolExecutor executor = new DynamicThreadPoolExecutor(
1, 1, 1000L, TimeUnit.MILLISECONDS,
1000L, true, 1000L,
new ArrayBlockingQueue<>(1), threadPoolId, Thread::new, new ThreadPoolExecutor.DiscardOldestPolicy());
ThreadPoolExecutorRegistry.putHolder(threadPoolId, executor, null);
ThreadPoolRunStateInfo threadPoolRunStateInfo = threadPoolRuntime.getPoolRunState(threadPoolId);
Assertions.assertNotNull(threadPoolRunStateInfo);
threadPoolRunStateInfo = threadPoolRuntime.getPoolRunState(threadPoolId, executor);
Assertions.assertNotNull(threadPoolRunStateInfo);
}
}

@ -1,127 +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.
*/
package cn.hippo4j.core.executor.state;
import cn.hippo4j.common.executor.ThreadPoolExecutorHolder;
import cn.hippo4j.common.executor.ThreadPoolExecutorRegistry;
import cn.hippo4j.common.handler.ThreadPoolStatusHandler;
import cn.hippo4j.common.model.ManyThreadPoolRunStateInfo;
import cn.hippo4j.common.model.ThreadPoolRunStateInfo;
import cn.hippo4j.common.toolkit.BeanUtil;
import cn.hippo4j.common.toolkit.ByteConvertUtil;
import cn.hippo4j.common.toolkit.MemoryUtil;
import cn.hippo4j.common.toolkit.StringUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.env.ConfigurableEnvironment;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import static cn.hippo4j.core.toolkit.IdentifyUtil.CLIENT_IDENTIFICATION_VALUE;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class ThreadPoolRunStateHandlerTest {
@Mock
ConfigurableEnvironment environment;
ThreadPoolRunStateInfo poolRunStateInfo = new ThreadPoolRunStateInfo();
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
poolRunStateInfo.setCurrentLoad(poolRunStateInfo.getCurrentLoad() + "%");
poolRunStateInfo.setPeakLoad(poolRunStateInfo.getPeakLoad() + "%");
poolRunStateInfo.setTpId("1");
}
@Test
void testSupplement() {
long used = MemoryUtil.heapMemoryUsed();
long max = MemoryUtil.heapMemoryMax();
String memoryProportion = StringUtil.newBuilder(
"Allocation: ",
ByteConvertUtil.getPrintSize(used),
" / Maximum available: ",
ByteConvertUtil.getPrintSize(max));
String ipAddress = "127.0.0.1";
poolRunStateInfo.setHost(ipAddress);
poolRunStateInfo.setMemoryProportion(memoryProportion);
poolRunStateInfo.setFreeMemory(ByteConvertUtil.getPrintSize(Math.subtractExact(max, used)));
String threadPoolId = poolRunStateInfo.getTpId();
try (final MockedStatic<ThreadPoolExecutorRegistry> globalThreadPoolManage = mockStatic(ThreadPoolExecutorRegistry.class)) {
globalThreadPoolManage.when(() -> ThreadPoolExecutorRegistry.getHolder("1")).thenReturn(new ThreadPoolExecutorHolder());
ThreadPoolExecutorHolder executorHolder = ThreadPoolExecutorRegistry.getHolder(threadPoolId);
Assertions.assertNotNull(executorHolder);
}
ThreadPoolExecutorHolder threadPoolExecutorHolderMock = mock(ThreadPoolExecutorHolder.class);
when(threadPoolExecutorHolderMock.getExecutor()).thenReturn(new ThreadPoolExecutor(2, 2, 2000, TimeUnit.SECONDS, new SynchronousQueue<>()));
ThreadPoolExecutor pool = threadPoolExecutorHolderMock.getExecutor();
Assertions.assertNotNull(pool);
String rejectedName;
rejectedName = "java.util.concurrent.ThreadPoolExecutor.AbortPolicy";
poolRunStateInfo.setRejectedName(rejectedName);
ManyThreadPoolRunStateInfo manyThreadPoolRunStateInfo = BeanUtil.convert(poolRunStateInfo, ManyThreadPoolRunStateInfo.class);
manyThreadPoolRunStateInfo.setIdentify(CLIENT_IDENTIFICATION_VALUE);
String active = environment.getProperty("spring.profiles.active", "UNKNOWN");
manyThreadPoolRunStateInfo.setActive("TRUE");
String threadPoolState = ThreadPoolStatusHandler.getThreadPoolState(pool);
manyThreadPoolRunStateInfo.setState(threadPoolState);
Assertions.assertNotNull(manyThreadPoolRunStateInfo);
}
@Test
void testGetHeapMemory() {
try (MockedStatic<MemoryUtil> memoryUtil = mockStatic(MemoryUtil.class)) {
memoryUtil.when(MemoryUtil::heapMemoryUsed).thenReturn(57534464L);
memoryUtil.when(MemoryUtil::heapMemoryMax).thenReturn(8566865920L);
Assertions.assertEquals(8566865920L, MemoryUtil.heapMemoryMax());
Assertions.assertEquals(57534464L, MemoryUtil.heapMemoryUsed());
}
}
@Test
void testMemoryProportion() {
long used = 57534464L;
long max = 8566865920L;
String memoryProportion = StringUtil.newBuilder(
"Allocation: ",
ByteConvertUtil.getPrintSize(used),
" / Maximum available: ",
ByteConvertUtil.getPrintSize(max));
Assertions.assertEquals("Allocation: 54.87MB / Maximum available: 7.98GB", memoryProportion);
}
}

@ -1,98 +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.
*/
package cn.hippo4j.core.executor.support;
import cn.hippo4j.common.toolkit.ThreadUtil;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* test for {@link AbstractBuildThreadPoolTemplate}
*
* @author dmego
*/
public class AbstractBuildThreadPoolTemplateTest {
AbstractBuildThreadPoolTemplate.ThreadPoolInitParam initParam;
@Before
public void before() {
initParam = new AbstractBuildThreadPoolTemplate.ThreadPoolInitParam(Executors.defaultThreadFactory());
initParam.setCorePoolNum(1)
.setMaximumPoolSize(1)
.setKeepAliveTime(1000L)
.setCapacity(10)
.setExecuteTimeOut(5000L)
.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy())
.setWorkQueue(new LinkedBlockingQueue<>(1))
.setTimeUnit(TimeUnit.MILLISECONDS)
.setAllowCoreThreadTimeOut(false)
.setThreadPoolId("test")
.setTaskDecorator(runnable -> runnable);
}
@Test
public void testBuildPool() {
ThreadPoolExecutor executor = AbstractBuildThreadPoolTemplate.buildPool(initParam);
AtomicInteger count = new AtomicInteger(0);
executor.submit(() -> {
ThreadUtil.sleep(100L);
return count.incrementAndGet();
});
executor.submit(() -> {
ThreadUtil.sleep(100L);
count.incrementAndGet();
});
// waiting for shutdown
executor.shutdown();
while (!executor.isTerminated()) {
}
Assert.assertEquals(2, count.get());
}
@Test
public void testBuildDynamicPool() {
initParam.setWaitForTasksToCompleteOnShutdown(true);
initParam.setAwaitTerminationMillis(5000L);
ThreadPoolExecutor executor = AbstractBuildThreadPoolTemplate.buildDynamicPool(initParam);
AtomicInteger count = new AtomicInteger(0);
executor.submit(() -> {
ThreadUtil.sleep(100L);
return count.incrementAndGet();
});
executor.submit(() -> {
ThreadUtil.sleep(100L);
count.incrementAndGet();
});
// waiting for shutdown
executor.shutdown();
while (!executor.isTerminated()) {
}
Assert.assertEquals(2, count.get());
}
}

@ -1,84 +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.
*/
package cn.hippo4j.core.extension;
import cn.hippo4j.common.extension.spi.ServiceLoaderRegistry;
import cn.hippo4j.core.extension.anymatch.AnyMatchExtImplA;
import cn.hippo4j.core.extension.anymatch.AnyMatchExtImplB;
import cn.hippo4j.core.extension.anymatch.IAnyMatchExtension;
import cn.hippo4j.core.extension.firstof.FirstOfExtImplA;
import cn.hippo4j.core.extension.firstof.FirstOfExtImplB;
import cn.hippo4j.core.extension.firstof.IFirstOfExtension;
import cn.hippo4j.core.extension.reducer.Reducers;
import cn.hippo4j.core.extension.spi.IOldSpi;
import cn.hippo4j.core.extension.support.ExtensionInvoker;
import cn.hippo4j.core.extension.support.ExtensionRegistry;
import org.assertj.core.util.Lists;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.Objects;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ExtensionInvokerTest {
@Before
public void before() {
ExtensionRegistry.getInstance().register(new FirstOfExtImplA());
ExtensionRegistry.getInstance().register(new FirstOfExtImplB());
ExtensionRegistry.getInstance().register(new AnyMatchExtImplA());
ExtensionRegistry.getInstance().register(new AnyMatchExtImplB());
ServiceLoaderRegistry.register(IOldSpi.class);
}
@Test
public void test() {
Integer arg = 20;
// first-of
Integer res1 = ExtensionInvoker.reduceExecute(IFirstOfExtension.class, (ext) -> ext.foo(arg),
Reducers.firstOfNotNull());
assertEquals(arg, res1);
// any-match
Boolean res2 = ExtensionInvoker.reduceExecute(IAnyMatchExtension.class, (ext) -> ext.foo(arg),
Reducers.anyMatch(Objects::nonNull));
assertTrue(res2);
// none
List<Integer> res3 = ExtensionInvoker.reduceExecute(IFirstOfExtension.class, (ext) -> ext.foo(arg));
assertArrayEquals(res3.toArray(new Integer[0]), Lists.newArrayList(null, arg).toArray());
// all-match
Boolean res4 = ExtensionInvoker.reduceExecute(IAnyMatchExtension.class, (ext) -> ext.foo(arg),
Reducers.allMatch(Objects::nonNull));
assertTrue(res4);
}
@Test
public void test_spi_old() {
Boolean res1 = ExtensionInvoker.reduceExecute(IOldSpi.class, IOldSpi::foo, Reducers.firstOfNotNull());
assertTrue(res1);
}
}

@ -1,29 +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.
*/
package cn.hippo4j.core.extension.anymatch;
import cn.hippo4j.core.extension.annotation.Realization;
@Realization
public class AnyMatchExtImplA implements IAnyMatchExtension {
@Override
public Integer foo(Integer arg) {
return arg > 0 ? arg : null;
}
}

@ -1,29 +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.
*/
package cn.hippo4j.core.extension.anymatch;
import cn.hippo4j.core.extension.annotation.Realization;
@Realization
public class AnyMatchExtImplB implements IAnyMatchExtension {
@Override
public Integer foo(Integer arg) {
return arg > 0 ? arg : null;
}
}

@ -1,25 +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.
*/
package cn.hippo4j.core.extension.anymatch;
import cn.hippo4j.core.extension.IExtension;
public interface IAnyMatchExtension extends IExtension {
Integer foo(Integer arg);
}

@ -1,29 +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.
*/
package cn.hippo4j.core.extension.firstof;
import cn.hippo4j.core.extension.annotation.Realization;
@Realization
public class FirstOfExtImplA implements IFirstOfExtension {
@Override
public Integer foo(Integer arg) {
return null;
}
}

@ -1,29 +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.
*/
package cn.hippo4j.core.extension.firstof;
import cn.hippo4j.core.extension.annotation.Realization;
@Realization
public class FirstOfExtImplB implements IFirstOfExtension {
@Override
public Integer foo(Integer arg) {
return arg;
}
}

@ -1,25 +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.
*/
package cn.hippo4j.core.extension.firstof;
import cn.hippo4j.core.extension.IExtension;
public interface IFirstOfExtension extends IExtension {
Integer foo(Integer arg);
}

@ -1,25 +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.
*/
package cn.hippo4j.core.extension.spi;
import cn.hippo4j.core.extension.IExtension;
public interface IOldSpi extends IExtension {
Boolean foo();
}

@ -1,27 +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.
*/
package cn.hippo4j.core.extension.spi;
public class IOldSpiImplA implements IOldSpi {
@Override
public Boolean foo() {
System.out.println(this.getClass().getName());
return true;
}
}

@ -1,74 +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.
*/
package cn.hippo4j.core.spi;
import java.util.Collection;
import cn.hippo4j.common.extension.spi.ServiceLoaderRegistry;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertTrue;
/**
* test {@link ServiceLoaderRegistry}
*/
public final class DynamicThreadPoolServiceLoaderTest {
@Test
public void assertRegister() {
ServiceLoaderRegistry.register(Collection.class);
Collection<?> collections = ServiceLoaderRegistry.getSingletonServiceInstances(Collection.class);
assertTrue(collections.isEmpty());
}
@Test
public void assertGetSingletonServiceInstances() {
ServiceLoaderRegistry.register(TestSingletonInterfaceSPI.class);
Collection<TestSingletonInterfaceSPI> instances = ServiceLoaderRegistry.getSingletonServiceInstances(TestSingletonInterfaceSPI.class);
assertThat(instances.size(), equalTo(1));
assertThat(instances.iterator().next(), is(ServiceLoaderRegistry.getSingletonServiceInstances(TestSingletonInterfaceSPI.class).iterator().next()));
}
@Test
public void assertNewServiceInstances() {
ServiceLoaderRegistry.register(TestSingletonInterfaceSPI.class);
Collection<TestSingletonInterfaceSPI> instances = ServiceLoaderRegistry.newServiceInstances(TestSingletonInterfaceSPI.class);
assertThat(instances.size(), equalTo(1));
assertThat(instances.iterator().next(), not(ServiceLoaderRegistry.getSingletonServiceInstances(TestSingletonInterfaceSPI.class).iterator().next()));
}
@Test
public void assertGetServiceInstancesWhenIsSingleton() {
ServiceLoaderRegistry.register(TestSingletonInterfaceSPI.class);
Collection<TestSingletonInterfaceSPI> instances = ServiceLoaderRegistry.getServiceInstances(TestSingletonInterfaceSPI.class);
assertThat(instances.iterator().next(), is(ServiceLoaderRegistry.getSingletonServiceInstances(TestSingletonInterfaceSPI.class).iterator().next()));
}
@Test
public void assertGetServiceInstancesWhenNotSingleton() {
ServiceLoaderRegistry.register(TestInterfaceSPI.class);
Collection<TestInterfaceSPI> instances = ServiceLoaderRegistry.getServiceInstances(TestInterfaceSPI.class);
assertThat(instances.iterator().next(), not(ServiceLoaderRegistry.getSingletonServiceInstances(TestInterfaceSPI.class).iterator().next()));
}
}

@ -1,44 +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.
*/
package cn.hippo4j.core.spi;
import cn.hippo4j.common.executor.support.CustomBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* SPI whit generic type test.
*/
public class MyArrayBlockingQueue implements CustomBlockingQueue<Runnable> {
@Override
public Integer getType() {
return null;
}
@Override
public String getName() {
return this.getClass().getSimpleName();
}
@Override
public BlockingQueue<Runnable> generateBlockingQueue() {
return new LinkedBlockingQueue<>(20);
}
}

@ -1,26 +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.
*/
package cn.hippo4j.core.spi;
import cn.hippo4j.common.extension.spi.ServiceLoaderRegistry;
/**
* test {@link ServiceLoaderRegistry}
*/
public interface TestInterfaceSPI {
}

@ -1,26 +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.
*/
package cn.hippo4j.core.spi;
import cn.hippo4j.common.extension.spi.ServiceLoaderRegistry;
/**
* test {@link ServiceLoaderRegistry}
*/
public class TestInterfaceSPIImpl implements TestInterfaceSPI {
}

@ -1,28 +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.
*/
package cn.hippo4j.core.spi;
import cn.hippo4j.common.extension.spi.ServiceLoaderRegistry;
import cn.hippo4j.common.extension.spi.SingletonSPI;
/**
* test {@link ServiceLoaderRegistry}
*/
@SingletonSPI
public interface TestSingletonInterfaceSPI {
}

@ -1,26 +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.
*/
package cn.hippo4j.core.spi;
import cn.hippo4j.common.extension.spi.ServiceLoaderRegistry;
/**
* test {@link ServiceLoaderRegistry}
*/
public class TestSingletonInterfaceSPIImpl implements TestSingletonInterfaceSPI {
}

@ -1,52 +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.
*/
package cn.hippo4j.core.toolkit;
import org.junit.Assert;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class FileUtilTest {
@Test
public void assertReadUtf8String() {
String testFilePath = "test/test_utf8.txt";
String contentByFileUtil = FileUtil.readUtf8String(testFilePath);
Assert.assertFalse(contentByFileUtil.isEmpty());
}
@Test
public void assertReadUtf8String2() {
String linebreaks = System.getProperty("line.separator");
String testText = "abcd简体繁体\uD83D\uDE04\uD83D\uDD25& *" + linebreaks +
"second line" + linebreaks +
"empty line next" + linebreaks;
String testFilePath = "test/test_utf8.txt";
String contentByFileUtil = FileUtil.readUtf8String(testFilePath);
Assert.assertTrue(testText.equals(contentByFileUtil));
}
@Test
public void assertReadLines() {
String testFilePath = "test/test_utf8.txt";
List<String> readLines = FileUtil.readLines(testFilePath, StandardCharsets.UTF_8);
Assert.assertEquals(3, readLines.size());
}
}

@ -22,7 +22,6 @@ import cn.hippo4j.common.model.ThreadPoolRunStateInfo;
import cn.hippo4j.core.executor.state.ThreadPoolRunStateHandler;
import cn.hippo4j.threadpool.monitor.api.DynamicThreadPoolMonitor;
import javax.annotation.Resource;
import java.util.List;
/**

@ -20,8 +20,7 @@ package cn.hippo4j.monitor.base;
import cn.hippo4j.adapter.web.WebThreadPoolService;
import cn.hippo4j.common.model.ThreadPoolRunStateInfo;
import cn.hippo4j.threadpool.monitor.api.WebThreadPoolMonitor;
import javax.annotation.Resource;
import jakarta.annotation.Resource;
/**
* Abstract web thread-pool monitor.

@ -28,8 +28,8 @@
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>

@ -23,26 +23,27 @@ import cn.hippo4j.auth.filter.JWTAuthorizationFilter;
import cn.hippo4j.auth.filter.LdapAuthenticationFilter;
import cn.hippo4j.auth.security.JwtTokenManager;
import cn.hippo4j.auth.service.impl.UserDetailsServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import javax.annotation.Resource;
import java.util.stream.Stream;
/**
@ -51,7 +52,7 @@ import java.util.stream.Stream;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class GlobalSecurityConfig extends WebSecurityConfigurerAdapter {
public class GlobalSecurityConfig {
@Value("${hippo4j.core.auth.enabled:true}")
private Boolean enableAuthentication;
@ -65,6 +66,8 @@ public class GlobalSecurityConfig extends WebSecurityConfigurerAdapter {
@Resource
private JwtTokenManager tokenManager;
private AuthenticationConfiguration authenticationConfiguration;
@Bean
public UserDetailsService customUserService() {
return new UserDetailsServiceImpl();
@ -76,9 +79,10 @@ public class GlobalSecurityConfig extends WebSecurityConfigurerAdapter {
}
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
@Autowired
public AuthenticationManager authenticationManagerBean(AuthenticationConfiguration authenticationConfiguration) throws Exception {
this.authenticationConfiguration = authenticationConfiguration;
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
@ -91,39 +95,43 @@ public class GlobalSecurityConfig extends WebSecurityConfigurerAdapter {
return source;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/static/**", "/index.html", "/favicon.ico", "/avatar.jpg").permitAll()
.antMatchers("/doc.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs").anonymous()
.requestMatchers("/static/**", "/index.html", "/favicon.ico", "/avatar.jpg").permitAll()
.requestMatchers("/doc.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs").anonymous()
.and()
.authenticationProvider(authenticationProvider())
.authenticationProvider(ldapAuthenticationProvider())
// .addFilter(new JWTAuthenticationFilter(authenticationManager())).authenticationProvider(authenticationProvider())
.addFilter(JWTAuthenticationFilter()).authenticationProvider(ldapAuthenticationProvider())
.addFilter(LdapAuthenticationFilter()).authenticationProvider(ldapAuthenticationProvider())
.addFilter(new JWTAuthorizationFilter(tokenManager, authenticationManager()))
.addFilter(new JWTAuthorizationFilter(tokenManager, authenticationManagerBean(authenticationConfiguration)))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
disableAuthenticationIfNeeded(http);
http.authorizeRequests().anyRequest().authenticated();
return http.build();
}
@Override
public void configure(WebSecurity web) throws Exception {
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
String[] ignores = Stream.of("/hippo4j/v1/cs/auth/users/apply/token/**").toArray(String[]::new);
web.ignoring().antMatchers(ignores);
return (web) -> web.ignoring().requestMatchers(ignores);
}
private LdapAuthenticationFilter LdapAuthenticationFilter() throws Exception {
LdapAuthenticationFilter filter = new LdapAuthenticationFilter(authenticationManager());
LdapAuthenticationFilter filter = new LdapAuthenticationFilter(authenticationManagerBean(authenticationConfiguration));
filter.setLdapUserDetailsService(ldapUserDetailsService);
filter.setAuthenticationManager(authenticationManagerBean());
filter.setAuthenticationManager(authenticationManagerBean(authenticationConfiguration));
return filter;
}
private JWTAuthenticationFilter JWTAuthenticationFilter() throws Exception {
JWTAuthenticationFilter filter = new JWTAuthenticationFilter(authenticationManager());
JWTAuthenticationFilter filter = new JWTAuthenticationFilter(authenticationManagerBean(authenticationConfiguration));
filter.setLdapUserDetailsService(userDetailsService);
filter.setAuthenticationManager(authenticationManagerBean());
filter.setAuthenticationManager(authenticationManagerBean(authenticationConfiguration));
return filter;
}
@ -149,15 +157,9 @@ public class GlobalSecurityConfig extends WebSecurityConfigurerAdapter {
return authProvider;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider())
.authenticationProvider(ldapAuthenticationProvider());
}
private void disableAuthenticationIfNeeded(HttpSecurity http) throws Exception {
if (Boolean.FALSE.equals(enableAuthentication)) {
http.authorizeRequests().antMatchers("/hippo4j/v1/cs/**").permitAll();
http.authorizeRequests().requestMatchers("/hippo4j/v1/cs/**").permitAll();
}
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save