repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TKvTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TKvTest.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.qos.textui;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
class TKvTest {
@Test
void test1() {
TKv tKv = new TKv(
new TTable.ColumnDefine(TTable.Align.RIGHT), new TTable.ColumnDefine(10, false, TTable.Align.LEFT));
tKv.add("KEY-1", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
tKv.add("KEY-2", "1234567890");
tKv.add("KEY-3", "1234567890");
TTable tTable = new TTable(new TTable.ColumnDefine[] {
new TTable.ColumnDefine(), new TTable.ColumnDefine(20, false, TTable.Align.LEFT)
});
String kv = tKv.rendering();
assertThat(kv, containsString("ABCDEFGHIJ" + System.lineSeparator()));
assertThat(kv, containsString("KLMNOPQRST" + System.lineSeparator()));
assertThat(kv, containsString("UVWXYZ" + System.lineSeparator()));
tTable.addRow("OPTIONS", kv);
String table = tTable.rendering();
assertThat(table, containsString("|OPTIONS|"));
assertThat(table, containsString("|KEY-3"));
}
@Test
void test2() throws Exception {
TKv tKv = new TKv();
tKv.add("KEY-1", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
tKv.add("KEY-2", "1234567890");
tKv.add("KEY-3", "1234567890");
String kv = tKv.rendering();
assertThat(kv, containsString("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TLadderTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TLadderTest.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.qos.textui;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
class TLadderTest {
@Test
void testRendering() throws Exception {
TLadder ladder = new TLadder();
ladder.addItem("1");
ladder.addItem("2");
ladder.addItem("3");
ladder.addItem("4");
String result = ladder.rendering();
String expected = "1" + System.lineSeparator() + " `-2"
+ System.lineSeparator() + " `-3"
+ System.lineSeparator() + " `-4"
+ System.lineSeparator();
assertThat(result, equalTo(expected));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TTreeTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TTreeTest.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.qos.textui;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
class TTreeTest {
@Test
void test() throws Exception {
TTree tree = new TTree(false, "root");
tree.begin("one").begin("ONE").end().end();
tree.begin("two").begin("TWO").end().begin("2").end().end();
tree.begin("three").end();
String result = tree.rendering();
String expected = "`---+root\n" + " +---+one\n"
+ " | `---ONE\n"
+ " +---+two\n"
+ " | +---TWO\n"
+ " | `---2\n"
+ " `---three\n";
assertThat(result, equalTo(expected));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TTableTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TTableTest.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.qos.textui;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
class TTableTest {
@Test
void test1() throws Exception {
TTable table = new TTable(4);
table.addRow(1, "one", "uno", "un");
table.addRow(2, "two", "dos", "deux");
String result = table.rendering();
String expected = "+-+---+---+----+" + System.lineSeparator() + "|1|one|uno|un |"
+ System.lineSeparator() + "+-+---+---+----+"
+ System.lineSeparator() + "|2|two|dos|deux|"
+ System.lineSeparator() + "+-+---+---+----+"
+ System.lineSeparator();
assertThat(result, equalTo(expected));
}
@Test
void test2() throws Exception {
TTable table = new TTable(new TTable.ColumnDefine[] {
new TTable.ColumnDefine(5, true, TTable.Align.LEFT),
new TTable.ColumnDefine(10, false, TTable.Align.MIDDLE),
new TTable.ColumnDefine(10, false, TTable.Align.RIGHT)
});
table.addRow(1, "abcde", "ABCDE");
String result = table.rendering();
String expected = "+-+----------+----------+" + System.lineSeparator() + "|1| abcde | ABCDE|"
+ System.lineSeparator() + "+-+----------+----------+"
+ System.lineSeparator();
assertThat(result, equalTo(expected));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/ProtocolUtils.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/ProtocolUtils.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.qos.legacy;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
/**
* TODO Comment of ProtocolUtils
*/
public class ProtocolUtils {
public static <T> T refer(Class<T> type, String url) {
return refer(type, URL.valueOf(url));
}
public static <T> T refer(Class<T> type, URL url) {
Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
ProxyFactory proxy =
ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
return proxy.getProxy(protocol.refer(type, url));
}
public static <T> Exporter<T> export(T instance, Class<T> type, String url) {
return export(instance, type, URL.valueOf(url));
}
public static <T> Exporter<T> export(T instance, Class<T> type, URL url) {
Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
ProxyFactory proxy =
ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
return protocol.export(proxy.getInvoker(instance, type, url));
}
public static void closeAll() {
DubboProtocol.getDubboProtocol().destroy();
ExtensionLoader.getExtensionLoader(Protocol.class).destroy();
FrameworkModel.destroyAll();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandlerTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandlerTest.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.qos.legacy;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.qos.legacy.service.DemoService;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import org.junit.jupiter.api.AfterAll;
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.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
/**
* ChangeTelnetHandlerTest.java
*/
class ChangeTelnetHandlerTest {
private static TelnetHandler change = new ChangeTelnetHandler();
private Channel mockChannel;
private Invoker<DemoService> mockInvoker;
private static int portIncrease;
@AfterAll
public static void tearDown() {}
@SuppressWarnings("unchecked")
@BeforeEach
public void setUp() {
mockChannel = mock(Channel.class);
mockInvoker = mock(Invoker.class);
given(mockChannel.getAttribute("telnet.service"))
.willReturn("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService");
mockChannel.setAttribute("telnet.service", "DemoService");
givenLastCall();
mockChannel.setAttribute("telnet.service", "org.apache.dubbo.rpc.protocol.dubbo.support.DemoService");
givenLastCall();
mockChannel.setAttribute("telnet.service", "demo");
givenLastCall();
mockChannel.removeAttribute("telnet.service");
givenLastCall();
given(mockInvoker.getInterface()).willReturn(DemoService.class);
given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:" + (20994 + portIncrease++) + "/demo"));
}
private void givenLastCall() {}
@AfterEach
public void after() {
FrameworkModel.destroyAll();
reset(mockChannel, mockInvoker);
}
@Test
void testChangeSimpleName() throws RemotingException {
ExtensionLoader.getExtensionLoader(Protocol.class)
.getExtension(DubboProtocol.NAME)
.export(mockInvoker);
String result = change.telnet(mockChannel, "DemoService");
assertEquals("Used the DemoService as default.\r\nYou can cancel default service by command: cd /", result);
}
@Test
void testChangeName() throws RemotingException {
ExtensionLoader.getExtensionLoader(Protocol.class)
.getExtension(DubboProtocol.NAME)
.export(mockInvoker);
String result = change.telnet(mockChannel, "org.apache.dubbo.qos.legacy.service.DemoService");
assertEquals(
"Used the org.apache.dubbo.qos.legacy.service.DemoService as default.\r\nYou can cancel default service by command: cd /",
result);
}
@Test
void testChangePath() throws RemotingException {
ExtensionLoader.getExtensionLoader(Protocol.class)
.getExtension(DubboProtocol.NAME)
.export(mockInvoker);
String result = change.telnet(mockChannel, "demo");
assertEquals("Used the demo as default.\r\nYou can cancel default service by command: cd /", result);
}
@Test
void testChangeMessageNull() throws RemotingException {
String result = change.telnet(mockChannel, null);
assertEquals("Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService", result);
}
@Test
void testChangeServiceNotExport() throws RemotingException {
String result = change.telnet(mockChannel, "demo");
assertEquals("No such service demo", result);
}
@Test
void testChangeCancel() throws RemotingException {
String result = change.telnet(mockChannel, "..");
assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result);
}
@Test
void testChangeCancel2() throws RemotingException {
String result = change.telnet(mockChannel, "/");
assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/TraceTelnetHandlerTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/TraceTelnetHandlerTest.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.qos.legacy;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.qos.legacy.service.DemoService;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import org.apache.dubbo.rpc.protocol.dubbo.filter.TraceFilter;
import java.lang.reflect.Field;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
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.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
class TraceTelnetHandlerTest {
private TelnetHandler handler;
private Channel mockChannel;
private Invoker<DemoService> mockInvoker;
private URL url = URL.valueOf("dubbo://127.0.0.1:20884/demo");
@BeforeEach
public void setUp() {
handler = new TraceTelnetHandler();
mockChannel = mock(Channel.class);
mockInvoker = mock(Invoker.class);
given(mockInvoker.getInterface()).willReturn(DemoService.class);
given(mockInvoker.getUrl()).willReturn(url);
}
@AfterEach
public void tearDown() {
reset(mockChannel, mockInvoker);
FrameworkModel.destroyAll();
}
@Test
void testTraceTelnetAddTracer() throws Exception {
String method = "sayHello";
String message = "org.apache.dubbo.qos.legacy.service.DemoService sayHello 1";
Class<?> type = DemoService.class;
ExtensionLoader.getExtensionLoader(Protocol.class)
.getExtension(DubboProtocol.NAME)
.export(mockInvoker);
handler.telnet(mockChannel, message);
String key = type.getName() + "." + method;
Field tracers = TraceFilter.class.getDeclaredField("TRACERS");
tracers.setAccessible(true);
ConcurrentHashMap<String, Set<Channel>> map =
(ConcurrentHashMap<String, Set<Channel>>) tracers.get(new ConcurrentHashMap<String, Set<Channel>>());
Set<Channel> channels = map.getOrDefault(key, null);
Assertions.assertNotNull(channels);
Assertions.assertTrue(channels.contains(mockChannel));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/LogTelnetHandlerTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/LogTelnetHandlerTest.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.qos.legacy;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
/**
* LogTelnetHandlerTest.java
*/
class LogTelnetHandlerTest {
private static TelnetHandler log = new LogTelnetHandler();
private Channel mockChannel;
@Test
void testChangeLogLevel() throws RemotingException {
mockChannel = mock(Channel.class);
String result = log.telnet(mockChannel, "error");
assertTrue(result.contains("\r\nCURRENT LOG LEVEL:ERROR"));
String result2 = log.telnet(mockChannel, "warn");
assertTrue(result2.contains("\r\nCURRENT LOG LEVEL:WARN"));
}
@Test
void testPrintLog() throws RemotingException {
mockChannel = mock(Channel.class);
String result = log.telnet(mockChannel, "100");
assertTrue(result.contains("CURRENT LOG APPENDER"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/Type.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/Type.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.qos.legacy.service;
public enum Type {
High,
Normal,
Lower
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/Person.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/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.qos.legacy.service;
import java.io.Serializable;
/**
* Person.java
*/
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private 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;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/DemoServiceImpl.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/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.qos.legacy.service;
import org.apache.dubbo.rpc.RpcContext;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DemoServiceImpl implements DemoService {
private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class);
public DemoServiceImpl() {
super();
}
public void sayHello(String name) {
logger.info("hello {}", name);
}
public String echo(String text) {
return text;
}
public Map echo(Map map) {
return map;
}
public long timestamp() {
return System.currentTimeMillis();
}
public String getThreadName() {
return Thread.currentThread().getName();
}
public int getSize(String[] strs) {
if (strs == null) return -1;
return strs.length;
}
public int getSize(Object[] os) {
if (os == null) return -1;
return os.length;
}
public Object invoke(String service, String method) throws Exception {
logger.info(
"RpcContext.getServerAttachment().getRemoteHost()={}",
RpcContext.getServiceContext().getRemoteHost());
return service + ":" + method;
}
public Type enumlength(Type... types) {
if (types.length == 0) return Type.Lower;
return types[0];
}
public Type getType(Type type) {
return type;
}
public int stringLength(String str) {
return str.length();
}
public String get(CustomArgument arg1) {
return arg1.toString();
}
public byte getbyte(byte arg) {
return arg;
}
public Person gerPerson(Person person) {
return person;
}
public Set<String> keys(Map<String, String> map) {
return map == null ? null : map.keySet();
}
public void nonSerializedParameter(NonSerialized ns) {}
public NonSerialized returnNonSerialized() {
return new NonSerialized();
}
public long add(int a, long b) {
return a + b;
}
@Override
public int getPerson(Person person) {
return person.getAge();
}
@Override
public int getPerson(Person person1, Person person2) {
return person1.getAge() + person2.getAge();
}
@Override
public String getPerson(Man man) {
return man.getName();
}
@Override
public String getRemoteApplicationName() {
return RpcContext.getServiceContext().getRemoteApplicationName();
}
@Override
public Map<Integer, Object> getMap(Map<Integer, Object> map) {
return map;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/DemoService.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/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.qos.legacy.service;
import java.util.Map;
import java.util.Set;
/**
* <code>TestService</code>
*/
public interface DemoService {
void sayHello(String name);
Set<String> keys(Map<String, String> map);
String echo(String text);
Map echo(Map map);
long timestamp();
String getThreadName();
int getSize(String[] strs);
int getSize(Object[] os);
Object invoke(String service, String method) throws Exception;
int stringLength(String str);
Type enumlength(Type... types);
Type getType(Type type);
String get(CustomArgument arg1);
byte getbyte(byte arg);
void nonSerializedParameter(NonSerialized ns);
NonSerialized returnNonSerialized();
long add(int a, long b);
int getPerson(Person person);
int getPerson(Person person1, Person perso2);
String getPerson(Man man);
String getRemoteApplicationName();
Map<Integer, Object> getMap(Map<Integer, Object> map);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/NonSerialized.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/NonSerialized.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.qos.legacy.service;
public class NonSerialized {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/Man.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/Man.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.qos.legacy.service;
import java.io.Serializable;
/**
* Man.java
*/
public class Man implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private 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;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/CustomArgument.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/CustomArgument.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.qos.legacy.service;
import java.io.Serializable;
@SuppressWarnings("serial")
public class CustomArgument implements Serializable {
Type type;
String name;
public CustomArgument() {}
public CustomArgument(Type type, String name) {
super();
this.type = type;
this.name = name;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/GenericServiceTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/GenericServiceTest.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.qos.legacy.service.generic;
import org.apache.dubbo.common.beanutil.JavaBeanAccessor;
import org.apache.dubbo.common.beanutil.JavaBeanDescriptor;
import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.serialize.Serialization;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.rpc.service.GenericException;
import org.apache.dubbo.rpc.service.GenericService;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA;
@Disabled("Keeps failing on Travis, but can not be reproduced locally.")
class GenericServiceTest {
@Test
void testGenericServiceException() {
ServiceConfig<GenericService> service = new ServiceConfig<GenericService>();
service.setInterface(DemoService.class.getName());
service.setRef(new GenericService() {
public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException {
if ("sayName".equals(method)) {
return "Generic " + args[0];
}
if ("throwDemoException".equals(method)) {
throw new GenericException(DemoException.class.getName(), "Generic");
}
if ("getUsers".equals(method)) {
return args[0];
}
return null;
}
});
ReferenceConfig<DemoService> reference = new ReferenceConfig<DemoService>();
reference.setInterface(DemoService.class);
reference.setUrl("dubbo://127.0.0.1:29581?generic=true&timeout=3000");
DubboBootstrap bootstrap = DubboBootstrap.getInstance()
.application(new ApplicationConfig("generic-test"))
.registry(new RegistryConfig("N/A"))
.protocol(new ProtocolConfig("dubbo", 29581))
.service(service)
.reference(reference);
bootstrap.start();
try {
DemoService demoService = bootstrap.getCache().get(reference);
// say name
Assertions.assertEquals("Generic Haha", demoService.sayName("Haha"));
// get users
List<User> users = new ArrayList<User>();
users.add(new User("Aaa"));
users = demoService.getUsers(users);
Assertions.assertEquals("Aaa", users.get(0).getName());
// throw demo exception
try {
demoService.throwDemoException();
Assertions.fail();
} catch (DemoException e) {
Assertions.assertEquals("Generic", e.getMessage());
}
} finally {
bootstrap.stop();
}
}
@SuppressWarnings("unchecked")
@Test
void testGenericReferenceException() {
ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
service.setInterface(DemoService.class.getName());
service.setRef(new DemoServiceImpl());
ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>();
reference.setInterface(DemoService.class);
reference.setUrl("dubbo://127.0.0.1:29581?scope=remote&timeout=3000");
reference.setGeneric(true);
DubboBootstrap bootstrap = DubboBootstrap.getInstance()
.application(new ApplicationConfig("generic-test"))
.registry(new RegistryConfig("N/A"))
.protocol(new ProtocolConfig("dubbo", 29581))
.service(service)
.reference(reference);
bootstrap.start();
try {
GenericService genericService = bootstrap.getCache().get(reference);
List<Map<String, Object>> users = new ArrayList<Map<String, Object>>();
Map<String, Object> user = new HashMap<String, Object>();
user.put("class", "org.apache.dubbo.config.api.User");
user.put("name", "actual.provider");
users.add(user);
users = (List<Map<String, Object>>)
genericService.$invoke("getUsers", new String[] {List.class.getName()}, new Object[] {users});
Assertions.assertEquals(1, users.size());
Assertions.assertEquals("actual.provider", users.get(0).get("name"));
} finally {
bootstrap.stop();
}
}
@Test
void testGenericSerializationJava() throws Exception {
ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
service.setInterface(DemoService.class.getName());
DemoServiceImpl ref = new DemoServiceImpl();
service.setRef(ref);
ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>();
reference.setInterface(DemoService.class);
reference.setUrl("dubbo://127.0.0.1:29581?scope=remote&timeout=3000");
reference.setGeneric(GENERIC_SERIALIZATION_NATIVE_JAVA);
DubboBootstrap bootstrap = DubboBootstrap.getInstance()
.application(new ApplicationConfig("generic-test"))
.registry(new RegistryConfig("N/A"))
.protocol(new ProtocolConfig("dubbo", 29581))
.service(service)
.reference(reference);
bootstrap.start();
try {
GenericService genericService = bootstrap.getCache().get(reference);
String name = "kimi";
ByteArrayOutputStream bos = new ByteArrayOutputStream(512);
ExtensionLoader.getExtensionLoader(Serialization.class)
.getExtension("nativejava")
.serialize(null, bos)
.writeObject(name);
byte[] arg = bos.toByteArray();
Object obj = genericService.$invoke("sayName", new String[] {String.class.getName()}, new Object[] {arg});
Assertions.assertTrue(obj instanceof byte[]);
byte[] result = (byte[]) obj;
Assertions.assertEquals(
ref.sayName(name),
ExtensionLoader.getExtensionLoader(Serialization.class)
.getExtension("nativejava")
.deserialize(null, new ByteArrayInputStream(result))
.readObject()
.toString());
// getUsers
List<User> users = new ArrayList<User>();
User user = new User();
user.setName(name);
users.add(user);
bos = new ByteArrayOutputStream(512);
ExtensionLoader.getExtensionLoader(Serialization.class)
.getExtension("nativejava")
.serialize(null, bos)
.writeObject(users);
obj = genericService.$invoke(
"getUsers", new String[] {List.class.getName()}, new Object[] {bos.toByteArray()});
Assertions.assertTrue(obj instanceof byte[]);
result = (byte[]) obj;
Assertions.assertEquals(
users,
ExtensionLoader.getExtensionLoader(Serialization.class)
.getExtension("nativejava")
.deserialize(null, new ByteArrayInputStream(result))
.readObject());
// echo(int)
bos = new ByteArrayOutputStream(512);
ExtensionLoader.getExtensionLoader(Serialization.class)
.getExtension("nativejava")
.serialize(null, bos)
.writeObject(Integer.MAX_VALUE);
obj = genericService.$invoke("echo", new String[] {int.class.getName()}, new Object[] {bos.toByteArray()});
Assertions.assertTrue(obj instanceof byte[]);
Assertions.assertEquals(
Integer.MAX_VALUE,
ExtensionLoader.getExtensionLoader(Serialization.class)
.getExtension("nativejava")
.deserialize(null, new ByteArrayInputStream((byte[]) obj))
.readObject());
} finally {
bootstrap.stop();
}
}
@Test
void testGenericInvokeWithBeanSerialization() {
ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
service.setInterface(DemoService.class);
DemoServiceImpl impl = new DemoServiceImpl();
service.setRef(impl);
ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>();
reference.setInterface(DemoService.class);
reference.setUrl("dubbo://127.0.0.1:29581?scope=remote&timeout=3000");
reference.setGeneric(GENERIC_SERIALIZATION_BEAN);
DubboBootstrap bootstrap = DubboBootstrap.getInstance()
.application(new ApplicationConfig("generic-test"))
.registry(new RegistryConfig("N/A"))
.protocol(new ProtocolConfig("dubbo", 29581))
.service(service)
.reference(reference);
bootstrap.start();
try {
GenericService genericService = bootstrap.getCache().get(reference);
User user = new User();
user.setName("zhangsan");
List<User> users = new ArrayList<User>();
users.add(user);
Object result =
genericService.$invoke("getUsers", new String[] {ReflectUtils.getName(List.class)}, new Object[] {
JavaBeanSerializeUtil.serialize(users, JavaBeanAccessor.METHOD)
});
Assertions.assertTrue(result instanceof JavaBeanDescriptor);
JavaBeanDescriptor descriptor = (JavaBeanDescriptor) result;
Assertions.assertTrue(descriptor.isCollectionType());
Assertions.assertEquals(1, descriptor.propertySize());
descriptor = (JavaBeanDescriptor) descriptor.getProperty(0);
Assertions.assertTrue(descriptor.isBeanType());
Assertions.assertEquals(
user.getName(), ((JavaBeanDescriptor) descriptor.getProperty("name")).getPrimitiveProperty());
} finally {
bootstrap.stop();
}
}
@Test
void testGenericImplementationWithBeanSerialization() {
final AtomicReference reference = new AtomicReference();
ServiceConfig<GenericService> service = new ServiceConfig<GenericService>();
service.setInterface(DemoService.class.getName());
service.setRef(new GenericService() {
public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException {
if ("getUsers".equals(method)) {
GenericParameter arg = new GenericParameter();
arg.method = method;
arg.parameterTypes = parameterTypes;
arg.arguments = args;
reference.set(arg);
return args[0];
}
if ("sayName".equals(method)) {
return null;
}
return args;
}
});
ReferenceConfig<DemoService> ref = null;
ref = new ReferenceConfig<DemoService>();
ref.setInterface(DemoService.class);
ref.setUrl("dubbo://127.0.0.1:29581?scope=remote&generic=bean&timeout=3000");
DubboBootstrap bootstrap = DubboBootstrap.getInstance()
.application(new ApplicationConfig("generic-test"))
.registry(new RegistryConfig("N/A"))
.protocol(new ProtocolConfig("dubbo", 29581))
.service(service)
.reference(ref);
bootstrap.start();
try {
DemoService demoService = bootstrap.getCache().get(ref);
User user = new User();
user.setName("zhangsan");
List<User> users = new ArrayList<User>();
users.add(user);
List<User> result = demoService.getUsers(users);
Assertions.assertEquals(users.size(), result.size());
Assertions.assertEquals(user.getName(), result.get(0).getName());
GenericParameter gp = (GenericParameter) reference.get();
Assertions.assertEquals("getUsers", gp.method);
Assertions.assertEquals(1, gp.parameterTypes.length);
Assertions.assertEquals(ReflectUtils.getName(List.class), gp.parameterTypes[0]);
Assertions.assertEquals(1, gp.arguments.length);
Assertions.assertTrue(gp.arguments[0] instanceof JavaBeanDescriptor);
JavaBeanDescriptor descriptor = (JavaBeanDescriptor) gp.arguments[0];
Assertions.assertTrue(descriptor.isCollectionType());
Assertions.assertEquals(ArrayList.class.getName(), descriptor.getClassName());
Assertions.assertEquals(1, descriptor.propertySize());
descriptor = (JavaBeanDescriptor) descriptor.getProperty(0);
Assertions.assertTrue(descriptor.isBeanType());
Assertions.assertEquals(User.class.getName(), descriptor.getClassName());
Assertions.assertEquals(
user.getName(), ((JavaBeanDescriptor) descriptor.getProperty("name")).getPrimitiveProperty());
Assertions.assertNull(demoService.sayName("zhangsan"));
} finally {
bootstrap.stop();
}
}
protected static class GenericParameter {
String method;
String[] parameterTypes;
Object[] arguments;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoServiceImpl.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/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.qos.legacy.service.generic;
import java.util.List;
public class DemoServiceImpl implements DemoService {
public String sayName(String name) {
return "say:" + name;
}
public void throwDemoException() throws DemoException {
throw new DemoException("DemoServiceImpl");
}
public List<User> getUsers(List<User> users) {
return users;
}
public int echo(int i) {
return i;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoService.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/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.qos.legacy.service.generic;
import java.util.List;
public interface DemoService {
String sayName(String name);
void throwDemoException() throws DemoException;
List<User> getUsers(List<User> users);
int echo(int i);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/User.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/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.qos.legacy.service.generic;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
public User() {}
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
return name == null ? -1 : name.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof User)) {
return false;
}
User other = (User) obj;
if (this == other) {
return true;
}
if (name != null && other.name != null) {
return name.equals(other.name);
}
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoException.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoException.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.qos.legacy.service.generic;
public class DemoException extends Exception {
private static final long serialVersionUID = -8213943026163641747L;
public DemoException() {
super();
}
public DemoException(String message, Throwable cause) {
super(message, cause);
}
public DemoException(String message) {
super(message);
}
public DemoException(Throwable cause) {
super(cause);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/channel/MockChannel.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/channel/MockChannel.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.qos.legacy.channel;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
public class MockChannel implements Channel {
public static final String ERROR_WHEN_SEND = "error_when_send";
InetSocketAddress localAddress;
InetSocketAddress remoteAddress;
private URL remoteUrl;
private ChannelHandler handler;
private boolean isClosed;
private volatile boolean closing;
private Map<String, Object> attributes = new HashMap<String, Object>(1);
private List<Object> receivedObjects = new LinkedList<>();
private CountDownLatch latch;
public MockChannel() {}
public MockChannel(URL remoteUrl) {
this.remoteUrl = remoteUrl;
}
public MockChannel(URL remoteUrl, CountDownLatch latch) {
this.remoteUrl = remoteUrl;
this.latch = latch;
}
public MockChannel(ChannelHandler handler) {
this.handler = handler;
}
@Override
public URL getUrl() {
return remoteUrl;
}
@Override
public ChannelHandler getChannelHandler() {
return handler;
}
@Override
public InetSocketAddress getLocalAddress() {
return localAddress;
}
@Override
public void send(Object message) throws RemotingException {
if (remoteUrl.getParameter(ERROR_WHEN_SEND, Boolean.FALSE)) {
throw new RemotingException(localAddress, remoteAddress, "mock error");
} else {
receivedObjects.add(message);
if (latch != null) {
latch.countDown();
}
}
}
@Override
public void send(Object message, boolean sent) throws RemotingException {
send(message);
}
@Override
public void close() {
close(0);
}
@Override
public void close(int timeout) {
isClosed = true;
}
@Override
public void startClose() {
closing = true;
}
@Override
public boolean isClosed() {
return isClosed;
}
@Override
public InetSocketAddress getRemoteAddress() {
return remoteAddress;
}
@Override
public boolean isConnected() {
return isClosed;
}
@Override
public boolean hasAttribute(String key) {
return attributes.containsKey(key);
}
@Override
public Object getAttribute(String key) {
return attributes.get(key);
}
@Override
public void setAttribute(String key, Object value) {
attributes.put(key, value);
}
@Override
public void removeAttribute(String key) {
attributes.remove(key);
}
public List<Object> getReceivedObjects() {
return receivedObjects;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandlerTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandlerTest.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.qos.server.handler;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.qos.api.QosConfiguration;
import org.apache.dubbo.rpc.model.FrameworkModel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class TelnetProcessHandlerTest {
@Test
void testPrompt() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
TelnetProcessHandler handler = new TelnetProcessHandler(
FrameworkModel.defaultModel(),
QosConfiguration.builder()
.anonymousAccessPermissionLevel(PermissionLevel.NONE.name())
.build());
handler.channelRead0(context, "");
verify(context).writeAndFlush(QosProcessHandler.PROMPT);
}
@Test
void testBye() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
TelnetProcessHandler handler = new TelnetProcessHandler(
FrameworkModel.defaultModel(), QosConfiguration.builder().build());
ChannelFuture future = mock(ChannelFuture.class);
when(context.writeAndFlush("BYE!\n")).thenReturn(future);
handler.channelRead0(context, "quit");
verify(future).addListener(ChannelFutureListener.CLOSE);
}
@Test
void testUnknownCommand() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
TelnetProcessHandler handler = new TelnetProcessHandler(
FrameworkModel.defaultModel(), QosConfiguration.builder().build());
handler.channelRead0(context, "unknown");
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(context, Mockito.atLeastOnce()).writeAndFlush(captor.capture());
assertThat(captor.getAllValues(), contains("unknown :no such command", "\r\ndubbo>"));
}
@Test
void testGreeting() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
TelnetProcessHandler handler = new TelnetProcessHandler(
FrameworkModel.defaultModel(),
QosConfiguration.builder()
.anonymousAccessPermissionLevel(PermissionLevel.NONE.name())
.build());
handler.channelRead0(context, "greeting");
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(context).writeAndFlush(captor.capture());
assertThat(captor.getValue(), containsString("greeting"));
assertThat(captor.getValue(), containsString("dubbo>"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/ForeignHostPermitHandlerTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/ForeignHostPermitHandlerTest.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.qos.server.handler;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.qos.api.QosConfiguration;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ForeignHostPermitHandlerTest {
@Test
void shouldShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndEmptyWhiteList() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
Channel channel = mock(Channel.class);
when(context.channel()).thenReturn(channel);
InetAddress addr = mock(InetAddress.class);
when(addr.isLoopbackAddress()).thenReturn(false);
InetSocketAddress address = new InetSocketAddress(addr, 12345);
when(channel.remoteAddress()).thenReturn(address);
ChannelFuture future = mock(ChannelFuture.class);
when(context.writeAndFlush(any(ByteBuf.class))).thenReturn(future);
ForeignHostPermitHandler handler = new ForeignHostPermitHandler(QosConfiguration.builder()
.acceptForeignIp(false)
.acceptForeignIpWhitelist(StringUtils.EMPTY_STRING)
.anonymousAccessPermissionLevel(PermissionLevel.NONE.name())
.build());
handler.handlerAdded(context);
ArgumentCaptor<ByteBuf> captor = ArgumentCaptor.forClass(ByteBuf.class);
verify(context).writeAndFlush(captor.capture());
assertThat(
new String(captor.getValue().array()),
containsString("Foreign Ip Not Permitted, Consider Config It In Whitelist"));
verify(future).addListener(ChannelFutureListener.CLOSE);
}
@Test
void shouldShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndNotMatchWhiteList() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
Channel channel = mock(Channel.class);
when(context.channel()).thenReturn(channel);
InetAddress addr = mock(InetAddress.class);
when(addr.isLoopbackAddress()).thenReturn(false);
when(addr.getHostAddress()).thenReturn("179.23.44.1");
InetSocketAddress address = new InetSocketAddress(addr, 12345);
when(channel.remoteAddress()).thenReturn(address);
ChannelFuture future = mock(ChannelFuture.class);
when(context.writeAndFlush(any(ByteBuf.class))).thenReturn(future);
ForeignHostPermitHandler handler = new ForeignHostPermitHandler(QosConfiguration.builder()
.acceptForeignIp(false)
.acceptForeignIpWhitelist("175.23.44.1 , 192.168.1.192/26")
.anonymousAccessPermissionLevel(PermissionLevel.NONE.name())
.build());
handler.handlerAdded(context);
ArgumentCaptor<ByteBuf> captor = ArgumentCaptor.forClass(ByteBuf.class);
verify(context).writeAndFlush(captor.capture());
assertThat(
new String(captor.getValue().array()),
containsString("Foreign Ip Not Permitted, Consider Config It In Whitelist"));
verify(future).addListener(ChannelFutureListener.CLOSE);
}
@Test
void shouldNotShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndMatchWhiteList() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
Channel channel = mock(Channel.class);
when(context.channel()).thenReturn(channel);
InetAddress addr = mock(InetAddress.class);
when(addr.isLoopbackAddress()).thenReturn(false);
when(addr.getHostAddress()).thenReturn("175.23.44.1");
InetSocketAddress address = new InetSocketAddress(addr, 12345);
when(channel.remoteAddress()).thenReturn(address);
ForeignHostPermitHandler handler = new ForeignHostPermitHandler(QosConfiguration.builder()
.acceptForeignIp(false)
.acceptForeignIpWhitelist("175.23.44.1, 192.168.1.192/26 ")
.build());
handler.handlerAdded(context);
verify(context, never()).writeAndFlush(any());
}
@Test
void shouldNotShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndMatchWhiteListRange() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
Channel channel = mock(Channel.class);
when(context.channel()).thenReturn(channel);
InetAddress addr = mock(InetAddress.class);
when(addr.isLoopbackAddress()).thenReturn(false);
when(addr.getHostAddress()).thenReturn("192.168.1.199");
InetSocketAddress address = new InetSocketAddress(addr, 12345);
when(channel.remoteAddress()).thenReturn(address);
ForeignHostPermitHandler handler = new ForeignHostPermitHandler(QosConfiguration.builder()
.acceptForeignIp(false)
.acceptForeignIpWhitelist("175.23.44.1, 192.168.1.192/26")
.build());
handler.handlerAdded(context);
verify(context, never()).writeAndFlush(any());
}
@Test
void shouldNotShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndNotMatchWhiteListAndPermissionConfig()
throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
Channel channel = mock(Channel.class);
when(context.channel()).thenReturn(channel);
ChannelFuture future = mock(ChannelFuture.class);
when(context.writeAndFlush(any(ByteBuf.class))).thenReturn(future);
ForeignHostPermitHandler handler = new ForeignHostPermitHandler(QosConfiguration.builder()
.acceptForeignIp(false)
.acceptForeignIpWhitelist("175.23.44.1 , 192.168.1.192/26")
.anonymousAccessPermissionLevel(PermissionLevel.PROTECTED.name())
.build());
handler.handlerAdded(context);
verify(future, never()).addListener(ChannelFutureListener.CLOSE);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/HttpProcessHandlerTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/HttpProcessHandlerTest.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.qos.server.handler;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.qos.api.QosConfiguration;
import org.apache.dubbo.rpc.model.FrameworkModel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class HttpProcessHandlerTest {
@Test
void test1() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
ChannelFuture future = mock(ChannelFuture.class);
when(context.writeAndFlush(any(FullHttpResponse.class))).thenReturn(future);
HttpRequest message = Mockito.mock(HttpRequest.class);
when(message.uri()).thenReturn("test");
HttpProcessHandler handler = new HttpProcessHandler(
FrameworkModel.defaultModel(), QosConfiguration.builder().build());
handler.channelRead0(context, message);
verify(future).addListener(ChannelFutureListener.CLOSE);
ArgumentCaptor<FullHttpResponse> captor = ArgumentCaptor.forClass(FullHttpResponse.class);
verify(context).writeAndFlush(captor.capture());
FullHttpResponse response = captor.getValue();
assertThat(response.status().code(), equalTo(404));
}
@Test
void test2() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
ChannelFuture future = mock(ChannelFuture.class);
when(context.writeAndFlush(any(FullHttpResponse.class))).thenReturn(future);
HttpRequest message = Mockito.mock(HttpRequest.class);
when(message.uri()).thenReturn("localhost:80/greeting");
when(message.method()).thenReturn(HttpMethod.GET);
HttpProcessHandler handler = new HttpProcessHandler(
FrameworkModel.defaultModel(),
QosConfiguration.builder()
.anonymousAccessPermissionLevel(PermissionLevel.NONE.name())
.build());
handler.channelRead0(context, message);
verify(future).addListener(ChannelFutureListener.CLOSE);
ArgumentCaptor<FullHttpResponse> captor = ArgumentCaptor.forClass(FullHttpResponse.class);
verify(context).writeAndFlush(captor.capture());
FullHttpResponse response = captor.getValue();
assertThat(response.status().code(), equalTo(200));
}
@Test
void test3() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
ChannelFuture future = mock(ChannelFuture.class);
when(context.writeAndFlush(any(FullHttpResponse.class))).thenReturn(future);
HttpRequest message = Mockito.mock(HttpRequest.class);
when(message.uri()).thenReturn("localhost:80/test");
when(message.method()).thenReturn(HttpMethod.GET);
HttpProcessHandler handler = new HttpProcessHandler(
FrameworkModel.defaultModel(),
QosConfiguration.builder()
.anonymousAccessPermissionLevel(PermissionLevel.NONE.name())
.build());
handler.channelRead0(context, message);
verify(future).addListener(ChannelFutureListener.CLOSE);
ArgumentCaptor<FullHttpResponse> captor = ArgumentCaptor.forClass(FullHttpResponse.class);
verify(context).writeAndFlush(captor.capture());
FullHttpResponse response = captor.getValue();
assertThat(response.status().code(), equalTo(404));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/QosProcessHandlerTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/QosProcessHandlerTest.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.qos.server.handler;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.QosConfiguration;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Collections;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
class QosProcessHandlerTest {
@Test
void testDecodeHttp() throws Exception {
ByteBuf buf = Unpooled.wrappedBuffer(new byte[] {'G'});
ChannelHandlerContext context = Mockito.mock(ChannelHandlerContext.class);
ChannelPipeline pipeline = Mockito.mock(ChannelPipeline.class);
Mockito.when(context.pipeline()).thenReturn(pipeline);
QosProcessHandler handler = new QosProcessHandler(
FrameworkModel.defaultModel(),
QosConfiguration.builder()
.welcome("welcome")
.acceptForeignIp(false)
.acceptForeignIpWhitelist(StringUtils.EMPTY_STRING)
.build());
handler.decode(context, buf, Collections.emptyList());
verify(pipeline).addLast(any(HttpServerCodec.class));
verify(pipeline).addLast(any(HttpObjectAggregator.class));
verify(pipeline).addLast(any(HttpProcessHandler.class));
verify(pipeline).remove(handler);
}
@Test
void testDecodeTelnet() throws Exception {
ByteBuf buf = Unpooled.wrappedBuffer(new byte[] {'A'});
ChannelHandlerContext context = Mockito.mock(ChannelHandlerContext.class);
ChannelPipeline pipeline = Mockito.mock(ChannelPipeline.class);
Mockito.when(context.pipeline()).thenReturn(pipeline);
QosProcessHandler handler = new QosProcessHandler(
FrameworkModel.defaultModel(),
QosConfiguration.builder()
.welcome("welcome")
.acceptForeignIp(false)
.acceptForeignIpWhitelist(StringUtils.EMPTY_STRING)
.build());
handler.decode(context, buf, Collections.emptyList());
verify(pipeline).addLast(any(LineBasedFrameDecoder.class));
verify(pipeline).addLast(any(StringDecoder.class));
verify(pipeline).addLast(any(StringEncoder.class));
verify(pipeline).addLast(any(TelnetProcessHandler.class));
verify(pipeline).remove(handler);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/CtrlCHandlerTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/CtrlCHandlerTest.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.qos.server.handler;
import org.apache.dubbo.qos.common.QosConstants;
import java.nio.charset.StandardCharsets;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
public class CtrlCHandlerTest {
private byte[] CTRLC_BYTES_SEQUENCE = new byte[] {(byte) 0xff, (byte) 0xf4, (byte) 0xff, (byte) 0xfd, (byte) 0x06};
private byte[] RESPONSE_SEQUENCE = new byte[] {(byte) 0xff, (byte) 0xfc, 0x06};
@Test
void testMatchedExactly() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
CtrlCHandler ctrlCHandler = new CtrlCHandler();
ctrlCHandler.channelRead(context, Unpooled.wrappedBuffer(CTRLC_BYTES_SEQUENCE));
verify(context).writeAndFlush(Unpooled.wrappedBuffer(RESPONSE_SEQUENCE));
verify(context)
.writeAndFlush(Unpooled.wrappedBuffer(
(QosConstants.BR_STR + QosProcessHandler.PROMPT).getBytes(CharsetUtil.UTF_8)));
}
@Test
void testMatchedNotExactly() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
CtrlCHandler ctrlCHandler = new CtrlCHandler();
// before 'ctrl c', user typed other command like 'help'
String arbitraryCommand = "help";
byte[] commandBytes = arbitraryCommand.getBytes(StandardCharsets.UTF_8);
ctrlCHandler.channelRead(context, Unpooled.wrappedBuffer(commandBytes, CTRLC_BYTES_SEQUENCE));
verify(context).writeAndFlush(Unpooled.wrappedBuffer(RESPONSE_SEQUENCE));
verify(context)
.writeAndFlush(Unpooled.wrappedBuffer(
(QosConstants.BR_STR + QosProcessHandler.PROMPT).getBytes(CharsetUtil.UTF_8)));
}
@Test
void testNotMatched() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
CtrlCHandler ctrlCHandler = new CtrlCHandler();
String arbitraryCommand = "help" + QosConstants.BR_STR;
byte[] commandBytes = arbitraryCommand.getBytes(StandardCharsets.UTF_8);
ctrlCHandler.channelRead(context, Unpooled.wrappedBuffer(commandBytes));
verify(context, never()).writeAndFlush(Unpooled.wrappedBuffer(RESPONSE_SEQUENCE));
verify(context, never())
.writeAndFlush(Unpooled.wrappedBuffer(
(QosConstants.BR_STR + QosProcessHandler.PROMPT).getBytes(CharsetUtil.UTF_8)));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.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.qos.protocol;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.server.Server;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
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 org.mockito.Mockito;
import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP;
import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE;
import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST;
import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class QosProtocolWrapperTest {
private URL url = Mockito.mock(URL.class);
private Invoker invoker = mock(Invoker.class);
private Protocol protocol = mock(Protocol.class);
private QosProtocolWrapper wrapper;
private URL triUrl = Mockito.mock(URL.class);
private Invoker triInvoker = mock(Invoker.class);
private Protocol triProtocol = mock(Protocol.class);
private QosProtocolWrapper triWrapper;
private Server server;
@BeforeEach
public void setUp() throws Exception {
when(url.getParameter(QOS_ENABLE, true)).thenReturn(true);
when(url.getParameter(QOS_HOST)).thenReturn("localhost");
when(url.getParameter(QOS_PORT, 22222)).thenReturn(12345);
when(url.getParameter(ACCEPT_FOREIGN_IP, "false")).thenReturn("false");
when(url.getProtocol()).thenReturn(REGISTRY_PROTOCOL);
when(invoker.getUrl()).thenReturn(url);
wrapper = new QosProtocolWrapper(protocol);
wrapper.setFrameworkModel(FrameworkModel.defaultModel());
// url2 use tri protocol and qos.accept.foreign.ip=true
when(triUrl.getParameter(QOS_ENABLE, true)).thenReturn(true);
when(triUrl.getParameter(QOS_HOST)).thenReturn("localhost");
when(triUrl.getParameter(QOS_PORT, 22222)).thenReturn(12345);
when(triUrl.getParameter(ACCEPT_FOREIGN_IP, "false")).thenReturn("true");
when(triUrl.getProtocol()).thenReturn(CommonConstants.TRIPLE);
when(triInvoker.getUrl()).thenReturn(triUrl);
triWrapper = new QosProtocolWrapper(triProtocol);
triWrapper.setFrameworkModel(FrameworkModel.defaultModel());
server = FrameworkModel.defaultModel().getBeanFactory().getBean(Server.class);
}
@AfterEach
public void tearDown() throws Exception {
if (server.isStarted()) {
server.stop();
}
FrameworkModel.defaultModel().destroy();
}
@Test
void testExport() throws Exception {
wrapper.export(invoker);
assertThat(server.isStarted(), is(true));
assertThat(server.getHost(), is("localhost"));
assertThat(server.getPort(), is(12345));
assertThat(server.isAcceptForeignIp(), is(false));
verify(protocol).export(invoker);
}
@Test
void testRefer() throws Exception {
wrapper.refer(BaseCommand.class, url);
assertThat(server.isStarted(), is(true));
assertThat(server.getHost(), is("localhost"));
assertThat(server.getPort(), is(12345));
assertThat(server.isAcceptForeignIp(), is(false));
verify(protocol).refer(BaseCommand.class, url);
}
@Test
void testMultiProtocol() throws Exception {
// tri protocol start first, acceptForeignIp = true
triWrapper.export(triInvoker);
assertThat(server.isStarted(), is(true));
assertThat(server.getHost(), is("localhost"));
assertThat(server.getPort(), is(12345));
assertThat(server.isAcceptForeignIp(), is(true));
verify(triProtocol).export(triInvoker);
// next registry protocol server still acceptForeignIp=true even though wrapper invoker url set false
wrapper.export(invoker);
assertThat(server.isStarted(), is(true));
assertThat(server.getHost(), is("localhost"));
assertThat(server.getPort(), is(12345));
assertThat(server.isAcceptForeignIp(), is(true));
verify(protocol).export(invoker);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/permission/DefaultAnonymousAccessPermissionCheckerTest.java | dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/permission/DefaultAnonymousAccessPermissionCheckerTest.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.qos.permission;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.qos.api.QosConfiguration;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import io.netty.channel.Channel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class DefaultAnonymousAccessPermissionCheckerTest {
@Test
void testPermission() throws UnknownHostException {
InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
InetSocketAddress socketAddress = Mockito.mock(InetSocketAddress.class);
Mockito.when(socketAddress.getAddress()).thenReturn(inetAddress);
Channel channel = Mockito.mock(Channel.class);
Mockito.when(channel.remoteAddress()).thenReturn(socketAddress);
CommandContext commandContext = Mockito.mock(CommandContext.class);
Mockito.when(commandContext.getRemote()).thenReturn(channel);
QosConfiguration qosConfiguration = Mockito.mock(QosConfiguration.class);
Mockito.when(qosConfiguration.getAnonymousAccessPermissionLevel()).thenReturn(PermissionLevel.PUBLIC);
Mockito.when(qosConfiguration.getAcceptForeignIpWhitelistPredicate()).thenReturn(ip -> false);
Mockito.when(commandContext.getQosConfiguration()).thenReturn(qosConfiguration);
DefaultAnonymousAccessPermissionChecker checker = new DefaultAnonymousAccessPermissionChecker();
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.NONE));
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PUBLIC));
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PROTECTED));
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PRIVATE));
inetAddress = InetAddress.getByName("1.1.1.1");
Mockito.when(socketAddress.getAddress()).thenReturn(inetAddress);
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.NONE));
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PUBLIC));
Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PROTECTED));
Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PRIVATE));
Mockito.when(qosConfiguration.getAnonymousAccessPermissionLevel()).thenReturn(PermissionLevel.PROTECTED);
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.NONE));
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PUBLIC));
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PROTECTED));
Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PRIVATE));
Mockito.when(qosConfiguration.getAnonymousAccessPermissionLevel()).thenReturn(PermissionLevel.NONE);
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.NONE));
Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PUBLIC));
Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PROTECTED));
Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PRIVATE));
Mockito.when(qosConfiguration.getAcceptForeignIpWhitelistPredicate()).thenReturn(ip -> true);
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.NONE));
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PUBLIC));
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PROTECTED));
Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PRIVATE));
Mockito.when(qosConfiguration.getAcceptForeignIpWhitelistPredicate()).thenReturn(ip -> false);
Mockito.when(qosConfiguration.getAnonymousAllowCommands()).thenReturn("test1,test2");
Mockito.when(commandContext.getCommandName()).thenReturn("test1");
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.NONE));
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PUBLIC));
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PROTECTED));
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PRIVATE));
Mockito.when(commandContext.getCommandName()).thenReturn("test2");
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.NONE));
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PUBLIC));
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PROTECTED));
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PRIVATE));
Mockito.when(commandContext.getCommandName()).thenReturn("test");
Assertions.assertTrue(checker.access(commandContext, PermissionLevel.NONE));
Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PUBLIC));
Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PROTECTED));
Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PRIVATE));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/QosScopeModelInitializer.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/QosScopeModelInitializer.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.qos;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.qos.command.ActuatorCommandExecutor;
import org.apache.dubbo.qos.command.util.SerializeCheckUtils;
import org.apache.dubbo.qos.server.Server;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
public class QosScopeModelInitializer implements ScopeModelInitializer {
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {
ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory();
beanFactory.registerBean(Server.class);
beanFactory.registerBean(SerializeCheckUtils.class);
}
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {
ScopeBeanFactory beanFactory = applicationModel.getBeanFactory();
beanFactory.registerBean(ActuatorCommandExecutor.class);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/ReadinessProbe.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/ReadinessProbe.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.qos.probe;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* A probe to indicate whether program is ready
* </p>
* If one or more spi return false, 'ready' command in dubbo-qos
* will return false. This can be extended with custom program and developers
* can implement this to customize life cycle.
*
* @since 3.0
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface ReadinessProbe {
/**
* Check if program is Ready
*
* @return {@link boolean} result of probe
*/
boolean check();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/LivenessProbe.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/LivenessProbe.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.qos.probe;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* A probe to indicate whether program is alive
* </p>
* If one or more spi return false, 'live' command in dubbo-qos
* will return false. This can be extended with custom program and developers
* can implement this to customize life cycle.
*
* @since 3.0
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface LivenessProbe {
/**
* Check if program is alive
*
* @return {@link boolean} result of probe
*/
boolean check();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/StartupProbe.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/StartupProbe.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.qos.probe;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* A probe to indicate whether program is startup
* </p>
* If one or more spi return false, 'startup' command in dubbo-qos
* will return false. This can be extended with custom program and developers
* can implement this to customize life cycle.
*
* @since 3.0
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface StartupProbe {
/**
* Check if program has been startup
*
* @return {@link boolean} result of probe
*/
boolean check();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/DeployerReadinessProbe.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/DeployerReadinessProbe.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.qos.probe.impl;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.qos.probe.ReadinessProbe;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.List;
@Activate
public class DeployerReadinessProbe implements ReadinessProbe {
private FrameworkModel frameworkModel;
public DeployerReadinessProbe(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public boolean check() {
if (this.frameworkModel == null) {
this.frameworkModel = FrameworkModel.defaultModel();
}
List<ApplicationModel> applicationModels = frameworkModel.getApplicationModels();
for (ApplicationModel applicationModel : applicationModels) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
if (!moduleModel.getDeployer().isCompletion()) {
return false;
}
}
}
return true;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/ProviderReadinessProbe.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/ProviderReadinessProbe.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.qos.probe.impl;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.qos.probe.ReadinessProbe;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.FrameworkServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import java.util.Collection;
@Activate
public class ProviderReadinessProbe implements ReadinessProbe {
private final FrameworkModel frameworkModel;
private final FrameworkServiceRepository serviceRepository;
public ProviderReadinessProbe(FrameworkModel frameworkModel) {
if (frameworkModel != null) {
this.frameworkModel = frameworkModel;
} else {
this.frameworkModel = FrameworkModel.defaultModel();
}
this.serviceRepository = this.frameworkModel.getServiceRepository();
}
@Override
public boolean check() {
Collection<ProviderModel> providerModelList = serviceRepository.allProviderModels();
if (providerModelList.isEmpty()) {
return true;
}
boolean hasService = false, anyOnline = false;
for (ProviderModel providerModel : providerModelList) {
if (providerModel.getModuleModel().isInternal()) {
continue;
}
hasService = true;
anyOnline = anyOnline
|| providerModel.getStatedUrl().isEmpty()
|| providerModel.getStatedUrl().stream().anyMatch(ProviderModel.RegisterStatedURL::isRegistered);
}
// no service => check pass
// has service and any online => check pass
// has service and none online => check fail
return !(hasService && !anyOnline);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/DeployerStartupProbe.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/DeployerStartupProbe.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.qos.probe.impl;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.qos.probe.StartupProbe;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.List;
@Activate
public class DeployerStartupProbe implements StartupProbe {
private FrameworkModel frameworkModel;
public DeployerStartupProbe(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public boolean check() {
if (this.frameworkModel == null) {
this.frameworkModel = FrameworkModel.defaultModel();
}
List<ApplicationModel> applicationModels = frameworkModel.getApplicationModels();
for (ApplicationModel applicationModel : applicationModels) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
if (moduleModel.getDeployer().isRunning()) {
return true;
}
}
}
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/CommandExecutor.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/CommandExecutor.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.qos.command;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.command.exception.NoSuchCommandException;
import org.apache.dubbo.qos.command.exception.PermissionDenyException;
public interface CommandExecutor {
/**
* Execute one command and return the execution result
*
* @param commandContext command context
* @return command execution result
* @throws NoSuchCommandException
*/
String execute(CommandContext commandContext) throws NoSuchCommandException, PermissionDenyException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/ActuatorExecutor.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/ActuatorExecutor.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.qos.command;
public interface ActuatorExecutor {
String execute(String command, String[] args);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/CommandContextFactory.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/CommandContextFactory.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.qos.command;
import org.apache.dubbo.qos.api.CommandContext;
public class CommandContextFactory {
public static CommandContext newInstance(String commandName) {
return new CommandContext(commandName);
}
public static CommandContext newInstance(String commandName, String[] args, boolean isHttp) {
return new CommandContext(commandName, args, isHttp);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/DefaultCommandExecutor.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/DefaultCommandExecutor.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.qos.command;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.qos.command.exception.NoSuchCommandException;
import org.apache.dubbo.qos.command.exception.PermissionDenyException;
import org.apache.dubbo.qos.common.QosConstants;
import org.apache.dubbo.qos.permission.DefaultAnonymousAccessPermissionChecker;
import org.apache.dubbo.qos.permission.PermissionChecker;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import io.netty.channel.Channel;
public class DefaultCommandExecutor implements CommandExecutor {
private static final Logger logger = LoggerFactory.getLogger(DefaultCommandExecutor.class);
private final FrameworkModel frameworkModel;
public DefaultCommandExecutor(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext) throws NoSuchCommandException, PermissionDenyException {
String remoteAddress = Optional.ofNullable(commandContext.getRemote())
.map(Channel::remoteAddress)
.map(Objects::toString)
.orElse("unknown");
logger.info("[Dubbo QoS] Command Process start. Command: " + commandContext.getCommandName() + ", Args: "
+ Arrays.toString(commandContext.getArgs()) + ", Remote Address: " + remoteAddress);
BaseCommand command = null;
try {
command =
frameworkModel.getExtensionLoader(BaseCommand.class).getExtension(commandContext.getCommandName());
} catch (Throwable throwable) {
// can't find command
}
if (command == null) {
logger.info("[Dubbo QoS] Command Not found. Command: " + commandContext.getCommandName()
+ ", Remote Address: " + remoteAddress);
throw new NoSuchCommandException(commandContext.getCommandName());
}
// check permission when configs allow anonymous access
if (commandContext.isAllowAnonymousAccess()) {
PermissionChecker permissionChecker = DefaultAnonymousAccessPermissionChecker.INSTANCE;
try {
permissionChecker = frameworkModel
.getExtensionLoader(PermissionChecker.class)
.getExtension(QosConstants.QOS_PERMISSION_CHECKER);
} catch (Throwable throwable) {
// can't find valid custom permissionChecker
}
final Cmd cmd = command.getClass().getAnnotation(Cmd.class);
final PermissionLevel cmdRequiredPermissionLevel = cmd.requiredPermissionLevel();
if (!permissionChecker.access(commandContext, cmdRequiredPermissionLevel)) {
logger.info(
"[Dubbo QoS] Command Deny to access. Command: " + commandContext.getCommandName() + ", Args: "
+ Arrays.toString(commandContext.getArgs()) + ", Required Permission Level: "
+ cmdRequiredPermissionLevel + ", Remote Address: "
+ remoteAddress);
throw new PermissionDenyException(commandContext.getCommandName());
}
}
try {
String result = command.execute(commandContext, commandContext.getArgs());
if (command.logResult()) {
logger.info("[Dubbo QoS] Command Process success. Command: " + commandContext.getCommandName()
+ ", Args: "
+ Arrays.toString(commandContext.getArgs()) + ", Result: " + result + ", Remote Address: "
+ remoteAddress);
}
return result;
} catch (Throwable t) {
logger.info(
"[Dubbo QoS] Command Process Failed. Command: " + commandContext.getCommandName() + ", Args: "
+ Arrays.toString(commandContext.getArgs()) + ", Remote Address: "
+ remoteAddress,
t);
throw t;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/ActuatorCommandExecutor.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/ActuatorCommandExecutor.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.qos.command;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Arrays;
public class ActuatorCommandExecutor implements ActuatorExecutor {
private static final Logger logger = LoggerFactory.getLogger(ActuatorCommandExecutor.class);
private final ApplicationModel applicationModel;
public ActuatorCommandExecutor(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
@Override
public String execute(String commandName, String[] parameters) {
CommandContext commandContext;
if (parameters == null || parameters.length == 0) {
commandContext = CommandContextFactory.newInstance(commandName);
commandContext.setHttp(true);
} else {
commandContext = CommandContextFactory.newInstance(commandName, parameters, true);
}
logger.info("[Dubbo Actuator QoS] Command Process start. Command: " + commandContext.getCommandName()
+ ", Args: " + Arrays.toString(commandContext.getArgs()));
BaseCommand command;
try {
command = applicationModel
.getExtensionLoader(BaseCommand.class)
.getExtension(commandContext.getCommandName());
return command.execute(commandContext, commandContext.getArgs());
} catch (Throwable t) {
logger.info(
"[Dubbo Actuator QoS] Command Process Failed. Command: " + commandContext.getCommandName()
+ ", Args: " + Arrays.toString(commandContext.getArgs()),
t);
throw t;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/ServiceCheckUtils.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/ServiceCheckUtils.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.qos.command.util;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.client.migration.MigrationInvoker;
import org.apache.dubbo.registry.client.migration.model.MigrationStep;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.ProviderModel;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class ServiceCheckUtils {
public static String getRegisterStatus(ProviderModel providerModel) {
// check all registries status
List<String> statuses = new LinkedList<>();
for (ProviderModel.RegisterStatedURL registerStatedURL : providerModel.getStatedUrl()) {
URL registryUrl = registerStatedURL.getRegistryUrl();
boolean isServiceDiscovery = UrlUtils.isServiceDiscoveryURL(registryUrl);
String protocol = isServiceDiscovery
? registryUrl.getParameter(RegistryConstants.REGISTRY_KEY)
: registryUrl.getProtocol();
// e.g. zookeeper-A(Y)
statuses.add(protocol + "-" + (isServiceDiscovery ? "A" : "I") + "("
+ (registerStatedURL.isRegistered() ? "Y" : "N") + ")");
}
// e.g. zookeeper-A(Y)/zookeeper-I(Y)
return String.join("/", statuses.toArray(new String[0]));
}
public static String getConsumerAddressNum(ConsumerModel consumerModel) {
int num = 0;
Object object = consumerModel.getServiceMetadata().getAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY);
Map<Registry, MigrationInvoker<?>> invokerMap;
List<String> nums = new LinkedList<>();
if (object instanceof Map) {
invokerMap = (Map<Registry, MigrationInvoker<?>>) object;
for (Map.Entry<Registry, MigrationInvoker<?>> entry : invokerMap.entrySet()) {
URL registryUrl = entry.getKey().getUrl();
boolean isServiceDiscovery = UrlUtils.isServiceDiscoveryURL(registryUrl);
String protocol = isServiceDiscovery
? registryUrl.getParameter(RegistryConstants.REGISTRY_KEY)
: registryUrl.getProtocol();
MigrationInvoker<?> migrationInvoker = entry.getValue();
MigrationStep migrationStep = migrationInvoker.getMigrationStep();
String interfaceSize = Optional.ofNullable(migrationInvoker.getInvoker())
.map(ClusterInvoker::getDirectory)
.map(Directory::getAllInvokers)
.map(List::size)
.map(String::valueOf)
.orElse("-");
String applicationSize = Optional.ofNullable(migrationInvoker.getServiceDiscoveryInvoker())
.map(ClusterInvoker::getDirectory)
.map(Directory::getAllInvokers)
.map(List::size)
.map(String::valueOf)
.orElse("-");
String step;
String size;
switch (migrationStep) {
case APPLICATION_FIRST:
step = "AF";
size = "I-" + interfaceSize + ",A-" + applicationSize;
break;
case FORCE_INTERFACE:
step = "I";
size = interfaceSize;
break;
default:
step = "A";
size = applicationSize;
break;
}
// zookeeper-AF(I-10,A-0)
// zookeeper-I(10)
// zookeeper-A(10)
nums.add(protocol + "-" + step + "(" + size + ")");
}
}
// zookeeper-AF(I-10,A-0)/nacos-I(10)
return String.join("/", nums.toArray(new String[0]));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/SerializeCheckUtils.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/SerializeCheckUtils.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.qos.command.util;
import org.apache.dubbo.common.utils.AllowClassNotifyListener;
import org.apache.dubbo.common.utils.SerializeCheckStatus;
import org.apache.dubbo.common.utils.SerializeSecurityManager;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Collections;
import java.util.Set;
public class SerializeCheckUtils implements AllowClassNotifyListener {
private final SerializeSecurityManager manager;
private volatile Set<String> allowedList = Collections.emptySet();
private volatile Set<String> disAllowedList = Collections.emptySet();
private volatile SerializeCheckStatus status = AllowClassNotifyListener.DEFAULT_STATUS;
private volatile boolean checkSerializable = true;
public SerializeCheckUtils(FrameworkModel frameworkModel) {
manager = frameworkModel.getBeanFactory().getOrRegisterBean(SerializeSecurityManager.class);
manager.registerListener(this);
}
@Override
public void notifyPrefix(Set<String> allowedList, Set<String> disAllowedList) {
this.allowedList = allowedList;
this.disAllowedList = disAllowedList;
}
@Override
public void notifyCheckStatus(SerializeCheckStatus status) {
this.status = status;
}
@Override
public void notifyCheckSerializable(boolean checkSerializable) {
this.checkSerializable = checkSerializable;
}
public Set<String> getAllowedList() {
return allowedList;
}
public Set<String> getDisAllowedList() {
return disAllowedList;
}
public SerializeCheckStatus getStatus() {
return status;
}
public boolean isCheckSerializable() {
return checkSerializable;
}
public Set<String> getWarnedClasses() {
return manager.getWarnedClasses();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/CommandHelper.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/CommandHelper.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.qos.command.util;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class CommandHelper {
private final FrameworkModel frameworkModel;
public CommandHelper(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
public boolean hasCommand(String commandName) {
BaseCommand command;
try {
command = frameworkModel.getExtensionLoader(BaseCommand.class).getExtension(commandName);
} catch (Throwable throwable) {
return false;
}
return command != null;
}
public List<Class<?>> getAllCommandClass() {
final Set<String> commandList =
frameworkModel.getExtensionLoader(BaseCommand.class).getSupportedExtensions();
final List<Class<?>> classes = new ArrayList<>();
for (String commandName : commandList) {
BaseCommand command =
frameworkModel.getExtensionLoader(BaseCommand.class).getExtension(commandName);
classes.add(command.getClass());
}
return classes;
}
public Class<?> getCommandClass(String commandName) {
if (hasCommand(commandName)) {
return frameworkModel
.getExtensionLoader(BaseCommand.class)
.getExtension(commandName)
.getClass();
} else {
return null;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/exception/NoSuchCommandException.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/exception/NoSuchCommandException.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.qos.command.exception;
public class NoSuchCommandException extends CommandException {
public NoSuchCommandException(String msg) {
super("NoSuchCommandException:" + msg);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/exception/CommandException.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/exception/CommandException.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.qos.command.exception;
public class CommandException extends Exception {
public CommandException(String msg) {
super(msg);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/exception/PermissionDenyException.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/exception/PermissionDenyException.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.qos.command.exception;
public class PermissionDenyException extends CommandException {
public PermissionDenyException(String msg) {
super("Permission Deny On Operation: " + msg);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableSimpleProfiler.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableSimpleProfiler.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.qos.command.impl;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.profiler.ProfilerSwitch;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_ENABLED;
@Cmd(name = "enableSimpleProfiler", summary = "Enable Dubbo Invocation Profiler.")
public class EnableSimpleProfiler implements BaseCommand {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(EnableSimpleProfiler.class);
@Override
public String execute(CommandContext commandContext, String[] args) {
ProfilerSwitch.enableSimpleProfiler();
logger.warn(QOS_PROFILER_ENABLED, "", "", "Dubbo Invocation Profiler has been enabled.");
return "OK";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Startup.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Startup.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.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.qos.probe.StartupProbe;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Cmd(name = "startup", summary = "Judge if service has started? ", requiredPermissionLevel = PermissionLevel.PUBLIC)
public class Startup implements BaseCommand {
private final FrameworkModel frameworkModel;
public Startup(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
String config = frameworkModel.getApplicationModels().stream()
.map(applicationModel ->
applicationModel.getApplicationConfigManager().getApplication())
.map(o -> o.orElse(null))
.filter(Objects::nonNull)
.map(ApplicationConfig::getStartupProbe)
.filter(Objects::nonNull)
.collect(Collectors.joining(","));
URL url = URL.valueOf("application://").addParameter(CommonConstants.QOS_STARTUP_PROBE_EXTENSION, config);
List<StartupProbe> startupProbes = frameworkModel
.getExtensionLoader(StartupProbe.class)
.getActivateExtension(url, CommonConstants.QOS_STARTUP_PROBE_EXTENSION);
if (!startupProbes.isEmpty()) {
for (StartupProbe startupProbe : startupProbes) {
if (!startupProbe.check()) {
// 503 Service Unavailable
commandContext.setHttpCode(503);
return "false";
}
}
}
// 200 OK
commandContext.setHttpCode(200);
return "true";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableRouterSnapshot.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableRouterSnapshot.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.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ServiceMetadata;
@Cmd(
name = "disableRouterSnapshot",
summary = "Disable Dubbo Invocation Level Router Snapshot Print",
example = "disableRouterSnapshot xx.xx.xxx.service")
public class DisableRouterSnapshot implements BaseCommand {
private final RouterSnapshotSwitcher routerSnapshotSwitcher;
private final FrameworkModel frameworkModel;
public DisableRouterSnapshot(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
this.routerSnapshotSwitcher = frameworkModel.getBeanFactory().getBean(RouterSnapshotSwitcher.class);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (args.length != 1) {
return "args count should be 1. example disableRouterSnapshot xx.xx.xxx.service";
}
String servicePattern = args[0];
int count = 0;
for (ConsumerModel consumerModel : frameworkModel.getServiceRepository().allConsumerModels()) {
try {
ServiceMetadata metadata = consumerModel.getServiceMetadata();
if (metadata.getServiceKey().matches(servicePattern)
|| metadata.getDisplayServiceKey().matches(servicePattern)) {
routerSnapshotSwitcher.removeEnabledService(metadata.getServiceKey());
count += 1;
}
} catch (Throwable ignore) {
}
}
return "OK. Found service count: " + count;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ShutdownTelnet.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ShutdownTelnet.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.qos.command.impl;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.List;
@Cmd(
name = "shutdown",
summary = "Shutdown Dubbo Application.",
example = {"shutdown -t <milliseconds>"})
public class ShutdownTelnet implements BaseCommand {
private final FrameworkModel frameworkModel;
public ShutdownTelnet(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
int sleepMilliseconds = 0;
if (args != null && args.length > 0) {
if (args.length == 2 && "-t".equals(args[0]) && StringUtils.isNumber(args[1])) {
sleepMilliseconds = Integer.parseInt(args[1]);
} else {
return "Invalid parameter,please input like shutdown -t 10000";
}
}
long start = System.currentTimeMillis();
if (sleepMilliseconds > 0) {
try {
Thread.sleep(sleepMilliseconds);
} catch (InterruptedException e) {
return "Failed to invoke shutdown command, cause: " + e.getMessage();
}
}
StringBuilder buf = new StringBuilder();
List<ApplicationModel> applicationModels = frameworkModel.getApplicationModels();
for (ApplicationModel applicationModel : new ArrayList<>(applicationModels)) {
applicationModel.destroy();
}
// TODO change to ApplicationDeployer.destroy() or ApplicationModel.destroy()
// DubboShutdownHook.getDubboShutdownHook().unregister();
// DubboShutdownHook.getDubboShutdownHook().doDestroy();
long end = System.currentTimeMillis();
buf.append("Application has shutdown successfully");
buf.append("\r\nelapsed: ");
buf.append(end - start);
buf.append(" ms.");
return buf.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Quit.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Quit.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.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.qos.common.QosConstants;
@Cmd(name = "quit", summary = "quit telnet console", requiredPermissionLevel = PermissionLevel.PUBLIC)
public class Quit implements BaseCommand {
@Override
public String execute(CommandContext commandContext, String[] args) {
return QosConstants.CLOSE;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ready.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ready.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.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.qos.probe.ReadinessProbe;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Cmd(name = "ready", summary = "Judge if service is ready to work? ", requiredPermissionLevel = PermissionLevel.PUBLIC)
public class Ready implements BaseCommand {
private final FrameworkModel frameworkModel;
public Ready(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
String config = frameworkModel.getApplicationModels().stream()
.map(applicationModel ->
applicationModel.getApplicationConfigManager().getApplication())
.map(o -> o.orElse(null))
.filter(Objects::nonNull)
.map(ApplicationConfig::getReadinessProbe)
.filter(Objects::nonNull)
.collect(Collectors.joining(","));
URL url = URL.valueOf("application://").addParameter(CommonConstants.QOS_READY_PROBE_EXTENSION, config);
List<ReadinessProbe> readinessProbes = frameworkModel
.getExtensionLoader(ReadinessProbe.class)
.getActivateExtension(url, CommonConstants.QOS_READY_PROBE_EXTENSION);
if (!readinessProbes.isEmpty()) {
for (ReadinessProbe readinessProbe : readinessProbes) {
if (!readinessProbe.check()) {
// 503 Service Unavailable
commandContext.setHttpCode(503);
return "false";
}
}
}
// 200 OK
commandContext.setHttpCode(200);
return "true";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SwitchLogger.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SwitchLogger.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.qos.command.impl;
import org.apache.dubbo.common.logger.Level;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.model.FrameworkModel;
@Cmd(
name = "switchLogger",
summary = "Switch logger",
example = {"switchLogger slf4j"})
public class SwitchLogger implements BaseCommand {
private final FrameworkModel frameworkModel;
public SwitchLogger(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (args.length != 1) {
return "Unexpected argument length.";
}
Level level = LoggerFactory.getLevel();
LoggerFactory.setLoggerAdapter(frameworkModel, args[0]);
LoggerFactory.setLevel(level);
return "OK";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Online.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Online.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.qos.command.impl;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.rpc.model.FrameworkModel;
@Cmd(
name = "online",
summary = "online app addresses",
example = {"online dubbo", "online xx.xx.xxx.service"})
public class Online extends BaseOnline {
public Online(FrameworkModel frameworkModel) {
super(frameworkModel);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableDetailProfiler.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableDetailProfiler.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.qos.command.impl;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.profiler.ProfilerSwitch;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_DISABLED;
@Cmd(name = "disableDetailProfiler", summary = "Disable Dubbo Invocation Profiler.")
public class DisableDetailProfiler implements BaseCommand {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DisableDetailProfiler.class);
@Override
public String execute(CommandContext commandContext, String[] args) {
ProfilerSwitch.disableDetailProfiler();
logger.warn(QOS_PROFILER_DISABLED, "", "", "Dubbo Invocation Profiler has been disabled.");
return "OK";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/CountTelnet.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/CountTelnet.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.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.telnet.support.TelnetUtils;
import org.apache.dubbo.remoting.utils.PayloadDropper;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcStatus;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.apache.dubbo.qos.server.handler.QosProcessHandler.PROMPT;
@Cmd(
name = "count",
summary = "Count the service.",
example = {"count [service] [method] [times]"})
public class CountTelnet implements BaseCommand {
private final DubboProtocol dubboProtocol;
public CountTelnet(FrameworkModel frameworkModel) {
this.dubboProtocol = DubboProtocol.getDubboProtocol(frameworkModel);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
Channel channel = commandContext.getRemote();
String service = channel.attr(ChangeTelnet.SERVICE_KEY).get();
if ((service == null || service.length() == 0) && (args == null || args.length == 0)) {
return "Please input service name, eg: \r\ncount XxxService\r\ncount XxxService xxxMethod\r\ncount XxxService xxxMethod 10\r\nor \"cd XxxService\" firstly.";
}
StringBuilder buf = new StringBuilder();
if (service != null && service.length() > 0) {
buf.append("Use default service ").append(service).append(".\r\n");
}
String method;
String times;
if (service == null || service.length() == 0) {
service = args[0];
method = args.length > 1 ? args[1] : null;
} else {
method = args.length > 0 ? args[0] : null;
}
if (StringUtils.isNumber(method)) {
times = method;
method = null;
} else {
times = args.length > 2 ? args[2] : "1";
}
if (!StringUtils.isNumber(times)) {
return "Illegal times " + times + ", must be integer.";
}
final int t = Integer.parseInt(times);
Invoker<?> invoker = null;
for (Exporter<?> exporter : dubboProtocol.getExporters()) {
if (service.equals(exporter.getInvoker().getInterface().getSimpleName())
|| service.equals(exporter.getInvoker().getInterface().getName())
|| service.equals(exporter.getInvoker().getUrl().getPath())
|| service.equals(exporter.getInvoker().getUrl().getServiceKey())) {
invoker = exporter.getInvoker();
break;
}
}
if (invoker != null) {
if (t > 0) {
final String mtd = method;
final Invoker<?> inv = invoker;
Thread thread = new Thread(
() -> {
for (int i = 0; i < t; i++) {
String result = count(inv, mtd);
try {
send(channel, "\r\n" + result);
} catch (RemotingException e1) {
return;
}
if (i < t - 1) {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
}
try {
send(channel, "\r\n" + PROMPT);
} catch (RemotingException ignored) {
}
},
"TelnetCount");
thread.setDaemon(true);
thread.start();
}
} else {
buf.append("No such service ").append(service);
}
return buf.toString();
}
public void send(Channel channel, Object message) throws RemotingException {
boolean success;
int timeout = 0;
try {
ChannelFuture future = channel.writeAndFlush(message);
success = future.await(DEFAULT_TIMEOUT);
Throwable cause = future.cause();
if (cause != null) {
throw cause;
}
} catch (Throwable e) {
throw new RemotingException(
(InetSocketAddress) channel.localAddress(),
(InetSocketAddress) channel.remoteAddress(),
"Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to "
+ channel.remoteAddress().toString() + ", cause: " + e.getMessage(),
e);
}
if (!success) {
throw new RemotingException(
(InetSocketAddress) channel.localAddress(),
(InetSocketAddress) channel.remoteAddress(),
"Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to "
+ channel.remoteAddress().toString() + "in timeout(" + timeout + "ms) limit");
}
}
private String count(Invoker<?> invoker, String method) {
URL url = invoker.getUrl();
List<List<String>> table = new ArrayList<>();
List<String> header = new ArrayList<>();
header.add("method");
header.add("total");
header.add("failed");
header.add("active");
header.add("average");
header.add("max");
if (method == null || method.length() == 0) {
for (Method m : invoker.getInterface().getMethods()) {
RpcStatus count = RpcStatus.getStatus(url, m.getName());
table.add(createRow(m.getName(), count));
}
} else {
boolean found = false;
for (Method m : invoker.getInterface().getMethods()) {
if (m.getName().equals(method)) {
found = true;
break;
}
}
if (found) {
RpcStatus count = RpcStatus.getStatus(url, method);
table.add(createRow(method, count));
} else {
return "No such method " + method + " in class "
+ invoker.getInterface().getName();
}
}
return TelnetUtils.toTable(header, table);
}
private List<String> createRow(String methodName, RpcStatus count) {
List<String> row = new ArrayList<>();
row.add(methodName);
row.add(String.valueOf(count.getTotal()));
row.add(String.valueOf(count.getFailed()));
row.add(String.valueOf(count.getActive()));
row.add(count.getSucceededAverageElapsed() + "ms");
row.add(count.getSucceededMaxElapsed() + "ms");
return row;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetRouterSnapshot.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetRouterSnapshot.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.qos.command.impl;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.client.migration.MigrationInvoker;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.directory.AbstractDirectory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ServiceMetadata;
import java.util.Map;
@Cmd(
name = "getRouterSnapshot",
summary = "Get State Router Snapshot.",
example = "getRouterSnapshot xx.xx.xxx.service")
public class GetRouterSnapshot implements BaseCommand {
private final FrameworkModel frameworkModel;
public GetRouterSnapshot(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (args.length != 1) {
return "args count should be 1. example getRouterSnapshot xx.xx.xxx.service";
}
String servicePattern = args[0];
StringBuilder stringBuilder = new StringBuilder();
for (ConsumerModel consumerModel : frameworkModel.getServiceRepository().allConsumerModels()) {
try {
ServiceMetadata metadata = consumerModel.getServiceMetadata();
if (metadata.getServiceKey().matches(servicePattern)
|| metadata.getDisplayServiceKey().matches(servicePattern)) {
Object object = metadata.getAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY);
Map<Registry, MigrationInvoker<?>> invokerMap;
if (object instanceof Map) {
invokerMap = (Map<Registry, MigrationInvoker<?>>) object;
for (Map.Entry<Registry, MigrationInvoker<?>> invokerEntry : invokerMap.entrySet()) {
Directory<?> directory = invokerEntry.getValue().getDirectory();
StateRouter<?> headStateRouter =
directory.getRouterChain().getHeadStateRouter();
stringBuilder
.append(metadata.getServiceKey())
.append('@')
.append(Integer.toHexString(System.identityHashCode(metadata)))
.append("\n")
.append("[ All Invokers:")
.append(directory.getAllInvokers().size())
.append(" ] ")
.append("[ Valid Invokers: ")
.append(((AbstractDirectory<?>) directory)
.getValidInvokers()
.size())
.append(" ]\n")
.append("\n")
.append(headStateRouter.buildSnapshot())
.append("\n\n");
}
}
}
} catch (Throwable ignore) {
}
}
return stringBuilder.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SerializeCheckStatus.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SerializeCheckStatus.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.qos.command.impl;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.command.util.SerializeCheckUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
@Cmd(name = "serializeCheckStatus", summary = "get serialize check status")
public class SerializeCheckStatus implements BaseCommand {
private final SerializeCheckUtils serializeCheckUtils;
public SerializeCheckStatus(FrameworkModel frameworkModel) {
serializeCheckUtils = frameworkModel.getBeanFactory().getBean(SerializeCheckUtils.class);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (commandContext.isHttp()) {
Map<String, Object> result = new HashMap<>();
result.put("checkStatus", serializeCheckUtils.getStatus());
result.put("checkSerializable", serializeCheckUtils.isCheckSerializable());
result.put("allowedPrefix", serializeCheckUtils.getAllowedList());
result.put("disAllowedPrefix", serializeCheckUtils.getDisAllowedList());
return JsonUtils.toJson(result);
} else {
return "CheckStatus: " + serializeCheckUtils.getStatus() + "\n\n" + "CheckSerializable: "
+ serializeCheckUtils.isCheckSerializable() + "\n\n" + "AllowedPrefix:"
+ "\n"
+ serializeCheckUtils.getAllowedList().stream().sorted().collect(Collectors.joining("\n"))
+ "\n\n"
+ "DisAllowedPrefix:"
+ "\n"
+ serializeCheckUtils.getDisAllowedList().stream().sorted().collect(Collectors.joining("\n"))
+ "\n\n";
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/BaseOnline.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/BaseOnline.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.qos.command.impl;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.FrameworkServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceMetadata;
import java.util.Collection;
import java.util.List;
public class BaseOnline implements BaseCommand {
private static final Logger logger = LoggerFactory.getLogger(BaseOnline.class);
public FrameworkServiceRepository serviceRepository;
public BaseOnline(FrameworkModel frameworkModel) {
this.serviceRepository = frameworkModel.getServiceRepository();
}
@Override
public String execute(CommandContext commandContext, String[] args) {
logger.info("receive online command");
String servicePattern = ".*";
if (ArrayUtils.isNotEmpty(args)) {
servicePattern = "" + args[0];
}
boolean hasService = doExecute(servicePattern);
if (hasService) {
return "OK";
} else {
return "service not found";
}
}
public boolean online(String servicePattern) {
boolean hasService = false;
Collection<ProviderModel> providerModelList = serviceRepository.allProviderModels();
for (ProviderModel providerModel : providerModelList) {
ServiceMetadata metadata = providerModel.getServiceMetadata();
if (metadata.getServiceKey().matches(servicePattern)
|| metadata.getDisplayServiceKey().matches(servicePattern)) {
hasService = true;
List<ProviderModel.RegisterStatedURL> statedUrls = providerModel.getStatedUrl();
for (ProviderModel.RegisterStatedURL statedURL : statedUrls) {
if (!statedURL.isRegistered()) {
doExport(statedURL);
}
}
}
}
return hasService;
}
protected boolean doExecute(String servicePattern) {
return this.online(servicePattern);
}
protected void doExport(ProviderModel.RegisterStatedURL statedURL) {
RegistryFactory registryFactory = statedURL
.getRegistryUrl()
.getOrDefaultApplicationModel()
.getExtensionLoader(RegistryFactory.class)
.getAdaptiveExtension();
Registry registry = registryFactory.getRegistry(statedURL.getRegistryUrl());
registry.register(statedURL.getProviderUrl());
statedURL.setRegistered(true);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OfflineApp.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OfflineApp.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.qos.command.impl;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ProviderModel;
@Cmd(
name = "offlineApp",
summary = "offline app addresses",
example = {"offlineApp", "offlineApp xx.xx.xxx.service"})
public class OfflineApp extends BaseOffline {
public OfflineApp(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected void doUnexport(ProviderModel.RegisterStatedURL statedURL) {
if (UrlUtils.isServiceDiscoveryURL(statedURL.getRegistryUrl())) {
super.doUnexport(statedURL);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OnlineInterface.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OnlineInterface.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.qos.command.impl;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ProviderModel;
@Cmd(
name = "onlineInterface",
summary = "online dubbo",
example = {"onlineInterface dubbo", "onlineInterface xx.xx.xxx.service"})
public class OnlineInterface extends BaseOnline {
public OnlineInterface(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected void doExport(ProviderModel.RegisterStatedURL statedURL) {
if (!UrlUtils.isServiceDiscoveryURL(statedURL.getRegistryUrl())) {
super.doExport(statedURL);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/BaseOffline.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/BaseOffline.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.qos.command.impl;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.FrameworkServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceMetadata;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BaseOffline implements BaseCommand {
private static final Logger logger = LoggerFactory.getLogger(BaseOffline.class);
public FrameworkServiceRepository serviceRepository;
public BaseOffline(FrameworkModel frameworkModel) {
this.serviceRepository = frameworkModel.getServiceRepository();
}
@Override
public String execute(CommandContext commandContext, String[] args) {
logger.info("receive offline command");
String servicePattern = ".*";
if (ArrayUtils.isNotEmpty(args)) {
servicePattern = args[0];
}
boolean hasService = doExecute(servicePattern);
if (hasService) {
return "OK";
} else {
return "service not found";
}
}
protected boolean doExecute(String servicePattern) {
return this.offline(servicePattern);
}
public boolean offline(String servicePattern) {
boolean hasService = false;
ExecutorService executorService = Executors.newFixedThreadPool(
Math.min(Runtime.getRuntime().availableProcessors(), 4), new NamedThreadFactory("Dubbo-Offline"));
try {
List<CompletableFuture<Void>> futures = new LinkedList<>();
Collection<ProviderModel> providerModelList = serviceRepository.allProviderModels();
for (ProviderModel providerModel : providerModelList) {
ServiceMetadata metadata = providerModel.getServiceMetadata();
if (metadata.getServiceKey().matches(servicePattern)
|| metadata.getDisplayServiceKey().matches(servicePattern)) {
hasService = true;
List<ProviderModel.RegisterStatedURL> statedUrls = providerModel.getStatedUrl();
for (ProviderModel.RegisterStatedURL statedURL : statedUrls) {
if (statedURL.isRegistered()) {
futures.add(CompletableFuture.runAsync(
() -> {
doUnexport(statedURL);
},
executorService));
}
}
}
}
for (CompletableFuture<Void> future : futures) {
future.get();
}
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
} finally {
executorService.shutdown();
}
return hasService;
}
protected void doUnexport(ProviderModel.RegisterStatedURL statedURL) {
RegistryFactory registryFactory = statedURL
.getRegistryUrl()
.getOrDefaultApplicationModel()
.getExtensionLoader(RegistryFactory.class)
.getAdaptiveExtension();
Registry registry = registryFactory.getRegistry(statedURL.getRegistryUrl());
registry.unregister(statedURL.getProviderUrl());
statedURL.setRegistered(false);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableSimpleProfiler.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableSimpleProfiler.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.qos.command.impl;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.profiler.ProfilerSwitch;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_DISABLED;
@Cmd(name = "disableSimpleProfiler", summary = "Disable Dubbo Invocation Profiler.")
public class DisableSimpleProfiler implements BaseCommand {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DisableSimpleProfiler.class);
@Override
public String execute(CommandContext commandContext, String[] args) {
ProfilerSwitch.disableSimpleProfiler();
logger.warn(QOS_PROFILER_DISABLED, "", "", "Dubbo Invocation Profiler has been disabled.");
return "OK";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableDetailProfiler.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableDetailProfiler.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.qos.command.impl;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.profiler.ProfilerSwitch;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_ENABLED;
@Cmd(name = "enableDetailProfiler", summary = "Enable Dubbo Invocation Profiler.")
public class EnableDetailProfiler implements BaseCommand {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(EnableDetailProfiler.class);
@Override
public String execute(CommandContext commandContext, String[] args) {
ProfilerSwitch.enableDetailProfiler();
logger.warn(QOS_PROFILER_ENABLED, "", "", "Dubbo Invocation Profiler has been enabled.");
return "OK. This will cause performance degradation, please be careful!";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SwitchLogLevel.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SwitchLogLevel.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.qos.command.impl;
import org.apache.dubbo.common.logger.Level;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import java.util.Locale;
@Cmd(
name = "switchLogLevel",
summary = "Switch log level",
example = {"switchLogLevel info"})
public class SwitchLogLevel implements BaseCommand {
@Override
public String execute(CommandContext commandContext, String[] args) {
if (args.length != 1) {
return "Unexpected argument length.";
}
Level level;
switch (args[0]) {
case "0":
level = Level.ALL;
break;
case "1":
level = Level.TRACE;
break;
case "2":
level = Level.DEBUG;
break;
case "3":
level = Level.INFO;
break;
case "4":
level = Level.WARN;
break;
case "5":
level = Level.ERROR;
break;
case "6":
level = Level.OFF;
break;
default:
level = Level.valueOf(args[0].toUpperCase(Locale.ROOT));
break;
}
LoggerFactory.setLevel(level);
return "OK";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Version.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Version.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.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
@Cmd(
name = "version",
summary = "version command(show dubbo version)",
example = {"version"})
public class Version implements BaseCommand {
@Override
public String execute(CommandContext commandContext, String[] args) {
StringBuilder versionDescBuilder = new StringBuilder();
versionDescBuilder.append("dubbo version \"");
versionDescBuilder.append(org.apache.dubbo.common.Version.getVersion());
versionDescBuilder.append('\"');
return versionDescBuilder.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableRouterSnapshot.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableRouterSnapshot.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.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ServiceMetadata;
@Cmd(
name = "enableRouterSnapshot",
summary = "Enable Dubbo Invocation Level Router Snapshot Print",
example = "enableRouterSnapshot xx.xx.xxx.service")
public class EnableRouterSnapshot implements BaseCommand {
private final RouterSnapshotSwitcher routerSnapshotSwitcher;
private final FrameworkModel frameworkModel;
public EnableRouterSnapshot(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
this.routerSnapshotSwitcher = frameworkModel.getBeanFactory().getBean(RouterSnapshotSwitcher.class);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (args.length != 1) {
return "args count should be 1. example enableRouterSnapshot xx.xx.xxx.service";
}
String servicePattern = args[0];
int count = 0;
for (ConsumerModel consumerModel : frameworkModel.getServiceRepository().allConsumerModels()) {
try {
ServiceMetadata metadata = consumerModel.getServiceMetadata();
if (metadata.getServiceKey().matches(servicePattern)
|| metadata.getDisplayServiceKey().matches(servicePattern)) {
routerSnapshotSwitcher.addEnabledService(metadata.getServiceKey());
count += 1;
}
} catch (Throwable ignore) {
}
}
return "OK. Found service count: " + count + ". This will cause performance degradation, please be careful!";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OnlineApp.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OnlineApp.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.qos.command.impl;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ProviderModel;
@Cmd(
name = "onlineApp",
summary = "online app addresses",
example = {"onlineApp", "onlineApp xx.xx.xxx.service"})
public class OnlineApp extends BaseOnline {
public OnlineApp(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected void doExport(ProviderModel.RegisterStatedURL statedURL) {
if (UrlUtils.isServiceDiscoveryURL(statedURL.getRegistryUrl())) {
super.doExport(statedURL);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SerializeWarnedClasses.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SerializeWarnedClasses.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.qos.command.impl;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.command.util.SerializeCheckUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
@Cmd(name = "serializeWarnedClasses", summary = "get serialize warned classes")
public class SerializeWarnedClasses implements BaseCommand {
private final SerializeCheckUtils serializeCheckUtils;
public SerializeWarnedClasses(FrameworkModel frameworkModel) {
serializeCheckUtils = frameworkModel.getBeanFactory().getBean(SerializeCheckUtils.class);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (commandContext.isHttp()) {
Map<String, Object> result = new HashMap<>();
result.put("warnedClasses", serializeCheckUtils.getWarnedClasses());
return JsonUtils.toJson(result);
} else {
return "WarnedClasses: \n"
+ serializeCheckUtils.getWarnedClasses().stream().sorted().collect(Collectors.joining("\n"))
+ "\n\n";
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Offline.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Offline.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.qos.command.impl;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ProviderModel;
@Cmd(
name = "offline",
summary = "offline dubbo",
example = {"offline dubbo", "offline xx.xx.xxx.service"})
public class Offline extends BaseOffline {
public Offline(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected void doUnexport(ProviderModel.RegisterStatedURL statedURL) {
super.doUnexport(statedURL);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetEnabledRouterSnapshot.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetEnabledRouterSnapshot.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.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher;
import org.apache.dubbo.rpc.model.FrameworkModel;
@Cmd(
name = "getEnabledRouterSnapshot",
summary = "Get enabled Dubbo invocation level router snapshot print service list")
public class GetEnabledRouterSnapshot implements BaseCommand {
private final RouterSnapshotSwitcher routerSnapshotSwitcher;
public GetEnabledRouterSnapshot(FrameworkModel frameworkModel) {
this.routerSnapshotSwitcher = frameworkModel.getBeanFactory().getBean(RouterSnapshotSwitcher.class);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
return String.join("\n", routerSnapshotSwitcher.getEnabledService());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GracefulShutdown.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GracefulShutdown.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.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.rpc.model.FrameworkModel;
@Cmd(
name = "gracefulShutdown",
summary = "Gracefully shutdown servers",
example = {"gracefulShutdown"},
requiredPermissionLevel = PermissionLevel.PRIVATE)
public class GracefulShutdown implements BaseCommand {
private final Offline offline;
private final FrameworkModel frameworkModel;
public GracefulShutdown(FrameworkModel frameworkModel) {
this.offline = new Offline(frameworkModel);
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
for (org.apache.dubbo.rpc.GracefulShutdown gracefulShutdown :
org.apache.dubbo.rpc.GracefulShutdown.getGracefulShutdowns(frameworkModel)) {
gracefulShutdown.readonly();
}
offline.execute(commandContext, new String[0]);
return "OK";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DefaultMetricsReporterCmd.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DefaultMetricsReporterCmd.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.qos.command.impl;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.metrics.report.DefaultMetricsReporter;
import org.apache.dubbo.metrics.report.MetricsReporter;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Cmd(name = "metrics_default", summary = "display metrics information")
public class DefaultMetricsReporterCmd implements BaseCommand {
public FrameworkModel frameworkModel;
public DefaultMetricsReporterCmd(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
List<ApplicationModel> models = frameworkModel.getApplicationModels();
String result = "There is no application with data";
if (notSpecifyApplication(args)) {
result = useFirst(models, result, null);
} else if (args.length == 1) {
result = specifyApplication(args[0], models, null);
} else if (args.length == 2) {
result = specifyApplication(args[0], models, args[1]);
}
return result;
}
private boolean notSpecifyApplication(String[] args) {
return args == null || args.length == 0;
}
private String useFirst(List<ApplicationModel> models, String result, String metricsName) {
for (ApplicationModel model : models) {
String current = getResponseByApplication(model, metricsName);
if (current != null && getLineNumber(current) > 0) {
result = current;
break;
}
}
return result;
}
private String specifyApplication(String appName, List<ApplicationModel> models, String metricsName) {
if ("application_all".equals(appName)) {
return allApplication(models);
} else {
return specifySingleApplication(appName, models, metricsName);
}
}
private String specifySingleApplication(String appName, List<ApplicationModel> models, String metricsName) {
Optional<ApplicationModel> modelOptional = models.stream()
.filter(applicationModel -> appName.equals(applicationModel.getApplicationName()))
.findFirst();
if (modelOptional.isPresent()) {
return getResponseByApplication(modelOptional.get(), metricsName);
} else {
return "Not exist application: " + appName;
}
}
private String allApplication(List<ApplicationModel> models) {
Map<String, String> appResultMap = new HashMap<>();
for (ApplicationModel model : models) {
appResultMap.put(model.getApplicationName(), getResponseByApplication(model, null));
}
return JsonUtils.toJson(appResultMap);
}
private String getResponseByApplication(ApplicationModel applicationModel, String metricsName) {
String response = "DefaultMetricsReporter not init";
MetricsReporter metricsReporter = applicationModel.getBeanFactory().getBean(DefaultMetricsReporter.class);
if (metricsReporter != null) {
metricsReporter.resetIfSamplesChanged();
response = metricsReporter.getResponseWithName(metricsName);
}
return response;
}
private static long getLineNumber(String content) {
LineNumberReader lnr = new LineNumberReader(new CharArrayReader(content.toCharArray()));
try {
lnr.skip(Long.MAX_VALUE);
lnr.close();
} catch (IOException ignore) {
}
return lnr.getLineNumber();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetAddress.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetAddress.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.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.client.migration.MigrationInvoker;
import org.apache.dubbo.registry.client.migration.model.MigrationStep;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.directory.AbstractDirectory;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.FrameworkServiceRepository;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Cmd(
name = "getAddress",
summary = "Get service available address ",
example = {"getAddress com.example.DemoService", "getAddress group/com.example.DemoService"},
requiredPermissionLevel = PermissionLevel.PRIVATE)
public class GetAddress implements BaseCommand {
public final FrameworkServiceRepository serviceRepository;
public GetAddress(FrameworkModel frameworkModel) {
this.serviceRepository = frameworkModel.getServiceRepository();
}
@Override
@SuppressWarnings("unchecked")
public String execute(CommandContext commandContext, String[] args) {
if (args == null || args.length != 1) {
return "Invalid parameters, please input like getAddress com.example.DemoService";
}
String serviceName = args[0];
StringBuilder plainOutput = new StringBuilder();
Map<String, Object> jsonOutput = new HashMap<>();
for (ConsumerModel consumerModel : serviceRepository.allConsumerModels()) {
if (serviceName.equals(consumerModel.getServiceKey())) {
appendConsumer(plainOutput, jsonOutput, consumerModel);
}
}
if (commandContext.isHttp()) {
return JsonUtils.toJson(jsonOutput);
} else {
return plainOutput.toString();
}
}
private static void appendConsumer(
StringBuilder plainOutput, Map<String, Object> jsonOutput, ConsumerModel consumerModel) {
plainOutput
.append("ConsumerModel: ")
.append(consumerModel.getServiceKey())
.append("@")
.append(Integer.toHexString(System.identityHashCode(consumerModel)))
.append("\n\n");
Map<String, Object> consumerMap = new HashMap<>();
jsonOutput.put(
consumerModel.getServiceKey() + "@" + Integer.toHexString(System.identityHashCode(consumerModel)),
consumerMap);
Object object = consumerModel.getServiceMetadata().getAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY);
Map<Registry, MigrationInvoker<?>> invokerMap;
if (object instanceof Map) {
invokerMap = (Map<Registry, MigrationInvoker<?>>) object;
for (Map.Entry<Registry, MigrationInvoker<?>> entry : invokerMap.entrySet()) {
appendInvokers(plainOutput, consumerMap, entry);
}
}
}
private static void appendInvokers(
StringBuilder plainOutput,
Map<String, Object> consumerMap,
Map.Entry<Registry, MigrationInvoker<?>> entry) {
URL registryUrl = entry.getKey().getUrl();
plainOutput.append("Registry: ").append(registryUrl).append("\n");
Map<String, Object> registryMap = new HashMap<>();
consumerMap.put(registryUrl.toString(), registryMap);
MigrationInvoker<?> migrationInvoker = entry.getValue();
MigrationStep migrationStep = migrationInvoker.getMigrationStep();
plainOutput.append("MigrationStep: ").append(migrationStep).append("\n\n");
registryMap.put("MigrationStep", migrationStep);
Map<String, Object> invokersMap = new HashMap<>();
registryMap.put("Invokers", invokersMap);
URL originConsumerUrl = RpcContext.getServiceContext().getConsumerUrl();
RpcContext.getServiceContext().setConsumerUrl(migrationInvoker.getConsumerUrl());
appendInterfaceLevel(plainOutput, migrationInvoker, invokersMap);
appendAppLevel(plainOutput, migrationInvoker, invokersMap);
RpcContext.getServiceContext().setConsumerUrl(originConsumerUrl);
}
private static void appendAppLevel(
StringBuilder plainOutput, MigrationInvoker<?> migrationInvoker, Map<String, Object> invokersMap) {
Map<String, Object> appMap = new HashMap<>();
invokersMap.put("Application-Level", appMap);
Optional.ofNullable(migrationInvoker.getServiceDiscoveryInvoker())
.ifPresent(i -> plainOutput.append("Application-Level: \n"));
Optional.ofNullable(migrationInvoker.getServiceDiscoveryInvoker())
.map(ClusterInvoker::getDirectory)
.map(Directory::getAllInvokers)
.ifPresent(invokers -> {
List<String> invokerUrls = new LinkedList<>();
plainOutput.append("All Invokers: \n");
for (org.apache.dubbo.rpc.Invoker<?> invoker : invokers) {
invokerUrls.add(invoker.getUrl().toFullString());
plainOutput.append(invoker.getUrl().toFullString()).append("\n");
}
plainOutput.append("\n");
appMap.put("All", invokerUrls);
});
Optional.ofNullable(migrationInvoker.getServiceDiscoveryInvoker())
.map(ClusterInvoker::getDirectory)
.map(s -> (AbstractDirectory<?>) s)
.map(AbstractDirectory::getValidInvokers)
.ifPresent(invokers -> {
List<String> invokerUrls = new LinkedList<>();
plainOutput.append("Valid Invokers: \n");
for (org.apache.dubbo.rpc.Invoker<?> invoker : invokers) {
invokerUrls.add(invoker.getUrl().toFullString());
plainOutput.append(invoker.getUrl().toFullString()).append("\n");
}
plainOutput.append("\n");
appMap.put("Valid", invokerUrls);
});
Optional.ofNullable(migrationInvoker.getServiceDiscoveryInvoker())
.map(ClusterInvoker::getDirectory)
.map(s -> (AbstractDirectory<?>) s)
.map(AbstractDirectory::getDisabledInvokers)
.ifPresent(invokers -> {
List<String> invokerUrls = new LinkedList<>();
plainOutput.append("Disabled Invokers: \n");
for (org.apache.dubbo.rpc.Invoker<?> invoker : invokers) {
invokerUrls.add(invoker.getUrl().toFullString());
plainOutput.append(invoker.getUrl().toFullString()).append("\n");
}
plainOutput.append("\n");
appMap.put("Disabled", invokerUrls);
});
}
private static void appendInterfaceLevel(
StringBuilder plainOutput, MigrationInvoker<?> migrationInvoker, Map<String, Object> invokersMap) {
Map<String, Object> interfaceMap = new HashMap<>();
invokersMap.put("Interface-Level", interfaceMap);
Optional.ofNullable(migrationInvoker.getInvoker()).ifPresent(i -> plainOutput.append("Interface-Level: \n"));
Optional.ofNullable(migrationInvoker.getInvoker())
.map(ClusterInvoker::getDirectory)
.map(Directory::getAllInvokers)
.ifPresent(invokers -> {
List<String> invokerUrls = new LinkedList<>();
plainOutput.append("All Invokers: \n");
for (org.apache.dubbo.rpc.Invoker<?> invoker : invokers) {
invokerUrls.add(invoker.getUrl().toFullString());
plainOutput.append(invoker.getUrl().toFullString()).append("\n");
}
plainOutput.append("\n");
interfaceMap.put("All", invokerUrls);
});
Optional.ofNullable(migrationInvoker.getInvoker())
.map(ClusterInvoker::getDirectory)
.map(s -> (AbstractDirectory<?>) s)
.map(AbstractDirectory::getValidInvokers)
.ifPresent(invokers -> {
List<String> invokerUrls = new LinkedList<>();
plainOutput.append("Valid Invokers: \n");
for (org.apache.dubbo.rpc.Invoker<?> invoker : invokers) {
invokerUrls.add(invoker.getUrl().toFullString());
plainOutput.append(invoker.getUrl().toFullString()).append("\n");
}
plainOutput.append("\n");
interfaceMap.put("Valid", invokerUrls);
});
Optional.ofNullable(migrationInvoker.getInvoker())
.map(ClusterInvoker::getDirectory)
.map(s -> (AbstractDirectory<?>) s)
.map(AbstractDirectory::getDisabledInvokers)
.ifPresent(invokers -> {
List<String> invokerUrls = new LinkedList<>();
plainOutput.append("Disabled Invokers: \n");
for (org.apache.dubbo.rpc.Invoker<?> invoker : invokers) {
invokerUrls.add(invoker.getUrl().toFullString());
plainOutput.append(invoker.getUrl().toFullString()).append("\n");
}
plainOutput.append("\n");
interfaceMap.put("Disabled", invokerUrls);
});
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Live.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Live.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.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.qos.probe.LivenessProbe;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Cmd(name = "live", summary = "Judge if service is alive? ", requiredPermissionLevel = PermissionLevel.PUBLIC)
public class Live implements BaseCommand {
private final FrameworkModel frameworkModel;
public Live(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
String config = frameworkModel.getApplicationModels().stream()
.map(applicationModel ->
applicationModel.getApplicationConfigManager().getApplication())
.map(o -> o.orElse(null))
.filter(Objects::nonNull)
.map(ApplicationConfig::getLivenessProbe)
.filter(Objects::nonNull)
.collect(Collectors.joining(","));
URL url = URL.valueOf("application://").addParameter(CommonConstants.QOS_LIVE_PROBE_EXTENSION, config);
List<LivenessProbe> livenessProbes = frameworkModel
.getExtensionLoader(LivenessProbe.class)
.getActivateExtension(url, CommonConstants.QOS_LIVE_PROBE_EXTENSION);
if (!livenessProbes.isEmpty()) {
for (LivenessProbe livenessProbe : livenessProbes) {
if (!livenessProbe.check()) {
// 503 Service Unavailable
commandContext.setHttpCode(503);
return "false";
}
}
}
// 200 OK
commandContext.setHttpCode(200);
return "true";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SelectTelnet.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SelectTelnet.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.qos.command.impl;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.lang.reflect.Method;
import java.util.List;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
@Cmd(
name = "select",
summary = "Select the index of the method you want to invoke",
example = {"select [index]"})
public class SelectTelnet implements BaseCommand {
public static final AttributeKey<Boolean> SELECT_KEY = AttributeKey.valueOf("telnet.select");
public static final AttributeKey<Method> SELECT_METHOD_KEY = AttributeKey.valueOf("telnet.select.method");
private final InvokeTelnet invokeTelnet;
public SelectTelnet(FrameworkModel frameworkModel) {
this.invokeTelnet = new InvokeTelnet(frameworkModel);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (ArrayUtils.isEmpty(args)) {
return "Please input the index of the method you want to invoke, eg: \r\n select 1";
}
Channel channel = commandContext.getRemote();
String message = args[0];
List<Method> methodList =
channel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).get();
if (CollectionUtils.isEmpty(methodList)) {
return "Please use the invoke command first.";
}
if (!StringUtils.isNumber(message)
|| Integer.parseInt(message) < 1
|| Integer.parseInt(message) > methodList.size()) {
return "Illegal index ,please input select 1~" + methodList.size();
}
Method method = methodList.get(Integer.parseInt(message) - 1);
channel.attr(SELECT_METHOD_KEY).set(method);
channel.attr(SELECT_KEY).set(Boolean.TRUE);
String invokeMessage = channel.attr(InvokeTelnet.INVOKE_MESSAGE_KEY).get();
return invokeTelnet.execute(commandContext, new String[] {invokeMessage});
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ls.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ls.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.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.command.util.ServiceCheckUtils;
import org.apache.dubbo.qos.textui.TTable;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ProviderModel;
import java.util.Collection;
import java.util.Comparator;
import java.util.stream.Collectors;
@Cmd(
name = "ls",
summary = "ls service",
example = {"ls"})
public class Ls implements BaseCommand {
private final FrameworkModel frameworkModel;
public Ls(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
StringBuilder result = new StringBuilder();
result.append(listProvider());
result.append(listConsumer());
return result.toString();
}
public String listProvider() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("As Provider side:" + System.lineSeparator());
Collection<ProviderModel> providerModelList =
frameworkModel.getServiceRepository().allProviderModels();
// Fix: Originally, providers were stored in ConcurrentHashMap, Disordered display of servicekey list
providerModelList = providerModelList.stream()
.sorted(Comparator.comparing(ProviderModel::getServiceKey))
.collect(Collectors.toList());
TTable tTable = new TTable(new TTable.ColumnDefine[] {
new TTable.ColumnDefine(TTable.Align.MIDDLE), new TTable.ColumnDefine(TTable.Align.MIDDLE)
});
// Header
tTable.addRow("Provider Service Name", "PUB");
// Content
for (ProviderModel providerModel : providerModelList) {
if (providerModel.getModuleModel().isInternal()) {
tTable.addRow(
"DubboInternal - " + providerModel.getServiceKey(),
ServiceCheckUtils.getRegisterStatus(providerModel));
} else {
tTable.addRow(providerModel.getServiceKey(), ServiceCheckUtils.getRegisterStatus(providerModel));
}
}
stringBuilder.append(tTable.rendering());
return stringBuilder.toString();
}
public String listConsumer() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("As Consumer side:" + System.lineSeparator());
Collection<ConsumerModel> consumerModelList =
frameworkModel.getServiceRepository().allConsumerModels();
// Fix: Originally, consumers were stored in ConcurrentHashMap, Disordered display of servicekey list
consumerModelList = consumerModelList.stream()
.sorted(Comparator.comparing(ConsumerModel::getServiceKey))
.collect(Collectors.toList());
TTable tTable = new TTable(new TTable.ColumnDefine[] {
new TTable.ColumnDefine(TTable.Align.MIDDLE), new TTable.ColumnDefine(TTable.Align.MIDDLE)
});
// Header
tTable.addRow("Consumer Service Name", "NUM");
// Content
// TODO to calculate consumerAddressNum
for (ConsumerModel consumerModel : consumerModelList) {
tTable.addRow(consumerModel.getServiceKey(), ServiceCheckUtils.getConsumerAddressNum(consumerModel));
}
stringBuilder.append(tTable.rendering());
return stringBuilder.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PortTelnet.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PortTelnet.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.qos.command.impl;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.rpc.ProtocolServer;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import java.util.Collection;
@Cmd(
name = "ps",
summary = "Print server ports and connections.",
example = {"ps -l [port]", "ps", "ps -l", "ps -l 20880"})
public class PortTelnet implements BaseCommand {
private final DubboProtocol dubboProtocol;
public PortTelnet(FrameworkModel frameworkModel) {
this.dubboProtocol = DubboProtocol.getDubboProtocol(frameworkModel);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
StringBuilder buf = new StringBuilder();
String port = null;
boolean detail = false;
if (args.length > 0) {
for (String part : args) {
if ("-l".equals(part)) {
detail = true;
} else {
if (!StringUtils.isNumber(part)) {
return "Illegal port " + part + ", must be integer.";
}
port = part;
}
}
}
if (StringUtils.isEmpty(port)) {
for (ProtocolServer server : dubboProtocol.getServers()) {
if (buf.length() > 0) {
buf.append("\r\n");
}
if (detail) {
buf.append(server.getUrl().getProtocol())
.append("://")
.append(server.getUrl().getAddress());
} else {
buf.append(server.getUrl().getPort());
}
}
} else {
int p = Integer.parseInt(port);
ProtocolServer protocolServer = null;
for (ProtocolServer s : dubboProtocol.getServers()) {
if (p == s.getUrl().getPort()) {
protocolServer = s;
break;
}
}
if (protocolServer != null) {
ExchangeServer server = (ExchangeServer) protocolServer.getRemotingServer();
Collection<ExchangeChannel> channels = server.getExchangeChannels();
for (ExchangeChannel c : channels) {
if (buf.length() > 0) {
buf.append("\r\n");
}
if (detail) {
buf.append(c.getRemoteAddress()).append(" -> ").append(c.getLocalAddress());
} else {
buf.append(c.getRemoteAddress());
}
}
} else {
buf.append("No such port ").append(port);
}
}
return buf.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetConfig.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetConfig.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.qos.command.impl;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConfigCenterConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.ReferenceConfigBase;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfigBase;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.config.TracingConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.context.ModuleConfigManager;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
@Cmd(
name = "getConfig",
summary = "Get current running config.",
example = {"getConfig ReferenceConfig com.example.DemoService", "getConfig ApplicationConfig"},
requiredPermissionLevel = PermissionLevel.PRIVATE)
public class GetConfig implements BaseCommand {
private final FrameworkModel frameworkModel;
public GetConfig(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
boolean http = commandContext.isHttp();
StringBuilder plainOutput = new StringBuilder();
Map<String, Object> frameworkMap = new HashMap<>();
appendFrameworkConfig(args, plainOutput, frameworkMap);
if (http) {
return JsonUtils.toJson(frameworkMap);
} else {
return plainOutput.toString();
}
}
private void appendFrameworkConfig(String[] args, StringBuilder plainOutput, Map<String, Object> frameworkMap) {
for (ApplicationModel applicationModel : frameworkModel.getApplicationModels()) {
Map<String, Object> applicationMap = new HashMap<>();
frameworkMap.put(applicationModel.getDesc(), applicationMap);
plainOutput
.append("ApplicationModel: ")
.append(applicationModel.getDesc())
.append("\n");
ConfigManager configManager = applicationModel.getApplicationConfigManager();
appendApplicationConfigs(args, plainOutput, applicationModel, applicationMap, configManager);
}
}
private static void appendApplicationConfigs(
String[] args,
StringBuilder plainOutput,
ApplicationModel applicationModel,
Map<String, Object> applicationMap,
ConfigManager configManager) {
Optional<ApplicationConfig> applicationConfig = configManager.getApplication();
applicationConfig.ifPresent(config ->
appendConfig("ApplicationConfig", config.getName(), config, plainOutput, applicationMap, args));
for (ProtocolConfig protocol : configManager.getProtocols()) {
appendConfigs("ProtocolConfig", protocol.getName(), protocol, plainOutput, applicationMap, args);
}
for (RegistryConfig registry : configManager.getRegistries()) {
appendConfigs("RegistryConfig", registry.getId(), registry, plainOutput, applicationMap, args);
}
for (MetadataReportConfig metadataConfig : configManager.getMetadataConfigs()) {
appendConfigs(
"MetadataReportConfig", metadataConfig.getId(), metadataConfig, plainOutput, applicationMap, args);
}
for (ConfigCenterConfig configCenter : configManager.getConfigCenters()) {
appendConfigs("ConfigCenterConfig", configCenter.getId(), configCenter, plainOutput, applicationMap, args);
}
Optional<MetricsConfig> metricsConfig = configManager.getMetrics();
metricsConfig.ifPresent(
config -> appendConfig("MetricsConfig", config.getId(), config, plainOutput, applicationMap, args));
Optional<TracingConfig> tracingConfig = configManager.getTracing();
tracingConfig.ifPresent(
config -> appendConfig("TracingConfig", config.getId(), config, plainOutput, applicationMap, args));
Optional<MonitorConfig> monitorConfig = configManager.getMonitor();
monitorConfig.ifPresent(
config -> appendConfig("MonitorConfig", config.getId(), config, plainOutput, applicationMap, args));
Optional<SslConfig> sslConfig = configManager.getSsl();
sslConfig.ifPresent(
config -> appendConfig("SslConfig", config.getId(), config, plainOutput, applicationMap, args));
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
Map<String, Object> moduleMap = new HashMap<>();
applicationMap.put(moduleModel.getDesc(), moduleMap);
plainOutput.append("ModuleModel: ").append(moduleModel.getDesc()).append("\n");
ModuleConfigManager moduleConfigManager = moduleModel.getConfigManager();
appendModuleConfigs(args, plainOutput, moduleMap, moduleConfigManager);
}
}
private static void appendModuleConfigs(
String[] args,
StringBuilder plainOutput,
Map<String, Object> moduleMap,
ModuleConfigManager moduleConfigManager) {
for (ProviderConfig provider : moduleConfigManager.getProviders()) {
appendConfigs("ProviderConfig", provider.getId(), provider, plainOutput, moduleMap, args);
}
for (ConsumerConfig consumer : moduleConfigManager.getConsumers()) {
appendConfigs("ConsumerConfig", consumer.getId(), consumer, plainOutput, moduleMap, args);
}
Optional<ModuleConfig> moduleConfig = moduleConfigManager.getModule();
moduleConfig.ifPresent(
config -> appendConfig("ModuleConfig", config.getId(), config, plainOutput, moduleMap, args));
for (ServiceConfigBase<?> service : moduleConfigManager.getServices()) {
appendConfigs("ServiceConfig", service.getUniqueServiceName(), service, plainOutput, moduleMap, args);
}
for (ReferenceConfigBase<?> reference : moduleConfigManager.getReferences()) {
appendConfigs("ReferenceConfig", reference.getUniqueServiceName(), reference, plainOutput, moduleMap, args);
}
}
@SuppressWarnings("unchecked")
private static void appendConfigs(
String type, String id, Object config, StringBuilder plainOutput, Map<String, Object> map, String[] args) {
if (!isMatch(type, id, args)) {
return;
}
id = id == null ? "(empty)" : id;
plainOutput
.append(type)
.append(": ")
.append(id)
.append("\n")
.append(config)
.append("\n\n");
Map<String, Object> typeMap =
(Map<String, Object>) map.computeIfAbsent(type, k -> new HashMap<String, Object>());
typeMap.put(id, config);
}
private static void appendConfig(
String type, String id, Object config, StringBuilder plainOutput, Map<String, Object> map, String[] args) {
if (!isMatch(type, id, args)) {
return;
}
id = id == null ? "(empty)" : id;
plainOutput
.append(type)
.append(": ")
.append(id)
.append("\n")
.append(config)
.append("\n\n");
map.put(type, config);
}
private static boolean isMatch(String type, String id, String[] args) {
if (args == null) {
return true;
}
switch (args.length) {
case 1:
if (!Objects.equals(args[0], type)) {
return false;
}
break;
case 2:
if (!Objects.equals(args[0], type) || !Objects.equals(args[1], id)) {
return false;
}
break;
default:
}
return true;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PwdTelnet.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PwdTelnet.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.qos.command.impl;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import java.util.Arrays;
@Cmd(
name = "pwd",
summary = "Print working default service.",
example = {"pwd"})
public class PwdTelnet implements BaseCommand {
@Override
public String execute(CommandContext commandContext, String[] args) {
if (args.length > 0) {
return "Unsupported parameter " + Arrays.toString(args) + " for pwd.";
}
String service =
commandContext.getRemote().attr(ChangeTelnet.SERVICE_KEY).get();
StringBuilder buf = new StringBuilder();
if (StringUtils.isEmpty(service)) {
buf.append('/');
} else {
buf.append(service);
}
return buf.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/LoggerInfo.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/LoggerInfo.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.qos.command.impl;
import org.apache.dubbo.common.logger.Level;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
@Cmd(
name = "loggerInfo",
summary = "Print logger info",
example = {"loggerInfo"})
public class LoggerInfo implements BaseCommand {
@Override
public String execute(CommandContext commandContext, String[] args) {
String availableAdapters =
String.join(", ", LoggerFactory.getAvailableAdapter().toArray(new String[0]));
String currentAdapter = LoggerFactory.getCurrentAdapter();
Level level = LoggerFactory.getLevel();
return "Available logger adapters: [" + availableAdapters + "]. Current Adapter: [" + currentAdapter
+ "]. Log level: " + level.name();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OfflineInterface.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OfflineInterface.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.qos.command.impl;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ProviderModel;
@Cmd(
name = "offlineInterface",
summary = "offline dubbo",
example = {"offlineInterface dubbo", "offlineInterface xx.xx.xxx.service"})
public class OfflineInterface extends BaseOffline {
public OfflineInterface(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected void doUnexport(ProviderModel.RegisterStatedURL statedURL) {
if (!UrlUtils.isServiceDiscoveryURL(statedURL.getRegistryUrl())) {
super.doUnexport(statedURL);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetRecentRouterSnapshot.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetRecentRouterSnapshot.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.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;
@Cmd(name = "getRecentRouterSnapshot", summary = "Get recent (32) router snapshot message")
public class GetRecentRouterSnapshot implements BaseCommand {
private final RouterSnapshotSwitcher routerSnapshotSwitcher;
public GetRecentRouterSnapshot(FrameworkModel frameworkModel) {
this.routerSnapshotSwitcher = frameworkModel.getBeanFactory().getBean(RouterSnapshotSwitcher.class);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
return Arrays.stream(routerSnapshotSwitcher.cloneSnapshot())
.filter(Objects::nonNull)
.sorted()
.collect(Collectors.joining("\n\n"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/InvokeTelnet.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/InvokeTelnet.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.qos.command.impl;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.AsyncContext;
import org.apache.dubbo.rpc.AsyncContextImpl;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.ProviderModel;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import static org.apache.dubbo.common.utils.PojoUtils.realize;
@Cmd(
name = "invoke",
summary = "Invoke the service method.",
example = {"invoke IHelloService.sayHello(\"xxxx\")", "invoke sayHello(\"xxxx\")"})
public class InvokeTelnet implements BaseCommand {
public static final AttributeKey<String> INVOKE_MESSAGE_KEY = AttributeKey.valueOf("telnet.invoke.method.message");
public static final AttributeKey<List<Method>> INVOKE_METHOD_LIST_KEY =
AttributeKey.valueOf("telnet.invoke.method.list");
public static final AttributeKey<ProviderModel> INVOKE_METHOD_PROVIDER_KEY =
AttributeKey.valueOf("telnet.invoke.method.provider");
private final FrameworkModel frameworkModel;
public InvokeTelnet(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (ArrayUtils.isEmpty(args)) {
return "Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n"
+ "invoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n"
+ "invoke com.xxx.XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})";
}
Channel channel = commandContext.getRemote();
String service = channel.attr(ChangeTelnet.SERVICE_KEY) != null
? channel.attr(ChangeTelnet.SERVICE_KEY).get()
: null;
String message = args[0];
int i = message.indexOf("(");
if (i < 0 || !message.endsWith(")")) {
return "Invalid parameters, format: service.method(args)";
}
String method = message.substring(0, i).trim();
String param = message.substring(i + 1, message.length() - 1).trim();
i = method.lastIndexOf(".");
if (i >= 0) {
service = method.substring(0, i).trim();
method = method.substring(i + 1).trim();
}
if (StringUtils.isEmpty(service)) {
return "If you want to invoke like [invoke sayHello(\"xxxx\")], please execute cd command first,"
+ " or you can execute it like [invoke IHelloService.sayHello(\"xxxx\")]";
}
List<Object> list;
try {
list = JsonUtils.toJavaList("[" + param + "]", Object.class);
} catch (Throwable t) {
return "Invalid json argument, cause: " + t.getMessage();
}
StringBuilder buf = new StringBuilder();
Method invokeMethod = null;
ProviderModel selectedProvider = null;
if (isInvokedSelectCommand(channel)) {
selectedProvider = channel.attr(INVOKE_METHOD_PROVIDER_KEY).get();
invokeMethod = channel.attr(SelectTelnet.SELECT_METHOD_KEY).get();
} else {
for (ProviderModel provider : frameworkModel.getServiceRepository().allProviderModels()) {
if (!isServiceMatch(service, provider)) {
continue;
}
selectedProvider = provider;
List<Method> methodList = findSameSignatureMethod(provider.getAllMethods(), method, list);
if (CollectionUtils.isEmpty(methodList)) {
break;
}
if (methodList.size() == 1) {
invokeMethod = methodList.get(0);
} else {
List<Method> matchMethods = findMatchMethods(methodList, list);
if (CollectionUtils.isEmpty(matchMethods)) {
break;
}
if (matchMethods.size() == 1) {
invokeMethod = matchMethods.get(0);
} else { // exist overridden method
channel.attr(INVOKE_METHOD_PROVIDER_KEY).set(provider);
channel.attr(INVOKE_METHOD_LIST_KEY).set(matchMethods);
channel.attr(INVOKE_MESSAGE_KEY).set(message);
printSelectMessage(buf, matchMethods);
return buf.toString();
}
}
break;
}
}
if (!StringUtils.isEmpty(service)) {
buf.append("Use default service ").append(service).append('.');
}
if (selectedProvider == null) {
buf.append("\r\nNo such service ").append(service);
return buf.toString();
}
if (invokeMethod == null) {
buf.append("\r\nNo such method ")
.append(method)
.append(" in service ")
.append(service);
return buf.toString();
}
try {
Object[] array =
realize(list.toArray(), invokeMethod.getParameterTypes(), invokeMethod.getGenericParameterTypes());
long start = System.currentTimeMillis();
AppResponse result = new AppResponse();
try {
Object o = invokeMethod.invoke(selectedProvider.getServiceInstance(), array);
boolean setValueDone = false;
if (RpcContext.getServerAttachment().isAsyncStarted()) {
AsyncContext asyncContext = RpcContext.getServerAttachment().getAsyncContext();
if (asyncContext instanceof AsyncContextImpl) {
CompletableFuture<Object> internalFuture =
((AsyncContextImpl) asyncContext).getInternalFuture();
result.setValue(internalFuture.get());
setValueDone = true;
}
}
if (!setValueDone) {
result.setValue(o);
}
} catch (Throwable t) {
result.setException(t);
if (t instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
} finally {
RpcContext.removeContext();
}
long end = System.currentTimeMillis();
buf.append("\r\nresult: ");
buf.append(JsonUtils.toJson(result.recreate()));
buf.append("\r\nelapsed: ");
buf.append(end - start);
buf.append(" ms.");
} catch (Throwable t) {
return "Failed to invoke method " + invokeMethod.getName() + ", cause: " + StringUtils.toString(t);
}
return buf.toString();
}
private boolean isServiceMatch(String service, ProviderModel provider) {
return provider.getServiceKey().equalsIgnoreCase(service)
|| provider.getServiceInterfaceClass().getSimpleName().equalsIgnoreCase(service)
|| provider.getServiceInterfaceClass().getName().equalsIgnoreCase(service)
|| StringUtils.isEmpty(service);
}
private List<Method> findSameSignatureMethod(
Set<MethodDescriptor> methods, String lookupMethodName, List<Object> args) {
List<Method> sameSignatureMethods = new ArrayList<>();
for (MethodDescriptor model : methods) {
Method method = model.getMethod();
if (method.getName().equals(lookupMethodName) && method.getParameterTypes().length == args.size()) {
sameSignatureMethods.add(method);
}
}
return sameSignatureMethods;
}
private List<Method> findMatchMethods(List<Method> methods, List<Object> args) {
List<Method> matchMethod = new ArrayList<>();
for (Method method : methods) {
if (isMatch(method, args)) {
matchMethod.add(method);
}
}
return matchMethod;
}
private static boolean isMatch(Method method, List<Object> args) {
Class<?>[] types = method.getParameterTypes();
if (types.length != args.size()) {
return false;
}
for (int i = 0; i < types.length; i++) {
Class<?> type = types[i];
Object arg = args.get(i);
if (arg == null) {
if (type.isPrimitive()) {
return false;
}
// if the type is not primitive, we choose to believe what the invoker want is a null value
continue;
}
if (ReflectUtils.isPrimitive(arg.getClass())) {
// allow string arg to enum type, @see PojoUtils.realize0()
if (arg instanceof String && type.isEnum()) {
continue;
}
if (!ReflectUtils.isPrimitive(type)) {
return false;
}
if (!ReflectUtils.isCompatible(type, arg)) {
return false;
}
} else if (arg instanceof Map) {
String name = (String) ((Map<?, ?>) arg).get("class");
if (StringUtils.isNotEmpty(name)) {
Class<?> cls = ReflectUtils.forName(name);
if (!type.isAssignableFrom(cls)) {
return false;
}
} else {
return true;
}
} else if (arg instanceof Collection) {
if (!type.isArray() && !type.isAssignableFrom(arg.getClass())) {
return false;
}
} else {
if (!type.isAssignableFrom(arg.getClass())) {
return false;
}
}
}
return true;
}
private void printSelectMessage(StringBuilder buf, List<Method> methods) {
buf.append("Methods:\r\n");
for (int i = 0; i < methods.size(); i++) {
Method method = methods.get(i);
buf.append(i + 1).append(". ").append(method.getName()).append('(');
Class<?>[] parameterTypes = method.getParameterTypes();
for (int n = 0; n < parameterTypes.length; n++) {
buf.append(parameterTypes[n].getSimpleName());
if (n != parameterTypes.length - 1) {
buf.append(',');
}
}
buf.append(")\r\n");
}
buf.append("Please use the select command to select the method you want to invoke. eg: select 1");
}
private boolean isInvokedSelectCommand(Channel channel) {
if (channel.attr(SelectTelnet.SELECT_KEY).get() != null) {
channel.attr(SelectTelnet.SELECT_KEY).remove();
return true;
}
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SetProfilerWarnPercent.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SetProfilerWarnPercent.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.qos.command.impl;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.profiler.ProfilerSwitch;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_WARN_PERCENT;
@Cmd(
name = "setProfilerWarnPercent",
example = "setProfilerWarnPercent 0.75",
summary = "Disable Dubbo Invocation Profiler.")
public class SetProfilerWarnPercent implements BaseCommand {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(SetProfilerWarnPercent.class);
@Override
public String execute(CommandContext commandContext, String[] args) {
if (args == null || args.length != 1) {
return "args error. example: setProfilerWarnPercent 0.75";
}
ProfilerSwitch.setWarnPercent(Double.parseDouble(args[0]));
logger.warn(
QOS_PROFILER_WARN_PERCENT, "", "", "Dubbo Invocation Profiler warn percent has been set to " + args[0]);
return "OK";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PublishMetadata.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PublishMetadata.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.qos.command.impl;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_PARAMETER_FORMAT_ERROR;
@Cmd(
name = "publishMetadata",
summary = "update service metadata and service instance",
example = {"publishMetadata", "publishMetadata 5"})
public class PublishMetadata implements BaseCommand {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PublishMetadata.class);
private final FrameworkModel frameworkModel;
public PublishMetadata(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
logger.info("received publishMetadata command.");
StringBuilder stringBuilder = new StringBuilder();
List<ApplicationModel> applicationModels = frameworkModel.getApplicationModels();
for (ApplicationModel applicationModel : applicationModels) {
if (ArrayUtils.isEmpty(args)) {
ServiceInstanceMetadataUtils.refreshMetadataAndInstance(applicationModel);
stringBuilder
.append("publish metadata succeeded. App:")
.append(applicationModel.getApplicationName())
.append("\n");
} else {
try {
int delay = Integer.parseInt(args[0]);
FrameworkExecutorRepository frameworkExecutorRepository = applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class);
frameworkExecutorRepository
.nextScheduledExecutor()
.schedule(
() -> ServiceInstanceMetadataUtils.refreshMetadataAndInstance(applicationModel),
delay,
TimeUnit.SECONDS);
} catch (NumberFormatException e) {
logger.error(CONFIG_PARAMETER_FORMAT_ERROR, "", "", "Wrong delay param", e);
return "publishMetadata failed! Wrong delay param!";
}
stringBuilder
.append("publish task submitted, will publish in ")
.append(args[0])
.append(" seconds. App:")
.append(applicationModel.getApplicationName())
.append("\n");
}
}
return stringBuilder.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetOpenAPI.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetOpenAPI.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.qos.command.impl;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.remoting.http12.rest.OpenAPIRequest;
import org.apache.dubbo.remoting.http12.rest.OpenAPIService;
import org.apache.dubbo.rpc.model.FrameworkModel;
@Cmd(
name = "getOpenAPI",
summary = "Get the openapi descriptor for specified services.",
example = {
"getOpenAPI",
"getOpenAPI groupA",
"getOpenAPI com.example.DemoService",
"getOpenAPI --group groupA --version 1.1.0 --tag tagA --service com.example. --openapi 3.0.0 --format yaml",
},
requiredPermissionLevel = PermissionLevel.PRIVATE)
public class GetOpenAPI implements BaseCommand {
private final FrameworkModel frameworkModel;
public GetOpenAPI(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
OpenAPIService openAPIService = frameworkModel.getBean(OpenAPIService.class);
if (openAPIService == null) {
return "OpenAPI is not available";
}
OpenAPIRequest request = new OpenAPIRequest();
int len = args.length;
if (len > 0) {
if (len == 1) {
String arg0 = args[0];
if (arg0.indexOf('.') > 0) {
request.setService(new String[] {arg0});
} else {
request.setGroup(arg0);
}
} else {
for (int i = 0; i < len; i += 2) {
String value = args[i + 1];
switch (StringUtils.substringAfterLast(args[i], '-')) {
case "group":
request.setGroup(value);
break;
case "version":
request.setVersion(value);
break;
case "tag":
request.setTag(StringUtils.tokenize(value));
break;
case "service":
request.setService(StringUtils.tokenize(value));
break;
case "openapi":
request.setOpenapi(value);
break;
case "format":
request.setFormat(value);
break;
default:
break;
}
}
}
}
return openAPIService.getDocument(request);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ChangeTelnet.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ChangeTelnet.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.qos.command.impl;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
@Cmd(
name = "cd",
summary = "Change default service.",
example = {"cd [service]"})
public class ChangeTelnet implements BaseCommand {
public static final AttributeKey<String> SERVICE_KEY = AttributeKey.valueOf("telnet.service");
private final DubboProtocol dubboProtocol;
public ChangeTelnet(FrameworkModel frameworkModel) {
this.dubboProtocol = DubboProtocol.getDubboProtocol(frameworkModel);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
Channel channel = commandContext.getRemote();
if (ArrayUtils.isEmpty(args)) {
return "Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService";
}
String message = args[0];
StringBuilder buf = new StringBuilder();
if ("/".equals(message) || "..".equals(message)) {
String service = channel.attr(SERVICE_KEY).getAndRemove();
buf.append("Cancelled default service ").append(service).append('.');
} else {
boolean found = false;
for (Exporter<?> exporter : dubboProtocol.getExporters()) {
if (message.equals(exporter.getInvoker().getInterface().getSimpleName())
|| message.equals(exporter.getInvoker().getInterface().getName())
|| message.equals(exporter.getInvoker().getUrl().getPath())
|| message.equals(exporter.getInvoker().getUrl().getServiceKey())) {
found = true;
break;
}
}
if (found) {
channel.attr(SERVICE_KEY).set(message);
buf.append("Used the ")
.append(message)
.append(" as default.\r\nYou can cancel default service by command: cd /");
} else {
buf.append("No such service ").append(message);
}
}
return buf.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Help.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Help.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.qos.command.impl;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.command.util.CommandHelper;
import org.apache.dubbo.qos.textui.TTable;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
@Cmd(
name = "help",
summary = "help command",
example = {"help", "help online"})
public class Help implements BaseCommand {
private final CommandHelper commandHelper;
private static final String MAIN_HELP = "mainHelp";
private static final Map<String, String> processedTable = new WeakHashMap<>();
public Help(FrameworkModel frameworkModel) {
this.commandHelper = new CommandHelper(frameworkModel);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (ArrayUtils.isNotEmpty(args)) {
return processedTable.computeIfAbsent(args[0], this::commandHelp);
} else {
return processedTable.computeIfAbsent(MAIN_HELP, commandName -> mainHelp());
}
}
private String commandHelp(String commandName) {
if (!commandHelper.hasCommand(commandName)) {
return "no such command:" + commandName;
}
Class<?> clazz = commandHelper.getCommandClass(commandName);
final Cmd cmd = clazz.getAnnotation(Cmd.class);
final TTable tTable = new TTable(new TTable.ColumnDefine[] {
new TTable.ColumnDefine(TTable.Align.RIGHT), new TTable.ColumnDefine(80, false, TTable.Align.LEFT)
});
tTable.addRow("COMMAND NAME", commandName);
if (null != cmd.example()) {
tTable.addRow("EXAMPLE", drawExample(cmd));
}
return tTable.padding(1).rendering();
}
private String drawExample(Cmd cmd) {
final StringBuilder drawExampleStringBuilder = new StringBuilder();
for (String example : cmd.example()) {
drawExampleStringBuilder.append(example).append('\n');
}
return drawExampleStringBuilder.toString();
}
/*
* output main help
*/
private String mainHelp() {
final TTable tTable = new TTable(new TTable.ColumnDefine[] {
new TTable.ColumnDefine(TTable.Align.RIGHT), new TTable.ColumnDefine(80, false, TTable.Align.LEFT)
});
final List<Class<?>> classes = commandHelper.getAllCommandClass();
Collections.sort(classes, new Comparator<Class<?>>() {
@Override
public int compare(Class<?> o1, Class<?> o2) {
final Integer o1s = o1.getAnnotation(Cmd.class).sort();
final Integer o2s = o2.getAnnotation(Cmd.class).sort();
return o1s.compareTo(o2s);
}
});
for (Class<?> clazz : classes) {
if (clazz.isAnnotationPresent(Cmd.class)) {
final Cmd cmd = clazz.getAnnotation(Cmd.class);
tTable.addRow(cmd.name(), cmd.summary());
}
}
return tTable.padding(1).rendering();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/TelnetCommandDecoder.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/TelnetCommandDecoder.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.qos.command.decoder;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.command.CommandContextFactory;
public class TelnetCommandDecoder {
public static final CommandContext decode(String str) {
CommandContext commandContext = null;
if (!StringUtils.isBlank(str)) {
str = str.trim();
String[] array = str.split("(?<![\\\\]) ");
if (array.length > 0) {
String[] targetArgs = new String[array.length - 1];
System.arraycopy(array, 1, targetArgs, 0, array.length - 1);
String name = array[0].trim();
if (name.equals("invoke") && array.length > 2) {
targetArgs = reBuildInvokeCmdArgs(str);
}
commandContext = CommandContextFactory.newInstance(name, targetArgs, false);
commandContext.setOriginRequest(str);
}
}
return commandContext;
}
private static String[] reBuildInvokeCmdArgs(String cmd) {
return new String[] {cmd.substring(cmd.indexOf(" ") + 1).trim()};
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoder.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoder.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.qos.command.decoder;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.command.CommandContextFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.multipart.Attribute;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
public class HttpCommandDecoder {
public static CommandContext decode(HttpRequest request) {
CommandContext commandContext = null;
if (request != null) {
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
String path = queryStringDecoder.path();
String[] array = path.split("/");
if (array.length == 2) {
String name = array[1];
// process GET request and POST request separately. Check url for GET, and check body for POST
if (request.method() == HttpMethod.GET) {
if (queryStringDecoder.parameters().isEmpty()) {
commandContext = CommandContextFactory.newInstance(name);
commandContext.setHttp(true);
} else {
List<String> valueList = new ArrayList<>();
for (List<String> values :
queryStringDecoder.parameters().values()) {
valueList.addAll(values);
}
commandContext =
CommandContextFactory.newInstance(name, valueList.toArray(new String[] {}), true);
}
} else if (request.method() == HttpMethod.POST) {
HttpPostRequestDecoder httpPostRequestDecoder = null;
try {
httpPostRequestDecoder = new HttpPostRequestDecoder(request);
List<String> valueList = new ArrayList<>();
for (InterfaceHttpData interfaceHttpData : httpPostRequestDecoder.getBodyHttpDatas()) {
if (interfaceHttpData.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
Attribute attribute = (Attribute) interfaceHttpData;
try {
valueList.add(attribute.getValue());
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
if (valueList.isEmpty()) {
commandContext = CommandContextFactory.newInstance(name);
commandContext.setHttp(true);
} else {
commandContext =
CommandContextFactory.newInstance(name, valueList.toArray(new String[] {}), true);
}
} finally {
if (httpPostRequestDecoder != null) {
httpPostRequestDecoder.destroy();
}
}
}
} else if (array.length == 3) {
String name = array[1];
String appName = array[2];
if (request.method() == HttpMethod.GET) {
commandContext = CommandContextFactory.newInstance(name, new String[] {appName}, true);
commandContext.setHttp(true);
}
}
}
return commandContext;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TComponent.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TComponent.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.qos.textui;
/**
* render component
*/
public interface TComponent {
/**
* render
*/
String rendering();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TKv.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TKv.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.qos.textui;
import org.apache.dubbo.common.utils.StringUtils;
import java.util.Scanner;
/**
* KV
*/
public class TKv implements TComponent {
private final TTable tTable;
public TKv() {
this.tTable = new TTable(new TTable.ColumnDefine[] {
new TTable.ColumnDefine(TTable.Align.RIGHT),
new TTable.ColumnDefine(TTable.Align.RIGHT),
new TTable.ColumnDefine(TTable.Align.LEFT)
})
.padding(0);
this.tTable.getBorder().set(TTable.Border.BORDER_NON);
}
public TKv(TTable.ColumnDefine keyColumnDefine, TTable.ColumnDefine valueColumnDefine) {
this.tTable = new TTable(new TTable.ColumnDefine[] {
keyColumnDefine, new TTable.ColumnDefine(TTable.Align.RIGHT), valueColumnDefine
})
.padding(0);
this.tTable.getBorder().set(TTable.Border.BORDER_NON);
}
public TKv add(final Object key, final Object value) {
tTable.addRow(key, " : ", value);
return this;
}
@Override
public String rendering() {
return filterEmptyLine(tTable.rendering());
}
private String filterEmptyLine(String content) {
final StringBuilder sb = new StringBuilder();
try (Scanner scanner = new Scanner(content)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line != null) {
// remove extra space at line's end
line = StringUtils.stripEnd(line, " ");
if (line.isEmpty()) {
line = " ";
}
}
sb.append(line).append(System.lineSeparator());
}
}
return sb.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTree.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTree.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.qos.textui;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import static java.lang.System.currentTimeMillis;
import static org.apache.dubbo.common.utils.StringUtils.EMPTY_STRING;
import static org.apache.dubbo.common.utils.StringUtils.length;
import static org.apache.dubbo.common.utils.StringUtils.repeat;
/**
* tree
*/
public class TTree implements TComponent {
private static final String STEP_FIRST_CHAR = "`---";
private static final String STEP_NORMAL_CHAR = "+---";
private static final String STEP_HAS_BOARD = "| ";
private static final String STEP_EMPTY_BOARD = " ";
// should output cost or not
private final boolean isPrintCost;
// tree node
private final Node root;
// current node
private Node current;
public TTree(boolean isPrintCost, String title) {
this.root = new Node(title).markBegin().markEnd();
this.current = root;
this.isPrintCost = isPrintCost;
}
@Override
public String rendering() {
final StringBuilder treeSB = new StringBuilder();
recursive(0, true, "", root, new Callback() {
@Override
public void callback(int deep, boolean isLast, String prefix, Node node) {
final boolean hasChild = !node.children.isEmpty();
final String stepString = isLast ? STEP_FIRST_CHAR : STEP_NORMAL_CHAR;
final int stepStringLength = length(stepString);
treeSB.append(prefix).append(stepString);
int costPrefixLength = 0;
if (hasChild) {
treeSB.append('+');
}
if (isPrintCost && !node.isRoot()) {
final String costPrefix = String.format(
"[%s,%sms]",
(node.endTimestamp - root.beginTimestamp), (node.endTimestamp - node.beginTimestamp));
costPrefixLength = length(costPrefix);
treeSB.append(costPrefix);
}
try (Scanner scanner = new Scanner(new StringReader(node.data.toString()))) {
boolean isFirst = true;
while (scanner.hasNextLine()) {
if (isFirst) {
treeSB.append(scanner.nextLine()).append('\n');
isFirst = false;
} else {
treeSB.append(prefix)
.append(repeat(' ', stepStringLength))
.append(hasChild ? "|" : EMPTY_STRING)
.append(repeat(' ', costPrefixLength))
.append(scanner.nextLine())
.append(System.lineSeparator());
}
}
}
}
});
return treeSB.toString();
}
/**
* recursive visit
*/
private void recursive(int deep, boolean isLast, String prefix, Node node, Callback callback) {
callback.callback(deep, isLast, prefix, node);
if (!node.isLeaf()) {
final int size = node.children.size();
for (int index = 0; index < size; index++) {
final boolean isLastFlag = index == size - 1;
final String currentPrefix = isLast ? prefix + STEP_EMPTY_BOARD : prefix + STEP_HAS_BOARD;
recursive(deep + 1, isLastFlag, currentPrefix, node.children.get(index), callback);
}
}
}
public boolean isTop() {
return current.isRoot();
}
/**
* create a branch node
*
* @param data node data
* @return this
*/
public TTree begin(Object data) {
current = new Node(current, data);
current.markBegin();
return this;
}
public TTree begin() {
return begin(null);
}
public Object get() {
if (current.isRoot()) {
throw new IllegalStateException("current node is root.");
}
return current.data;
}
public TTree set(Object data) {
if (current.isRoot()) {
throw new IllegalStateException("current node is root.");
}
current.data = data;
return this;
}
/**
* end a branch node
*
* @return this
*/
public TTree end() {
if (current.isRoot()) {
throw new IllegalStateException("current node is root.");
}
current.markEnd();
current = current.parent;
return this;
}
/**
* tree node
*/
private static class Node {
/**
* parent node
*/
final Node parent;
/**
* node data
*/
Object data;
/**
* child nodes
*/
final List<Node> children = new ArrayList<>();
/**
* begin timestamp
*/
private long beginTimestamp;
/**
* end timestamp
*/
private long endTimestamp;
/**
* construct root node
*/
private Node(Object data) {
this.parent = null;
this.data = data;
}
/**
* construct a regular node
*
* @param parent parent node
* @param data node data
*/
private Node(Node parent, Object data) {
this.parent = parent;
this.data = data;
parent.children.add(this);
}
/**
* is the current node the root node
*
* @return true / false
*/
boolean isRoot() {
return null == parent;
}
/**
* if the current node the leaf node
*
* @return true / false
*/
boolean isLeaf() {
return children.isEmpty();
}
Node markBegin() {
beginTimestamp = currentTimeMillis();
return this;
}
Node markEnd() {
endTimestamp = currentTimeMillis();
return this;
}
}
/**
* callback interface for recursive visit
*/
private interface Callback {
void callback(int deep, boolean isLast, String prefix, Node node);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTable.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTable.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.qos.textui;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.String.format;
import static org.apache.dubbo.common.utils.StringUtils.EMPTY_STRING;
import static org.apache.dubbo.common.utils.StringUtils.length;
import static org.apache.dubbo.common.utils.StringUtils.repeat;
import static org.apache.dubbo.common.utils.StringUtils.replace;
/**
* Table
*/
public class TTable implements TComponent {
// column definition
private final ColumnDefine[] columnDefineArray;
// border
private final Border border = new Border();
// padding
private int padding;
public TTable(ColumnDefine[] columnDefineArray) {
this.columnDefineArray = null == columnDefineArray ? new ColumnDefine[0] : columnDefineArray;
}
public TTable(int columnNum) {
this.columnDefineArray = new ColumnDefine[columnNum];
for (int index = 0; index < this.columnDefineArray.length; index++) {
columnDefineArray[index] = new ColumnDefine();
}
}
@Override
public String rendering() {
final StringBuilder tableSB = new StringBuilder();
// process width cache
final int[] widthCacheArray = new int[getColumnCount()];
for (int index = 0; index < widthCacheArray.length; index++) {
widthCacheArray[index] = abs(columnDefineArray[index].getWidth());
}
final int rowCount = getRowCount();
for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) {
final boolean isFirstRow = rowIndex == 0;
final boolean isLastRow = rowIndex == rowCount - 1;
// print first separation line
if (isFirstRow && border.has(Border.BORDER_OUTER_TOP)) {
tableSB.append(drawSeparationLine(widthCacheArray)).append(System.lineSeparator());
}
// print inner separation lines
if (!isFirstRow && border.has(Border.BORDER_INNER_H)) {
tableSB.append(drawSeparationLine(widthCacheArray)).append(System.lineSeparator());
}
// draw one line
tableSB.append(drawRow(widthCacheArray, rowIndex));
// print ending separation line
if (isLastRow && border.has(Border.BORDER_OUTER_BOTTOM)) {
tableSB.append(drawSeparationLine(widthCacheArray)).append(System.lineSeparator());
}
}
return tableSB.toString();
}
private String drawRow(int[] widthCacheArray, int rowIndex) {
final StringBuilder rowSB = new StringBuilder();
final Scanner[] scannerArray = new Scanner[getColumnCount()];
try {
boolean hasNextLine;
do {
hasNextLine = false;
final StringBuilder segmentSB = new StringBuilder();
for (int colIndex = 0; colIndex < getColumnCount(); colIndex++) {
final int width = widthCacheArray[colIndex];
final boolean isFirstColOfRow = colIndex == 0;
final boolean isLastColOfRow = colIndex == widthCacheArray.length - 1;
final String borderChar;
if (isFirstColOfRow && border.has(Border.BORDER_OUTER_LEFT)) {
borderChar = "|";
} else if (!isFirstColOfRow && border.has(Border.BORDER_INNER_V)) {
borderChar = "|";
} else {
borderChar = EMPTY_STRING;
}
if (null == scannerArray[colIndex]) {
scannerArray[colIndex] = new Scanner(
new StringReader(wrap(getData(rowIndex, columnDefineArray[colIndex]), width)));
}
final Scanner scanner = scannerArray[colIndex];
final String data;
if (scanner.hasNextLine()) {
data = scanner.nextLine();
hasNextLine = true;
} else {
data = EMPTY_STRING;
}
if (width > 0) {
final ColumnDefine columnDefine = columnDefineArray[colIndex];
final String dataFormat = getDataFormat(columnDefine, width, data);
final String paddingChar = repeat(" ", padding);
segmentSB.append(format(borderChar + paddingChar + dataFormat + paddingChar, data));
}
if (isLastColOfRow) {
if (border.has(Border.BORDER_OUTER_RIGHT)) {
segmentSB.append('|');
}
segmentSB.append(System.lineSeparator());
}
}
if (hasNextLine) {
rowSB.append(segmentSB);
}
} while (hasNextLine);
return rowSB.toString();
} finally {
for (Scanner scanner : scannerArray) {
if (null != scanner) {
scanner.close();
}
}
}
}
private String getData(int rowIndex, ColumnDefine columnDefine) {
return columnDefine.getRowCount() <= rowIndex ? EMPTY_STRING : columnDefine.rows.get(rowIndex);
}
private String getDataFormat(ColumnDefine columnDefine, int width, String data) {
switch (columnDefine.align) {
case MIDDLE: {
final int length = length(data);
final int diff = width - length;
final int left = diff / 2;
return repeat(" ", diff - left) + "%s" + repeat(" ", left);
}
case RIGHT: {
return "%" + width + "s";
}
case LEFT:
default: {
return "%-" + width + "s";
}
}
}
/**
* get row count
*/
private int getRowCount() {
int rowCount = 0;
for (ColumnDefine columnDefine : columnDefineArray) {
rowCount = max(rowCount, columnDefine.getRowCount());
}
return rowCount;
}
/**
* position to last column
*/
private int indexLastCol(final int[] widthCacheArray) {
for (int colIndex = widthCacheArray.length - 1; colIndex >= 0; colIndex--) {
final int width = widthCacheArray[colIndex];
if (width <= 0) {
continue;
}
return colIndex;
}
return 0;
}
/**
* draw separation line
*/
private String drawSeparationLine(final int[] widthCacheArray) {
final StringBuilder separationLineSB = new StringBuilder();
final int lastCol = indexLastCol(widthCacheArray);
final int colCount = widthCacheArray.length;
for (int colIndex = 0; colIndex < colCount; colIndex++) {
final int width = widthCacheArray[colIndex];
if (width <= 0) {
continue;
}
final boolean isFirstCol = colIndex == 0;
final boolean isLastCol = colIndex == lastCol;
if (isFirstCol && border.has(Border.BORDER_OUTER_LEFT)) {
separationLineSB.append('+');
}
if (!isFirstCol && border.has(Border.BORDER_INNER_V)) {
separationLineSB.append('+');
}
separationLineSB.append(repeat("-", width + 2 * padding));
if (isLastCol && border.has(Border.BORDER_OUTER_RIGHT)) {
separationLineSB.append('+');
}
}
return separationLineSB.toString();
}
/**
* Add a row
*/
public TTable addRow(Object... columnDataArray) {
if (null != columnDataArray) {
for (int index = 0; index < columnDefineArray.length; index++) {
final ColumnDefine columnDefine = columnDefineArray[index];
if (index < columnDataArray.length && null != columnDataArray[index]) {
columnDefine.rows.add(replaceTab(columnDataArray[index].toString()));
} else {
columnDefine.rows.add(EMPTY_STRING);
}
}
}
return this;
}
/**
* alignment
*/
public enum Align {
/**
* left-alignment
*/
LEFT,
/**
* right-alignment
*/
RIGHT,
/**
* middle-alignment
*/
MIDDLE
}
/**
* column definition
*/
public static class ColumnDefine {
// column width
private final int width;
// whether to auto resize
private final boolean isAutoResize;
// alignment
private final Align align;
// data rows
private final List<String> rows = new ArrayList<>();
public ColumnDefine(int width, boolean isAutoResize, Align align) {
this.width = width;
this.isAutoResize = isAutoResize;
this.align = align;
}
public ColumnDefine(Align align) {
this(0, true, align);
}
public ColumnDefine(int width) {
this(width, false, Align.LEFT);
}
public ColumnDefine(int width, Align align) {
this(width, false, align);
}
public ColumnDefine() {
this(Align.LEFT);
}
/**
* get current width
*
* @return width
*/
public int getWidth() {
// if not auto resize, return preset width
if (!isAutoResize) {
return width;
}
// if it's auto resize, then calculate the possible max width
int maxWidth = 0;
for (String data : rows) {
maxWidth = max(width(data), maxWidth);
}
return maxWidth;
}
/**
* get rows for the current column
*
* @return current column's rows
*/
public int getRowCount() {
return rows.size();
}
}
/**
* set padding
*
* @param padding padding
*/
public TTable padding(int padding) {
this.padding = padding;
return this;
}
/**
* get column count
*
* @return column count
*/
public int getColumnCount() {
return columnDefineArray.length;
}
/**
* replace tab to four spaces
*
* @param string the original string
* @return the replaced string
*/
private static String replaceTab(String string) {
return replace(string, "\t", " ");
}
/**
* visible width for the given string.
*
* for example: "abc\n1234"'s width is 4.
*
* @param string the given string
* @return visible width
*/
private static int width(String string) {
int maxWidth = 0;
try (Scanner scanner = new Scanner(new StringReader(string))) {
while (scanner.hasNextLine()) {
maxWidth = max(length(scanner.nextLine()), maxWidth);
}
}
return maxWidth;
}
/**
* get border
*
* @return table border
*/
public Border getBorder() {
return border;
}
/**
* border style
*/
public class Border {
private int borders = BORDER_OUTER | BORDER_INNER;
/**
* border outer top
*/
public static final int BORDER_OUTER_TOP = 1 << 0;
/**
* border outer right
*/
public static final int BORDER_OUTER_RIGHT = 1 << 1;
/**
* border outer bottom
*/
public static final int BORDER_OUTER_BOTTOM = 1 << 2;
/**
* border outer left
*/
public static final int BORDER_OUTER_LEFT = 1 << 3;
/**
* inner border: horizon
*/
public static final int BORDER_INNER_H = 1 << 4;
/**
* inner border: vertical
*/
public static final int BORDER_INNER_V = 1 << 5;
/**
* outer border
*/
public static final int BORDER_OUTER =
BORDER_OUTER_TOP | BORDER_OUTER_BOTTOM | BORDER_OUTER_LEFT | BORDER_OUTER_RIGHT;
/**
* inner border
*/
public static final int BORDER_INNER = BORDER_INNER_H | BORDER_INNER_V;
/**
* no border
*/
public static final int BORDER_NON = 0;
/**
* whether has one of the specified border styles
*
* @param borderArray border styles
* @return whether has one of the specified border styles
*/
public boolean has(int... borderArray) {
if (null == borderArray) {
return false;
}
for (int b : borderArray) {
if ((this.borders & b) == b) {
return true;
}
}
return false;
}
/**
* get border style
*
* @return border style
*/
public int get() {
return borders;
}
/**
* set border style
*
* @param border border style
* @return this
*/
public Border set(int border) {
this.borders = border;
return this;
}
public Border add(int border) {
return set(get() | border);
}
public Border remove(int border) {
return set(get() ^ border);
}
}
public static String wrap(String string, int width) {
final StringBuilder sb = new StringBuilder();
final char[] buffer = string.toCharArray();
int count = 0;
for (char c : buffer) {
if (count == width) {
count = 0;
sb.append('\n');
if (c == '\n') {
continue;
}
}
if (c == '\n') {
count = 0;
} else {
count++;
}
sb.append(c);
}
return sb.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TLadder.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TLadder.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.qos.textui;
import java.util.LinkedList;
import java.util.List;
import static org.apache.dubbo.common.utils.StringUtils.repeat;
/**
* Ladder
*/
public class TLadder implements TComponent {
// separator
private static final String LADDER_CHAR = "`-";
// tab
private static final String STEP_CHAR = " ";
// indent length
private static final int INDENT_STEP = 2;
private final List<String> items = new LinkedList<>();
@Override
public String rendering() {
final StringBuilder ladderSB = new StringBuilder();
int deep = 0;
for (String item : items) {
// no separator is required for the first item
if (deep == 0) {
ladderSB.append(item).append(System.lineSeparator());
}
// need separator for others
else {
ladderSB.append(repeat(STEP_CHAR, deep * INDENT_STEP))
.append(LADDER_CHAR)
.append(item)
.append(System.lineSeparator());
}
deep++;
}
return ladderSB.toString();
}
/**
* add one item
*/
public TLadder addItem(String item) {
items.add(item);
return this;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/common/QosConstants.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/common/QosConstants.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.qos.common;
public interface QosConstants {
int DEFAULT_PORT = 22222;
String BR_STR = "\r\n";
String CLOSE = "close!";
String QOS_PERMISSION_CHECKER = "qosPermissionChecker";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/aot/QosReflectionTypeDescriberRegistrar.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/aot/QosReflectionTypeDescriberRegistrar.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.qos.aot;
import org.apache.dubbo.aot.api.MemberCategory;
import org.apache.dubbo.aot.api.ReflectionTypeDescriberRegistrar;
import org.apache.dubbo.aot.api.TypeDescriber;
import org.apache.dubbo.qos.server.handler.ForeignHostPermitHandler;
import org.apache.dubbo.qos.server.handler.QosProcessHandler;
import org.apache.dubbo.qos.server.handler.TelnetIdleEventHandler;
import java.nio.channels.spi.SelectorProvider;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class QosReflectionTypeDescriberRegistrar implements ReflectionTypeDescriberRegistrar {
@Override
public List<TypeDescriber> getTypeDescribers() {
List<TypeDescriber> typeDescribers = new ArrayList<>();
typeDescribers.add(buildTypeDescriberWithPublicMethod(SelectorProvider.class));
typeDescribers.add(buildTypeDescriberWithPublicMethod(ForeignHostPermitHandler.class));
typeDescribers.add(buildTypeDescriberWithPublicMethod(QosProcessHandler.class));
typeDescribers.add(buildTypeDescriberWithPublicMethod(TelnetIdleEventHandler.class));
return typeDescribers;
}
private TypeDescriber buildTypeDescriberWithPublicMethod(Class<?> cl) {
Set<MemberCategory> memberCategories = new HashSet<>();
memberCategories.add(MemberCategory.INVOKE_PUBLIC_METHODS);
return new TypeDescriber(
cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/LogTelnetHandler.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/LogTelnetHandler.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.qos.legacy;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.Level;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.apache.dubbo.remoting.telnet.support.Help;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
@Activate
@Help(parameter = "level", summary = "Change log level or show log ", detail = "Change log level or show log")
public class LogTelnetHandler implements TelnetHandler {
public static final String SERVICE_KEY = "telnet.log";
@Override
public String telnet(Channel channel, String message) {
long size;
File file = LoggerFactory.getFile();
StringBuilder buf = new StringBuilder();
if (message == null || message.trim().length() == 0) {
buf.append("EXAMPLE: log error / log 100");
} else {
String[] str = message.split(" ");
if (!StringUtils.isNumber(str[0])) {
LoggerFactory.setLevel(Level.valueOf(message.toUpperCase()));
} else {
int showLogLength = Integer.parseInt(str[0]);
if (file != null && file.exists()) {
try (FileInputStream fis = new FileInputStream(file)) {
FileChannel filechannel = fis.getChannel();
size = filechannel.size();
ByteBuffer bb;
if (size <= showLogLength) {
bb = ByteBuffer.allocate((int) size);
filechannel.read(bb, 0);
} else {
int pos = (int) (size - showLogLength);
bb = ByteBuffer.allocate(showLogLength);
filechannel.read(bb, pos);
}
bb.flip();
String content = new String(bb.array())
.replace("<", "<")
.replace(">", ">")
.replace("\n", "<br/><br/>");
buf.append("\r\ncontent:").append(content);
buf.append("\r\nmodified:")
.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date(file.lastModified())));
buf.append("\r\nsize:").append(size).append("\r\n");
} catch (Exception e) {
buf.append(e.getMessage());
}
} else {
buf.append("\r\nMESSAGE: log file not exists or log appender is console .");
}
}
}
buf.append("\r\nCURRENT LOG LEVEL:")
.append(LoggerFactory.getLevel())
.append("\r\nCURRENT LOG APPENDER:")
.append(file == null ? "console" : file.getAbsolutePath());
return buf.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandler.java | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandler.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.qos.legacy;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.apache.dubbo.remoting.telnet.support.Help;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
/**
* ChangeServiceTelnetHandler
*/
@Activate
@Help(parameter = "[service]", summary = "Change default service.", detail = "Change default service.")
public class ChangeTelnetHandler implements TelnetHandler {
public static final String SERVICE_KEY = "telnet.service";
@Override
public String telnet(Channel channel, String message) {
if (StringUtils.isEmpty(message)) {
return "Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService";
}
StringBuilder buf = new StringBuilder();
if ("/".equals(message) || "..".equals(message)) {
String service = (String) channel.getAttribute(SERVICE_KEY);
channel.removeAttribute(SERVICE_KEY);
buf.append("Cancelled default service ").append(service).append('.');
} else {
boolean found = false;
for (Exporter<?> exporter : DubboProtocol.getDubboProtocol().getExporters()) {
if (message.equals(exporter.getInvoker().getInterface().getSimpleName())
|| message.equals(exporter.getInvoker().getInterface().getName())
|| message.equals(exporter.getInvoker().getUrl().getPath())) {
found = true;
break;
}
}
if (found) {
channel.setAttribute(SERVICE_KEY, message);
buf.append("Used the ")
.append(message)
.append(" as default.\r\nYou can cancel default service by command: cd /");
} else {
buf.append("No such service ").append(message);
}
}
return buf.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.