index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/status | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReportServiceTest.java | /*
* 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 org.apache.dubbo.common.status.reporter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTER_MODE_INSTANCE;
import static org.apache.dubbo.common.status.reporter.FrameworkStatusReportService.ADDRESS_CONSUMPTION_STATUS;
import static org.apache.dubbo.common.status.reporter.FrameworkStatusReportService.MIGRATION_STEP_STATUS;
import static org.apache.dubbo.common.status.reporter.FrameworkStatusReportService.REGISTRATION_STATUS;
/**
* {@link FrameworkStatusReportService}
*/
class FrameworkStatusReportServiceTest {
@Test
void test() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ApplicationConfig app = new ApplicationConfig("APP");
applicationModel.getApplicationConfigManager().setApplication(app);
FrameworkStatusReportService reportService =
applicationModel.getBeanFactory().getBean(FrameworkStatusReportService.class);
// 1. reportRegistrationStatus
reportService.reportRegistrationStatus(reportService.createRegistrationReport(DEFAULT_REGISTER_MODE_INSTANCE));
// 2. createConsumptionReport
URL consumerURL = Mockito.mock(URL.class);
Mockito.when(consumerURL.getServiceInterface()).thenReturn("Test");
Mockito.when(consumerURL.getGroup()).thenReturn("Group");
Mockito.when(consumerURL.getVersion()).thenReturn("0.0.0");
Mockito.when(consumerURL.getServiceKey()).thenReturn("Group/Test:0.0.0");
Mockito.when(consumerURL.getDisplayServiceKey()).thenReturn("Test:0.0.0");
reportService.reportConsumptionStatus(reportService.createConsumptionReport(
consumerURL.getServiceInterface(), consumerURL.getVersion(), consumerURL.getGroup(), "status"));
// 3. reportMigrationStepStatus
reportService.reportMigrationStepStatus(reportService.createMigrationStepReport(
consumerURL.getServiceInterface(),
consumerURL.getVersion(),
consumerURL.getGroup(),
"FORCE_INTERFACE",
"FORCE_APPLICATION",
"ture"));
MockFrameworkStatusReporter statusReporter =
(MockFrameworkStatusReporter) applicationModel.getExtension(FrameworkStatusReporter.class, "mock");
// "migrationStepStatus" ->
// "{"originStep":"FORCE_INTERFACE","application":"APP","service":"Test","success":"ture","newStep":"FORCE_APPLICATION","type":"migrationStepStatus","version":"0.0.0","group":"Group"}"
// "registration" -> "{"application":"APP","status":"instance"}"
// "consumption" ->
// "{"application":"APP","service":"Test","type":"consumption","version":"0.0.0","group":"Group","status":"status"}"
Map<String, Object> reportContent = statusReporter.getReportContent();
Assertions.assertEquals(reportContent.size(), 3);
// verify registrationStatus
Object registrationStatus = reportContent.get(REGISTRATION_STATUS);
Map<String, String> registrationMap = JsonUtils.toJavaObject(String.valueOf(registrationStatus), Map.class);
Assertions.assertEquals(registrationMap.get("application"), "APP");
Assertions.assertEquals(registrationMap.get("status"), "instance");
// verify addressConsumptionStatus
Object addressConsumptionStatus = reportContent.get(ADDRESS_CONSUMPTION_STATUS);
Map<String, String> consumptionMap =
JsonUtils.toJavaObject(String.valueOf(addressConsumptionStatus), Map.class);
Assertions.assertEquals(consumptionMap.get("application"), "APP");
Assertions.assertEquals(consumptionMap.get("service"), "Test");
Assertions.assertEquals(consumptionMap.get("status"), "status");
Assertions.assertEquals(consumptionMap.get("type"), "consumption");
Assertions.assertEquals(consumptionMap.get("version"), "0.0.0");
Assertions.assertEquals(consumptionMap.get("group"), "Group");
// verify migrationStepStatus
Object migrationStepStatus = reportContent.get(MIGRATION_STEP_STATUS);
Map<String, String> migrationStepStatusMap =
JsonUtils.toJavaObject(String.valueOf(migrationStepStatus), Map.class);
Assertions.assertEquals(migrationStepStatusMap.get("originStep"), "FORCE_INTERFACE");
Assertions.assertEquals(migrationStepStatusMap.get("application"), "APP");
Assertions.assertEquals(migrationStepStatusMap.get("service"), "Test");
Assertions.assertEquals(migrationStepStatusMap.get("success"), "ture");
Assertions.assertEquals(migrationStepStatusMap.get("newStep"), "FORCE_APPLICATION");
Assertions.assertEquals(migrationStepStatusMap.get("type"), "migrationStepStatus");
Assertions.assertEquals(migrationStepStatusMap.get("version"), "0.0.0");
Assertions.assertEquals(migrationStepStatusMap.get("group"), "Group");
frameworkModel.destroy();
}
}
| 6,500 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/status | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/StatusUtilsTest.java | /*
* 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 org.apache.dubbo.common.status.support;
import org.apache.dubbo.common.status.Status;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.not;
class StatusUtilsTest {
@Test
void testGetSummaryStatus1() throws Exception {
Status status1 = new Status(Status.Level.ERROR);
Status status2 = new Status(Status.Level.WARN);
Status status3 = new Status(Status.Level.OK);
Map<String, Status> statuses = new HashMap<String, Status>();
statuses.put("status1", status1);
statuses.put("status2", status2);
statuses.put("status3", status3);
Status status = StatusUtils.getSummaryStatus(statuses);
assertThat(status.getLevel(), is(Status.Level.ERROR));
assertThat(status.getMessage(), containsString("status1"));
assertThat(status.getMessage(), containsString("status2"));
assertThat(status.getMessage(), not(containsString("status3")));
}
@Test
void testGetSummaryStatus2() throws Exception {
Status status1 = new Status(Status.Level.WARN);
Status status2 = new Status(Status.Level.OK);
Map<String, Status> statuses = new HashMap<String, Status>();
statuses.put("status1", status1);
statuses.put("status2", status2);
Status status = StatusUtils.getSummaryStatus(statuses);
assertThat(status.getLevel(), is(Status.Level.WARN));
assertThat(status.getMessage(), containsString("status1"));
assertThat(status.getMessage(), not(containsString("status2")));
}
@Test
void testGetSummaryStatus3() throws Exception {
Status status1 = new Status(Status.Level.OK);
Map<String, Status> statuses = new HashMap<String, Status>();
statuses.put("status1", status1);
Status status = StatusUtils.getSummaryStatus(statuses);
assertThat(status.getLevel(), is(Status.Level.OK));
assertThat(status.getMessage(), isEmptyOrNullString());
}
}
| 6,501 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/status | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/MemoryStatusCheckerTest.java | /*
* 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 org.apache.dubbo.common.status.support;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.status.Status;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.status.Status.Level.OK;
import static org.apache.dubbo.common.status.Status.Level.WARN;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
class MemoryStatusCheckerTest {
private static final Logger logger = LoggerFactory.getLogger(MemoryStatusCheckerTest.class);
@Test
void test() {
MemoryStatusChecker statusChecker = new MemoryStatusChecker();
Status status = statusChecker.check();
assertThat(status.getLevel(), anyOf(is(OK), is(WARN)));
logger.info("memory status level: " + status.getLevel());
logger.info("memory status message: " + status.getMessage());
}
}
| 6,502 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/status | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/LoadStatusCheckerTest.java | /*
* 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 org.apache.dubbo.common.status.support;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.status.Status;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
class LoadStatusCheckerTest {
private static Logger logger = LoggerFactory.getLogger(LoadStatusCheckerTest.class);
@Test
void test() {
LoadStatusChecker statusChecker = new LoadStatusChecker();
Status status = statusChecker.check();
assertThat(status, notNullValue());
logger.info("load status level: " + status.getLevel());
logger.info("load status message: " + status.getMessage());
}
}
| 6,503 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/function/StreamsTest.java | /*
* 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 org.apache.dubbo.common.function;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static org.apache.dubbo.common.function.Streams.filterList;
import static org.apache.dubbo.common.function.Streams.filterSet;
import static org.apache.dubbo.common.function.Streams.filterStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link Streams} Test
*
* @since 2.7.5
*/
class StreamsTest {
@Test
void testFilterStream() {
Stream<Integer> stream = filterStream(asList(1, 2, 3, 4, 5), i -> i % 2 == 0);
assertEquals(asList(2, 4), stream.collect(toList()));
}
@Test
void testFilterList() {
List<Integer> list = filterList(asList(1, 2, 3, 4, 5), i -> i % 2 == 0);
assertEquals(asList(2, 4), list);
}
@Test
void testFilterSet() {
Set<Integer> set = filterSet(asList(1, 2, 3, 4, 5), i -> i % 2 == 0);
assertEquals(new LinkedHashSet<>(asList(2, 4)), set);
}
}
| 6,504 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableActionTest.java | /*
* 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 org.apache.dubbo.common.function;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.function.ThrowableAction.execute;
/**
* {@link ThrowableAction} Test
*
* @since 2.7.5
*/
class ThrowableActionTest {
@Test
void testExecute() {
Assertions.assertThrows(
RuntimeException.class,
() -> execute(() -> {
throw new Exception("Test");
}),
"Test");
}
}
| 6,505 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/function/PredicatesTest.java | /*
* 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 org.apache.dubbo.common.function;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.function.Predicates.alwaysFalse;
import static org.apache.dubbo.common.function.Predicates.alwaysTrue;
import static org.apache.dubbo.common.function.Predicates.and;
import static org.apache.dubbo.common.function.Predicates.or;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link Predicates} Test
*
* @since 2.7.5
*/
class PredicatesTest {
@Test
void testAlwaysTrue() {
assertTrue(alwaysTrue().test(null));
}
@Test
void testAlwaysFalse() {
assertFalse(alwaysFalse().test(null));
}
@Test
void testAnd() {
assertTrue(and(alwaysTrue(), alwaysTrue(), alwaysTrue()).test(null));
assertFalse(and(alwaysFalse(), alwaysFalse(), alwaysFalse()).test(null));
assertFalse(and(alwaysTrue(), alwaysFalse(), alwaysFalse()).test(null));
assertFalse(and(alwaysTrue(), alwaysTrue(), alwaysFalse()).test(null));
}
@Test
void testOr() {
assertTrue(or(alwaysTrue(), alwaysTrue(), alwaysTrue()).test(null));
assertTrue(or(alwaysTrue(), alwaysTrue(), alwaysFalse()).test(null));
assertTrue(or(alwaysTrue(), alwaysFalse(), alwaysFalse()).test(null));
assertFalse(or(alwaysFalse(), alwaysFalse(), alwaysFalse()).test(null));
}
}
| 6,506 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableConsumerTest.java | /*
* 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 org.apache.dubbo.common.function;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.function.ThrowableConsumer.execute;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* {@link ThrowableConsumer} Test
*
* @since 2.7.5
*/
class ThrowableConsumerTest {
@Test
void testExecute() {
assertThrows(
RuntimeException.class,
() -> execute("Hello,World", m -> {
throw new Exception(m);
}),
"Hello,World");
}
}
| 6,507 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableFunctionTest.java | /*
* 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 org.apache.dubbo.common.function;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.function.ThrowableConsumer.execute;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* {@link ThrowableFunction} Test
*
* @since 2.7.5
*/
class ThrowableFunctionTest {
@Test
void testExecute() {
assertThrows(
RuntimeException.class,
() -> execute("Hello,World", m -> {
throw new Exception(m);
}),
"Hello,World");
}
}
| 6,508 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemoryLimitedLinkedBlockingQueueTest.java | /*
* 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 org.apache.dubbo.common.threadpool;
import java.lang.instrument.Instrumentation;
import net.bytebuddy.agent.ByteBuddyAgent;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
class MemoryLimitedLinkedBlockingQueueTest {
@Test
void test() {
ByteBuddyAgent.install();
final Instrumentation instrumentation = ByteBuddyAgent.getInstrumentation();
MemoryLimitedLinkedBlockingQueue<Runnable> queue = new MemoryLimitedLinkedBlockingQueue<>(1, instrumentation);
// an object needs more than 1 byte of space, so it will fail here
assertThat(queue.offer(() -> System.out.println("add fail")), is(false));
// will success
queue.setMemoryLimit(Integer.MAX_VALUE);
assertThat(queue.offer(() -> System.out.println("add success")), is(true));
}
}
| 6,509 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/ThreadlessExecutorTest.java | /*
* 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 org.apache.dubbo.common.threadpool;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class ThreadlessExecutorTest {
private static final ThreadlessExecutor executor;
static {
executor = new ThreadlessExecutor();
}
@Test
void test() throws InterruptedException {
for (int i = 0; i < 10; i++) {
executor.execute(() -> {
throw new RuntimeException("test");
});
}
executor.waitAndDrain(123);
AtomicBoolean invoked = new AtomicBoolean(false);
executor.execute(() -> {
invoked.set(true);
});
executor.waitAndDrain(123);
Assertions.assertTrue(invoked.get());
executor.shutdown();
}
}
| 6,510 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueueTest.java | /*
* 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 org.apache.dubbo.common.threadpool;
import org.apache.dubbo.common.concurrent.AbortPolicy;
import org.apache.dubbo.common.concurrent.RejectException;
import java.lang.instrument.Instrumentation;
import java.util.concurrent.LinkedBlockingQueue;
import net.bytebuddy.agent.ByteBuddyAgent;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;
class MemorySafeLinkedBlockingQueueTest {
@Test
void test() {
ByteBuddyAgent.install();
final Instrumentation instrumentation = ByteBuddyAgent.getInstrumentation();
final long objectSize = instrumentation.getObjectSize((Runnable) () -> {});
long maxFreeMemory = (long) MemoryLimitCalculator.maxAvailable();
MemorySafeLinkedBlockingQueue<Runnable> queue = new MemorySafeLinkedBlockingQueue<>(maxFreeMemory);
// all memory is reserved for JVM, so it will fail here
assertThat(queue.offer(() -> {}), is(false));
// maxFreeMemory-objectSize Byte memory is reserved for the JVM, so this will succeed
queue.setMaxFreeMemory((int) (MemoryLimitCalculator.maxAvailable() - objectSize));
assertThat(queue.offer(() -> {}), is(true));
}
@Test
void testCustomReject() {
MemorySafeLinkedBlockingQueue<Runnable> queue = new MemorySafeLinkedBlockingQueue<>(Long.MAX_VALUE);
queue.setRejector(new AbortPolicy<>());
assertThrows(RejectException.class, () -> queue.offer(() -> {}));
}
@Test
@Disabled("This test is not stable, it may fail due to performance (C1, C2)")
void testEfficiency() throws InterruptedException {
// if length is vert large(unit test may runs for a long time), so you may need to modify JVM param such as :
// -Xms=1024m -Xmx=2048m
// if you want to test efficiency of MemorySafeLinkedBlockingQueue, you may modify following param: length and
// times
int length = 1000, times = 1;
// LinkedBlockingQueue insert Integer: 500W * 20 times
long spent1 = spend(new LinkedBlockingQueue<>(), length, times);
// MemorySafeLinkedBlockingQueue insert Integer: 500W * 20 times
long spent2 = spend(newMemorySafeLinkedBlockingQueue(), length, times);
System.gc();
System.out.println(String.format(
"LinkedBlockingQueue spent %s millis, MemorySafeLinkedBlockingQueue spent %s millis", spent1, spent2));
// efficiency between LinkedBlockingQueue and MemorySafeLinkedBlockingQueue is very nearly the same
Assertions.assertTrue(spent1 - spent2 <= 1);
}
private static long spend(LinkedBlockingQueue<Integer> lbq, int length, int times) throws InterruptedException {
// new Queue
if (lbq instanceof MemorySafeLinkedBlockingQueue) {
lbq = newMemorySafeLinkedBlockingQueue();
} else {
lbq = new LinkedBlockingQueue<>();
}
long total = 0L;
for (int i = 0; i < times; i++) {
long start = System.currentTimeMillis();
for (int j = 0; j < length; j++) {
lbq.offer(j);
}
long end = System.currentTimeMillis();
long spent = end - start;
total += spent;
}
long result = total / times;
// gc
System.gc();
return result;
}
private static MemorySafeLinkedBlockingQueue<Integer> newMemorySafeLinkedBlockingQueue() {
ByteBuddyAgent.install();
final Instrumentation instrumentation = ByteBuddyAgent.getInstrumentation();
final long objectSize = instrumentation.getObjectSize((Runnable) () -> {});
int maxFreeMemory = (int) MemoryLimitCalculator.maxAvailable();
MemorySafeLinkedBlockingQueue<Integer> queue = new MemorySafeLinkedBlockingQueue<>(maxFreeMemory);
queue.setMaxFreeMemory((int) (MemoryLimitCalculator.maxAvailable() - objectSize));
queue.setRejector(new AbortPolicy<>());
return queue;
}
}
| 6,511 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepositoryTest.java | /*
* 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 org.apache.dubbo.common.threadpool.manager;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.awaitility.Awaitility.await;
class FrameworkExecutorRepositoryTest {
private FrameworkModel frameworkModel;
private FrameworkExecutorRepository frameworkExecutorRepository;
@BeforeEach
public void setup() {
frameworkModel = new FrameworkModel();
frameworkExecutorRepository = frameworkModel.getBeanFactory().getBean(FrameworkExecutorRepository.class);
}
@AfterEach
public void teardown() {
frameworkModel.destroy();
}
@Test
void testGetExecutor() {
Assertions.assertNotNull(frameworkExecutorRepository.getSharedExecutor());
frameworkExecutorRepository.nextScheduledExecutor();
}
@Test
void testSharedExecutor() throws Exception {
ExecutorService sharedExecutor = frameworkExecutorRepository.getSharedExecutor();
CountDownLatch latch = new CountDownLatch(3);
CountDownLatch latch1 = new CountDownLatch(1);
sharedExecutor.execute(() -> {
latch.countDown();
try {
latch1.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
sharedExecutor.execute(() -> {
latch.countDown();
try {
latch1.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
sharedExecutor.submit(() -> {
latch.countDown();
try {
latch1.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
await().until(() -> latch.getCount() == 0);
Assertions.assertEquals(3, ((ThreadPoolExecutor) sharedExecutor).getActiveCount());
latch1.countDown();
await().until(() -> ((ThreadPoolExecutor) sharedExecutor).getActiveCount() == 0);
Assertions.assertEquals(3, ((ThreadPoolExecutor) sharedExecutor).getCompletedTaskCount());
}
}
| 6,512 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepositoryTest.java | /*
* 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 org.apache.dubbo.common.threadpool.manager;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.awaitility.Awaitility.await;
class ExecutorRepositoryTest {
private ApplicationModel applicationModel;
private ExecutorRepository executorRepository;
@BeforeEach
public void setup() {
applicationModel = FrameworkModel.defaultModel().newApplication();
executorRepository = ExecutorRepository.getInstance(applicationModel);
}
@AfterEach
public void teardown() {
applicationModel.destroy();
}
@Test
void testGetExecutor() {
testGet(URL.valueOf("dubbo://127.0.0.1:23456/TestService"));
testGet(URL.valueOf("dubbo://127.0.0.1:23456/TestService?side=consumer"));
Assertions.assertNotNull(executorRepository.getSharedExecutor());
Assertions.assertNotNull(executorRepository.getServiceExportExecutor());
Assertions.assertNotNull(executorRepository.getServiceReferExecutor());
executorRepository.nextScheduledExecutor();
}
private void testGet(URL url) {
ExecutorService executorService = executorRepository.createExecutorIfAbsent(url);
executorService.shutdown();
executorService = executorRepository.createExecutorIfAbsent(url);
Assertions.assertFalse(executorService.isShutdown());
Assertions.assertEquals(executorService, executorRepository.getExecutor(url));
executorService.shutdown();
Assertions.assertNotEquals(executorService, executorRepository.getExecutor(url));
}
@Test
void testUpdateExecutor() {
URL url = URL.valueOf("dubbo://127.0.0.1:23456/TestService?threads=5");
ThreadPoolExecutor executorService = (ThreadPoolExecutor) executorRepository.createExecutorIfAbsent(url);
executorService.setCorePoolSize(3);
executorRepository.updateThreadpool(url, executorService);
executorService.setCorePoolSize(3);
executorService.setMaximumPoolSize(3);
executorRepository.updateThreadpool(url, executorService);
executorService.setMaximumPoolSize(20);
executorService.setCorePoolSize(10);
executorRepository.updateThreadpool(url, executorService);
executorService.setCorePoolSize(10);
executorService.setMaximumPoolSize(10);
executorRepository.updateThreadpool(url, executorService);
executorService.setCorePoolSize(5);
executorRepository.updateThreadpool(url, executorService);
}
@Test
void testSharedExecutor() throws Exception {
ExecutorService sharedExecutor = executorRepository.getSharedExecutor();
CountDownLatch latch = new CountDownLatch(3);
CountDownLatch latch1 = new CountDownLatch(1);
sharedExecutor.execute(() -> {
latch.countDown();
try {
latch1.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
sharedExecutor.execute(() -> {
latch.countDown();
try {
latch1.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
sharedExecutor.submit(() -> {
latch.countDown();
try {
latch1.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
await().until(() -> latch.getCount() == 0);
Assertions.assertEquals(3, ((ThreadPoolExecutor) sharedExecutor).getActiveCount());
latch1.countDown();
await().until(() -> ((ThreadPoolExecutor) sharedExecutor).getActiveCount() == 0);
Assertions.assertEquals(3, ((ThreadPoolExecutor) sharedExecutor).getCompletedTaskCount());
}
}
| 6,513 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReportTest.java | /*
* 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 org.apache.dubbo.common.threadpool.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedEvent;
import org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedListener;
import java.io.FileOutputStream;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.OS_NAME_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.OS_WIN_PREFIX;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
class AbortPolicyWithReportTest {
@Test
void jStackDumpTest() {
URL url = URL.valueOf(
"dubbo://admin:hello1234@10.20.130.230:20880/context/path?dump.directory=/tmp&version=1.0.0&application=morgan&noValue=");
AtomicReference<FileOutputStream> fileOutputStream = new AtomicReference<>();
AbortPolicyWithReport abortPolicyWithReport = new AbortPolicyWithReport("Test", url) {
@Override
protected void jstack(FileOutputStream jStackStream) {
fileOutputStream.set(jStackStream);
}
};
ExecutorService executorService = Executors.newFixedThreadPool(1);
AbortPolicyWithReport.lastPrintTime = 0;
Assertions.assertThrows(RejectedExecutionException.class, () -> {
abortPolicyWithReport.rejectedExecution(
() -> System.out.println("hello"), (ThreadPoolExecutor) executorService);
});
await().until(() -> AbortPolicyWithReport.guard.availablePermits() == 1);
Assertions.assertNotNull(fileOutputStream.get());
}
@Test
void jStackDumpTest_dumpDirectoryNotExists_cannotBeCreatedTakeUserHome() {
final String dumpDirectory = dumpDirectoryCannotBeCreated();
URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?dump.directory="
+ dumpDirectory
+ "&version=1.0.0&application=morgan&noValue=true");
AbortPolicyWithReport abortPolicyWithReport = new AbortPolicyWithReport("Test", url);
Assertions.assertEquals(System.getProperty("user.home"), abortPolicyWithReport.getDumpPath());
}
private String dumpDirectoryCannotBeCreated() {
final String os = System.getProperty(OS_NAME_KEY).toLowerCase();
if (os.contains(OS_WIN_PREFIX)) {
// "con" is one of Windows reserved names,
// https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
return "con";
} else {
return "/dev/full/" + UUID.randomUUID().toString();
}
}
@Test
void jStackDumpTest_dumpDirectoryNotExists_canBeCreated() {
final String dumpDirectory = UUID.randomUUID().toString();
URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?dump.directory="
+ dumpDirectory
+ "&version=1.0.0&application=morgan&noValue=true");
AbortPolicyWithReport abortPolicyWithReport = new AbortPolicyWithReport("Test", url);
Assertions.assertNotEquals(System.getProperty("user.home"), abortPolicyWithReport.getDumpPath());
}
@Test
void test_dispatchThreadPoolExhaustedEvent() {
URL url = URL.valueOf(
"dubbo://admin:hello1234@10.20.130.230:20880/context/path?dump.directory=/tmp&version=1.0.0&application=morgan&noValue=");
AbortPolicyWithReport abortPolicyWithReport = new AbortPolicyWithReport("Test", url);
String msg =
"Thread pool is EXHAUSTED! Thread Name: DubboServerHandler-127.0.0.1:12345, Pool Size: 1 (active: 0, core: 1, max: 1, largest: 1), Task: 6 (completed: 6), Executor status:(isShutdown:false, isTerminated:false, isTerminating:false), in dubbo://127.0.0.1:12345!, dubbo version: 2.7.3, current host: 127.0.0.1";
MyListener listener = new MyListener();
abortPolicyWithReport.addThreadPoolExhaustedEventListener(listener);
abortPolicyWithReport.dispatchThreadPoolExhaustedEvent(msg);
assertEquals(listener.getThreadPoolExhaustedEvent().getMsg(), msg);
}
static class MyListener implements ThreadPoolExhaustedListener {
private ThreadPoolExhaustedEvent threadPoolExhaustedEvent;
@Override
public void onEvent(ThreadPoolExhaustedEvent event) {
this.threadPoolExhaustedEvent = event;
}
public ThreadPoolExhaustedEvent getThreadPoolExhaustedEvent() {
return threadPoolExhaustedEvent;
}
}
}
| 6,514 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPoolTest.java | /*
* 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 org.apache.dubbo.common.threadpool.support.cached;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadlocal.InternalThread;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
class CachedThreadPoolTest {
@Test
void getExecutor1() throws Exception {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY
+ "=demo&" + CORE_THREADS_KEY
+ "=1&" + THREADS_KEY
+ "=2&" + ALIVE_KEY
+ "=1000&" + QUEUES_KEY
+ "=0");
ThreadPool threadPool = new CachedThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor.getCorePoolSize(), is(1));
assertThat(executor.getMaximumPoolSize(), is(2));
assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(SynchronousQueue.class));
assertThat(
executor.getRejectedExecutionHandler(),
Matchers.<RejectedExecutionHandler>instanceOf(AbortPolicyWithReport.class));
final CountDownLatch latch = new CountDownLatch(1);
executor.execute(() -> {
Thread thread = Thread.currentThread();
assertThat(thread, instanceOf(InternalThread.class));
assertThat(thread.getName(), startsWith("demo"));
latch.countDown();
});
latch.await();
assertThat(latch.getCount(), is(0L));
}
@Test
void getExecutor2() {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + QUEUES_KEY + "=1");
ThreadPool threadPool = new CachedThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(LinkedBlockingQueue.class));
}
}
| 6,515 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPoolTest.java | /*
* 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 org.apache.dubbo.common.threadpool.support.fixed;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadlocal.InternalThread;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
class FixedThreadPoolTest {
@Test
void getExecutor1() throws Exception {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY
+ "=demo&" + CORE_THREADS_KEY
+ "=1&" + THREADS_KEY
+ "=2&" + QUEUES_KEY
+ "=0");
ThreadPool threadPool = new FixedThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor.getCorePoolSize(), is(2));
assertThat(executor.getMaximumPoolSize(), is(2));
assertThat(executor.getKeepAliveTime(TimeUnit.MILLISECONDS), is(0L));
assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(SynchronousQueue.class));
assertThat(
executor.getRejectedExecutionHandler(),
Matchers.<RejectedExecutionHandler>instanceOf(AbortPolicyWithReport.class));
final CountDownLatch latch = new CountDownLatch(1);
executor.execute(new Runnable() {
@Override
public void run() {
Thread thread = Thread.currentThread();
assertThat(thread, instanceOf(InternalThread.class));
assertThat(thread.getName(), startsWith("demo"));
latch.countDown();
}
});
latch.await();
assertThat(latch.getCount(), is(0L));
}
@Test
void getExecutor2() throws Exception {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + QUEUES_KEY + "=1");
ThreadPool threadPool = new FixedThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(LinkedBlockingQueue.class));
}
}
| 6,516 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPoolTest.java | /*
* 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 org.apache.dubbo.common.threadpool.support.limited;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadlocal.InternalThread;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
class LimitedThreadPoolTest {
@Test
void getExecutor1() throws Exception {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY
+ "=demo&" + CORE_THREADS_KEY
+ "=1&" + THREADS_KEY
+ "=2&" + QUEUES_KEY
+ "=0");
ThreadPool threadPool = new LimitedThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor.getCorePoolSize(), is(1));
assertThat(executor.getMaximumPoolSize(), is(2));
assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(SynchronousQueue.class));
assertThat(
executor.getRejectedExecutionHandler(),
Matchers.<RejectedExecutionHandler>instanceOf(AbortPolicyWithReport.class));
final CountDownLatch latch = new CountDownLatch(1);
executor.execute(new Runnable() {
@Override
public void run() {
Thread thread = Thread.currentThread();
assertThat(thread, instanceOf(InternalThread.class));
assertThat(thread.getName(), startsWith("demo"));
latch.countDown();
}
});
latch.await();
assertThat(latch.getCount(), is(0L));
}
@Test
void getExecutor2() {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + QUEUES_KEY + "=1");
ThreadPool threadPool = new LimitedThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(LinkedBlockingQueue.class));
}
}
| 6,517 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/TaskQueueTest.java | /*
* 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 org.apache.dubbo.common.threadpool.support.eager;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
class TaskQueueTest {
@Test
void testOffer1() throws Exception {
Assertions.assertThrows(RejectedExecutionException.class, () -> {
TaskQueue<Runnable> queue = new TaskQueue<Runnable>(1);
queue.offer(mock(Runnable.class));
});
}
@Test
void testOffer2() throws Exception {
TaskQueue<Runnable> queue = new TaskQueue<Runnable>(1);
EagerThreadPoolExecutor executor = mock(EagerThreadPoolExecutor.class);
Mockito.when(executor.getPoolSize()).thenReturn(2);
Mockito.when(executor.getActiveCount()).thenReturn(1);
queue.setExecutor(executor);
assertThat(queue.offer(mock(Runnable.class)), is(true));
}
@Test
void testOffer3() throws Exception {
TaskQueue<Runnable> queue = new TaskQueue<Runnable>(1);
EagerThreadPoolExecutor executor = mock(EagerThreadPoolExecutor.class);
Mockito.when(executor.getPoolSize()).thenReturn(2);
Mockito.when(executor.getActiveCount()).thenReturn(2);
Mockito.when(executor.getMaximumPoolSize()).thenReturn(4);
queue.setExecutor(executor);
assertThat(queue.offer(mock(Runnable.class)), is(false));
}
@Test
void testOffer4() throws Exception {
TaskQueue<Runnable> queue = new TaskQueue<Runnable>(1);
EagerThreadPoolExecutor executor = mock(EagerThreadPoolExecutor.class);
Mockito.when(executor.getPoolSize()).thenReturn(4);
Mockito.when(executor.getActiveCount()).thenReturn(4);
Mockito.when(executor.getMaximumPoolSize()).thenReturn(4);
queue.setExecutor(executor);
assertThat(queue.offer(mock(Runnable.class)), is(true));
}
@Test
void testRetryOffer1() throws Exception {
Assertions.assertThrows(RejectedExecutionException.class, () -> {
TaskQueue<Runnable> queue = new TaskQueue<Runnable>(1);
EagerThreadPoolExecutor executor = mock(EagerThreadPoolExecutor.class);
Mockito.when(executor.isShutdown()).thenReturn(true);
queue.setExecutor(executor);
queue.retryOffer(mock(Runnable.class), 1000, TimeUnit.MILLISECONDS);
});
}
@Test
void testRetryOffer2() throws Exception {
TaskQueue<Runnable> queue = new TaskQueue<Runnable>(1);
EagerThreadPoolExecutor executor = mock(EagerThreadPoolExecutor.class);
Mockito.when(executor.isShutdown()).thenReturn(false);
queue.setExecutor(executor);
assertThat(queue.retryOffer(mock(Runnable.class), 1000, TimeUnit.MILLISECONDS), is(true));
}
}
| 6,518 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutorTest.java | /*
* 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 org.apache.dubbo.common.threadpool.support.eager;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.awaitility.Awaitility.await;
class EagerThreadPoolExecutorTest {
private static final URL URL = new ServiceConfigURL("dubbo", "localhost", 8080);
/**
* It print like this:
* thread number in current pool:1, task number in task queue:0 executor size: 1
* thread number in current pool:2, task number in task queue:0 executor size: 2
* thread number in current pool:3, task number in task queue:0 executor size: 3
* thread number in current pool:4, task number in task queue:0 executor size: 4
* thread number in current pool:5, task number in task queue:0 executor size: 5
* thread number in current pool:6, task number in task queue:0 executor size: 6
* thread number in current pool:7, task number in task queue:0 executor size: 7
* thread number in current pool:8, task number in task queue:0 executor size: 8
* thread number in current pool:9, task number in task queue:0 executor size: 9
* thread number in current pool:10, task number in task queue:0 executor size: 10
* thread number in current pool:10, task number in task queue:4 executor size: 10
* thread number in current pool:10, task number in task queue:3 executor size: 10
* thread number in current pool:10, task number in task queue:2 executor size: 10
* thread number in current pool:10, task number in task queue:1 executor size: 10
* thread number in current pool:10, task number in task queue:0 executor size: 10
* <p>
* We can see , when the core threads are in busy,
* the thread pool create thread (but thread nums always less than max) instead of put task into queue.
*/
@Disabled("replaced to testEagerThreadPoolFast for performance")
@Test
void testEagerThreadPool() throws Exception {
String name = "eager-tf";
int queues = 5;
int cores = 5;
int threads = 10;
// alive 1 second
long alive = 1000;
// init queue and executor
TaskQueue<Runnable> taskQueue = new TaskQueue<Runnable>(queues);
final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(
cores,
threads,
alive,
TimeUnit.MILLISECONDS,
taskQueue,
new NamedThreadFactory(name, true),
new AbortPolicyWithReport(name, URL));
taskQueue.setExecutor(executor);
for (int i = 0; i < 15; i++) {
Thread.sleep(50);
executor.execute(() -> {
System.out.println(
"thread number in current pool:" + executor.getPoolSize() + ", task number in task queue:"
+ executor.getQueue().size() + " executor size: " + executor.getPoolSize());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
Thread.sleep(5000);
// cores theads are all alive.
Assertions.assertEquals(executor.getPoolSize(), cores, "more than cores threads alive!");
}
@Test
void testEagerThreadPoolFast() {
String name = "eager-tf";
int queues = 5;
int cores = 5;
int threads = 10;
// alive 1 second
long alive = 1000;
// init queue and executor
TaskQueue<Runnable> taskQueue = new TaskQueue<>(queues);
final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(
cores,
threads,
alive,
TimeUnit.MILLISECONDS,
taskQueue,
new NamedThreadFactory(name, true),
new AbortPolicyWithReport(name, URL));
taskQueue.setExecutor(executor);
CountDownLatch countDownLatch1 = new CountDownLatch(1);
for (int i = 0; i < 10; i++) {
executor.execute(() -> {
try {
countDownLatch1.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
}
await().until(() -> executor.getPoolSize() == 10);
Assertions.assertEquals(10, executor.getActiveCount());
CountDownLatch countDownLatch2 = new CountDownLatch(1);
AtomicBoolean started = new AtomicBoolean(false);
for (int i = 0; i < 5; i++) {
executor.execute(() -> {
started.set(true);
try {
countDownLatch2.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
}
await().until(() -> executor.getQueue().size() == 5);
Assertions.assertEquals(10, executor.getActiveCount());
Assertions.assertEquals(10, executor.getPoolSize());
Assertions.assertFalse(started.get());
countDownLatch1.countDown();
await().until(() -> executor.getActiveCount() == 5);
Assertions.assertTrue(started.get());
countDownLatch2.countDown();
await().until(() -> executor.getActiveCount() == 0);
await().until(() -> executor.getPoolSize() == cores);
}
@Test
void testSPI() {
ExtensionLoader<ThreadPool> extensionLoader =
ApplicationModel.defaultModel().getDefaultModule().getExtensionLoader(ThreadPool.class);
ExecutorService executorService =
(ExecutorService) extensionLoader.getExtension("eager").getExecutor(URL);
Assertions.assertEquals(
"EagerThreadPoolExecutor", executorService.getClass().getSimpleName(), "test spi fail!");
}
@Test
void testEagerThreadPool_rejectExecution1() {
String name = "eager-tf";
int cores = 1;
int threads = 3;
int queues = 2;
long alive = 1000;
// init queue and executor
TaskQueue<Runnable> taskQueue = new TaskQueue<>(queues);
final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(
cores,
threads,
alive,
TimeUnit.MILLISECONDS,
taskQueue,
new NamedThreadFactory(name, true),
new AbortPolicyWithReport(name, URL));
taskQueue.setExecutor(executor);
CountDownLatch countDownLatch = new CountDownLatch(1);
Runnable runnable = () -> {
try {
countDownLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
};
for (int i = 0; i < 5; i++) {
executor.execute(runnable);
}
await().until(() -> executor.getPoolSize() == threads);
await().until(() -> executor.getQueue().size() == queues);
Assertions.assertThrows(RejectedExecutionException.class, () -> executor.execute(runnable));
countDownLatch.countDown();
await().until(() -> executor.getActiveCount() == 0);
executor.execute(runnable);
}
@Test
void testEagerThreadPool_rejectExecution2() {
String name = "eager-tf";
int cores = 1;
int threads = 3;
int queues = 2;
long alive = 1000;
// init queue and executor
AtomicReference<Runnable> runnableWhenRetryOffer = new AtomicReference<>();
TaskQueue<Runnable> taskQueue = new TaskQueue<Runnable>(queues) {
@Override
public boolean retryOffer(Runnable o, long timeout, TimeUnit unit) throws InterruptedException {
if (runnableWhenRetryOffer.get() != null) {
runnableWhenRetryOffer.get().run();
}
return super.retryOffer(o, timeout, unit);
}
};
final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(
cores,
threads,
alive,
TimeUnit.MILLISECONDS,
taskQueue,
new NamedThreadFactory(name, true),
new AbortPolicyWithReport(name, URL));
taskQueue.setExecutor(executor);
Semaphore semaphore = new Semaphore(0);
Runnable runnable = () -> {
try {
semaphore.acquire();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
};
for (int i = 0; i < 5; i++) {
executor.execute(runnable);
}
await().until(() -> executor.getPoolSize() == threads);
await().until(() -> executor.getQueue().size() == queues);
Assertions.assertThrows(RejectedExecutionException.class, () -> executor.execute(runnable));
runnableWhenRetryOffer.set(() -> {
semaphore.release();
await().until(() -> executor.getCompletedTaskCount() == 1);
});
executor.execute(runnable);
semaphore.release(5);
await().until(() -> executor.getActiveCount() == 0);
}
}
| 6,519 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolTest.java | /*
* 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 org.apache.dubbo.common.threadpool.support.eager;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadlocal.InternalThread;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
class EagerThreadPoolTest {
@Test
void getExecutor1() throws Exception {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY
+ "=demo&" + CORE_THREADS_KEY
+ "=1&" + THREADS_KEY
+ "=2&" + ALIVE_KEY
+ "=1000&" + QUEUES_KEY
+ "=0");
ThreadPool threadPool = new EagerThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor, instanceOf(EagerThreadPoolExecutor.class));
assertThat(executor.getCorePoolSize(), is(1));
assertThat(executor.getMaximumPoolSize(), is(2));
assertThat(executor.getKeepAliveTime(TimeUnit.MILLISECONDS), is(1000L));
assertThat(executor.getQueue().remainingCapacity(), is(1));
assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(TaskQueue.class));
assertThat(
executor.getRejectedExecutionHandler(),
Matchers.<RejectedExecutionHandler>instanceOf(AbortPolicyWithReport.class));
final CountDownLatch latch = new CountDownLatch(1);
executor.execute(() -> {
Thread thread = Thread.currentThread();
assertThat(thread, instanceOf(InternalThread.class));
assertThat(thread.getName(), startsWith("demo"));
latch.countDown();
});
latch.await();
assertThat(latch.getCount(), is(0L));
}
@Test
void getExecutor2() {
URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + QUEUES_KEY + "=2");
ThreadPool threadPool = new EagerThreadPool();
ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url);
assertThat(executor.getQueue().remainingCapacity(), is(2));
}
}
| 6,520 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEventTest.java | /*
* 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 org.apache.dubbo.common.threadpool.event;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link ThreadPoolExhaustedEvent} Test
*/
class ThreadPoolExhaustedEventTest {
@Test
void test() {
String msg =
"Thread pool is EXHAUSTED! Thread Name: DubboServerHandler-127.0.0.1:12345, Pool Size: 1 (active: 0, core: 1, max: 1, largest: 1), Task: 6 (completed: 6), Executor status:(isShutdown:false, isTerminated:false, isTerminating:false), in dubbo://127.0.0.1:12345!, dubbo version: 2.7.3, current host: 127.0.0.1";
ThreadPoolExhaustedEvent event = new ThreadPoolExhaustedEvent(msg);
assertEquals(msg, event.getMsg());
}
}
| 6,521 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEventListenerTest.java | /*
* 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 org.apache.dubbo.common.threadpool.event;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link ThreadPoolExhaustedEvent} Test
*/
class ThreadPoolExhaustedEventListenerTest {
private MyListener listener;
@BeforeEach
public void init() {
this.listener = new MyListener();
}
@Test
void testOnEvent() {
String msg =
"Thread pool is EXHAUSTED! Thread Name: DubboServerHandler-127.0.0.1:12345, Pool Size: 1 (active: 0, core: 1, max: 1, largest: 1), Task: 6 (completed: 6), Executor status:(isShutdown:false, isTerminated:false, isTerminating:false), in dubbo://127.0.0.1:12345!, dubbo version: 2.7.3, current host: 127.0.0.1";
ThreadPoolExhaustedEvent exhaustedEvent = new ThreadPoolExhaustedEvent(msg);
listener.onEvent(exhaustedEvent);
assertEquals(exhaustedEvent, listener.getThreadPoolExhaustedEvent());
}
static class MyListener implements ThreadPoolExhaustedListener {
private ThreadPoolExhaustedEvent threadPoolExhaustedEvent;
@Override
public void onEvent(ThreadPoolExhaustedEvent event) {
this.threadPoolExhaustedEvent = event;
}
public ThreadPoolExhaustedEvent getThreadPoolExhaustedEvent() {
return threadPoolExhaustedEvent;
}
}
}
| 6,522 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutorTest.java | /*
* 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 org.apache.dubbo.common.threadpool.serial;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.awaitility.Awaitility.await;
class SerializingExecutorTest {
private ExecutorService service;
private SerializingExecutor serializingExecutor;
@BeforeEach
public void before() {
service = Executors.newFixedThreadPool(4);
serializingExecutor = new SerializingExecutor(service);
}
@Test
void testSerial() throws InterruptedException {
int total = 10000;
Map<String, Integer> map = new HashMap<>();
map.put("val", 0);
Semaphore semaphore = new Semaphore(1);
CountDownLatch startLatch = new CountDownLatch(1);
AtomicBoolean failed = new AtomicBoolean(false);
for (int i = 0; i < total; i++) {
final int index = i;
serializingExecutor.execute(() -> {
if (!semaphore.tryAcquire()) {
System.out.println("Concurrency");
failed.set(true);
}
try {
startLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
int num = map.get("val");
map.put("val", num + 1);
if (num != index) {
System.out.println("Index error. Excepted :" + index + " but actual: " + num);
failed.set(true);
}
semaphore.release();
});
}
startLatch.countDown();
await().until(() -> map.get("val") == total);
Assertions.assertFalse(failed.get());
}
@Test
void testNonSerial() {
int total = 10;
Map<String, Integer> map = new HashMap<>();
map.put("val", 0);
Semaphore semaphore = new Semaphore(1);
CountDownLatch startLatch = new CountDownLatch(1);
AtomicBoolean failed = new AtomicBoolean(false);
for (int i = 0; i < total; i++) {
final int index = i;
service.execute(() -> {
if (!semaphore.tryAcquire()) {
failed.set(true);
}
try {
startLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
int num = map.get("val");
map.put("val", num + 1);
if (num != index) {
failed.set(true);
}
semaphore.release();
});
}
await().until(() -> ((ThreadPoolExecutor) service).getActiveCount() == 4);
startLatch.countDown();
await().until(() -> ((ThreadPoolExecutor) service).getCompletedTaskCount() == total);
Assertions.assertTrue(failed.get());
}
}
| 6,523 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/url/URLParamTest.java | /*
* 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 org.apache.dubbo.common.url;
import org.apache.dubbo.common.url.component.URLParam;
import org.apache.dubbo.common.utils.CollectionUtils;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class URLParamTest {
@Test
void testParseWithRawParam() {
URLParam urlParam1 = URLParam.parse("aaa=aaa&bbb&version=1.0&default.ccc=123");
Assertions.assertEquals("aaa", urlParam1.getParameter("aaa"));
Assertions.assertEquals("bbb", urlParam1.getParameter("bbb"));
Assertions.assertEquals("1.0", urlParam1.getParameter("version"));
Assertions.assertEquals("123", urlParam1.getParameter("default.ccc"));
Assertions.assertEquals("123", urlParam1.getParameter("ccc"));
Assertions.assertEquals(urlParam1, URLParam.parse(urlParam1.getRawParam()));
Assertions.assertEquals(urlParam1, URLParam.parse(urlParam1.toString()));
URLParam urlParam2 = URLParam.parse("aaa%3dtest", true, null);
Assertions.assertEquals("test", urlParam2.getParameter("aaa"));
Map<String, String> overrideMap = Collections.singletonMap("aaa", "bbb");
URLParam urlParam3 = URLParam.parse("aaa%3dtest", true, overrideMap);
Assertions.assertEquals("bbb", urlParam3.getParameter("aaa"));
URLParam urlParam4 = URLParam.parse("ccc=456&&default.ccc=123");
Assertions.assertEquals("456", urlParam4.getParameter("ccc"));
URLParam urlParam5 = URLParam.parse("version=2.0&&default.version=1.0");
Assertions.assertEquals("2.0", urlParam5.getParameter("version"));
}
@Test
void testParseWithMap() {
Map<String, String> map = new HashMap<>();
map.put("aaa", "aaa");
map.put("bbb", "bbb");
map.put("version", "2.0");
map.put("side", "consumer");
URLParam urlParam1 = URLParam.parse(map);
Assertions.assertEquals("aaa", urlParam1.getParameter("aaa"));
Assertions.assertEquals("bbb", urlParam1.getParameter("bbb"));
Assertions.assertEquals("2.0", urlParam1.getParameter("version"));
Assertions.assertEquals("consumer", urlParam1.getParameter("side"));
Assertions.assertEquals(urlParam1, URLParam.parse(urlParam1.getRawParam()));
map.put("bbb", "ccc");
Assertions.assertEquals("bbb", urlParam1.getParameter("bbb"));
URLParam urlParam2 = URLParam.parse(map);
Assertions.assertEquals("ccc", urlParam2.getParameter("bbb"));
URLParam urlParam3 = URLParam.parse(null, null);
Assertions.assertFalse(urlParam3.hasParameter("aaa"));
Assertions.assertEquals(urlParam3, URLParam.parse(urlParam3.getRawParam()));
}
@Test
void testDefault() {
Map<String, String> map = new HashMap<>();
map.put("aaa", "aaa");
map.put("bbb", "bbb");
map.put("version", "2.0");
map.put("timeout", "1234");
map.put("default.timeout", "5678");
URLParam urlParam1 = URLParam.parse(map);
Assertions.assertEquals("1234", urlParam1.getParameter("timeout"));
Assertions.assertEquals("5678", urlParam1.getParameter("default.timeout"));
map.remove("timeout");
URLParam urlParam2 = URLParam.parse(map);
Assertions.assertEquals("5678", urlParam2.getParameter("timeout"));
Assertions.assertEquals("5678", urlParam2.getParameter("default.timeout"));
URLParam urlParam3 = URLParam.parse("timeout=1234&default.timeout=5678");
Assertions.assertEquals("1234", urlParam3.getParameter("timeout"));
Assertions.assertEquals("5678", urlParam3.getParameter("default.timeout"));
URLParam urlParam4 = URLParam.parse("default.timeout=5678");
Assertions.assertEquals("5678", urlParam4.getParameter("timeout"));
Assertions.assertEquals("5678", urlParam4.getParameter("default.timeout"));
}
@Test
void testGetParameter() {
URLParam urlParam1 = URLParam.parse("aaa=aaa&bbb&version=1.0&default.ccc=123");
Assertions.assertNull(urlParam1.getParameter("abcde"));
URLParam urlParam2 = URLParam.parse("aaa=aaa&bbb&default.ccc=123");
Assertions.assertNull(urlParam2.getParameter("version"));
URLParam urlParam3 = URLParam.parse("aaa=aaa&side=consumer");
Assertions.assertEquals("consumer", urlParam3.getParameter("side"));
URLParam urlParam4 = URLParam.parse("aaa=aaa&side=provider");
Assertions.assertEquals("provider", urlParam4.getParameter("side"));
}
@Test
void testHasParameter() {
URLParam urlParam1 = URLParam.parse("aaa=aaa&side=provider");
Assertions.assertTrue(urlParam1.hasParameter("aaa"));
Assertions.assertFalse(urlParam1.hasParameter("bbb"));
Assertions.assertTrue(urlParam1.hasParameter("side"));
Assertions.assertFalse(urlParam1.hasParameter("version"));
}
@Test
void testRemoveParameters() {
URLParam urlParam1 = URLParam.parse("aaa=aaa&side=provider&version=1.0");
Assertions.assertTrue(urlParam1.hasParameter("aaa"));
Assertions.assertTrue(urlParam1.hasParameter("side"));
Assertions.assertTrue(urlParam1.hasParameter("version"));
URLParam urlParam2 = urlParam1.removeParameters("side");
Assertions.assertFalse(urlParam2.hasParameter("side"));
URLParam urlParam3 = urlParam1.removeParameters("aaa", "version");
Assertions.assertFalse(urlParam3.hasParameter("aaa"));
Assertions.assertFalse(urlParam3.hasParameter("version"));
URLParam urlParam4 = urlParam1.removeParameters();
Assertions.assertTrue(urlParam4.hasParameter("aaa"));
Assertions.assertTrue(urlParam4.hasParameter("side"));
Assertions.assertTrue(urlParam4.hasParameter("version"));
URLParam urlParam5 = urlParam1.clearParameters();
Assertions.assertFalse(urlParam5.hasParameter("aaa"));
Assertions.assertFalse(urlParam5.hasParameter("side"));
Assertions.assertFalse(urlParam5.hasParameter("version"));
URLParam urlParam6 = urlParam1.removeParameters("aaa");
Assertions.assertFalse(urlParam6.hasParameter("aaa"));
URLParam urlParam7 = URLParam.parse("side=consumer").removeParameters("side");
Assertions.assertFalse(urlParam7.hasParameter("side"));
}
@Test
void testAddParameters() {
URLParam urlParam1 = URLParam.parse("aaa=aaa&side=provider");
Assertions.assertTrue(urlParam1.hasParameter("aaa"));
Assertions.assertTrue(urlParam1.hasParameter("side"));
URLParam urlParam2 = urlParam1.addParameter("bbb", "bbb");
Assertions.assertEquals("aaa", urlParam2.getParameter("aaa"));
Assertions.assertEquals("bbb", urlParam2.getParameter("bbb"));
URLParam urlParam3 = urlParam1.addParameter("aaa", "ccc");
Assertions.assertEquals("aaa", urlParam1.getParameter("aaa"));
Assertions.assertEquals("ccc", urlParam3.getParameter("aaa"));
URLParam urlParam4 = urlParam1.addParameter("aaa", "aaa");
Assertions.assertEquals("aaa", urlParam4.getParameter("aaa"));
URLParam urlParam5 = urlParam1.addParameter("version", "0.1");
Assertions.assertEquals("0.1", urlParam5.getParameter("version"));
URLParam urlParam6 = urlParam5.addParameterIfAbsent("version", "0.2");
Assertions.assertEquals("0.1", urlParam6.getParameter("version"));
URLParam urlParam7 = urlParam1.addParameterIfAbsent("version", "0.2");
Assertions.assertEquals("0.2", urlParam7.getParameter("version"));
Map<String, String> map = new HashMap<>();
map.put("version", "1.0");
map.put("side", "provider");
URLParam urlParam8 = urlParam1.addParameters(map);
Assertions.assertEquals("1.0", urlParam8.getParameter("version"));
Assertions.assertEquals("provider", urlParam8.getParameter("side"));
map.put("side", "consumer");
Assertions.assertEquals("provider", urlParam8.getParameter("side"));
URLParam urlParam9 = urlParam8.addParameters(map);
Assertions.assertEquals("consumer", urlParam9.getParameter("side"));
URLParam urlParam10 = urlParam8.addParametersIfAbsent(map);
Assertions.assertEquals("provider", urlParam10.getParameter("side"));
Assertions.assertThrows(IllegalArgumentException.class, () -> urlParam1.addParameter("side", "unrecognized"));
}
@Test
void testURLParamMap() {
URLParam urlParam1 = URLParam.parse("");
Assertions.assertTrue(urlParam1.getParameters().isEmpty());
Assertions.assertEquals(0, urlParam1.getParameters().size());
Assertions.assertFalse(urlParam1.getParameters().containsKey("aaa"));
Assertions.assertFalse(urlParam1.getParameters().containsKey("version"));
Assertions.assertFalse(urlParam1.getParameters().containsKey(new Object()));
Assertions.assertEquals(
new HashMap<>(urlParam1.getParameters()).toString(),
urlParam1.getParameters().toString());
URLParam urlParam2 = URLParam.parse("aaa=aaa&version=1.0");
URLParam.URLParamMap urlParam2Map = (URLParam.URLParamMap) urlParam2.getParameters();
Assertions.assertTrue(urlParam2Map.containsKey("version"));
Assertions.assertFalse(urlParam2Map.containsKey("side"));
Assertions.assertTrue(urlParam2Map.containsValue("1.0"));
Assertions.assertFalse(urlParam2Map.containsValue("2.0"));
Assertions.assertEquals("1.0", urlParam2Map.get("version"));
Assertions.assertEquals("aaa", urlParam2Map.get("aaa"));
Assertions.assertNull(urlParam2Map.get(new Object()));
Assertions.assertEquals(urlParam2, urlParam2Map.getUrlParam());
urlParam2Map.put("version", "1.0");
Assertions.assertEquals(urlParam2, urlParam2Map.getUrlParam());
urlParam2Map.putAll(Collections.singletonMap("version", "1.0"));
Assertions.assertEquals(urlParam2, urlParam2Map.getUrlParam());
urlParam2Map.put("side", "consumer");
Assertions.assertNotEquals(urlParam2, urlParam2Map.getUrlParam());
urlParam2Map = (URLParam.URLParamMap) urlParam2.getParameters();
Assertions.assertEquals(urlParam2, urlParam2Map.getUrlParam());
urlParam2Map.remove("version");
Assertions.assertNotEquals(urlParam2, urlParam2Map.getUrlParam());
Assertions.assertFalse(urlParam2Map.containsValue("version"));
Assertions.assertNull(urlParam2Map.getUrlParam().getParameter("version"));
urlParam2Map = (URLParam.URLParamMap) urlParam2.getParameters();
Assertions.assertEquals(urlParam2, urlParam2Map.getUrlParam());
urlParam2Map.clear();
Assertions.assertTrue(urlParam2Map.isEmpty());
Assertions.assertEquals(0, urlParam2Map.size());
Assertions.assertNull(urlParam2Map.getUrlParam().getParameter("aaa"));
Assertions.assertNull(urlParam2Map.getUrlParam().getParameter("version"));
urlParam2Map = (URLParam.URLParamMap) urlParam2.getParameters();
Assertions.assertEquals(urlParam2, urlParam2Map.getUrlParam());
URLParam urlParam3 = URLParam.parse("aaa=aaa&version=1.0");
Assertions.assertTrue(CollectionUtils.mapEquals(urlParam2Map, urlParam3.getParameters()));
Assertions.assertTrue(CollectionUtils.equals(
urlParam2Map.entrySet(), urlParam3.getParameters().entrySet()));
Assertions.assertTrue(CollectionUtils.equals(
urlParam2Map.keySet(), urlParam3.getParameters().keySet()));
Assertions.assertTrue(CollectionUtils.equals(
urlParam2Map.values(), urlParam3.getParameters().values()));
URLParam urlParam4 = URLParam.parse("aaa=aaa&version=1.0&side=consumer");
Assertions.assertFalse(CollectionUtils.mapEquals(urlParam2Map, urlParam4.getParameters()));
Assertions.assertFalse(CollectionUtils.equals(
urlParam2Map.entrySet(), urlParam4.getParameters().entrySet()));
Assertions.assertFalse(CollectionUtils.equals(
urlParam2Map.keySet(), urlParam4.getParameters().keySet()));
Assertions.assertFalse(CollectionUtils.equals(
urlParam2Map.values(), urlParam4.getParameters().values()));
Set<Map<String, String>> set = new HashSet<>();
set.add(urlParam2Map);
set.add(urlParam3.getParameters());
Assertions.assertEquals(1, set.size());
set.add(urlParam4.getParameters());
Assertions.assertEquals(2, set.size());
URLParam urlParam5 = URLParam.parse("version=1.0");
Assertions.assertEquals(
new HashMap<>(urlParam5.getParameters()).toString(),
urlParam5.getParameters().toString());
}
@Test
void testMethodParameters() {
URLParam urlParam1 = URLParam.parse("aaa.method1=aaa&bbb.method2=bbb");
Assertions.assertEquals("aaa", urlParam1.getAnyMethodParameter("method1"));
Assertions.assertEquals("bbb", urlParam1.getAnyMethodParameter("method2"));
URLParam urlParam2 = URLParam.parse("methods=aaa&aaa.method1=aaa&bbb.method2=bbb");
Assertions.assertEquals("aaa", urlParam2.getAnyMethodParameter("method1"));
Assertions.assertNull(urlParam2.getAnyMethodParameter("method2"));
}
}
| 6,524 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/lang/ShutdownHookCallbacksTest.java | /*
* 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 org.apache.dubbo.common.lang;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link ShutdownHookCallbacks}
*
* @since 2.7.5
*/
class ShutdownHookCallbacksTest {
private ShutdownHookCallbacks callbacks;
@BeforeEach
public void init() {
callbacks = new ShutdownHookCallbacks(ApplicationModel.defaultModel());
}
@Test
void testSingleton() {
assertNotNull(callbacks);
}
@Test
void testCallback() {
callbacks.callback();
DefaultShutdownHookCallback callback = (DefaultShutdownHookCallback)
callbacks.getCallbacks().iterator().next();
assertTrue(callback.isExecuted());
}
@AfterEach
public void destroy() {
callbacks.destroy();
assertTrue(callbacks.getCallbacks().isEmpty());
}
}
| 6,525 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/lang/DefaultShutdownHookCallback.java | /*
* 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 org.apache.dubbo.common.lang;
/**
* Default {@link ShutdownHookCallback}
*
* @since 2.7.5
*/
public class DefaultShutdownHookCallback implements ShutdownHookCallback {
private boolean executed = false;
@Override
public void callback() throws Throwable {
executed = true;
}
public boolean isExecuted() {
return executed;
}
}
| 6,526 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/lang/PrioritizedTest.java | /*
* 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 org.apache.dubbo.common.lang;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static java.util.Collections.sort;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link Prioritized} Test
*
* @since 2.7.5
*/
class PrioritizedTest {
@Test
void testConstants() {
assertEquals(Integer.MAX_VALUE, Prioritized.MIN_PRIORITY);
assertEquals(Integer.MIN_VALUE, Prioritized.MAX_PRIORITY);
}
@Test
void testGetPriority() {
assertEquals(Prioritized.NORMAL_PRIORITY, new Prioritized() {}.getPriority());
}
@Test
void testComparator() {
List<Object> list = new LinkedList<>();
// All Prioritized
list.add(of(1));
list.add(of(2));
list.add(of(3));
List<Object> copy = new LinkedList<>(list);
sort(list, Prioritized.COMPARATOR);
assertEquals(copy, list);
// MIX non-Prioritized and Prioritized
list.clear();
list.add(1);
list.add(of(2));
list.add(of(1));
sort(list, Prioritized.COMPARATOR);
copy = asList(of(1), of(2), 1);
assertEquals(copy, list);
// All non-Prioritized
list.clear();
list.add(1);
list.add(2);
list.add(3);
sort(list, Prioritized.COMPARATOR);
copy = asList(1, 2, 3);
assertEquals(copy, list);
}
public static PrioritizedValue of(int value) {
return new PrioritizedValue(value);
}
static class PrioritizedValue implements Prioritized {
private final int value;
private PrioritizedValue(int value) {
this.value = value;
}
@Override
public int getPriority() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PrioritizedValue)) return false;
PrioritizedValue that = (PrioritizedValue) o;
return value == that.value;
}
@Override
public int hashCode() {
return Objects.hash(value);
}
}
}
| 6,527 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/json/GsonUtilsTest.java | /*
* 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 org.apache.dubbo.common.json;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class GsonUtilsTest {
@Test
void test1() {
Object user = GsonUtils.fromJson("{'name':'Tom','age':24}", User.class);
Assertions.assertInstanceOf(User.class, user);
Assertions.assertEquals("Tom", ((User) user).getName());
Assertions.assertEquals(24, ((User) user).getAge());
try {
GsonUtils.fromJson("{'name':'Tom','age':}", User.class);
Assertions.fail();
} catch (RuntimeException ex) {
Assertions.assertEquals(
"Generic serialization [gson] Json syntax exception thrown when parsing (message:{'name':'Tom','age':} type:class org.apache.dubbo.common.json.GsonUtilsTest$User) error:com.google.gson.stream.MalformedJsonException: Expected value at line 1 column 21 path $.age",
ex.getMessage());
}
}
@Test
void test2() {
ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader();
AtomicReference<List<String>> removedPackages = new AtomicReference<>(Collections.emptyList());
ClassLoader newClassLoader = new ClassLoader(originClassLoader) {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
for (String removedPackage : removedPackages.get()) {
if (name.startsWith(removedPackage)) {
throw new ClassNotFoundException("Test");
}
}
return super.loadClass(name);
}
};
Thread.currentThread().setContextClassLoader(newClassLoader);
// TCCL not found gson
removedPackages.set(Collections.singletonList("com.google.gson"));
GsonUtils.setSupportGson(null);
try {
GsonUtils.fromJson("{'name':'Tom','age':24}", User.class);
Assertions.fail();
} catch (RuntimeException ex) {
Assertions.assertEquals("Gson is not supported. Please import Gson in JVM env.", ex.getMessage());
}
Thread.currentThread().setContextClassLoader(originClassLoader);
GsonUtils.setSupportGson(null);
}
private static class User {
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
| 6,528 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/json | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/json/impl/FastJsonImplTest.java | /*
* 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 org.apache.dubbo.common.json.impl;
import java.lang.reflect.Type;
import com.alibaba.fastjson.JSON;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.mockito.Answers.CALLS_REAL_METHODS;
class FastJsonImplTest {
private static MockedStatic<JSON> fastjsonMock;
@BeforeAll
static void setup() {
fastjsonMock = Mockito.mockStatic(JSON.class, CALLS_REAL_METHODS);
}
@AfterAll
static void teardown() {
fastjsonMock.close();
}
@Test
void testSupported() {
Assertions.assertTrue(new FastJsonImpl().isSupport());
fastjsonMock.when(() -> JSON.toJSONString(Mockito.any(), Mockito.any())).thenThrow(new RuntimeException());
Assertions.assertFalse(new FastJsonImpl().isSupport());
fastjsonMock.reset();
fastjsonMock.when(() -> JSON.toJSONString(Mockito.any(), Mockito.any())).thenReturn(null);
Assertions.assertFalse(new FastJsonImpl().isSupport());
fastjsonMock.reset();
fastjsonMock
.when(() -> JSON.parseObject((String) Mockito.any(), (Type) Mockito.any()))
.thenReturn(null);
Assertions.assertFalse(new FastJsonImpl().isSupport());
fastjsonMock.reset();
fastjsonMock
.when(() -> JSON.parseArray(Mockito.any(), (Class) Mockito.any()))
.thenReturn(null);
Assertions.assertFalse(new FastJsonImpl().isSupport());
fastjsonMock.reset();
}
}
| 6,529 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/json | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/json/impl/FastJson2ImplTest.java | /*
* 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 org.apache.dubbo.common.json.impl;
import java.lang.reflect.Type;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.mockito.Answers.CALLS_REAL_METHODS;
class FastJson2ImplTest {
private static MockedStatic<JSON> fastjson2Mock;
@BeforeAll
static void setup() {
fastjson2Mock = Mockito.mockStatic(JSON.class, CALLS_REAL_METHODS);
}
@AfterAll
static void teardown() {
fastjson2Mock.close();
}
@Test
void testSupported() {
Assertions.assertTrue(new FastJson2Impl().isSupport());
fastjson2Mock
.when(() -> JSON.toJSONString(Mockito.any(), (JSONWriter.Feature) Mockito.any()))
.thenThrow(new RuntimeException());
Assertions.assertFalse(new FastJson2Impl().isSupport());
fastjson2Mock.reset();
fastjson2Mock
.when(() -> JSON.toJSONString(Mockito.any(), (JSONWriter.Feature) Mockito.any()))
.thenReturn(null);
Assertions.assertFalse(new FastJson2Impl().isSupport());
fastjson2Mock.reset();
fastjson2Mock
.when(() -> JSON.parseObject((String) Mockito.any(), (Type) Mockito.any()))
.thenReturn(null);
Assertions.assertFalse(new FastJson2Impl().isSupport());
fastjson2Mock.reset();
fastjson2Mock
.when(() -> JSON.parseArray(Mockito.any(), (Class) Mockito.any()))
.thenReturn(null);
Assertions.assertFalse(new FastJson2Impl().isSupport());
fastjson2Mock.reset();
}
}
| 6,530 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/json | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/json/impl/GsonImplTest.java | /*
* 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 org.apache.dubbo.common.json.impl;
import java.lang.reflect.Type;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import com.google.gson.Gson;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;
public class GsonImplTest {
private static Gson gson = new Gson();
private static AtomicReference<Gson> gsonReference = new AtomicReference<>();
private static MockedConstruction<Gson> gsonMock;
private static AtomicReference<Consumer<Gson>> gsonInit = new AtomicReference<>();
@BeforeAll
static void setup() {
gsonMock = Mockito.mockConstruction(Gson.class, (mock, context) -> {
gsonReference.set(mock);
Mockito.when(mock.toJson((Object) Mockito.any()))
.thenAnswer(invocation -> gson.toJson((Object) invocation.getArgument(0)));
Mockito.when(mock.fromJson(Mockito.anyString(), (Type) Mockito.any()))
.thenAnswer(invocation ->
gson.fromJson((String) invocation.getArgument(0), (Type) invocation.getArgument(1)));
Consumer<Gson> gsonConsumer = gsonInit.get();
if (gsonConsumer != null) {
gsonConsumer.accept(mock);
}
});
}
@AfterAll
static void teardown() {
gsonMock.close();
}
@Test
void testSupported() {
Assertions.assertTrue(new GsonImpl().isSupport());
gsonInit.set(g -> Mockito.when(g.toJson((Object) Mockito.any())).thenThrow(new RuntimeException()));
Assertions.assertFalse(new GsonImpl().isSupport());
gsonInit.set(null);
gsonInit.set(g -> Mockito.when(g.fromJson(Mockito.anyString(), (Type) Mockito.any()))
.thenThrow(new RuntimeException()));
Assertions.assertFalse(new GsonImpl().isSupport());
gsonInit.set(null);
gsonInit.set(g -> Mockito.when(g.toJson((Object) Mockito.any())).thenReturn(null));
Assertions.assertFalse(new GsonImpl().isSupport());
gsonInit.set(null);
gsonInit.set(g -> Mockito.when(g.fromJson(Mockito.anyString(), (Type) Mockito.any()))
.thenReturn(null));
Assertions.assertFalse(new GsonImpl().isSupport());
gsonInit.set(null);
gsonInit.set(g -> Mockito.when(g.fromJson(Mockito.eq("[\"json\"]"), (Type) Mockito.any()))
.thenReturn(null));
Assertions.assertFalse(new GsonImpl().isSupport());
gsonInit.set(null);
}
}
| 6,531 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/version/VersionTest.java | /*
* 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 org.apache.dubbo.common.version;
import org.apache.dubbo.common.Version;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.Enumeration;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class VersionTest {
@Test
void testGetProtocolVersion() {
Assertions.assertEquals(Version.getProtocolVersion(), Version.DEFAULT_DUBBO_PROTOCOL_VERSION);
}
@Test
void testSupportResponseAttachment() {
Assertions.assertTrue(Version.isSupportResponseAttachment("2.0.2"));
Assertions.assertTrue(Version.isSupportResponseAttachment("2.0.3"));
Assertions.assertTrue(Version.isSupportResponseAttachment("2.0.99"));
Assertions.assertFalse(Version.isSupportResponseAttachment("2.1.0"));
Assertions.assertFalse(Version.isSupportResponseAttachment("2.0.0"));
Assertions.assertFalse(Version.isSupportResponseAttachment("1.0.0"));
Assertions.assertFalse(Version.isSupportResponseAttachment("3.0.0"));
Assertions.assertFalse(Version.isSupportResponseAttachment("2.6.6-stable"));
Assertions.assertFalse(Version.isSupportResponseAttachment("2.6.6.RC1"));
Assertions.assertFalse(Version.isSupportResponseAttachment("2.0.contains"));
Assertions.assertFalse(Version.isSupportResponseAttachment("version.string"));
Assertions.assertFalse(Version.isSupportResponseAttachment("prefix2.0"));
}
@Test
void testGetIntVersion() {
Assertions.assertEquals(2060100, Version.getIntVersion("2.6.1"));
Assertions.assertEquals(2060101, Version.getIntVersion("2.6.1.1"));
Assertions.assertEquals(2070001, Version.getIntVersion("2.7.0.1"));
Assertions.assertEquals(2070000, Version.getIntVersion("2.7.0"));
Assertions.assertEquals(Version.HIGHEST_PROTOCOL_VERSION, Version.getIntVersion("2.0.99"));
Assertions.assertEquals(2070000, Version.getIntVersion("2.7.0.RC1"));
Assertions.assertEquals(2070000, Version.getIntVersion("2.7.0-SNAPSHOT"));
Assertions.assertEquals(3000000, Version.getIntVersion("3.0.0-SNAPSHOT"));
Assertions.assertEquals(3010000, Version.getIntVersion("3.1.0"));
}
@Test
void testCompare() {
Assertions.assertEquals(0, Version.compare("3.0.0", "3.0.0"));
Assertions.assertEquals(0, Version.compare("3.0.0-SNAPSHOT", "3.0.0"));
Assertions.assertEquals(1, Version.compare("3.0.0.1", "3.0.0"));
Assertions.assertEquals(1, Version.compare("3.1.0", "3.0.0"));
Assertions.assertEquals(1, Version.compare("3.1.2.3", "3.0.0"));
Assertions.assertEquals(-1, Version.compare("2.9.9.9", "3.0.0"));
Assertions.assertEquals(-1, Version.compare("2.6.3.1", "3.0.0"));
}
@Test
void testIsFramework270OrHigher() {
Assertions.assertTrue(Version.isRelease270OrHigher("2.7.0"));
Assertions.assertTrue(Version.isRelease270OrHigher("2.7.0.1"));
Assertions.assertTrue(Version.isRelease270OrHigher("2.7.0.2"));
Assertions.assertTrue(Version.isRelease270OrHigher("2.8.0"));
Assertions.assertFalse(Version.isRelease270OrHigher("2.6.3"));
Assertions.assertFalse(Version.isRelease270OrHigher("2.6.3.1"));
}
@Test
void testIsFramework263OrHigher() {
Assertions.assertTrue(Version.isRelease263OrHigher("2.7.0"));
Assertions.assertTrue(Version.isRelease263OrHigher("2.7.0.1"));
Assertions.assertTrue(Version.isRelease263OrHigher("2.6.4"));
Assertions.assertFalse(Version.isRelease263OrHigher("2.6.2"));
Assertions.assertFalse(Version.isRelease263OrHigher("2.6.2.1"));
Assertions.assertFalse(Version.isRelease263OrHigher("2.6.1.1"));
Assertions.assertTrue(Version.isRelease263OrHigher("2.6.3"));
Assertions.assertTrue(Version.isRelease263OrHigher("2.6.3.0"));
}
@Test
void testGetVersion()
throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<?> versionClass = reloadVersionClass();
Assertions.assertEquals(
"1.0.0", versionClass.getDeclaredMethod("getVersion").invoke(null));
}
private static Class<?> reloadVersionClass() throws ClassNotFoundException {
ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader classLoader = new ClassLoader(originClassLoader) {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.equals("org.apache.dubbo.common.Version")) {
return findClass(name);
}
return super.loadClass(name);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
try {
byte[] bytes = loadClassData(name);
return defineClass(name, bytes, 0, bytes.length);
} catch (Exception e) {
return getParent().loadClass(name);
}
}
public byte[] loadClassData(String className) throws IOException {
className = className.replaceAll("\\.", "/");
String path = Version.class
.getProtectionDomain()
.getCodeSource()
.getLocation()
.getPath() + className + ".class";
FileInputStream fileInputStream;
byte[] classBytes;
fileInputStream = new FileInputStream(path);
int length = fileInputStream.available();
classBytes = new byte[length];
fileInputStream.read(classBytes);
fileInputStream.close();
return classBytes;
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
if (name.equals("META-INF/versions/dubbo-common")) {
return super.getResources("META-INF/test-versions/dubbo-common");
}
return super.getResources(name);
}
};
Class<?> versionClass = classLoader.loadClass("org.apache.dubbo.common.Version");
return versionClass;
}
@Test
void testGetLastCommitId()
throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, IllegalAccessException {
Class<?> versionClass = reloadVersionClass();
Assertions.assertEquals(
"82a29fcd674216fe9bea10b6efef3196929dd7ca",
versionClass.getDeclaredMethod("getLastCommitId").invoke(null));
}
}
| 6,532 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/concurrent/CompletableFutureTaskTest.java | /*
* 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 org.apache.dubbo.common.concurrent;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
class CompletableFutureTaskTest {
private static final ExecutorService executor = new ThreadPoolExecutor(
0,
10,
60L,
TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
new NamedThreadFactory("DubboMonitorCreator", true));
@Test
void testCreate() throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(1);
CompletableFuture<Boolean> completableFuture = CompletableFuture.supplyAsync(
() -> {
countDownLatch.countDown();
return true;
},
executor);
countDownLatch.await();
}
@Test
void testRunnableResponse() throws ExecutionException, InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
CompletableFuture<Boolean> completableFuture = CompletableFuture.supplyAsync(
() -> {
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return true;
},
executor);
Assertions.assertNull(completableFuture.getNow(null));
latch.countDown();
Boolean result = completableFuture.get();
assertThat(result, is(true));
}
@Test
void testListener() throws InterruptedException {
AtomicBoolean run = new AtomicBoolean(false);
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(
() -> {
run.set(true);
return "hello";
},
executor);
final CountDownLatch countDownLatch = new CountDownLatch(1);
completableFuture.thenRunAsync(countDownLatch::countDown);
countDownLatch.await();
Assertions.assertTrue(run.get());
}
@Test
void testCustomExecutor() {
Executor mockedExecutor = mock(Executor.class);
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
return 0;
});
completableFuture
.thenRunAsync(mock(Runnable.class), mockedExecutor)
.whenComplete((s, e) -> verify(mockedExecutor, times(1)).execute(any(Runnable.class)));
}
}
| 6,533 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/beans/InstantiationStrategyTest.java | /*
* 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 org.apache.dubbo.common.beans;
import org.apache.dubbo.common.beans.model.FooBeanWithApplicationModel;
import org.apache.dubbo.common.beans.model.FooBeanWithFrameworkModel;
import org.apache.dubbo.common.beans.model.FooBeanWithModuleModel;
import org.apache.dubbo.common.beans.model.FooBeanWithScopeModel;
import org.apache.dubbo.common.beans.model.FooBeanWithoutUniqueConstructors;
import org.apache.dubbo.common.beans.support.InstantiationStrategy;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ScopeModelAccessor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class InstantiationStrategyTest {
private ScopeModelAccessor scopeModelAccessor = new ScopeModelAccessor() {
@Override
public ScopeModel getScopeModel() {
return ApplicationModel.defaultModel().getDefaultModule();
}
};
@Test
void testCreateBeanWithScopeModelArgument() throws ReflectiveOperationException {
InstantiationStrategy instantiationStrategy = new InstantiationStrategy(scopeModelAccessor);
FooBeanWithFrameworkModel beanWithFrameworkModel =
instantiationStrategy.instantiate(FooBeanWithFrameworkModel.class);
Assertions.assertSame(scopeModelAccessor.getFrameworkModel(), beanWithFrameworkModel.getFrameworkModel());
FooBeanWithApplicationModel beanWithApplicationModel =
instantiationStrategy.instantiate(FooBeanWithApplicationModel.class);
Assertions.assertSame(scopeModelAccessor.getApplicationModel(), beanWithApplicationModel.getApplicationModel());
FooBeanWithModuleModel beanWithModuleModel = instantiationStrategy.instantiate(FooBeanWithModuleModel.class);
Assertions.assertSame(scopeModelAccessor.getModuleModel(), beanWithModuleModel.getModuleModel());
FooBeanWithScopeModel beanWithScopeModel = instantiationStrategy.instantiate(FooBeanWithScopeModel.class);
Assertions.assertSame(scopeModelAccessor.getScopeModel(), beanWithScopeModel.getScopeModel());
// test not unique matched constructors
try {
instantiationStrategy.instantiate(FooBeanWithoutUniqueConstructors.class);
Assertions.fail("Expect throwing exception");
} catch (Exception e) {
Assertions.assertTrue(
e.getMessage().contains("Expect only one but found 2 matched constructors"),
StringUtils.toString(e));
}
}
}
| 6,534 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/beans/ScopeBeanFactoryTest.java | /*
* 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 org.apache.dubbo.common.beans;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.common.beans.model.FooBeanWithApplicationModel;
import org.apache.dubbo.common.beans.model.FooBeanWithFrameworkModel;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class ScopeBeanFactoryTest {
@Test
void testInjection() {
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ScopeBeanFactory beanFactory = applicationModel.getBeanFactory();
FooBeanWithApplicationModel beanWithApplicationModel =
beanFactory.registerBean(FooBeanWithApplicationModel.class);
Assertions.assertSame(applicationModel, beanWithApplicationModel.getApplicationModel());
FrameworkModel frameworkModel = applicationModel.getFrameworkModel();
FooBeanWithFrameworkModel beanWithFrameworkModel =
frameworkModel.getBeanFactory().registerBean(FooBeanWithFrameworkModel.class);
Assertions.assertSame(frameworkModel, beanWithFrameworkModel.getFrameworkModel());
// child bean factory can obtain bean from parent bean factory
FooBeanWithFrameworkModel beanWithFrameworkModelFromApp =
applicationModel.getBeanFactory().getBean(FooBeanWithFrameworkModel.class);
Assertions.assertSame(beanWithFrameworkModel, beanWithFrameworkModelFromApp);
Object objectBean = applicationModel.getBeanFactory().getBean(Object.class);
Assertions.assertNull(objectBean);
// child bean factory can obtain bean from parent bean factory by classType
frameworkModel.getBeanFactory().registerBean(new TestBean());
applicationModel.getBeanFactory().registerBean(new TestBean());
List<TestBean> testBeans = applicationModel.getBeanFactory().getBeansOfType(TestBean.class);
Assertions.assertEquals(testBeans.size(), 2);
// father can't get son's
List<TestBean> testBeans_1 = frameworkModel.getBeanFactory().getBeansOfType(TestBean.class);
Assertions.assertEquals(testBeans_1.size(), 1);
Assertions.assertFalse(beanWithApplicationModel.isDestroyed());
Assertions.assertFalse(beanWithFrameworkModel.isDestroyed());
// destroy
frameworkModel.destroy();
Assertions.assertTrue(beanWithApplicationModel.isDestroyed());
Assertions.assertTrue(beanWithFrameworkModel.isDestroyed());
}
static class TestBean {}
}
| 6,535 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/beans | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/beans/model/FooBeanWithScopeModel.java | /*
* 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 org.apache.dubbo.common.beans.model;
import org.apache.dubbo.rpc.model.ScopeModel;
public class FooBeanWithScopeModel {
private ScopeModel scopeModel;
public FooBeanWithScopeModel(ScopeModel scopeModel) {
this.scopeModel = scopeModel;
}
public ScopeModel getScopeModel() {
return scopeModel;
}
}
| 6,536 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/beans | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/beans/model/FooBeanWithModuleModel.java | /*
* 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 org.apache.dubbo.common.beans.model;
import org.apache.dubbo.rpc.model.ModuleModel;
public class FooBeanWithModuleModel {
private ModuleModel moduleModel;
public FooBeanWithModuleModel(ModuleModel moduleModel) {
this.moduleModel = moduleModel;
}
public ModuleModel getModuleModel() {
return moduleModel;
}
}
| 6,537 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/beans | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/beans/model/FooBeanWithFrameworkModel.java | /*
* 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 org.apache.dubbo.common.beans.model;
import org.apache.dubbo.common.resource.Disposable;
import org.apache.dubbo.rpc.model.FrameworkModel;
public class FooBeanWithFrameworkModel implements Disposable {
private FrameworkModel frameworkModel;
private boolean destroyed;
public FooBeanWithFrameworkModel(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
public FrameworkModel getFrameworkModel() {
return frameworkModel;
}
@Override
public void destroy() {
this.destroyed = true;
}
public boolean isDestroyed() {
return destroyed;
}
}
| 6,538 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/beans | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/beans/model/FooBeanWithApplicationModel.java | /*
* 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 org.apache.dubbo.common.beans.model;
import org.apache.dubbo.common.resource.Disposable;
import org.apache.dubbo.rpc.model.ApplicationModel;
public class FooBeanWithApplicationModel implements Disposable {
private ApplicationModel applicationModel;
private boolean destroyed;
public FooBeanWithApplicationModel(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
public ApplicationModel getApplicationModel() {
return applicationModel;
}
@Override
public void destroy() {
this.destroyed = true;
}
public boolean isDestroyed() {
return destroyed;
}
}
| 6,539 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/beans | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/beans/model/FooBeanWithoutUniqueConstructors.java | /*
* 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 org.apache.dubbo.common.beans.model;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
public class FooBeanWithoutUniqueConstructors {
private ModuleModel moduleModel;
private ApplicationModel applicationModel;
public FooBeanWithoutUniqueConstructors(ModuleModel moduleModel) {
this.moduleModel = moduleModel;
}
public FooBeanWithoutUniqueConstructors(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
}
| 6,540 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model/User.java | /*
* 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 org.apache.dubbo.common.model;
import java.io.Serializable;
import java.util.Objects;
/**
* this class has no nullary constructor and some field is primitive
*/
public class User implements Serializable {
private int age;
private String name;
public User(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return String.format("User name(%s) age(%d) ", name, age);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
if (name == null) {
if (user.name != null) {
return false;
}
} else if (!name.equals(user.name)) {
return false;
}
return Objects.equals(age, user.age);
}
@Override
public int hashCode() {
return Objects.hash(age, name);
}
}
| 6,541 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model/SerializablePerson.java | /*
* 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 org.apache.dubbo.common.model;
import java.io.Serializable;
import java.util.Arrays;
public class SerializablePerson implements Serializable {
private static final long serialVersionUID = 1L;
byte oneByte = 123;
private String name = "name1";
private int age = 11;
private String[] value = {"value1", "value2"};
public SerializablePerson(char description, boolean adult) {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte getOneByte() {
return oneByte;
}
public void setOneByte(byte b) {
this.oneByte = b;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String[] getValue() {
return value;
}
public void setValue(String[] value) {
this.value = value;
}
@Override
public String toString() {
return String.format("Person name(%s) age(%d) byte(%s) [value=%s]", name, age, oneByte, Arrays.toString(value));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + Arrays.hashCode(value);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
SerializablePerson other = (SerializablePerson) obj;
if (age != other.age) return false;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
if (!Arrays.equals(value, other.value)) return false;
return true;
}
}
| 6,542 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model/Person.java | /*
* 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 org.apache.dubbo.common.model;
import java.io.Serializable;
import java.util.Arrays;
public class Person implements Serializable {
byte oneByte = 123;
private String name = "name1";
private int age = 11;
private String[] value = {"value1", "value2"};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte getOneByte() {
return oneByte;
}
public void setOneByte(byte b) {
this.oneByte = b;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String[] getValue() {
return value;
}
public void setValue(String[] value) {
this.value = value;
}
@Override
public String toString() {
return String.format("Person name(%s) age(%d) byte(%s) [value=%s]", name, age, oneByte, Arrays.toString(value));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + Arrays.hashCode(value);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Person other = (Person) obj;
if (age != other.age) return false;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
if (!Arrays.equals(value, other.value)) return false;
return true;
}
}
| 6,543 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/PersonStatus.java | /*
* 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 org.apache.dubbo.common.model.person;
public enum PersonStatus {
ENABLED,
DISABLED
}
| 6,544 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/Phone.java | /*
* 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 org.apache.dubbo.common.model.person;
import java.io.Serializable;
public class Phone implements Serializable {
private static final long serialVersionUID = 4399060521859707703L;
private String country;
private String area;
private String number;
private String extensionNumber;
public Phone() {}
public Phone(String country, String area, String number, String extensionNumber) {
this.country = country;
this.area = area;
this.number = number;
this.extensionNumber = extensionNumber;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getExtensionNumber() {
return extensionNumber;
}
public void setExtensionNumber(String extensionNumber) {
this.extensionNumber = extensionNumber;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((area == null) ? 0 : area.hashCode());
result = prime * result + ((country == null) ? 0 : country.hashCode());
result = prime * result + ((extensionNumber == null) ? 0 : extensionNumber.hashCode());
result = prime * result + ((number == null) ? 0 : number.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Phone other = (Phone) obj;
if (area == null) {
if (other.area != null) return false;
} else if (!area.equals(other.area)) return false;
if (country == null) {
if (other.country != null) return false;
} else if (!country.equals(other.country)) return false;
if (extensionNumber == null) {
if (other.extensionNumber != null) return false;
} else if (!extensionNumber.equals(other.extensionNumber)) return false;
if (number == null) {
if (other.number != null) return false;
} else if (!number.equals(other.number)) return false;
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (country != null && country.length() > 0) {
sb.append(country);
sb.append('-');
}
if (area != null && area.length() > 0) {
sb.append(area);
sb.append('-');
}
if (number != null && number.length() > 0) {
sb.append(number);
}
if (extensionNumber != null && extensionNumber.length() > 0) {
sb.append('-');
sb.append(extensionNumber);
}
return sb.toString();
}
}
| 6,545 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/Cgeneric.java | /*
* 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 org.apache.dubbo.common.model.person;
import java.io.Serializable;
public class Cgeneric<T> implements Serializable {
public static String NAME = "C";
private String name = NAME;
private T data;
private Ageneric<T> a;
private Bgeneric<PersonInfo> b;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getName() {
return name;
}
public Ageneric<T> getA() {
return a;
}
public void setA(Ageneric<T> a) {
this.a = a;
}
public Bgeneric<PersonInfo> getB() {
return b;
}
public void setB(Bgeneric<PersonInfo> b) {
this.b = b;
}
}
| 6,546 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/PersonMap.java | /*
* 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 org.apache.dubbo.common.model.person;
import java.util.HashMap;
public class PersonMap extends HashMap<String, String> {
private static final String ID = "1";
private static final String NAME = "hand";
String personId;
String personName;
public String getPersonId() {
return get(ID);
}
public void setPersonId(String personId) {
this.personId = personId;
}
public String getPersonName() {
return get(NAME);
}
public void setPersonName(String personName) {
this.personName = personName;
}
}
| 6,547 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/Ageneric.java | /*
* 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 org.apache.dubbo.common.model.person;
import java.io.Serializable;
public class Ageneric<T> implements Serializable {
public static String NAME = "A";
private String name = NAME;
private T data;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getName() {
return name;
}
}
| 6,548 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/Dgeneric.java | /*
* 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 org.apache.dubbo.common.model.person;
import java.io.Serializable;
public class Dgeneric<T, Y, Z> implements Serializable {
public static String NAME = "D";
private String name = NAME;
private T t;
private Y y;
private Z z;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
public Y getY() {
return y;
}
public void setY(Y y) {
this.y = y;
}
public Z getZ() {
return z;
}
public void setZ(Z z) {
this.z = z;
}
public String getName() {
return name;
}
}
| 6,549 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/FullAddress.java | /*
* 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 org.apache.dubbo.common.model.person;
import java.io.Serializable;
public class FullAddress implements Serializable {
private static final long serialVersionUID = 5163979984269419831L;
private String countryId;
private String countryName;
private String provinceName;
private String cityId;
private String cityName;
private String streetAddress;
private String zipCode;
public FullAddress() {}
public FullAddress(String countryId, String provinceName, String cityId, String streetAddress, String zipCode) {
this.countryId = countryId;
this.countryName = countryId;
this.provinceName = provinceName;
this.cityId = cityId;
this.cityName = cityId;
this.streetAddress = streetAddress;
this.zipCode = zipCode;
}
public FullAddress(
String countryId,
String countryName,
String provinceName,
String cityId,
String cityName,
String streetAddress,
String zipCode) {
this.countryId = countryId;
this.countryName = countryName;
this.provinceName = provinceName;
this.cityId = cityId;
this.cityName = cityName;
this.streetAddress = streetAddress;
this.zipCode = zipCode;
}
public String getCountryId() {
return countryId;
}
public void setCountryId(String countryId) {
this.countryId = countryId;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getProvinceName() {
return provinceName;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
public String getCityId() {
return cityId;
}
public void setCityId(String cityId) {
this.cityId = cityId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((cityId == null) ? 0 : cityId.hashCode());
result = prime * result + ((cityName == null) ? 0 : cityName.hashCode());
result = prime * result + ((countryId == null) ? 0 : countryId.hashCode());
result = prime * result + ((countryName == null) ? 0 : countryName.hashCode());
result = prime * result + ((provinceName == null) ? 0 : provinceName.hashCode());
result = prime * result + ((streetAddress == null) ? 0 : streetAddress.hashCode());
result = prime * result + ((zipCode == null) ? 0 : zipCode.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
FullAddress other = (FullAddress) obj;
if (cityId == null) {
if (other.cityId != null) return false;
} else if (!cityId.equals(other.cityId)) return false;
if (cityName == null) {
if (other.cityName != null) return false;
} else if (!cityName.equals(other.cityName)) return false;
if (countryId == null) {
if (other.countryId != null) return false;
} else if (!countryId.equals(other.countryId)) return false;
if (countryName == null) {
if (other.countryName != null) return false;
} else if (!countryName.equals(other.countryName)) return false;
if (provinceName == null) {
if (other.provinceName != null) return false;
} else if (!provinceName.equals(other.provinceName)) return false;
if (streetAddress == null) {
if (other.streetAddress != null) return false;
} else if (!streetAddress.equals(other.streetAddress)) return false;
if (zipCode == null) {
if (other.zipCode != null) return false;
} else if (!zipCode.equals(other.zipCode)) return false;
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (countryName != null && countryName.length() > 0) {
sb.append(countryName);
}
if (provinceName != null && provinceName.length() > 0) {
sb.append(' ');
sb.append(provinceName);
}
if (cityName != null && cityName.length() > 0) {
sb.append(' ');
sb.append(cityName);
}
if (streetAddress != null && streetAddress.length() > 0) {
sb.append(' ');
sb.append(streetAddress);
}
return sb.toString();
}
}
| 6,550 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/PersonInfo.java | /*
* 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 org.apache.dubbo.common.model.person;
import java.io.Serializable;
import java.util.List;
public class PersonInfo implements Serializable {
private static final long serialVersionUID = 7443011149612231882L;
List<Phone> phones;
Phone fax;
FullAddress fullAddress;
String mobileNo;
String name;
boolean male;
boolean female;
String department;
String jobTitle;
String homepageUrl;
public List<Phone> getPhones() {
return phones;
}
public void setPhones(List<Phone> phones) {
this.phones = phones;
}
public boolean isMale() {
return male;
}
public void setMale(boolean male) {
this.male = male;
}
public boolean isFemale() {
return female;
}
public void setFemale(boolean female) {
this.female = female;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public Phone getFax() {
return fax;
}
public void setFax(Phone fax) {
this.fax = fax;
}
public FullAddress getFullAddress() {
return fullAddress;
}
public void setFullAddress(FullAddress fullAddress) {
this.fullAddress = fullAddress;
}
public String getHomepageUrl() {
return homepageUrl;
}
public void setHomepageUrl(String homepageUrl) {
this.homepageUrl = homepageUrl;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((department == null) ? 0 : department.hashCode());
result = prime * result + ((fax == null) ? 0 : fax.hashCode());
result = prime * result + (female ? 1231 : 1237);
result = prime * result + ((fullAddress == null) ? 0 : fullAddress.hashCode());
result = prime * result + ((homepageUrl == null) ? 0 : homepageUrl.hashCode());
result = prime * result + ((jobTitle == null) ? 0 : jobTitle.hashCode());
result = prime * result + (male ? 1231 : 1237);
result = prime * result + ((mobileNo == null) ? 0 : mobileNo.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((phones == null) ? 0 : phones.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
PersonInfo other = (PersonInfo) obj;
if (department == null) {
if (other.department != null) return false;
} else if (!department.equals(other.department)) return false;
if (fax == null) {
if (other.fax != null) return false;
} else if (!fax.equals(other.fax)) return false;
if (female != other.female) return false;
if (fullAddress == null) {
if (other.fullAddress != null) return false;
} else if (!fullAddress.equals(other.fullAddress)) return false;
if (homepageUrl == null) {
if (other.homepageUrl != null) return false;
} else if (!homepageUrl.equals(other.homepageUrl)) return false;
if (jobTitle == null) {
if (other.jobTitle != null) return false;
} else if (!jobTitle.equals(other.jobTitle)) return false;
if (male != other.male) return false;
if (mobileNo == null) {
if (other.mobileNo != null) return false;
} else if (!mobileNo.equals(other.mobileNo)) return false;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
if (phones == null) {
if (other.phones != null) return false;
} else if (!phones.equals(other.phones)) return false;
return true;
}
@Override
public String toString() {
return "PersonInfo [phones=" + phones + ", fax=" + fax + ", fullAddress=" + fullAddress
+ ", mobileNo=" + mobileNo + ", name=" + name + ", male=" + male + ", female="
+ female + ", department=" + department + ", jobTitle=" + jobTitle
+ ", homepageUrl=" + homepageUrl + "]";
}
}
| 6,551 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/Bgeneric.java | /*
* 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 org.apache.dubbo.common.model.person;
import java.io.Serializable;
public class Bgeneric<T> implements Serializable {
public static String NAME = "B";
private String name = NAME;
private T data;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getName() {
return name;
}
}
| 6,552 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/BigPerson.java | /*
* 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 org.apache.dubbo.common.model.person;
import java.io.Serializable;
public class BigPerson implements Serializable {
private static final long serialVersionUID = 1L;
String personId;
String loginName;
PersonStatus status;
String email;
String penName;
PersonInfo infoProfile;
public BigPerson() {}
public BigPerson(String id) {
this.personId = id;
}
public String getPersonId() {
return personId;
}
public void setPersonId(String personId) {
this.personId = personId;
}
public PersonInfo getInfoProfile() {
return infoProfile;
}
public void setInfoProfile(PersonInfo infoProfile) {
this.infoProfile = infoProfile;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getLoginName() {
return this.loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public PersonStatus getStatus() {
return this.status;
}
public void setStatus(PersonStatus status) {
this.status = status;
}
public String getPenName() {
return penName;
}
public void setPenName(String penName) {
this.penName = penName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((infoProfile == null) ? 0 : infoProfile.hashCode());
result = prime * result + ((loginName == null) ? 0 : loginName.hashCode());
result = prime * result + ((penName == null) ? 0 : penName.hashCode());
result = prime * result + ((personId == null) ? 0 : personId.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
BigPerson other = (BigPerson) obj;
if (email == null) {
if (other.email != null) return false;
} else if (!email.equals(other.email)) return false;
if (infoProfile == null) {
if (other.infoProfile != null) return false;
} else if (!infoProfile.equals(other.infoProfile)) return false;
if (loginName == null) {
if (other.loginName != null) return false;
} else if (!loginName.equals(other.loginName)) return false;
if (penName == null) {
if (other.penName != null) return false;
} else if (!penName.equals(other.penName)) return false;
if (personId == null) {
if (other.personId != null) return false;
} else if (!personId.equals(other.personId)) return false;
if (status != other.status) return false;
return true;
}
@Override
public String toString() {
return "BigPerson [personId=" + personId + ", loginName=" + loginName + ", status="
+ status + ", email=" + email + ", penName=" + penName + ", infoProfile="
+ infoProfile + "]";
}
}
| 6,553 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model/media/Image.java | /*
* 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 org.apache.dubbo.common.model.media;
public class Image implements java.io.Serializable {
private static final long serialVersionUID = 1L;
public String uri;
public String title; // Can be null
public int width;
public int height;
public Size size;
public Image() {}
public Image(String uri, String title, int width, int height, Size size) {
this.height = height;
this.title = title;
this.uri = uri;
this.width = width;
this.size = size;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Image image = (Image) o;
if (height != image.height) return false;
if (width != image.width) return false;
if (size != image.size) return false;
if (title != null ? !title.equals(image.title) : image.title != null) return false;
if (uri != null ? !uri.equals(image.uri) : image.uri != null) return false;
return true;
}
@Override
public int hashCode() {
int result = uri != null ? uri.hashCode() : 0;
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + width;
result = 31 * result + height;
result = 31 * result + (size != null ? size.hashCode() : 0);
return result;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[Image ");
sb.append("uri=").append(uri);
sb.append(", title=").append(title);
sb.append(", width=").append(width);
sb.append(", height=").append(height);
sb.append(", size=").append(size);
sb.append(']');
return sb.toString();
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public Size getSize() {
return size;
}
public void setSize(Size size) {
this.size = size;
}
public enum Size {
SMALL,
LARGE
}
}
| 6,554 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/model/media/Media.java | /*
* 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 org.apache.dubbo.common.model.media;
import java.util.List;
@SuppressWarnings("serial")
public class Media implements java.io.Serializable {
public String uri;
public String title; // Can be unset.
public int width;
public int height;
public String format;
public long duration;
public long size;
public int bitrate; // Can be unset.
public boolean hasBitrate;
public List<String> persons;
public Player player;
public String copyright; // Can be unset.
public Media() {}
public Media(
String uri,
String title,
int width,
int height,
String format,
long duration,
long size,
int bitrate,
boolean hasBitrate,
List<String> persons,
Player player,
String copyright) {
this.uri = uri;
this.title = title;
this.width = width;
this.height = height;
this.format = format;
this.duration = duration;
this.size = size;
this.bitrate = bitrate;
this.hasBitrate = hasBitrate;
this.persons = persons;
this.player = player;
this.copyright = copyright;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Media media = (Media) o;
if (bitrate != media.bitrate) return false;
if (duration != media.duration) return false;
if (hasBitrate != media.hasBitrate) return false;
if (height != media.height) return false;
if (size != media.size) return false;
if (width != media.width) return false;
if (copyright != null ? !copyright.equals(media.copyright) : media.copyright != null) return false;
if (format != null ? !format.equals(media.format) : media.format != null) return false;
if (persons != null ? !persons.equals(media.persons) : media.persons != null) return false;
if (player != media.player) return false;
if (title != null ? !title.equals(media.title) : media.title != null) return false;
if (uri != null ? !uri.equals(media.uri) : media.uri != null) return false;
return true;
}
@Override
public int hashCode() {
int result = uri != null ? uri.hashCode() : 0;
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + width;
result = 31 * result + height;
result = 31 * result + (format != null ? format.hashCode() : 0);
result = 31 * result + (int) (duration ^ (duration >>> 32));
result = 31 * result + (int) (size ^ (size >>> 32));
result = 31 * result + bitrate;
result = 31 * result + (hasBitrate ? 1 : 0);
result = 31 * result + (persons != null ? persons.hashCode() : 0);
result = 31 * result + (player != null ? player.hashCode() : 0);
result = 31 * result + (copyright != null ? copyright.hashCode() : 0);
return result;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[Media ");
sb.append("uri=").append(uri);
sb.append(", title=").append(title);
sb.append(", width=").append(width);
sb.append(", height=").append(height);
sb.append(", format=").append(format);
sb.append(", duration=").append(duration);
sb.append(", size=").append(size);
sb.append(", hasBitrate=").append(hasBitrate);
sb.append(", bitrate=").append(String.valueOf(bitrate));
sb.append(", persons=").append(persons);
sb.append(", player=").append(player);
sb.append(", copyright=").append(copyright);
sb.append(']');
return sb.toString();
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public int getBitrate() {
return bitrate;
}
public void setBitrate(int bitrate) {
this.bitrate = bitrate;
this.hasBitrate = true;
}
public List<String> getPersons() {
return persons;
}
public void setPersons(List<String> persons) {
this.persons = persons;
}
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public enum Player {
JAVA,
FLASH
}
}
| 6,555 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/ClassGeneratorTest.java | /*
* 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 org.apache.dubbo.common.bytecode;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javassist.ClassPool;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
interface Builder<T> {
T getName(Bean bean);
void setName(Bean bean, T name);
}
class BaseClass {
public BaseClass() {}
public BaseClass(StringBuilder sb) {
sb.append("constructor comes from BaseClass");
}
public String baseClassMethod() {
return "method comes from BaseClass";
}
}
interface BaseInterface {}
class ClassGeneratorTest {
@Test
void test() throws Exception {
ClassGenerator cg = ClassGenerator.newInstance();
// add className, interface, superClass
String className = BaseClass.class.getPackage().getName() + ".TestClass";
cg.setClassName(className);
cg.addInterface(BaseInterface.class);
cg.setSuperClass(BaseClass.class);
// add constructor
cg.addDefaultConstructor();
cg.addConstructor(
Modifier.PUBLIC,
new Class[] {String.class, int.class},
new Class[] {Throwable.class, RuntimeException.class},
"this.strAttr = arg0;this.intAttr = arg1;");
cg.addConstructor(BaseClass.class.getConstructor(StringBuilder.class));
// add field
cg.addField(
"staticAttr", Modifier.PUBLIC | Modifier.STATIC | Modifier.VOLATILE, String.class, "\"defaultVal\"");
cg.addField("strAttr", Modifier.PROTECTED | Modifier.VOLATILE, String.class);
cg.addField("intAttr", Modifier.PRIVATE | Modifier.VOLATILE, int.class);
// add method
cg.addMethod(
"setStrAttr",
Modifier.PUBLIC,
void.class,
new Class[] {String.class, int.class},
new Class[] {Throwable.class, RuntimeException.class},
"this.strAttr = arg0;");
cg.addMethod(
"setIntAttr",
Modifier.PUBLIC,
void.class,
new Class[] {String.class, int.class},
new Class[] {Throwable.class, RuntimeException.class},
"this.intAttr = arg1;");
cg.addMethod(
"getStrAttr",
Modifier.PUBLIC,
String.class,
new Class[] {},
new Class[] {Throwable.class, RuntimeException.class},
"return this.strAttr;");
cg.addMethod(
"getIntAttr",
Modifier.PUBLIC,
int.class,
new Class[] {},
new Class[] {Throwable.class, RuntimeException.class},
"return this.intAttr;");
cg.addMethod(BaseClass.class.getMethod("baseClassMethod"));
// cg.toClass
Class<?> clz = cg.toClass(Bean.class);
// after cg.toClass, the TestClass.class generated by javassist is like the following file content
getClass().getResource("/org/apache/dubbo/common/bytecode/TestClass");
// verify class, superClass, interfaces
Assertions.assertTrue(ClassGenerator.isDynamicClass(clz));
Assertions.assertEquals(clz.getName(), className);
Assertions.assertEquals(clz.getSuperclass(), BaseClass.class);
Assertions.assertArrayEquals(clz.getInterfaces(), new Class[] {ClassGenerator.DC.class, BaseInterface.class});
// get constructors
Constructor<?>[] constructors = clz.getConstructors();
Assertions.assertEquals(constructors.length, 3);
Constructor<?> constructor0 = clz.getConstructor();
Constructor<?> constructor1 = clz.getConstructor(new Class[] {String.class, int.class});
Constructor<?> constructor2 = clz.getConstructor(new Class[] {StringBuilder.class});
Assertions.assertEquals(constructor1.getModifiers(), Modifier.PUBLIC);
Assertions.assertArrayEquals(
constructor1.getExceptionTypes(), new Class[] {Throwable.class, RuntimeException.class});
// get fields
Field staticAttrField = clz.getDeclaredField("staticAttr");
Field strAttrField = clz.getDeclaredField("strAttr");
Field intAttrField = clz.getDeclaredField("intAttr");
Assertions.assertNotNull(staticAttrField);
Assertions.assertNotNull(strAttrField);
Assertions.assertNotNull(intAttrField);
Assertions.assertEquals(staticAttrField.get(null), "defaultVal");
// get methods
Method setStrAttrMethod = clz.getMethod("setStrAttr", new Class[] {String.class, int.class});
Method setIntAttrMethod = clz.getMethod("setIntAttr", new Class[] {String.class, int.class});
Method getStrAttrMethod = clz.getMethod("getStrAttr");
Method getIntAttrMethod = clz.getMethod("getIntAttr");
Method baseClassMethod = clz.getMethod("baseClassMethod");
Assertions.assertNotNull(setStrAttrMethod);
Assertions.assertNotNull(setIntAttrMethod);
Assertions.assertNotNull(getStrAttrMethod);
Assertions.assertNotNull(getIntAttrMethod);
Assertions.assertNotNull(baseClassMethod);
// verify constructor0
Object objByConstructor0 = constructor0.newInstance();
Assertions.assertEquals(getStrAttrMethod.invoke(objByConstructor0), null);
Assertions.assertEquals(getIntAttrMethod.invoke(objByConstructor0), 0);
// verify constructor1
Object objByConstructor1 = constructor1.newInstance("v1", 1);
Assertions.assertEquals(getStrAttrMethod.invoke(objByConstructor1), "v1");
Assertions.assertEquals(getIntAttrMethod.invoke(objByConstructor1), 1);
// verify getter setter method
setStrAttrMethod.invoke(objByConstructor0, "v2", 2);
setIntAttrMethod.invoke(objByConstructor0, "v3", 3);
Assertions.assertEquals(getStrAttrMethod.invoke(objByConstructor0), "v2");
Assertions.assertEquals(getIntAttrMethod.invoke(objByConstructor0), 3);
// verify constructor and method witch comes from baseClass
StringBuilder sb = new StringBuilder();
Object objByConstructor2 = constructor2.newInstance(sb);
Assertions.assertEquals(sb.toString(), "constructor comes from BaseClass");
Object res = baseClassMethod.invoke(objByConstructor2);
Assertions.assertEquals(res, "method comes from BaseClass");
cg.release();
}
@SuppressWarnings("unchecked")
@Test
void testMain() throws Exception {
Bean b = new Bean();
Field fname = Bean.class.getDeclaredField("name");
fname.setAccessible(true);
ClassGenerator cg = ClassGenerator.newInstance();
cg.setClassName(Bean.class.getName() + "$Builder");
cg.addInterface(Builder.class);
cg.addField("public static java.lang.reflect.Field FNAME;");
cg.addMethod("public Object getName(" + Bean.class.getName()
+ " o){ boolean[][][] bs = new boolean[0][][]; return (String)FNAME.get($1); }");
cg.addMethod("public void setName(" + Bean.class.getName() + " o, Object name){ FNAME.set($1, $2); }");
cg.addDefaultConstructor();
Class<?> cl = cg.toClass(Bean.class);
cl.getField("FNAME").set(null, fname);
System.out.println(cl.getName());
Builder<String> builder = (Builder<String>) cl.getDeclaredConstructor().newInstance();
System.out.println(b.getName());
builder.setName(b, "ok");
System.out.println(b.getName());
}
@Test
void testMain0() throws Exception {
Bean b = new Bean();
Field fname = Bean.class.getDeclaredField("name");
fname.setAccessible(true);
ClassGenerator cg = ClassGenerator.newInstance();
cg.setClassName(Bean.class.getName() + "$Builder2");
cg.addInterface(Builder.class);
cg.addField("FNAME", Modifier.PUBLIC | Modifier.STATIC, java.lang.reflect.Field.class);
cg.addMethod("public Object getName(" + Bean.class.getName()
+ " o){ boolean[][][] bs = new boolean[0][][]; return (String)FNAME.get($1); }");
cg.addMethod("public void setName(" + Bean.class.getName() + " o, Object name){ FNAME.set($1, $2); }");
cg.addDefaultConstructor();
Class<?> cl = cg.toClass(Bean.class);
cl.getField("FNAME").set(null, fname);
System.out.println(cl.getName());
Builder<String> builder = (Builder<String>) cl.getDeclaredConstructor().newInstance();
System.out.println(b.getName());
builder.setName(b, "ok");
System.out.println(b.getName());
}
@Test
public void test_getClassPool() throws InterruptedException {
int threadCount = 5;
CountDownLatch LATCH = new CountDownLatch(threadCount);
ClassLoader loader = Thread.currentThread().getContextClassLoader();
List<Integer> hashCodeList = new ArrayList<>();
for (int i = 0; i < threadCount; i++) {
new Thread(new Runnable() {
@Override
public void run() {
ClassPool classPool = ClassGenerator.getClassPool(loader);
int currentHashCode = classPool.hashCode();
hashCodeList.add(currentHashCode);
System.out.println(currentHashCode);
LATCH.countDown();
}
})
.start();
}
LATCH.await();
Integer firstHashCode = null;
for (Integer currentHashCode : hashCodeList) {
if (firstHashCode == null) {
firstHashCode = currentHashCode;
continue;
}
Assertions.assertTrue(firstHashCode.intValue() == currentHashCode.intValue());
}
}
}
class Bean {
int age = 30;
private String name = "qianlei";
public int getAge() {
return age;
}
public String getName() {
return name;
}
public static volatile String abc = "df";
}
| 6,556 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/WrapperTest.java | /*
* 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 org.apache.dubbo.common.bytecode;
import org.apache.dubbo.common.utils.ClassUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
class WrapperTest {
@Test
void testMain() throws Exception {
Wrapper w = Wrapper.getWrapper(I1.class);
String[] ns = w.getDeclaredMethodNames();
assertEquals(ns.length, 5);
ns = w.getMethodNames();
assertEquals(ns.length, 6);
Object obj = new Impl1();
assertEquals(w.getPropertyValue(obj, "name"), "you name");
w.setPropertyValue(obj, "name", "changed");
assertEquals(w.getPropertyValue(obj, "name"), "changed");
w.invokeMethod(obj, "hello", new Class<?>[] {String.class}, new Object[] {"qianlei"});
w.setPropertyValues(obj, new String[] {"name", "float"}, new Object[] {"mrh", 1.0f});
Object[] propertyValues = w.getPropertyValues(obj, new String[] {"name", "float"});
Assertions.assertEquals(propertyValues.length, 2);
Assertions.assertEquals(propertyValues[0], "mrh");
Assertions.assertEquals(propertyValues[1], 1.0f);
}
// bug: DUBBO-132
@Test
void test_unwantedArgument() throws Exception {
Wrapper w = Wrapper.getWrapper(I1.class);
Object obj = new Impl1();
try {
w.invokeMethod(
obj, "hello", new Class<?>[] {String.class, String.class}, new Object[] {"qianlei", "badboy"});
fail();
} catch (NoSuchMethodException expected) {
}
}
// bug: DUBBO-425
@Test
void test_makeEmptyClass() throws Exception {
Wrapper.getWrapper(EmptyServiceImpl.class);
}
@Test
void testHasMethod() throws Exception {
Wrapper w = Wrapper.getWrapper(I1.class);
Assertions.assertTrue(w.hasMethod("setName"));
Assertions.assertTrue(w.hasMethod("hello"));
Assertions.assertTrue(w.hasMethod("showInt"));
Assertions.assertTrue(w.hasMethod("getFloat"));
Assertions.assertTrue(w.hasMethod("setFloat"));
Assertions.assertFalse(w.hasMethod("setFloatXXX"));
}
@Test
void testWrapperObject() throws Exception {
Wrapper w = Wrapper.getWrapper(Object.class);
Assertions.assertEquals(4, w.getMethodNames().length);
Assertions.assertEquals(4, w.getDeclaredMethodNames().length);
Assertions.assertEquals(0, w.getPropertyNames().length);
Assertions.assertNull(w.getPropertyType(null));
Assertions.assertFalse(w.hasProperty(null));
}
@Test
void testGetPropertyValue() throws Exception {
Assertions.assertThrows(NoSuchPropertyException.class, () -> {
Wrapper w = Wrapper.getWrapper(Object.class);
w.getPropertyValue(null, null);
});
}
@Test
void testSetPropertyValue() throws Exception {
Assertions.assertThrows(NoSuchPropertyException.class, () -> {
Wrapper w = Wrapper.getWrapper(Object.class);
w.setPropertyValue(null, null, null);
});
}
@Test
void testWrapPrimitive() throws Exception {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
Wrapper.getWrapper(Byte.TYPE);
});
}
@Test
void testInvokeWrapperObject() throws Exception {
Wrapper w = Wrapper.getWrapper(Object.class);
Object instance = new Object();
Assertions.assertEquals(instance.getClass(), w.invokeMethod(instance, "getClass", null, null));
Assertions.assertEquals(instance.hashCode(), (int) w.invokeMethod(instance, "hashCode", null, null));
Assertions.assertEquals(instance.toString(), w.invokeMethod(instance, "toString", null, null));
Assertions.assertTrue((boolean)
w.invokeMethod(instance, "equals", new Class[] {instance.getClass()}, new Object[] {instance}));
Assertions.assertThrows(
IllegalArgumentException.class,
() -> w.invokeMethod(
instance, "equals", new Class[] {instance.getClass()}, new Object[] {instance, instance}));
}
@Test
void testNoSuchMethod() throws Exception {
Assertions.assertThrows(NoSuchMethodException.class, () -> {
Wrapper w = Wrapper.getWrapper(Object.class);
w.invokeMethod(new Object(), "__XX__", null, null);
});
}
@Test
void testOverloadMethod() throws Exception {
Wrapper w = Wrapper.getWrapper(I2.class);
assertEquals(2, w.getMethodNames().length);
Impl2 impl = new Impl2();
w.invokeMethod(impl, "setFloat", new Class[] {float.class}, new Object[] {1F});
assertEquals(1F, impl.getFloat1());
assertNull(impl.getFloat2());
w.invokeMethod(impl, "setFloat", new Class[] {Float.class}, new Object[] {2f});
assertEquals(1F, impl.getFloat1());
assertEquals(2F, impl.getFloat2());
w.invokeMethod(impl, "setFloat", new Class[] {Float.class}, new Object[] {null});
assertEquals(1F, impl.getFloat1());
assertNull(impl.getFloat2());
}
@Test
void test_getDeclaredMethodNames_ContainExtendsParentMethods() throws Exception {
assertArrayEquals(
new String[] {
"hello",
},
Wrapper.getWrapper(Parent1.class).getMethodNames());
assertArrayEquals(
new String[] {
"hello",
},
ClassUtils.getMethodNames(Parent1.class));
assertArrayEquals(new String[] {}, Wrapper.getWrapper(Son.class).getDeclaredMethodNames());
assertArrayEquals(new String[] {}, ClassUtils.getDeclaredMethodNames(Son.class));
}
@Test
void test_getMethodNames_ContainExtendsParentMethods() throws Exception {
assertArrayEquals(
new String[] {"hello", "world"}, Wrapper.getWrapper(Son.class).getMethodNames());
assertArrayEquals(new String[] {"hello", "world"}, ClassUtils.getMethodNames(Son.class));
}
@Test
void testWrapImplClass() {
Wrapper w = Wrapper.getWrapper(Impl0.class);
String[] propertyNames = w.getPropertyNames();
Assertions.assertArrayEquals(propertyNames, new String[] {"a", "b", "c"});
// fields that do not contain the static|final|transient modifier
Assertions.assertFalse(w.hasProperty("f"));
Assertions.assertFalse(w.hasProperty("l"));
Assertions.assertFalse(w.hasProperty("ch"));
// only has public methods, do not contain the private or comes from object methods
Assertions.assertTrue(w.hasMethod("publicMethod"));
Assertions.assertFalse(w.hasMethod("privateMethod"));
Assertions.assertFalse(w.hasMethod("hashcode"));
}
public interface I0 {
String getName();
}
public interface I1 extends I0 {
void setName(String name);
void hello(String name);
int showInt(int v);
float getFloat();
void setFloat(float f);
}
public interface I2 {
void setFloat(float f);
void setFloat(Float f);
}
public interface EmptyService {}
public interface Parent1 {
void hello();
}
public interface Parent2 {
void world();
}
public interface Son extends Parent1, Parent2 {}
public static class Impl0 {
public float a, b, c;
public transient boolean f;
public static long l = 1;
public final char ch = 'c';
private void privateMethod() {}
public void publicMethod() {}
}
public static class Impl1 implements I1 {
private String name = "you name";
private float fv = 0;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void hello(String name) {
System.out.println("hello " + name);
}
public int showInt(int v) {
return v;
}
public float getFloat() {
return fv;
}
public void setFloat(float f) {
fv = f;
}
}
public static class Impl2 implements I2 {
private float float1;
private Float float2;
@Override
public void setFloat(float f) {
this.float1 = f;
}
@Override
public void setFloat(Float f) {
this.float2 = f;
}
public float getFloat1() {
return float1;
}
public Float getFloat2() {
return float2;
}
}
public static class EmptyServiceImpl implements EmptyService {}
}
| 6,557 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/ProxyTest.java | /*
* 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 org.apache.dubbo.common.bytecode;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
@DisabledForJreRange(min = JRE.JAVA_16)
class ProxyTest {
@Test
void testMain() throws Exception {
Proxy proxy = Proxy.getProxy(ITest.class, ITest.class);
ITest instance = (ITest) proxy.newInstance((proxy1, method, args) -> {
if ("getName".equals(method.getName())) {
assertEquals(args.length, 0);
} else if ("setName".equals(method.getName())) {
assertEquals(args.length, 2);
assertEquals(args[0], "qianlei");
assertEquals(args[1], "hello");
}
return null;
});
assertNull(instance.getName());
instance.setName("qianlei", "hello");
}
@Test
void testCglibProxy() throws Exception {
ITest test = (ITest) Proxy.getProxy(ITest.class).newInstance((proxy, method, args) -> {
System.out.println(method.getName());
return null;
});
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(test.getClass());
enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> null);
try {
enhancer.create();
} catch (IllegalArgumentException e) {
e.printStackTrace();
Assertions.fail();
}
}
public interface ITest {
String getName();
void setName(String name, String name2);
static String sayBye() {
return "Bye!";
}
}
}
| 6,558 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/MixinTest.java | /*
* 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 org.apache.dubbo.common.bytecode;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
class MixinTest {
@Test
void testMain() {
Mixin mixin = Mixin.mixin(new Class[] {I1.class, I2.class, I3.class}, new Class[] {C1.class, C2.class});
Object o = mixin.newInstance(new Object[] {new C1(), new C2()});
assertTrue(o instanceof I1);
assertTrue(o instanceof I2);
assertTrue(o instanceof I3);
((I1) o).m1();
((I2) o).m2();
((I3) o).m3();
}
public interface I1 {
void m1();
}
public interface I2 {
void m2();
}
public interface I3 {
void m3();
}
public class C1 implements Mixin.MixinAware {
public void m1() {
System.out.println("c1.m1();");
}
public void m2() {
System.out.println("c1.m2();");
}
public void setMixinInstance(Object mi) {
System.out.println("setMixinInstance:" + mi);
}
}
public class C2 implements Mixin.MixinAware {
public void m3() {
System.out.println("c2.m3();");
}
public void setMixinInstance(Object mi) {
System.out.println("setMixinInstance:" + mi);
}
}
}
| 6,559 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/profiler/ProfilerTest.java | /*
* 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 org.apache.dubbo.common.profiler;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class ProfilerTest {
@Test
void testProfiler() {
ProfilerEntry one = Profiler.start("1");
ProfilerEntry two = Profiler.enter(one, "1-2");
ProfilerEntry three = Profiler.enter(two, "1-2-3");
ProfilerEntry four = Profiler.enter(three, "1-2-3-4");
Assertions.assertEquals(three, Profiler.release(four));
ProfilerEntry five = Profiler.enter(three, "1-2-3-5");
Assertions.assertEquals(three, Profiler.release(five));
Assertions.assertEquals(two, Profiler.release(three));
ProfilerEntry six = Profiler.enter(two, "1-2-6");
Assertions.assertEquals(two, Profiler.release(six));
ProfilerEntry seven = Profiler.enter(six, "1-2-6-7");
Assertions.assertEquals(six, Profiler.release(seven));
ProfilerEntry eight = Profiler.enter(six, "1-2-6-8");
Assertions.assertEquals(six, Profiler.release(eight));
Assertions.assertEquals(2, two.getSub().size());
Assertions.assertEquals(three, two.getSub().get(0));
Assertions.assertEquals(six, two.getSub().get(1));
Profiler.release(two);
ProfilerEntry nine = Profiler.enter(one, "1-9");
Profiler.release(nine);
Profiler.release(one);
/*
* Start time: 287395734500659
* +-[ Offset: 0.000000ms; Usage: 4.721583ms, 100% ] 1
* +-[ Offset: 0.013136ms; Usage: 4.706288ms, 99% ] 1-2
* | +-[ Offset: 0.027903ms; Usage: 4.662918ms, 98% ] 1-2-3
* | | +-[ Offset: 0.029742ms; Usage: 0.003785ms, 0% ] 1-2-3-4
* | | +-[ Offset: 4.688477ms; Usage: 0.001398ms, 0% ] 1-2-3-5
* | +-[ Offset: 4.693346ms; Usage: 0.000316ms, 0% ] 1-2-6
* | +-[ Offset: 4.695191ms; Usage: 0.000212ms, 0% ] 1-2-6-7
* | +-[ Offset: 4.696655ms; Usage: 0.000195ms, 0% ] 1-2-6-8
* +-[ Offset: 4.721044ms; Usage: 0.000270ms, 0% ] 1-9
*/
Assertions.assertNotEquals(Profiler.buildDetail(one), Profiler.buildDetail(two));
Assertions.assertNotEquals(Profiler.buildDetail(one), Profiler.buildDetail(three));
Assertions.assertNotEquals(Profiler.buildDetail(one), Profiler.buildDetail(four));
Assertions.assertNotEquals(Profiler.buildDetail(one), Profiler.buildDetail(five));
Assertions.assertNotEquals(Profiler.buildDetail(one), Profiler.buildDetail(six));
Assertions.assertNotEquals(Profiler.buildDetail(one), Profiler.buildDetail(seven));
Assertions.assertNotEquals(Profiler.buildDetail(one), Profiler.buildDetail(eight));
Assertions.assertNotEquals(Profiler.buildDetail(one), Profiler.buildDetail(nine));
}
@Test
void testBizProfiler() {
Assertions.assertNull(Profiler.getBizProfiler());
ProfilerEntry one = Profiler.start("1");
Profiler.setToBizProfiler(one);
Profiler.release(Profiler.enter(Profiler.getBizProfiler(), "1-2"));
Assertions.assertEquals(one, Profiler.getBizProfiler());
Assertions.assertEquals(1, one.getSub().size());
Profiler.removeBizProfiler();
Assertions.assertNull(Profiler.getBizProfiler());
}
}
| 6,560 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/resource/GlobalResourcesRepositoryTest.java | /*
* 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 org.apache.dubbo.common.resource;
import java.util.concurrent.ExecutorService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* {@link GlobalResourcesRepository}
*/
class GlobalResourcesRepositoryTest {
@Test
void test() {
GlobalResourcesRepository repository = GlobalResourcesRepository.getInstance();
ExecutorService globalExecutorService = GlobalResourcesRepository.getGlobalExecutorService();
Assertions.assertNotNull(globalExecutorService);
GlobalDisposable globalDisposable = new GlobalDisposable();
GlobalResourcesRepository.registerGlobalDisposable(globalDisposable);
OneOffDisposable oneOffDisposable = new OneOffDisposable();
repository.registerDisposable(oneOffDisposable);
repository.destroy();
Assertions.assertTrue(globalExecutorService.isShutdown());
Assertions.assertTrue(globalDisposable.isDestroyed());
Assertions.assertTrue(oneOffDisposable.isDestroyed());
Assertions.assertTrue(
!GlobalResourcesRepository.getGlobalReusedDisposables().isEmpty());
Assertions.assertTrue(
GlobalResourcesRepository.getGlobalReusedDisposables().contains(globalDisposable));
Assertions.assertTrue(repository.getOneoffDisposables().isEmpty());
}
class GlobalDisposable implements Disposable {
boolean destroyed = false;
@Override
public void destroy() {
destroyed = true;
}
public boolean isDestroyed() {
return destroyed;
}
}
class OneOffDisposable implements Disposable {
boolean destroyed = false;
@Override
public void destroy() {
destroyed = true;
}
public boolean isDestroyed() {
return destroyed;
}
}
}
| 6,561 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/compiler | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/ClassUtilsTest.java | /*
* 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 org.apache.dubbo.common.compiler.support;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class ClassUtilsTest {
@Test
void testNewInstance() {
HelloServiceImpl0 instance = (HelloServiceImpl0) ClassUtils.newInstance(HelloServiceImpl0.class.getName());
Assertions.assertEquals("Hello world!", instance.sayHello());
}
@Test
void testNewInstance0() {
Assertions.assertThrows(
IllegalStateException.class, () -> ClassUtils.newInstance(PrivateHelloServiceImpl.class.getName()));
}
@Test
void testNewInstance1() {
Assertions.assertThrows(
IllegalStateException.class,
() -> ClassUtils.newInstance(
"org.apache.dubbo.common.compiler.support.internal.HelloServiceInternalImpl"));
}
@Test
void testNewInstance2() {
Assertions.assertThrows(
IllegalStateException.class,
() -> ClassUtils.newInstance("org.apache.dubbo.common.compiler.support.internal.NotExistsImpl"));
}
@Test
void testForName() {
ClassUtils.forName(new String[] {"org.apache.dubbo.common.compiler.support"}, "HelloServiceImpl0");
}
@Test
void testForName1() {
Assertions.assertThrows(
IllegalStateException.class,
() -> ClassUtils.forName(
new String[] {"org.apache.dubbo.common.compiler.support"}, "HelloServiceImplXX"));
}
@Test
void testForName2() {
Assertions.assertEquals(boolean.class, ClassUtils.forName("boolean"));
Assertions.assertEquals(byte.class, ClassUtils.forName("byte"));
Assertions.assertEquals(char.class, ClassUtils.forName("char"));
Assertions.assertEquals(short.class, ClassUtils.forName("short"));
Assertions.assertEquals(int.class, ClassUtils.forName("int"));
Assertions.assertEquals(long.class, ClassUtils.forName("long"));
Assertions.assertEquals(float.class, ClassUtils.forName("float"));
Assertions.assertEquals(double.class, ClassUtils.forName("double"));
Assertions.assertEquals(boolean[].class, ClassUtils.forName("boolean[]"));
Assertions.assertEquals(byte[].class, ClassUtils.forName("byte[]"));
Assertions.assertEquals(char[].class, ClassUtils.forName("char[]"));
Assertions.assertEquals(short[].class, ClassUtils.forName("short[]"));
Assertions.assertEquals(int[].class, ClassUtils.forName("int[]"));
Assertions.assertEquals(long[].class, ClassUtils.forName("long[]"));
Assertions.assertEquals(float[].class, ClassUtils.forName("float[]"));
Assertions.assertEquals(double[].class, ClassUtils.forName("double[]"));
}
@Test
void testGetBoxedClass() {
Assertions.assertEquals(Boolean.class, ClassUtils.getBoxedClass(boolean.class));
Assertions.assertEquals(Character.class, ClassUtils.getBoxedClass(char.class));
Assertions.assertEquals(Byte.class, ClassUtils.getBoxedClass(byte.class));
Assertions.assertEquals(Short.class, ClassUtils.getBoxedClass(short.class));
Assertions.assertEquals(Integer.class, ClassUtils.getBoxedClass(int.class));
Assertions.assertEquals(Long.class, ClassUtils.getBoxedClass(long.class));
Assertions.assertEquals(Float.class, ClassUtils.getBoxedClass(float.class));
Assertions.assertEquals(Double.class, ClassUtils.getBoxedClass(double.class));
Assertions.assertEquals(ClassUtilsTest.class, ClassUtils.getBoxedClass(ClassUtilsTest.class));
}
@Test
void testBoxedAndUnboxed() {
Assertions.assertEquals(Boolean.valueOf(true), ClassUtils.boxed(true));
Assertions.assertEquals(Character.valueOf('0'), ClassUtils.boxed('0'));
Assertions.assertEquals(Byte.valueOf((byte) 0), ClassUtils.boxed((byte) 0));
Assertions.assertEquals(Short.valueOf((short) 0), ClassUtils.boxed((short) 0));
Assertions.assertEquals(Integer.valueOf((int) 0), ClassUtils.boxed((int) 0));
Assertions.assertEquals(Long.valueOf((long) 0), ClassUtils.boxed((long) 0));
Assertions.assertEquals(Float.valueOf((float) 0), ClassUtils.boxed((float) 0));
Assertions.assertEquals(Double.valueOf((double) 0), ClassUtils.boxed((double) 0));
Assertions.assertTrue(ClassUtils.unboxed(Boolean.valueOf(true)));
Assertions.assertEquals('0', ClassUtils.unboxed(Character.valueOf('0')));
Assertions.assertEquals((byte) 0, ClassUtils.unboxed(Byte.valueOf((byte) 0)));
Assertions.assertEquals((short) 0, ClassUtils.unboxed(Short.valueOf((short) 0)));
Assertions.assertEquals(0, ClassUtils.unboxed(Integer.valueOf((int) 0)));
Assertions.assertEquals((long) 0, ClassUtils.unboxed(Long.valueOf((long) 0)));
// Assertions.assertEquals((float) 0, ClassUtils.unboxed(Float.valueOf((float) 0)), ((float) 0));
// Assertions.assertEquals((double) 0, ClassUtils.unboxed(Double.valueOf((double) 0)), ((double) 0));
}
@Test
void testGetSize() {
Assertions.assertEquals(0, ClassUtils.getSize(null));
List<Integer> list = new ArrayList<>();
list.add(1);
Assertions.assertEquals(1, ClassUtils.getSize(list));
Map map = new HashMap();
map.put(1, 1);
Assertions.assertEquals(1, ClassUtils.getSize(map));
int[] array = new int[1];
Assertions.assertEquals(1, ClassUtils.getSize(array));
Assertions.assertEquals(-1, ClassUtils.getSize(new Object()));
}
@Test
void testToUri() {
Assertions.assertThrows(RuntimeException.class, () -> ClassUtils.toURI("#xx_abc#hello"));
}
@Test
void testGetSizeMethod() {
Assertions.assertEquals("getLength()", ClassUtils.getSizeMethod(GenericClass3.class));
}
@Test
void testGetSimpleClassName() {
Assertions.assertNull(ClassUtils.getSimpleClassName(null));
Assertions.assertEquals("Map", ClassUtils.getSimpleClassName(Map.class.getName()));
Assertions.assertEquals("Map", ClassUtils.getSimpleClassName(Map.class.getSimpleName()));
}
private interface GenericInterface<T> {}
private class GenericClass<T> implements GenericInterface<T> {}
private class GenericClass0 implements GenericInterface<String> {}
private class GenericClass1 implements GenericInterface<Collection<String>> {}
private class GenericClass2<T> implements GenericInterface<T[]> {}
private class GenericClass3<T> implements GenericInterface<T[][]> {
public int getLength() {
return -1;
}
}
private class PrivateHelloServiceImpl implements HelloService {
private PrivateHelloServiceImpl() {}
@Override
public String sayHello() {
return "Hello world!";
}
}
}
| 6,562 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/compiler | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JavaCodeTest.java | /*
* 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 org.apache.dubbo.common.compiler.support;
import java.util.concurrent.atomic.AtomicInteger;
class JavaCodeTest {
public static final AtomicInteger SUBFIX = new AtomicInteger(8);
boolean shouldIgnoreWithoutPackage() {
String jdkVersion = System.getProperty("java.specification.version");
try {
return Integer.parseInt(jdkVersion) > 15;
} catch (Throwable t) {
return false;
}
}
String getSimpleCode() {
StringBuilder code = new StringBuilder();
code.append("package org.apache.dubbo.common.compiler.support;");
code.append("public class HelloServiceImpl" + SUBFIX.getAndIncrement() + " implements HelloService {");
code.append(" public String sayHello() { ");
code.append(" return \"Hello world!\"; ");
code.append(" }");
code.append('}');
return code.toString();
}
String getSimpleCodeWithoutPackage() {
StringBuilder code = new StringBuilder();
code.append("public class HelloServiceImpl" + SUBFIX.getAndIncrement()
+ "implements org.apache.dubbo.common.compiler.support.HelloService.HelloService {");
code.append(" public String sayHello() { ");
code.append(" return \"Hello world!\"; ");
code.append(" }");
code.append('}');
return code.toString();
}
String getSimpleCodeWithSyntax() {
StringBuilder code = new StringBuilder();
code.append("package org.apache.dubbo.common.compiler.support;");
code.append("public class HelloServiceImpl" + SUBFIX.getAndIncrement() + " implements HelloService {");
code.append(" public String sayHello() { ");
code.append(" return \"Hello world!\"; ");
// code.append(" }");
// }
return code.toString();
}
// only used for javassist
String getSimpleCodeWithSyntax0() {
StringBuilder code = new StringBuilder();
code.append("package org.apache.dubbo.common.compiler.support;");
code.append("public class HelloServiceImpl_0 implements HelloService {");
code.append(" public String sayHello() { ");
code.append(" return \"Hello world!\"; ");
// code.append(" }");
// }
return code.toString();
}
String getSimpleCodeWithImports() {
StringBuilder code = new StringBuilder();
code.append("package org.apache.dubbo.common.compiler.support;");
code.append("import java.lang.*;\n");
code.append("import org.apache.dubbo.common.compiler.support;\n");
code.append("public class HelloServiceImpl2" + SUBFIX.getAndIncrement() + " implements HelloService {");
code.append(" public String sayHello() { ");
code.append(" return \"Hello world!\"; ");
code.append(" }");
code.append('}');
return code.toString();
}
String getSimpleCodeWithWithExtends() {
StringBuilder code = new StringBuilder();
code.append("package org.apache.dubbo.common.compiler.support;");
code.append("import java.lang.*;\n");
code.append("import org.apache.dubbo.common.compiler.support;\n");
code.append("public class HelloServiceImpl" + SUBFIX.getAndIncrement()
+ " extends org.apache.dubbo.common.compiler.support.HelloServiceImpl0 {\n");
code.append(" public String sayHello() { ");
code.append(" return \"Hello world3!\"; ");
code.append(" }");
code.append('}');
return code.toString();
}
}
| 6,563 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/compiler | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/HelloServiceImpl0.java | /*
* 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 org.apache.dubbo.common.compiler.support;
public class HelloServiceImpl0 implements HelloService {
@Override
public String sayHello() {
return "Hello world!";
}
}
| 6,564 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/compiler | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JdkCompilerTest.java | /*
* 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 org.apache.dubbo.common.compiler.support;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class JdkCompilerTest extends JavaCodeTest {
@Test
void test_compileJavaClass() throws Exception {
JdkCompiler compiler = new JdkCompiler();
Class<?> clazz = compiler.compile(JavaCodeTest.class, getSimpleCode(), JdkCompiler.class.getClassLoader());
Object instance = clazz.getDeclaredConstructor().newInstance();
Method sayHello = instance.getClass().getMethod("sayHello");
Assertions.assertEquals("Hello world!", sayHello.invoke(instance));
}
@Test
void test_compileJavaClass0() {
Assertions.assertThrows(IllegalStateException.class, () -> {
JdkCompiler compiler = new JdkCompiler();
Class<?> clazz = compiler.compile(
JavaCodeTest.class, getSimpleCodeWithoutPackage(), JdkCompiler.class.getClassLoader());
Object instance = clazz.getDeclaredConstructor().newInstance();
Method sayHello = instance.getClass().getMethod("sayHello");
Assertions.assertEquals("Hello world!", sayHello.invoke(instance));
});
}
@Test
void test_compileJavaClass1() {
Assertions.assertThrows(IllegalStateException.class, () -> {
JdkCompiler compiler = new JdkCompiler();
Class<?> clazz =
compiler.compile(JavaCodeTest.class, getSimpleCodeWithSyntax(), JdkCompiler.class.getClassLoader());
Object instance = clazz.getDeclaredConstructor().newInstance();
Method sayHello = instance.getClass().getMethod("sayHello");
Assertions.assertEquals("Hello world!", sayHello.invoke(instance));
});
}
@Test
void test_compileJavaClass_java8() throws Exception {
JdkCompiler compiler = new JdkCompiler("1.8");
Class<?> clazz = compiler.compile(JavaCodeTest.class, getSimpleCode(), JdkCompiler.class.getClassLoader());
Object instance = clazz.getDeclaredConstructor().newInstance();
Method sayHello = instance.getClass().getMethod("sayHello");
Assertions.assertEquals("Hello world!", sayHello.invoke(instance));
}
@Test
void test_compileJavaClass0_java8() {
Assertions.assertThrows(IllegalStateException.class, () -> {
JdkCompiler compiler = new JdkCompiler("1.8");
Class<?> clazz = compiler.compile(
JavaCodeTest.class, getSimpleCodeWithoutPackage(), JdkCompiler.class.getClassLoader());
Object instance = clazz.getDeclaredConstructor().newInstance();
Method sayHello = instance.getClass().getMethod("sayHello");
Assertions.assertEquals("Hello world!", sayHello.invoke(instance));
});
}
@Test
void test_compileJavaClass1_java8() {
Assertions.assertThrows(IllegalStateException.class, () -> {
JdkCompiler compiler = new JdkCompiler("1.8");
Class<?> clazz =
compiler.compile(JavaCodeTest.class, getSimpleCodeWithSyntax(), JdkCompiler.class.getClassLoader());
Object instance = clazz.getDeclaredConstructor().newInstance();
Method sayHello = instance.getClass().getMethod("sayHello");
Assertions.assertEquals("Hello world!", sayHello.invoke(instance));
});
}
}
| 6,565 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/compiler | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JavassistCompilerTest.java | /*
* 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 org.apache.dubbo.common.compiler.support;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
class JavassistCompilerTest extends JavaCodeTest {
@Test
void testCompileJavaClass() throws Exception {
JavassistCompiler compiler = new JavassistCompiler();
Class<?> clazz =
compiler.compile(JavaCodeTest.class, getSimpleCode(), JavassistCompiler.class.getClassLoader());
// Because javassist compiles using the caller class loader, we should't use HelloService directly
Object instance = clazz.getDeclaredConstructor().newInstance();
Method sayHello = instance.getClass().getMethod("sayHello");
Assertions.assertEquals("Hello world!", sayHello.invoke(instance));
}
/**
* javassist compile will find HelloService in classpath
*/
@Test
@DisabledForJreRange(min = JRE.JAVA_16)
public void testCompileJavaClass0() throws Exception {
boolean ignoreWithoutPackage = shouldIgnoreWithoutPackage();
JavassistCompiler compiler = new JavassistCompiler();
if (ignoreWithoutPackage) {
Assertions.assertThrows(
RuntimeException.class,
() -> compiler.compile(
null, getSimpleCodeWithoutPackage(), JavassistCompiler.class.getClassLoader()));
} else {
Class<?> clazz =
compiler.compile(null, getSimpleCodeWithoutPackage(), JavassistCompiler.class.getClassLoader());
Object instance = clazz.getDeclaredConstructor().newInstance();
Method sayHello = instance.getClass().getMethod("sayHello");
Assertions.assertEquals("Hello world!", sayHello.invoke(instance));
}
}
@Test
void testCompileJavaClass1() {
Assertions.assertThrows(IllegalStateException.class, () -> {
JavassistCompiler compiler = new JavassistCompiler();
Class<?> clazz = compiler.compile(
JavaCodeTest.class, getSimpleCodeWithSyntax0(), JavassistCompiler.class.getClassLoader());
Object instance = clazz.getDeclaredConstructor().newInstance();
Method sayHello = instance.getClass().getMethod("sayHello");
Assertions.assertEquals("Hello world!", sayHello.invoke(instance));
});
}
@Test
void testCompileJavaClassWithImport() throws Exception {
JavassistCompiler compiler = new JavassistCompiler();
Class<?> clazz = compiler.compile(
JavaCodeTest.class, getSimpleCodeWithImports(), JavassistCompiler.class.getClassLoader());
Object instance = clazz.getDeclaredConstructor().newInstance();
Method sayHello = instance.getClass().getMethod("sayHello");
Assertions.assertEquals("Hello world!", sayHello.invoke(instance));
}
@Test
void testCompileJavaClassWithExtends() throws Exception {
JavassistCompiler compiler = new JavassistCompiler();
Class<?> clazz = compiler.compile(
JavaCodeTest.class, getSimpleCodeWithWithExtends(), JavassistCompiler.class.getClassLoader());
Object instance = clazz.getDeclaredConstructor().newInstance();
Method sayHello = instance.getClass().getMethod("sayHello");
Assertions.assertEquals("Hello world3!", sayHello.invoke(instance));
}
}
| 6,566 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/compiler | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/HelloService.java | /*
* 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 org.apache.dubbo.common.compiler.support;
public interface HelloService {
String sayHello();
}
| 6,567 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/compiler | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/AdaptiveCompilerTest.java | /*
* 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 org.apache.dubbo.common.compiler.support;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class AdaptiveCompilerTest extends JavaCodeTest {
@Test
void testAvailableCompiler() throws Exception {
AdaptiveCompiler.setDefaultCompiler("jdk");
AdaptiveCompiler compiler = new AdaptiveCompiler();
compiler.setFrameworkModel(FrameworkModel.defaultModel());
Class<?> clazz = compiler.compile(JavaCodeTest.class, getSimpleCode(), AdaptiveCompiler.class.getClassLoader());
HelloService helloService =
(HelloService) clazz.getDeclaredConstructor().newInstance();
Assertions.assertEquals("Hello world!", helloService.sayHello());
}
}
| 6,568 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/internal/HelloServiceInternalImpl.java | /*
* 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 org.apache.dubbo.common.compiler.support.internal;
final class HelloServiceInternalImpl {}
| 6,569 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToIntegerConverterTest.java | /*
* 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 org.apache.dubbo.common.convert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToIntegerConverter} Test
*
* @since 2.7.6
*/
class StringToIntegerConverterTest {
private StringToIntegerConverter converter;
@BeforeEach
public void init() {
converter =
(StringToIntegerConverter) getExtensionLoader(Converter.class).getExtension("string-to-integer");
}
@Test
void testAccept() {
assertTrue(converter.accept(String.class, Integer.class));
}
@Test
void testConvert() {
assertEquals(Integer.valueOf("1"), converter.convert("1"));
assertNull(converter.convert(null));
assertThrows(NumberFormatException.class, () -> {
converter.convert("ttt");
});
}
}
| 6,570 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToLongConverterTest.java | /*
* 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 org.apache.dubbo.common.convert;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToLongConverter} Test
*
* @since 2.7.6
*/
class StringToLongConverterTest {
private StringToLongConverter converter;
@BeforeEach
public void init() {
converter = (StringToLongConverter) getExtensionLoader(Converter.class).getExtension("string-to-long");
}
@Test
void testAccept() {
assertTrue(converter.accept(String.class, Long.class));
}
@Test
void testConvert() {
assertEquals(Long.valueOf("1"), converter.convert("1"));
assertNull(converter.convert(null));
assertThrows(NumberFormatException.class, () -> {
converter.convert("ttt");
});
}
private <T> ExtensionLoader<T> getExtensionLoader(Class<T> extClass) {
return ApplicationModel.defaultModel().getDefaultModule().getExtensionLoader(extClass);
}
}
| 6,571 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToStringConverterTest.java | /*
* 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 org.apache.dubbo.common.convert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToStringConverter} Test
*
* @since 2.7.6
*/
class StringToStringConverterTest {
private StringToStringConverter converter;
@BeforeEach
public void init() {
converter =
(StringToStringConverter) getExtensionLoader(Converter.class).getExtension("string-to-string");
}
@Test
void testAccept() {
assertTrue(converter.accept(String.class, String.class));
}
@Test
void testConvert() {
assertEquals("1", converter.convert("1"));
assertNull(converter.convert(null));
}
}
| 6,572 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToBooleanConverterTest.java | /*
* 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 org.apache.dubbo.common.convert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToBooleanConverter} Test
*
* @since 2.7.6
*/
class StringToBooleanConverterTest {
private StringToBooleanConverter converter;
@BeforeEach
public void init() {
converter =
(StringToBooleanConverter) getExtensionLoader(Converter.class).getExtension("string-to-boolean");
}
@Test
void testAccept() {
assertTrue(converter.accept(String.class, Boolean.class));
}
@Test
void testConvert() {
assertTrue(converter.convert("true"));
assertTrue(converter.convert("true"));
assertTrue(converter.convert("True"));
assertFalse(converter.convert("a"));
assertNull(converter.convert(""));
assertNull(converter.convert(null));
}
}
| 6,573 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToCharArrayConverterTest.java | /*
* 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 org.apache.dubbo.common.convert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToCharArrayConverter} Test
*
* @since 2.7.6
*/
class StringToCharArrayConverterTest {
private StringToCharArrayConverter converter;
@BeforeEach
public void init() {
converter =
(StringToCharArrayConverter) getExtensionLoader(Converter.class).getExtension("string-to-char-array");
}
@Test
void testAccept() {
assertTrue(converter.accept(String.class, char[].class));
}
@Test
void testConvert() {
assertArrayEquals(new char[] {'1', '2', '3'}, converter.convert("123"));
assertNull(converter.convert(null));
}
}
| 6,574 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/ConverterTest.java | /*
* 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 org.apache.dubbo.common.convert;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
/**
* {@link Converter} Test-Cases
*
* @since 2.7.8
*/
class ConverterTest {
private ConverterUtil converterUtil;
@BeforeEach
public void setup() {
converterUtil = FrameworkModel.defaultModel().getBeanFactory().getBean(ConverterUtil.class);
}
@AfterEach
public void tearDown() {
FrameworkModel.destroyAll();
}
@Test
void testGetConverter() {
getExtensionLoader(Converter.class).getSupportedExtensionInstances().forEach(converter -> {
assertSame(converter, converterUtil.getConverter(converter.getSourceType(), converter.getTargetType()));
});
}
@Test
void testConvertIfPossible() {
assertEquals(Integer.valueOf(2), converterUtil.convertIfPossible("2", Integer.class));
assertEquals(Boolean.FALSE, converterUtil.convertIfPossible("false", Boolean.class));
assertEquals(Double.valueOf(1), converterUtil.convertIfPossible("1", Double.class));
}
private <T> ExtensionLoader<T> getExtensionLoader(Class<T> extClass) {
return ApplicationModel.defaultModel().getDefaultModule().getExtensionLoader(extClass);
}
}
| 6,575 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToCharacterConverterTest.java | /*
* 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 org.apache.dubbo.common.convert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToCharacterConverter} Test
*
* @since 2.7.6
*/
class StringToCharacterConverterTest {
private StringToCharacterConverter converter;
@BeforeEach
public void init() {
converter =
(StringToCharacterConverter) getExtensionLoader(Converter.class).getExtension("string-to-character");
}
@Test
void testAccept() {
assertTrue(converter.accept(String.class, Character.class));
}
@Test
void testConvert() {
assertEquals('t', converter.convert("t"));
assertNull(converter.convert(null));
assertThrows(IllegalArgumentException.class, () -> {
converter.convert("ttt");
});
}
}
| 6,576 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToShortConverterTest.java | /*
* 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 org.apache.dubbo.common.convert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToShortConverter} Test
*
* @since 2.7.6
*/
class StringToShortConverterTest {
private StringToShortConverter converter;
@BeforeEach
public void init() {
converter = (StringToShortConverter) getExtensionLoader(Converter.class).getExtension("string-to-short");
}
@Test
void testAccept() {
assertTrue(converter.accept(String.class, Short.class));
}
@Test
void testConvert() {
assertEquals(Short.valueOf("1"), converter.convert("1"));
assertNull(converter.convert(null));
assertThrows(NumberFormatException.class, () -> {
converter.convert("ttt");
});
}
}
| 6,577 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToDurationConverterTest.java | /*
* 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 org.apache.dubbo.common.convert;
import java.time.Duration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToDurationConverter} Test
*
* @since 3.2.3
*/
class StringToDurationConverterTest {
private StringToDurationConverter converter;
@BeforeEach
public void init() {
converter =
(StringToDurationConverter) getExtensionLoader(Converter.class).getExtension("string-to-duration");
}
@Test
void testAccept() {
assertTrue(converter.accept(String.class, Duration.class));
}
@Test
void testConvert() {
assertEquals(Duration.ofMillis(1000), converter.convert("1000ms"));
assertEquals(Duration.ofSeconds(1), converter.convert("1s"));
assertEquals(Duration.ofMinutes(1), converter.convert("1m"));
assertEquals(Duration.ofHours(1), converter.convert("1h"));
assertEquals(Duration.ofDays(1), converter.convert("1d"));
assertNull(converter.convert(null));
assertThrows(IllegalArgumentException.class, () -> {
converter.convert("ttt");
});
}
}
| 6,578 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToDoubleConverterTest.java | /*
* 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 org.apache.dubbo.common.convert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToDoubleConverter} Test
*
* @since 2.7.6
*/
class StringToDoubleConverterTest {
private StringToDoubleConverter converter;
@BeforeEach
public void init() {
converter =
(StringToDoubleConverter) getExtensionLoader(Converter.class).getExtension("string-to-double");
}
@Test
void testAccept() {
assertTrue(converter.accept(String.class, Double.class));
}
@Test
void testConvert() {
assertEquals(Double.valueOf("1.0"), converter.convert("1.0"));
assertNull(converter.convert(null));
assertThrows(NumberFormatException.class, () -> {
converter.convert("ttt");
});
}
}
| 6,579 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToOptionalConverterTest.java | /*
* 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 org.apache.dubbo.common.convert;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToOptionalConverter} Test
*
* @since 2.7.6
*/
class StringToOptionalConverterTest {
private StringToOptionalConverter converter;
@BeforeEach
public void init() {
converter =
(StringToOptionalConverter) getExtensionLoader(Converter.class).getExtension("string-to-optional");
}
@Test
void testAccept() {
assertTrue(converter.accept(String.class, Optional.class));
}
@Test
void testConvert() {
assertEquals(Optional.of("1"), converter.convert("1"));
assertEquals(Optional.empty(), converter.convert(null));
}
}
| 6,580 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToFloatConverterTest.java | /*
* 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 org.apache.dubbo.common.convert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToFloatConverter} Test
*
* @since 2.7.6
*/
class StringToFloatConverterTest {
private StringToFloatConverter converter;
@BeforeEach
public void init() {
converter = (StringToFloatConverter) getExtensionLoader(Converter.class).getExtension("string-to-float");
}
@Test
void testAccept() {
assertTrue(converter.accept(String.class, Float.class));
}
@Test
void testConvert() {
assertEquals(Float.valueOf("1.0"), converter.convert("1.0"));
assertNull(converter.convert(null));
assertThrows(NumberFormatException.class, () -> {
converter.convert("ttt");
});
}
}
| 6,581 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToSetConverterTest.java | /*
* 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 org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.TransferQueue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToSetConverter} Test
*
* @since 2.7.6
*/
class StringToSetConverterTest {
private StringToSetConverter converter;
@BeforeEach
public void init() {
converter = new StringToSetConverter(FrameworkModel.defaultModel());
}
@Test
void testAccept() {
assertFalse(converter.accept(String.class, Collection.class));
assertFalse(converter.accept(String.class, List.class));
assertFalse(converter.accept(String.class, AbstractList.class));
assertFalse(converter.accept(String.class, LinkedList.class));
assertFalse(converter.accept(String.class, ArrayList.class));
assertTrue(converter.accept(String.class, Set.class));
assertTrue(converter.accept(String.class, SortedSet.class));
assertTrue(converter.accept(String.class, NavigableSet.class));
assertTrue(converter.accept(String.class, TreeSet.class));
assertTrue(converter.accept(String.class, ConcurrentSkipListSet.class));
assertFalse(converter.accept(String.class, Queue.class));
assertFalse(converter.accept(String.class, BlockingQueue.class));
assertFalse(converter.accept(String.class, TransferQueue.class));
assertFalse(converter.accept(String.class, Deque.class));
assertFalse(converter.accept(String.class, BlockingDeque.class));
assertFalse(converter.accept(null, char[].class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, null));
}
@Test
void testConvert() {
Set values = new HashSet(asList(1.0, 2.0, 3.0));
Set result = (Set<Double>) converter.convert("1.0,2.0,3.0", Queue.class, Double.class);
assertTrue(CollectionUtils.equals(values, result));
values.clear();
values.add(123);
result = (Set) converter.convert("123", Queue.class, Integer.class);
assertTrue(CollectionUtils.equals(values, result));
assertNull(converter.convert(null, Collection.class, Integer.class));
assertNull(converter.convert("", Collection.class, null));
}
@Test
void testGetSourceType() {
assertEquals(String.class, converter.getSourceType());
}
@Test
void testGetPriority() {
assertEquals(Integer.MAX_VALUE - 2, converter.getPriority());
}
}
| 6,582 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToNavigableSetConverterTest.java | /*
* 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 org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JRE;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.TransferQueue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToNavigableSetConverter} Test
*
* @since 2.7.6
*/
class StringToNavigableSetConverterTest {
private MultiValueConverter converter;
@BeforeEach
public void init() {
converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-navigable-set");
}
@Test
void testAccept() {
assertFalse(converter.accept(String.class, Collection.class));
assertFalse(converter.accept(String.class, List.class));
assertFalse(converter.accept(String.class, AbstractList.class));
assertFalse(converter.accept(String.class, LinkedList.class));
assertFalse(converter.accept(String.class, ArrayList.class));
assertFalse(converter.accept(String.class, Set.class));
assertFalse(converter.accept(String.class, SortedSet.class));
assertTrue(converter.accept(String.class, NavigableSet.class));
assertTrue(converter.accept(String.class, TreeSet.class));
assertTrue(converter.accept(String.class, ConcurrentSkipListSet.class));
assertFalse(converter.accept(String.class, Queue.class));
assertFalse(converter.accept(String.class, BlockingQueue.class));
assertFalse(converter.accept(String.class, TransferQueue.class));
assertFalse(converter.accept(String.class, Deque.class));
assertFalse(converter.accept(String.class, BlockingDeque.class));
assertFalse(converter.accept(null, char[].class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, null));
}
@Test
void testConvert() {
Set values = new TreeSet(asList(1, 2, 3));
NavigableSet result = (NavigableSet) converter.convert("1,2,3", List.class, Integer.class);
assertTrue(CollectionUtils.equals(values, result));
values = new TreeSet(asList("123"));
result = (NavigableSet) converter.convert("123", NavigableSet.class, String.class);
assertTrue(CollectionUtils.equals(values, result));
assertNull(converter.convert(null, Collection.class, Integer.class));
assertNull(converter.convert("", Collection.class, null));
}
@Test
void testGetSourceType() {
assertEquals(String.class, converter.getSourceType());
}
@Test
void testGetPriority() {
// Since JDK21, add SequencedCollection, SequencedSet
assertEquals(
Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 6 : 4),
converter.getPriority());
}
}
| 6,583 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToTransferQueueConverterTest.java | /*
* 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 org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.common.utils.CollectionUtils;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToTransferQueueConverter} Test
*
* @since 2.7.6
*/
class StringToTransferQueueConverterTest {
private MultiValueConverter converter;
@BeforeEach
public void init() {
converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-transfer-queue");
}
@Test
void testAccept() {
assertFalse(converter.accept(String.class, Collection.class));
assertFalse(converter.accept(String.class, List.class));
assertFalse(converter.accept(String.class, AbstractList.class));
assertFalse(converter.accept(String.class, LinkedList.class));
assertFalse(converter.accept(String.class, ArrayList.class));
assertFalse(converter.accept(String.class, Set.class));
assertFalse(converter.accept(String.class, SortedSet.class));
assertFalse(converter.accept(String.class, NavigableSet.class));
assertFalse(converter.accept(String.class, TreeSet.class));
assertFalse(converter.accept(String.class, ConcurrentSkipListSet.class));
assertFalse(converter.accept(String.class, Queue.class));
assertFalse(converter.accept(String.class, BlockingQueue.class));
assertFalse(converter.accept(String.class, Deque.class));
assertFalse(converter.accept(String.class, BlockingDeque.class));
assertTrue(converter.accept(String.class, TransferQueue.class));
assertFalse(converter.accept(null, char[].class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, null));
}
@Test
void testConvert() {
TransferQueue values = new LinkedTransferQueue(asList(1, 2, 3));
TransferQueue result = (TransferQueue) converter.convert("1,2,3", List.class, Integer.class);
assertTrue(CollectionUtils.equals(values, result));
values.clear();
values.addAll(asList("123"));
result = (TransferQueue) converter.convert("123", NavigableSet.class, String.class);
assertTrue(CollectionUtils.equals(values, result));
assertNull(converter.convert(null, Collection.class, Integer.class));
assertNull(converter.convert("", Collection.class, null));
}
@Test
void testGetSourceType() {
assertEquals(String.class, converter.getSourceType());
}
@Test
void testGetPriority() {
assertEquals(Integer.MAX_VALUE - 4, converter.getPriority());
}
}
| 6,584 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToListConverterTest.java | /*
* 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 org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JRE;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.TransferQueue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToListConverter} Test
*
* @since 2.7.6
*/
class StringToListConverterTest {
private MultiValueConverter converter;
@BeforeEach
public void init() {
converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-list");
}
@Test
void testAccept() {
assertFalse(converter.accept(String.class, Collection.class));
assertTrue(converter.accept(String.class, List.class));
assertTrue(converter.accept(String.class, AbstractList.class));
assertTrue(converter.accept(String.class, LinkedList.class));
assertTrue(converter.accept(String.class, ArrayList.class));
assertFalse(converter.accept(String.class, Set.class));
assertFalse(converter.accept(String.class, SortedSet.class));
assertFalse(converter.accept(String.class, NavigableSet.class));
assertFalse(converter.accept(String.class, TreeSet.class));
assertFalse(converter.accept(String.class, ConcurrentSkipListSet.class));
assertFalse(converter.accept(String.class, Queue.class));
assertFalse(converter.accept(String.class, BlockingQueue.class));
assertFalse(converter.accept(String.class, TransferQueue.class));
assertFalse(converter.accept(String.class, Deque.class));
assertFalse(converter.accept(String.class, BlockingDeque.class));
assertFalse(converter.accept(null, char[].class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, null));
}
@Test
void testConvert() {
List values = asList(1, 2, 3);
List result = (List<Integer>) converter.convert("1,2,3", List.class, Integer.class);
assertTrue(CollectionUtils.equals(values, result));
values = asList("123");
result = (List<String>) converter.convert("123", List.class, String.class);
assertTrue(CollectionUtils.equals(values, result));
assertNull(converter.convert(null, Collection.class, Integer.class));
assertNull(converter.convert("", Collection.class, null));
}
@Test
void testGetSourceType() {
assertEquals(String.class, converter.getSourceType());
}
@Test
void testGetPriority() {
// Since JDK21, add SequencedCollection
assertEquals(
Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 3 : 2),
converter.getPriority());
}
}
| 6,585 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/MultiValueConverterTest.java | /*
* 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 org.apache.dubbo.common.convert.multiple;
import java.util.Collection;
import java.util.Deque;
import java.util.List;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TransferQueue;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link MultiValueConverter} Test
*
* @since 2.7.8
*/
class MultiValueConverterTest {
@Test
void testFind() {
MultiValueConverter converter = MultiValueConverter.find(String.class, String[].class);
assertEquals(StringToArrayConverter.class, converter.getClass());
converter = MultiValueConverter.find(String.class, BlockingDeque.class);
assertEquals(StringToBlockingDequeConverter.class, converter.getClass());
converter = MultiValueConverter.find(String.class, BlockingQueue.class);
assertEquals(StringToBlockingQueueConverter.class, converter.getClass());
converter = MultiValueConverter.find(String.class, Collection.class);
assertEquals(StringToCollectionConverter.class, converter.getClass());
converter = MultiValueConverter.find(String.class, Deque.class);
assertEquals(StringToDequeConverter.class, converter.getClass());
converter = MultiValueConverter.find(String.class, List.class);
assertEquals(StringToListConverter.class, converter.getClass());
converter = MultiValueConverter.find(String.class, NavigableSet.class);
assertEquals(StringToNavigableSetConverter.class, converter.getClass());
converter = MultiValueConverter.find(String.class, Queue.class);
assertEquals(StringToQueueConverter.class, converter.getClass());
converter = MultiValueConverter.find(String.class, Set.class);
assertEquals(StringToSetConverter.class, converter.getClass());
converter = MultiValueConverter.find(String.class, TransferQueue.class);
assertEquals(StringToTransferQueueConverter.class, converter.getClass());
}
}
| 6,586 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToSortedSetConverterTest.java | /*
* 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 org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JRE;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.TransferQueue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToSortedSetConverter} Test
*
* @since 2.7.6
*/
class StringToSortedSetConverterTest {
private MultiValueConverter converter;
@BeforeEach
public void init() {
converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-sorted-set");
}
@Test
void testAccept() {
assertFalse(converter.accept(String.class, Collection.class));
assertFalse(converter.accept(String.class, List.class));
assertFalse(converter.accept(String.class, AbstractList.class));
assertFalse(converter.accept(String.class, LinkedList.class));
assertFalse(converter.accept(String.class, ArrayList.class));
assertFalse(converter.accept(String.class, Set.class));
assertTrue(converter.accept(String.class, SortedSet.class));
assertTrue(converter.accept(String.class, NavigableSet.class));
assertTrue(converter.accept(String.class, TreeSet.class));
assertTrue(converter.accept(String.class, ConcurrentSkipListSet.class));
assertFalse(converter.accept(String.class, Queue.class));
assertFalse(converter.accept(String.class, BlockingQueue.class));
assertFalse(converter.accept(String.class, TransferQueue.class));
assertFalse(converter.accept(String.class, Deque.class));
assertFalse(converter.accept(String.class, BlockingDeque.class));
assertFalse(converter.accept(null, char[].class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, null));
}
@Test
void testConvert() {
Set values = new TreeSet(asList(1, 2, 3));
SortedSet result = (SortedSet) converter.convert("1,2,3", List.class, Integer.class);
assertTrue(CollectionUtils.equals(values, result));
values = new TreeSet(asList("123"));
result = (SortedSet) converter.convert("123", NavigableSet.class, String.class);
assertTrue(CollectionUtils.equals(values, result));
assertNull(converter.convert(null, Collection.class, Integer.class));
assertNull(converter.convert("", Collection.class, null));
}
@Test
void testGetSourceType() {
assertEquals(String.class, converter.getSourceType());
}
@Test
void testGetPriority() {
// Since JDK21, add SequencedCollection, SequencedSet
assertEquals(
Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 5 : 3),
converter.getPriority());
}
}
| 6,587 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToBlockingQueueConverterTest.java | /*
* 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 org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.common.utils.CollectionUtils;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.TransferQueue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToBlockingQueueConverter} Test
*
* @see BlockingDeque
* @since 2.7.6
*/
class StringToBlockingQueueConverterTest {
private MultiValueConverter converter;
@BeforeEach
public void init() {
converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-blocking-queue");
}
@Test
void testAccept() {
assertFalse(converter.accept(String.class, Collection.class));
assertFalse(converter.accept(String.class, List.class));
assertFalse(converter.accept(String.class, AbstractList.class));
assertFalse(converter.accept(String.class, ArrayList.class));
assertFalse(converter.accept(String.class, LinkedList.class));
assertFalse(converter.accept(String.class, Set.class));
assertFalse(converter.accept(String.class, SortedSet.class));
assertFalse(converter.accept(String.class, NavigableSet.class));
assertFalse(converter.accept(String.class, TreeSet.class));
assertFalse(converter.accept(String.class, ConcurrentSkipListSet.class));
assertFalse(converter.accept(String.class, Queue.class));
assertTrue(converter.accept(String.class, BlockingQueue.class));
assertTrue(converter.accept(String.class, TransferQueue.class));
assertFalse(converter.accept(String.class, Deque.class));
assertTrue(converter.accept(String.class, BlockingDeque.class));
assertFalse(converter.accept(null, char[].class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, null));
}
@Test
void testConvert() {
BlockingQueue values = new ArrayBlockingQueue(3);
values.offer(1);
values.offer(2);
values.offer(3);
BlockingQueue<Integer> result =
(BlockingQueue<Integer>) converter.convert("1,2,3", BlockingDeque.class, Integer.class);
assertTrue(CollectionUtils.equals(values, result));
values.clear();
values.offer(123);
result = (BlockingQueue<Integer>) converter.convert("123", BlockingDeque.class, Integer.class);
assertTrue(CollectionUtils.equals(values, result));
assertNull(converter.convert(null, Collection.class, null));
assertNull(converter.convert("", Collection.class, null));
}
@Test
void testGetSourceType() {
assertEquals(String.class, converter.getSourceType());
}
@Test
void testGetPriority() {
assertEquals(Integer.MAX_VALUE - 3, converter.getPriority());
}
}
| 6,588 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToBlockingDequeConverterTest.java | /*
* 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 org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JRE;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TransferQueue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToBlockingDequeConverter} Test
*
* @see BlockingDeque
* @since 2.7.6
*/
class StringToBlockingDequeConverterTest {
private MultiValueConverter converter;
@BeforeEach
public void init() {
converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-blocking-deque");
}
@Test
void testAccept() {
assertFalse(converter.accept(String.class, Collection.class));
assertFalse(converter.accept(String.class, List.class));
assertFalse(converter.accept(String.class, AbstractList.class));
assertFalse(converter.accept(String.class, ArrayList.class));
assertFalse(converter.accept(String.class, LinkedList.class));
assertFalse(converter.accept(String.class, Set.class));
assertFalse(converter.accept(String.class, SortedSet.class));
assertFalse(converter.accept(String.class, NavigableSet.class));
assertFalse(converter.accept(String.class, TreeSet.class));
assertFalse(converter.accept(String.class, ConcurrentSkipListSet.class));
assertFalse(converter.accept(String.class, Queue.class));
assertFalse(converter.accept(String.class, BlockingQueue.class));
assertFalse(converter.accept(String.class, TransferQueue.class));
assertFalse(converter.accept(String.class, Deque.class));
assertTrue(converter.accept(String.class, BlockingDeque.class));
assertFalse(converter.accept(null, char[].class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, null));
}
@Test
void testConvert() throws NoSuchFieldException {
BlockingQueue<Integer> values = new LinkedBlockingDeque(asList(1, 2, 3));
BlockingDeque<Integer> result =
(BlockingDeque<Integer>) converter.convert("1,2,3", BlockingDeque.class, Integer.class);
assertTrue(CollectionUtils.equals(values, result));
values = new LinkedBlockingDeque(asList(123));
result = (BlockingDeque<Integer>) converter.convert("123", BlockingDeque.class, Integer.class);
assertTrue(CollectionUtils.equals(values, result));
assertNull(converter.convert(null, Collection.class, null));
assertNull(converter.convert("", Collection.class, null));
}
@Test
void testGetSourceType() {
assertEquals(String.class, converter.getSourceType());
}
@Test
void testGetPriority() {
// Since JDK21, add SequencedCollection
assertEquals(
Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 6 : 5),
converter.getPriority());
}
}
| 6,589 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToArrayConverterTest.java | /*
* 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 org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static java.util.Objects.deepEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToArrayConverter} Test
*
* @since 2.7.6
*/
class StringToArrayConverterTest {
private StringToArrayConverter converter;
@BeforeEach
public void init() {
converter = new StringToArrayConverter(FrameworkModel.defaultModel());
}
@Test
void testAccept() {
assertTrue(converter.accept(String.class, char[].class));
assertTrue(converter.accept(null, char[].class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, null));
}
@Test
void testConvert() {
assertTrue(deepEquals(new Integer[] {123}, converter.convert("123", Integer[].class, Integer.class)));
assertTrue(deepEquals(new Integer[] {1, 2, 3}, converter.convert("1,2,3", Integer[].class, null)));
assertNull(converter.convert("", Integer[].class, null));
assertNull(converter.convert(null, Integer[].class, null));
}
@Test
void testGetSourceType() {
assertEquals(String.class, converter.getSourceType());
}
@Test
void testGetPriority() {
assertEquals(Integer.MAX_VALUE, converter.getPriority());
}
}
| 6,590 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToDequeConverterTest.java | /*
* 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 org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JRE;
import java.util.AbstractList;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.TransferQueue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToDequeConverter} Test
*
* @since 2.7.6
*/
class StringToDequeConverterTest {
private MultiValueConverter converter;
@BeforeEach
public void init() {
converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-deque");
}
@Test
void testAccept() {
assertFalse(converter.accept(String.class, Collection.class));
assertFalse(converter.accept(String.class, List.class));
assertFalse(converter.accept(String.class, AbstractList.class));
assertTrue(converter.accept(String.class, LinkedList.class));
assertFalse(converter.accept(String.class, ArrayList.class));
assertFalse(converter.accept(String.class, Queue.class));
assertFalse(converter.accept(String.class, BlockingQueue.class));
assertFalse(converter.accept(String.class, TransferQueue.class));
assertTrue(converter.accept(String.class, Deque.class));
assertTrue(converter.accept(String.class, BlockingDeque.class));
assertFalse(converter.accept(String.class, Set.class));
assertFalse(converter.accept(String.class, SortedSet.class));
assertFalse(converter.accept(String.class, NavigableSet.class));
assertFalse(converter.accept(String.class, TreeSet.class));
assertFalse(converter.accept(String.class, ConcurrentSkipListSet.class));
assertFalse(converter.accept(null, char[].class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, null));
}
@Test
void testConvert() {
Deque values = new ArrayDeque(asList(1, 2, 3));
Deque result = (Deque) converter.convert("1,2,3", Deque.class, Integer.class);
assertTrue(CollectionUtils.equals(values, result));
values = new ArrayDeque(asList("123"));
result = (Deque) converter.convert("123", Deque.class, String.class);
assertTrue(CollectionUtils.equals(values, result));
assertNull(converter.convert(null, Collection.class, Integer.class));
assertNull(converter.convert("", Collection.class, null));
}
@Test
void testGetSourceType() {
assertEquals(String.class, converter.getSourceType());
}
@Test
void testGetPriority() {
// Since JDK21, add SequencedCollection
assertEquals(
Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 4 : 3),
converter.getPriority());
}
}
| 6,591 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToQueueConverterTest.java | /*
* 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 org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.AbstractList;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.TransferQueue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToQueueConverter} Test
*
* @since 2.7.6
*/
class StringToQueueConverterTest {
private StringToQueueConverter converter;
@BeforeEach
public void init() {
converter = new StringToQueueConverter(FrameworkModel.defaultModel());
}
@Test
void testAccept() {
assertFalse(converter.accept(String.class, Collection.class));
assertFalse(converter.accept(String.class, List.class));
assertFalse(converter.accept(String.class, AbstractList.class));
assertTrue(converter.accept(String.class, LinkedList.class));
assertFalse(converter.accept(String.class, ArrayList.class));
assertTrue(converter.accept(String.class, Queue.class));
assertTrue(converter.accept(String.class, BlockingQueue.class));
assertTrue(converter.accept(String.class, TransferQueue.class));
assertTrue(converter.accept(String.class, Deque.class));
assertTrue(converter.accept(String.class, BlockingDeque.class));
assertFalse(converter.accept(String.class, Set.class));
assertFalse(converter.accept(String.class, SortedSet.class));
assertFalse(converter.accept(String.class, NavigableSet.class));
assertFalse(converter.accept(String.class, TreeSet.class));
assertFalse(converter.accept(String.class, ConcurrentSkipListSet.class));
assertFalse(converter.accept(null, char[].class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, null));
}
@Test
void testConvert() {
Queue values = new ArrayDeque(asList(1.0, 2.0, 3.0));
Queue result = (Queue<Double>) converter.convert("1.0,2.0,3.0", Queue.class, Double.class);
assertTrue(CollectionUtils.equals(values, result));
values.clear();
values.add(123);
result = (Queue) converter.convert("123", Queue.class, Integer.class);
assertTrue(CollectionUtils.equals(values, result));
assertNull(converter.convert(null, Collection.class, Integer.class));
assertNull(converter.convert("", Collection.class, null));
}
@Test
void testGetSourceType() {
assertEquals(String.class, converter.getSourceType());
}
@Test
void testGetPriority() {
assertEquals(Integer.MAX_VALUE - 2, converter.getPriority());
}
}
| 6,592 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToCollectionConverterTest.java | /*
* 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 org.apache.dubbo.common.convert.multiple;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.TransferQueue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link StringToCollectionConverter} Test
*
* @since 2.7.6
*/
class StringToCollectionConverterTest {
private MultiValueConverter converter;
@BeforeEach
public void init() {
converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-collection");
}
@Test
void testAccept() {
assertTrue(converter.accept(String.class, Collection.class));
assertTrue(converter.accept(String.class, List.class));
assertTrue(converter.accept(String.class, AbstractList.class));
assertTrue(converter.accept(String.class, ArrayList.class));
assertTrue(converter.accept(String.class, LinkedList.class));
assertTrue(converter.accept(String.class, Set.class));
assertTrue(converter.accept(String.class, SortedSet.class));
assertTrue(converter.accept(String.class, NavigableSet.class));
assertTrue(converter.accept(String.class, TreeSet.class));
assertTrue(converter.accept(String.class, ConcurrentSkipListSet.class));
assertTrue(converter.accept(String.class, Queue.class));
assertTrue(converter.accept(String.class, BlockingQueue.class));
assertTrue(converter.accept(String.class, TransferQueue.class));
assertTrue(converter.accept(String.class, Deque.class));
assertTrue(converter.accept(String.class, BlockingDeque.class));
assertFalse(converter.accept(null, char[].class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, String.class));
assertFalse(converter.accept(null, null));
}
@Test
void testConvert() {
List values = asList(1L, 2L, 3L);
Collection result = (Collection<Long>) converter.convert("1,2,3", Collection.class, Long.class);
assertEquals(values, result);
values = asList(123);
result = (Collection<Integer>) converter.convert("123", Collection.class, Integer.class);
assertEquals(values, result);
assertNull(converter.convert(null, Collection.class, Integer.class));
assertNull(converter.convert("", Collection.class, Integer.class));
}
@Test
void testGetSourceType() {
assertEquals(String.class, converter.getSourceType());
}
@Test
void testGetPriority() {
assertEquals(Integer.MAX_VALUE - 1, converter.getPriority());
}
}
| 6,593 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/store | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/common/store/support/SimpleDataStoreTest.java | /*
* 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 org.apache.dubbo.common.store.support;
import java.util.Map;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SimpleDataStoreTest {
private SimpleDataStore dataStore = new SimpleDataStore();
@Test
void testPutGet() throws Exception {
assertNull(dataStore.get("xxx", "yyy"));
dataStore.put("name", "key", "1");
assertEquals("1", dataStore.get("name", "key"));
assertNull(dataStore.get("xxx", "yyy"));
}
@Test
void testRemove() throws Exception {
dataStore.remove("xxx", "yyy");
dataStore.put("name", "key", "1");
dataStore.remove("name", "key");
assertNull(dataStore.get("name", "key"));
}
@Test
void testGetComponent() throws Exception {
Map<String, Object> map = dataStore.get("component");
assertTrue(map != null && map.isEmpty());
dataStore.put("component", "key", "value");
map = dataStore.get("component");
assertTrue(map != null && map.size() == 1);
dataStore.remove("component", "key");
assertNotEquals(map, dataStore.get("component"));
}
}
| 6,594 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/rpc/support/MockScopeModelDestroyListener.java | /*
* 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 org.apache.dubbo.rpc.support;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ScopeModelDestroyListener;
public class MockScopeModelDestroyListener implements ScopeModelDestroyListener {
private boolean destroyed = false;
private ScopeModel scopeModel;
@Override
public void onDestroy(ScopeModel scopeModel) {
this.destroyed = true;
this.scopeModel = scopeModel;
}
public boolean isDestroyed() {
return destroyed;
}
public ScopeModel getScopeModel() {
return scopeModel;
}
}
| 6,595 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/rpc/support/DemoService1Impl.java | /*
* 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 org.apache.dubbo.rpc.support;
import org.apache.dubbo.common.stream.StreamObserver;
public class DemoService1Impl implements DemoService1 {
@Override
public StreamObserver<String> sayHello(StreamObserver<String> request) {
request.onNext("BI_STREAM");
return request;
}
@Override
public void sayHello(String msg, StreamObserver<String> request) {
request.onNext(msg);
request.onNext("SERVER_STREAM");
request.onCompleted();
}
}
| 6,596 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/rpc/support/DemoServiceImpl.java | /*
* 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 org.apache.dubbo.rpc.support;
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
return "hello " + name;
}
}
| 6,597 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/rpc/support/DemoService1.java | /*
* 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 org.apache.dubbo.rpc.support;
import org.apache.dubbo.common.stream.StreamObserver;
public interface DemoService1 {
StreamObserver<String> sayHello(StreamObserver<String> request);
void sayHello(String msg, StreamObserver<String> request);
}
| 6,598 |
0 | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-common/src/test/java/org/apache/dubbo/rpc/support/DemoService.java | /*
* 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 org.apache.dubbo.rpc.support;
public interface DemoService {
String sayHello(String name);
}
| 6,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.