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-mcp/src/test/java/org/apache/dubbo/mcp/transport/DubboMcpSseTransportProviderTest.java
dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/transport/DubboMcpSseTransportProviderTest.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.mcp.transport; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.remoting.http12.HttpMethods; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.HttpStatus; import org.apache.dubbo.remoting.http12.exception.HttpResultPayloadException; import org.apache.dubbo.remoting.http12.message.ServerSentEvent; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcServiceContext; import java.io.ByteArrayInputStream; import com.fasterxml.jackson.databind.ObjectMapper; import io.modelcontextprotocol.spec.McpSchema; import io.modelcontextprotocol.spec.McpServerSession; 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 org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) class DubboMcpSseTransportProviderTest { @Mock private StreamObserver<ServerSentEvent<String>> responseObserver; @Mock private HttpRequest httpRequest; @Mock private HttpResponse httpResponse; @Mock private McpServerSession.Factory sessionFactory; @Mock private RpcServiceContext rpcServiceContext; @Mock private McpServerSession mockSession; private MockedStatic<RpcContext> rpcContextMockedStatic; @InjectMocks private DubboMcpSseTransportProvider transportProvider; private final ObjectMapper objectMapper = new ObjectMapper(); @BeforeEach void setUp() { rpcContextMockedStatic = mockStatic(RpcContext.class); rpcContextMockedStatic.when(RpcContext::getServiceContext).thenReturn(rpcServiceContext); when(rpcServiceContext.getRequest(HttpRequest.class)).thenReturn(httpRequest); when(rpcServiceContext.getResponse(HttpResponse.class)).thenReturn(httpResponse); transportProvider = new DubboMcpSseTransportProvider(objectMapper); transportProvider.setSessionFactory(sessionFactory); } @Test void handleRequestHandlesGetRequest() { when(httpRequest.method()).thenReturn(HttpMethods.GET.name()); when(sessionFactory.create(any())).thenReturn(mockSession); when(mockSession.getId()).thenReturn("1"); transportProvider.handleRequest(responseObserver); verify(httpRequest, times(1)).method(); ArgumentCaptor<ServerSentEvent> captor = ArgumentCaptor.forClass(ServerSentEvent.class); verify(responseObserver, times(1)).onNext(captor.capture()); ServerSentEvent evt = captor.getValue(); Assertions.assertEquals("endpoint", evt.getEvent()); Assertions.assertTrue(((String) evt.getData()).startsWith("/mcp/message?sessionId=")); } @Test void handleRequestHandlesPostRequest() { when(httpRequest.method()).thenReturn(HttpMethods.GET.name()); when(sessionFactory.create(any())).thenReturn(mockSession); when(mockSession.getId()).thenReturn("1"); when(httpRequest.parameter("sessionId")).thenReturn("1"); when(httpRequest.inputStream()) .thenReturn(new ByteArrayInputStream("{\"jsonrpc\":\"2.0\",\"method\":\"test\"}".getBytes())); when(mockSession.handle(any(McpSchema.JSONRPCMessage.class))).thenReturn(mock()); transportProvider.handleRequest(responseObserver); when(httpRequest.method()).thenReturn(HttpMethods.POST.name()); transportProvider.handleRequest(responseObserver); verify(httpRequest, times(3)).method(); verify(httpResponse).setStatus(HttpStatus.OK.getCode()); } @Test void handleRequestIgnoresUnsupportedMethods() { when(httpRequest.method()).thenReturn(HttpMethods.PUT.name()); transportProvider.handleRequest(responseObserver); verify(httpRequest, times(2)).method(); verifyNoInteractions(responseObserver); verifyNoInteractions(httpResponse); } @Test void handleMessageReturnsBadRequestWhenSessionIdIsMissing() { when(httpRequest.parameter("sessionId")).thenReturn(null); try { transportProvider.handleMessage(); } catch (Exception e) { Assertions.assertInstanceOf(HttpResultPayloadException.class, e); HttpResultPayloadException httpResultPayloadException = (HttpResultPayloadException) e; Assertions.assertEquals( HttpStatus.BAD_REQUEST.getCode(), httpResultPayloadException.getResult().getStatus()); } } @Test void handleMessageReturnsNotFoundForUnknownSessionId() { when(httpRequest.parameter("sessionId")).thenReturn("unknownSessionId"); try { transportProvider.handleMessage(); } catch (Exception e) { Assertions.assertInstanceOf(HttpResultPayloadException.class, e); HttpResultPayloadException httpResultPayloadException = (HttpResultPayloadException) e; Assertions.assertEquals( HttpStatus.NOT_FOUND.getCode(), httpResultPayloadException.getResult().getStatus()); } } @AfterEach public void tearDown() { if (rpcContextMockedStatic != null) { rpcContextMockedStatic.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-mcp/src/test/java/org/apache/dubbo/mcp/tool/DubboOpenApiToolConverterTest.java
dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/tool/DubboOpenApiToolConverterTest.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.mcp.tool; import org.apache.dubbo.common.URL; import org.apache.dubbo.mcp.core.McpServiceFilter; import org.apache.dubbo.remoting.http12.HttpMethods; import org.apache.dubbo.remoting.http12.rest.OpenAPIRequest; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.protocol.tri.rest.openapi.DefaultOpenAPIService; import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI; import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Operation; import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Parameter; import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.PathItem; import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Schema; import java.util.HashMap; import java.util.Map; import io.modelcontextprotocol.spec.McpSchema; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; class DubboOpenApiToolConverterTest { @Mock private DefaultOpenAPIService openApiService; @Mock private ServiceDescriptor serviceDescriptor; @Mock private URL serviceUrl; private DubboOpenApiToolConverter converter; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); converter = new DubboOpenApiToolConverter(openApiService); } @Test void testConverterConstruction() { assertNotNull(converter); } @Test void testConvertToTools_WithNullOpenAPI() { when(serviceDescriptor.getInterfaceName()).thenReturn("TestService"); when(openApiService.getOpenAPI(any(OpenAPIRequest.class))).thenReturn(null); Map<String, McpSchema.Tool> result = converter.convertToTools(serviceDescriptor, serviceUrl, null); assertTrue(result.isEmpty()); } @Test void testConvertToTools_WithEmptyPaths() { when(serviceDescriptor.getInterfaceName()).thenReturn("TestService"); OpenAPI openAPI = new OpenAPI(); openAPI.setPaths(new HashMap<>()); when(openApiService.getOpenAPI(any(OpenAPIRequest.class))).thenReturn(openAPI); Map<String, McpSchema.Tool> result = converter.convertToTools(serviceDescriptor, serviceUrl, null); assertTrue(result.isEmpty()); } @Test void testConvertToTools_WithValidOperation() { when(serviceDescriptor.getInterfaceName()).thenReturn("TestService"); OpenAPI openAPI = createMockOpenAPI(); when(openApiService.getOpenAPI(any(OpenAPIRequest.class))).thenReturn(openAPI); Map<String, McpSchema.Tool> result = converter.convertToTools(serviceDescriptor, serviceUrl, null); assertFalse(result.isEmpty()); assertTrue(result.containsKey("testOperation")); McpSchema.Tool tool = result.get("testOperation"); assertEquals("testOperation", tool.name()); assertNotNull(tool.description()); assertNotNull(tool.inputSchema()); } @Test void testConvertToTools_WithCustomToolConfig() { when(serviceDescriptor.getInterfaceName()).thenReturn("TestService"); OpenAPI openAPI = createMockOpenAPI(); when(openApiService.getOpenAPI(any(OpenAPIRequest.class))).thenReturn(openAPI); McpServiceFilter.McpToolConfig toolConfig = new McpServiceFilter.McpToolConfig(); toolConfig.setToolName("customTool"); toolConfig.setDescription("Custom description"); Map<String, McpSchema.Tool> result = converter.convertToTools(serviceDescriptor, serviceUrl, toolConfig); assertFalse(result.isEmpty()); McpSchema.Tool tool = result.values().iterator().next(); assertEquals("customTool", tool.name()); assertEquals("Custom description", tool.description()); } @Test void testGetOperationByToolName_WithExistingTool() { when(serviceDescriptor.getInterfaceName()).thenReturn("TestService"); OpenAPI openAPI = createMockOpenAPI(); when(openApiService.getOpenAPI(any(OpenAPIRequest.class))).thenReturn(openAPI); converter.convertToTools(serviceDescriptor, serviceUrl, null); Operation operation = converter.getOperationByToolName("testOperation"); assertNotNull(operation); assertEquals("testOperation", operation.getOperationId()); } @Test void testGetOperationByToolName_WithNonExistentTool() { Operation operation = converter.getOperationByToolName("nonExistent"); assertNull(operation); } @Test void testConvertToTools_WithParameter() { when(serviceDescriptor.getInterfaceName()).thenReturn("TestService"); OpenAPI openAPI = createMockOpenAPIWithParameters(); when(openApiService.getOpenAPI(any(OpenAPIRequest.class))).thenReturn(openAPI); Map<String, McpSchema.Tool> result = converter.convertToTools(serviceDescriptor, serviceUrl, null); assertFalse(result.isEmpty()); McpSchema.Tool tool = result.get("testOperation"); assertNotNull(tool); assertNotNull(tool.inputSchema()); } @Test void testConvertToTools_WithException() { when(serviceDescriptor.getInterfaceName()).thenReturn("TestService"); when(openApiService.getOpenAPI(any(OpenAPIRequest.class))).thenThrow(new RuntimeException("Test exception")); assertThrows(RuntimeException.class, () -> { converter.convertToTools(serviceDescriptor, serviceUrl, null); }); } private OpenAPI createMockOpenAPI() { OpenAPI openAPI = new OpenAPI(); Map<String, PathItem> paths = new HashMap<>(); PathItem pathItem = new PathItem(); Map<HttpMethods, Operation> operations = new HashMap<>(); Operation operation = new Operation(); operation.setOperationId("testOperation"); operation.setSummary("Test operation summary"); operation.setDescription("Test operation description"); operations.put(HttpMethods.GET, operation); pathItem.setOperations(operations); paths.put("/test", pathItem); openAPI.setPaths(paths); return openAPI; } private OpenAPI createMockOpenAPIWithParameters() { OpenAPI openAPI = createMockOpenAPI(); PathItem pathItem = openAPI.getPaths().get("/test"); Operation operation = pathItem.getOperations().get(HttpMethods.GET); Parameter parameter = new Parameter("testParam", Parameter.In.QUERY); parameter.setSchema(new Schema()); operation.setParameters(java.util.Arrays.asList(parameter)); return openAPI; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/tool/DubboServiceToolRegistryTest.java
dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/tool/DubboServiceToolRegistryTest.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.mcp.tool; import org.apache.dubbo.common.URL; import org.apache.dubbo.mcp.core.McpServiceFilter; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import java.util.ArrayList; import java.util.List; import io.modelcontextprotocol.server.McpAsyncServer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import reactor.core.publisher.Mono; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.*; class DubboServiceToolRegistryTest { @Mock private McpAsyncServer mcpServer; @Mock private DubboOpenApiToolConverter toolConverter; @Mock private DubboMcpGenericCaller genericCaller; @Mock private McpServiceFilter mcpServiceFilter; @Mock private ProviderModel providerModel; @Mock private ServiceDescriptor serviceDescriptor; private DubboServiceToolRegistry registry; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); registry = new DubboServiceToolRegistry(mcpServer, toolConverter, genericCaller, mcpServiceFilter); } @Test void testRegistryConstruction() { assertNotNull(registry); } @Test void testRegisterService_WithNullUrls() { when(providerModel.getServiceModel()).thenReturn(serviceDescriptor); when(providerModel.getServiceUrls()).thenReturn(null); int result = registry.registerService(providerModel); assertEquals(0, result); } @Test void testRegisterService_WithEmptyUrls() { when(providerModel.getServiceModel()).thenReturn(serviceDescriptor); when(providerModel.getServiceUrls()).thenReturn(new ArrayList<>()); int result = registry.registerService(providerModel); assertEquals(0, result); } @Test void testRegisterService_WithNullServiceInterface() { List<URL> urls = createMockUrls(); when(providerModel.getServiceModel()).thenReturn(serviceDescriptor); when(providerModel.getServiceUrls()).thenReturn(urls); when(serviceDescriptor.getServiceInterfaceClass()).thenReturn(null); int result = registry.registerService(providerModel); assertEquals(0, result); } @Test void testRegisterService_WithValidService() { setupValidProviderModel(); when(mcpServiceFilter.shouldExposeMethodAsMcpTool(any(), any())).thenReturn(true); when(mcpServiceFilter.getMcpToolConfig(any(), any())).thenReturn(createMockToolConfig()); when(mcpServer.addTool(any())).thenReturn(Mono.empty()); int result = registry.registerService(providerModel); assertTrue(result > 0); verify(mcpServer, atLeastOnce()).addTool(any()); } @Test void testRegisterService_WithServiceLevelTools() { setupValidProviderModel(); when(mcpServiceFilter.shouldExposeMethodAsMcpTool(any(), any())).thenReturn(false); when(mcpServiceFilter.shouldExposeAsMcpTool(any())).thenReturn(true); when(toolConverter.convertToTools(any(), any(), any())).thenReturn(createMockTools()); when(mcpServer.addTool(any())).thenReturn(Mono.empty()); int result = registry.registerService(providerModel); assertTrue(result >= 0); } @Test void testRegisterService_WithException() { when(providerModel.getServiceModel()).thenThrow(new RuntimeException("Test exception")); assertThrows(RuntimeException.class, () -> { registry.registerService(providerModel); }); } @Test void testUnregisterService_WithExistingService() { setupValidProviderModel(); when(mcpServiceFilter.shouldExposeMethodAsMcpTool(any(), any())).thenReturn(true); when(mcpServiceFilter.getMcpToolConfig(any(), any())).thenReturn(createMockToolConfig()); when(mcpServer.addTool(any())).thenReturn(Mono.empty()); when(mcpServer.removeTool(anyString())).thenReturn(Mono.empty()); registry.registerService(providerModel); assertDoesNotThrow(() -> registry.unregisterService(providerModel)); } @Test void testUnregisterService_WithNonExistentService() { when(providerModel.getServiceKey()).thenReturn("nonExistentService"); assertDoesNotThrow(() -> registry.unregisterService(providerModel)); } @Test void testUnregisterService_WithException() { setupValidProviderModel(); when(mcpServiceFilter.shouldExposeMethodAsMcpTool(any(), any())).thenReturn(true); when(mcpServiceFilter.getMcpToolConfig(any(), any())).thenReturn(createMockToolConfig()); when(mcpServer.addTool(any())).thenReturn(Mono.empty()); when(mcpServer.removeTool(anyString())).thenThrow(new RuntimeException("Test exception")); registry.registerService(providerModel); assertDoesNotThrow(() -> registry.unregisterService(providerModel)); } @Test void testClearRegistry() { assertDoesNotThrow(() -> registry.clearRegistry()); } private void setupValidProviderModel() { List<URL> urls = createMockUrls(); Class<?> mockInterface = TestInterface.class; when(providerModel.getServiceModel()).thenReturn(serviceDescriptor); when(providerModel.getServiceUrls()).thenReturn(urls); when(providerModel.getServiceKey()).thenReturn("testService"); when(serviceDescriptor.getServiceInterfaceClass()).thenReturn((Class) mockInterface); when(serviceDescriptor.getInterfaceName()).thenReturn("TestInterface"); } private List<URL> createMockUrls() { List<URL> urls = new ArrayList<>(); URL url = URL.valueOf("dubbo://localhost:20880/TestInterface"); urls.add(url); return urls; } private McpServiceFilter.McpToolConfig createMockToolConfig() { McpServiceFilter.McpToolConfig config = new McpServiceFilter.McpToolConfig(); config.setToolName("testTool"); config.setDescription("Test tool description"); return config; } private java.util.Map<String, io.modelcontextprotocol.spec.McpSchema.Tool> createMockTools() { java.util.Map<String, io.modelcontextprotocol.spec.McpSchema.Tool> tools = new java.util.HashMap<>(); io.modelcontextprotocol.spec.McpSchema.Tool tool = new io.modelcontextprotocol.spec.McpSchema.Tool("testTool", "Test description", "{}"); tools.put("testTool", tool); return tools; } public interface TestInterface { String testMethod(String param); void anotherMethod(int value); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/tool/DubboMcpGenericCallerTest.java
dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/tool/DubboMcpGenericCallerTest.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.mcp.tool; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; class DubboMcpGenericCallerTest { @Mock private ApplicationModel applicationModel; @Mock private ApplicationConfig applicationConfig; private DubboMcpGenericCaller genericCaller; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); } @Test void testConstructor_WithValidApplicationModel() { when(applicationModel.getCurrentConfig()).thenReturn(applicationConfig); assertDoesNotThrow(() -> { genericCaller = new DubboMcpGenericCaller(applicationModel); }); } @Test void testConstructor_WithNullApplicationModel() { assertThrows(IllegalArgumentException.class, () -> { new DubboMcpGenericCaller(null); }); } @Test void testConstructor_WithNullApplicationConfig() { when(applicationModel.getCurrentConfig()).thenReturn(null); when(applicationModel.getApplicationName()).thenReturn("TestApp"); assertThrows(IllegalStateException.class, () -> { new DubboMcpGenericCaller(applicationModel); }); } @Test void testConstructor_WithNullApplicationName() { when(applicationModel.getCurrentConfig()).thenReturn(null); when(applicationModel.getApplicationName()).thenReturn(null); assertThrows(IllegalStateException.class, () -> { new DubboMcpGenericCaller(applicationModel); }); } @Test void testExecute_WithValidParameters() { when(applicationModel.getCurrentConfig()).thenReturn(applicationConfig); genericCaller = new DubboMcpGenericCaller(applicationModel); String interfaceName = "TestInterface"; String methodName = "testMethod"; List<String> orderedJavaParameterNames = createParameterNames(); Class<?>[] parameterJavaTypes = createParameterTypes(); Map<String, Object> mcpProvidedParameters = createMcpParameters(); String group = "testGroup"; String version = "1.0.0"; assertThrows(RuntimeException.class, () -> { genericCaller.execute( interfaceName, methodName, orderedJavaParameterNames, parameterJavaTypes, mcpProvidedParameters, group, version); }); } @Test void testExecute_WithNullGroup() { when(applicationModel.getCurrentConfig()).thenReturn(applicationConfig); genericCaller = new DubboMcpGenericCaller(applicationModel); String interfaceName = "TestInterface"; String methodName = "testMethod"; List<String> orderedJavaParameterNames = createParameterNames(); Class<?>[] parameterJavaTypes = createParameterTypes(); Map<String, Object> mcpProvidedParameters = createMcpParameters(); String version = "1.0.0"; assertThrows(RuntimeException.class, () -> { genericCaller.execute( interfaceName, methodName, orderedJavaParameterNames, parameterJavaTypes, mcpProvidedParameters, null, version); }); } @Test void testExecute_WithNullVersion() { when(applicationModel.getCurrentConfig()).thenReturn(applicationConfig); genericCaller = new DubboMcpGenericCaller(applicationModel); String interfaceName = "TestInterface"; String methodName = "testMethod"; List<String> orderedJavaParameterNames = createParameterNames(); Class<?>[] parameterJavaTypes = createParameterTypes(); Map<String, Object> mcpProvidedParameters = createMcpParameters(); String group = "testGroup"; assertThrows(RuntimeException.class, () -> { genericCaller.execute( interfaceName, methodName, orderedJavaParameterNames, parameterJavaTypes, mcpProvidedParameters, group, null); }); } @Test void testExecute_WithMissingParameters() { when(applicationModel.getCurrentConfig()).thenReturn(applicationConfig); genericCaller = new DubboMcpGenericCaller(applicationModel); String interfaceName = "TestInterface"; String methodName = "testMethod"; List<String> orderedJavaParameterNames = createParameterNames(); Class<?>[] parameterJavaTypes = createParameterTypes(); Map<String, Object> mcpProvidedParameters = new HashMap<>(); String group = "testGroup"; String version = "1.0.0"; assertThrows(RuntimeException.class, () -> { genericCaller.execute( interfaceName, methodName, orderedJavaParameterNames, parameterJavaTypes, mcpProvidedParameters, group, version); }); } @Test void testExecute_WithEmptyStrings() { when(applicationModel.getCurrentConfig()).thenReturn(applicationConfig); genericCaller = new DubboMcpGenericCaller(applicationModel); String interfaceName = "TestInterface"; String methodName = "testMethod"; List<String> orderedJavaParameterNames = createParameterNames(); Class<?>[] parameterJavaTypes = createParameterTypes(); Map<String, Object> mcpProvidedParameters = createMcpParameters(); assertThrows(RuntimeException.class, () -> { genericCaller.execute( interfaceName, methodName, orderedJavaParameterNames, parameterJavaTypes, mcpProvidedParameters, "", ""); }); } private List<String> createParameterNames() { List<String> names = new ArrayList<>(); names.add("param1"); names.add("param2"); return names; } private Class<?>[] createParameterTypes() { return new Class<?>[] {String.class, Integer.class}; } private Map<String, Object> createMcpParameters() { Map<String, Object> parameters = new HashMap<>(); parameters.put("param1", "value1"); parameters.put("param2", 42); return parameters; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/McpConstant.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/McpConstant.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.mcp; /** * Constants for MCP (Model Context Protocol) integration */ public interface McpConstant { String SETTINGS_MCP_PREFIX = "dubbo.protocol.triple.rest.mcp"; String SETTINGS_MCP_ENABLE = "dubbo.protocol.triple.rest.mcp.enabled"; String SETTINGS_MCP_PORT = "dubbo.protocol.triple.rest.mcp.port"; String SETTINGS_MCP_PROTOCOL = "dubbo.protocol.triple.rest.mcp.protocol"; String SETTINGS_MCP_SESSION_TIMEOUT = "dubbo.protocol.triple.rest.mcp.session-timeout"; String SETTINGS_MCP_DEFAULT_ENABLED = "dubbo.protocol.triple.rest.mcp.default.enabled"; String SETTINGS_MCP_INCLUDE_PATTERNS = "dubbo.protocol.triple.rest.mcp.include-patterns"; String SETTINGS_MCP_EXCLUDE_PATTERNS = "dubbo.protocol.triple.rest.mcp.exclude-patterns"; String SETTINGS_MCP_PATHS_SSE = "dubbo.protocol.triple.rest.mcp.path.sse"; String SETTINGS_MCP_PATHS_MESSAGE = "dubbo.protocol.triple.rest.mcp.path.message"; Integer DEFAULT_SESSION_TIMEOUT = 60; // MCP service control-related configuration String SETTINGS_MCP_SERVICE_PREFIX = "dubbo.protocol.triple.rest.mcp.service"; String SETTINGS_MCP_SERVICE_ENABLED_SUFFIX = "enabled"; String SETTINGS_MCP_SERVICE_NAME_SUFFIX = "tool-name"; String SETTINGS_MCP_SERVICE_DESCRIPTION_SUFFIX = "description"; String SETTINGS_MCP_SERVICE_TAGS_SUFFIX = "tags"; String MCP_SERVICE_PROTOCOL = "tri"; int MCP_SERVICE_PORT = 8081; String DEFAULT_TOOL_NAME_PREFIX = "arg"; String DEFAULT_TOOL_DESCRIPTION_TEMPLATE = "Execute method '%s' from service '%s'"; String DEFAULT_PARAMETER_DESCRIPTION_TEMPLATE = "Parameter %d of type %s"; String SCHEMA_PROPERTY_TYPE = "type"; String SCHEMA_PROPERTY_DESCRIPTION = "description"; String SCHEMA_PROPERTY_PROPERTIES = "properties"; // Common JSON Schema property names String SCHEMA_PROPERTY_FORMAT = "format"; String SCHEMA_PROPERTY_ENUM = "enum"; String SCHEMA_PROPERTY_DEFAULT = "default"; String SCHEMA_PROPERTY_REF = "$ref"; String SCHEMA_PROPERTY_ITEMS = "items"; String SCHEMA_PROPERTY_ADDITIONAL_PROPERTIES = "additionalProperties"; String SCHEMA_PROPERTY_REQUIRED = "required"; // Specific parameter names String PARAM_TRIPLE_SERVICE_GROUP = "tri-service-group"; String PARAM_REQUEST_BODY_PAYLOAD = "requestBodyPayload"; // URL parameter names for MCP configuration String PARAM_MCP_ENABLED = "mcp.enabled"; String PARAM_MCP_TOOL_NAME = "mcp.tool-name"; String PARAM_MCP_DESCRIPTION = "mcp.description"; String PARAM_MCP_TAGS = "mcp.tags"; String PARAM_MCP_PRIORITY = "mcp.priority"; // Default parameter descriptions String PARAM_DESCRIPTION_DOUBLE = "A numeric value of type Double"; String PARAM_DESCRIPTION_INTEGER = "An integer value"; String PARAM_DESCRIPTION_STRING = "A string value"; String PARAM_DESCRIPTION_BOOLEAN = "A boolean value"; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/JsonSchemaType.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/JsonSchemaType.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.mcp; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public enum JsonSchemaType { BOOLEAN(boolean.class, "boolean", null), BOOLEAN_OBJ(Boolean.class, "boolean", null), BYTE(byte.class, "integer", null), BYTE_OBJ(Byte.class, "integer", null), SHORT(short.class, "integer", null), SHORT_OBJ(Short.class, "integer", null), INT(int.class, "integer", null), INTEGER_OBJ(Integer.class, "integer", null), LONG(long.class, "integer", "int64"), LONG_OBJ(Long.class, "integer", "int64"), BIG_INTEGER(BigInteger.class, "integer", "int64"), FLOAT(float.class, "number", "float"), FLOAT_OBJ(Float.class, "number", "float"), DOUBLE(double.class, "number", "double"), DOUBLE_OBJ(Double.class, "number", "double"), BIG_DECIMAL(BigDecimal.class, "number", null), // BigDecimal often without specific format CHAR(char.class, "string", null), CHARACTER_OBJ(Character.class, "string", null), STRING(String.class, "string", null), CHAR_SEQUENCE(CharSequence.class, "string", null), STRING_BUFFER(StringBuffer.class, "string", null), STRING_BUILDER(StringBuilder.class, "string", null), BYTE_ARRAY(byte[].class, "string", "byte"), // Generic JSON Schema Types OBJECT_SCHEMA(null, "object", null), ARRAY_SCHEMA(null, "array", null), STRING_SCHEMA(null, "string", null), NUMBER_SCHEMA(null, "number", null), INTEGER_SCHEMA(null, "integer", null), BOOLEAN_SCHEMA(null, "boolean", null), // Date/Time Formats DATE_FORMAT(null, null, "date"), TIME_FORMAT(null, null, "time"), DATE_TIME_FORMAT(null, null, "date-time"); private final Class<?> javaType; private final String jsonSchemaType; private final String jsonSchemaFormat; private static final Map<Class<?>, JsonSchemaType> javaTypeLookup = new HashMap<>(); static { for (JsonSchemaType mapping : values()) { javaTypeLookup.put(mapping.javaType, mapping); } } JsonSchemaType(Class<?> javaType, String jsonSchemaType, String jsonSchemaFormat) { this.javaType = javaType; this.jsonSchemaType = jsonSchemaType; this.jsonSchemaFormat = jsonSchemaFormat; } public Class<?> getJavaType() { return javaType; } public String getJsonSchemaType() { return jsonSchemaType; } public String getJsonSchemaFormat() { return jsonSchemaFormat; } public static JsonSchemaType fromJavaType(Class<?> type) { return javaTypeLookup.get(type); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/util/TypeSchemaUtils.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/util/TypeSchemaUtils.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.mcp.util; import org.apache.dubbo.mcp.JsonSchemaType; import org.apache.dubbo.mcp.McpConstant; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public final class TypeSchemaUtils { public static TypeSchemaInfo resolveTypeSchema(Class<?> javaType, Type genericType, String description) { TypeSchemaInfo.Builder builder = TypeSchemaInfo.builder().description(description).javaType(javaType.getName()); if (isPrimitiveType(javaType)) { return builder.type(getPrimitiveJsonSchemaType(javaType)) .format(getFormatForType(javaType)) .build(); } if (javaType.isArray()) { TypeSchemaInfo itemSchema = resolveTypeSchema(javaType.getComponentType(), javaType.getComponentType(), "Array item"); return builder.type(JsonSchemaType.ARRAY_SCHEMA.getJsonSchemaType()) .items(itemSchema) .build(); } if (genericType instanceof ParameterizedType) { return resolveParameterizedType((ParameterizedType) genericType, javaType, description, builder); } if (java.util.Collection.class.isAssignableFrom(javaType)) { return builder.type(JsonSchemaType.ARRAY_SCHEMA.getJsonSchemaType()) .items(TypeSchemaInfo.builder() .type(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType()) .description("Collection item") .build()) .build(); } if (java.util.Map.class.isAssignableFrom(javaType)) { return builder.type(JsonSchemaType.OBJECT_SCHEMA.getJsonSchemaType()) .additionalProperties(TypeSchemaInfo.builder() .type(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType()) .description("Map value") .build()) .build(); } if (javaType.isEnum()) { Object[] enumConstants = javaType.getEnumConstants(); List<String> enumValues = new ArrayList<>(); if (enumConstants != null) { for (Object enumConstant : enumConstants) { enumValues.add(enumConstant.toString()); } } return builder.type(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType()) .enumValues(enumValues) .build(); } if (isDateTimeType(javaType)) { return builder.type(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType()) .format(getDateTimeFormat(javaType)) .build(); } return builder.type(JsonSchemaType.OBJECT_SCHEMA.getJsonSchemaType()) .description( description != null ? description + " (POJO type: " + javaType.getSimpleName() + ")" : "Complex object of type " + javaType.getSimpleName()) .build(); } private static TypeSchemaInfo resolveParameterizedType( ParameterizedType paramType, Class<?> rawType, String description, TypeSchemaInfo.Builder builder) { Type[] typeArgs = paramType.getActualTypeArguments(); if (java.util.Collection.class.isAssignableFrom(rawType)) { TypeSchemaInfo itemSchema; if (typeArgs.length > 0) { Class<?> itemType = getClassFromType(typeArgs[0]); itemSchema = resolveTypeSchema(itemType, typeArgs[0], "Collection item"); } else { itemSchema = TypeSchemaInfo.builder() .type(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType()) .description("Collection item") .build(); } return builder.type(JsonSchemaType.ARRAY_SCHEMA.getJsonSchemaType()) .items(itemSchema) .build(); } if (java.util.Map.class.isAssignableFrom(rawType)) { TypeSchemaInfo valueSchema; if (typeArgs.length > 1) { Class<?> valueType = getClassFromType(typeArgs[1]); valueSchema = resolveTypeSchema(valueType, typeArgs[1], "Map value"); } else { valueSchema = TypeSchemaInfo.builder() .type(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType()) .description("Map value") .build(); } return builder.type(JsonSchemaType.OBJECT_SCHEMA.getJsonSchemaType()) .additionalProperties(valueSchema) .build(); } return builder.type(JsonSchemaType.OBJECT_SCHEMA.getJsonSchemaType()) .description( description != null ? description + " (Generic type: " + rawType.getSimpleName() + ")" : "Complex generic object of type " + rawType.getSimpleName()) .build(); } public static Map<String, Object> toSchemaMap(TypeSchemaInfo schemaInfo) { Map<String, Object> schemaMap = new HashMap<>(); schemaMap.put(McpConstant.SCHEMA_PROPERTY_TYPE, schemaInfo.getType()); if (schemaInfo.getFormat() != null) { schemaMap.put(McpConstant.SCHEMA_PROPERTY_FORMAT, schemaInfo.getFormat()); } if (schemaInfo.getDescription() != null) { schemaMap.put(McpConstant.SCHEMA_PROPERTY_DESCRIPTION, schemaInfo.getDescription()); } if (schemaInfo.getEnumValues() != null && !schemaInfo.getEnumValues().isEmpty()) { schemaMap.put(McpConstant.SCHEMA_PROPERTY_ENUM, schemaInfo.getEnumValues()); } if (schemaInfo.getItems() != null) { schemaMap.put(McpConstant.SCHEMA_PROPERTY_ITEMS, toSchemaMap(schemaInfo.getItems())); } if (schemaInfo.getAdditionalProperties() != null) { schemaMap.put( McpConstant.SCHEMA_PROPERTY_ADDITIONAL_PROPERTIES, toSchemaMap(schemaInfo.getAdditionalProperties())); } return schemaMap; } public static TypeSchemaInfo resolveNestedType(Type type, String description) { if (type instanceof Class) { return resolveTypeSchema((Class<?>) type, type, description); } if (type instanceof ParameterizedType paramType) { Class<?> rawType = (Class<?>) paramType.getRawType(); return resolveTypeSchema(rawType, type, description); } if (type instanceof TypeVariable) { Type[] bounds = ((TypeVariable<?>) type).getBounds(); if (bounds.length > 0) { return resolveNestedType(bounds[0], description); } } if (type instanceof WildcardType) { Type[] upperBounds = ((WildcardType) type).getUpperBounds(); if (upperBounds.length > 0) { return resolveNestedType(upperBounds[0], description); } } if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType) type).getGenericComponentType(); TypeSchemaInfo itemSchema = resolveNestedType(componentType, "Array item"); return TypeSchemaInfo.builder() .type(JsonSchemaType.ARRAY_SCHEMA.getJsonSchemaType()) .items(itemSchema) .description(description) .build(); } // Fallback to object type return TypeSchemaInfo.builder() .type(JsonSchemaType.OBJECT_SCHEMA.getJsonSchemaType()) .description(description != null ? description : "Unknown type") .build(); } public static boolean isPrimitiveType(Class<?> type) { return JsonSchemaType.fromJavaType(type) != null; } public static String getPrimitiveJsonSchemaType(Class<?> javaType) { JsonSchemaType mapping = JsonSchemaType.fromJavaType(javaType); return mapping != null ? mapping.getJsonSchemaType() : JsonSchemaType.STRING_SCHEMA.getJsonSchemaType(); } public static String getFormatForType(Class<?> javaType) { JsonSchemaType mapping = JsonSchemaType.fromJavaType(javaType); return mapping != null ? mapping.getJsonSchemaFormat() : null; } public static boolean isDateTimeType(Class<?> type) { return java.util.Date.class.isAssignableFrom(type) || java.time.temporal.Temporal.class.isAssignableFrom(type) || java.util.Calendar.class.isAssignableFrom(type); } public static String getDateTimeFormat(Class<?> type) { if (java.time.LocalDate.class.isAssignableFrom(type)) { return JsonSchemaType.DATE_FORMAT.getJsonSchemaFormat(); } if (java.time.LocalTime.class.isAssignableFrom(type) || java.time.OffsetTime.class.isAssignableFrom(type)) { return JsonSchemaType.TIME_FORMAT.getJsonSchemaFormat(); } return JsonSchemaType.DATE_TIME_FORMAT.getJsonSchemaFormat(); } public static Class<?> getClassFromType(Type type) { if (type instanceof Class) { return (Class<?>) type; } if (type instanceof ParameterizedType) { return (Class<?>) ((ParameterizedType) type).getRawType(); } if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType) type).getGenericComponentType(); Class<?> componentClass = getClassFromType(componentType); return java.lang.reflect.Array.newInstance(componentClass, 0).getClass(); } if (type instanceof TypeVariable) { Type[] bounds = ((TypeVariable<?>) type).getBounds(); if (bounds.length > 0) { return getClassFromType(bounds[0]); } } if (type instanceof WildcardType) { Type[] upperBounds = ((WildcardType) type).getUpperBounds(); if (upperBounds.length > 0) { return getClassFromType(upperBounds[0]); } } return Object.class; } public static boolean isPrimitiveOrWrapper(Class<?> type) { return isPrimitiveType(type); } public static class TypeSchemaInfo { private final String type; private final String format; private final String description; private final String javaType; private final List<String> enumValues; private final TypeSchemaInfo items; private final TypeSchemaInfo additionalProperties; private TypeSchemaInfo(Builder builder) { this.type = builder.type; this.format = builder.format; this.description = builder.description; this.javaType = builder.javaType; this.enumValues = builder.enumValues; this.items = builder.items; this.additionalProperties = builder.additionalProperties; } public static Builder builder() { return new Builder(); } public String getType() { return type; } public String getFormat() { return format; } public String getDescription() { return description; } public String getJavaType() { return javaType; } public List<String> getEnumValues() { return enumValues; } public TypeSchemaInfo getItems() { return items; } public TypeSchemaInfo getAdditionalProperties() { return additionalProperties; } public static class Builder { private String type; private String format; private String description; private String javaType; private List<String> enumValues; private TypeSchemaInfo items; private TypeSchemaInfo additionalProperties; public Builder type(String type) { this.type = type; return this; } public Builder format(String format) { this.format = format; return this; } public Builder description(String description) { this.description = description; return this; } public Builder javaType(String javaType) { this.javaType = javaType; return this; } public Builder enumValues(List<String> enumValues) { this.enumValues = enumValues; return this; } public Builder items(TypeSchemaInfo items) { this.items = items; return this; } public Builder additionalProperties(TypeSchemaInfo additionalProperties) { this.additionalProperties = additionalProperties; return this; } public TypeSchemaInfo build() { return new TypeSchemaInfo(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-mcp/src/main/java/org/apache/dubbo/mcp/annotations/McpTool.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/annotations/McpTool.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.mcp.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation to expose a Dubbo service method as an MCP tool. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface McpTool { /** * Specifies whether this method should be exposed as an MCP tool. * Default is true. */ boolean enabled() default true; /** * The unique name of the MCP tool. If not specified, the method name will be used. */ String name() default ""; /** * A description of the tool's functionality. This will be visible to AI models. * If not specified, a default description will be generated. */ String description() default ""; /** * A list of tags for categorizing the tool. */ String[] tags() default {}; /** * The priority of this tool. Higher values indicate higher priority. */ int priority() default 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-mcp/src/main/java/org/apache/dubbo/mcp/annotations/McpToolParam.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/annotations/McpToolParam.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.mcp.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER, ElementType.FIELD}) public @interface McpToolParam { /** * The name of the parameter. This will be the key in the JSON schema properties. * If not specified, the parameter name will be inferred from the method signature * or a default name like "arg0", "arg1", etc. */ String name() default ""; /** * A description of the parameter. This will be used in the JSON schema for clarity. * If not specified, a default description will be generated. */ String description() default ""; /** * Specifies whether the parameter is required. */ boolean required() default 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-mcp/src/main/java/org/apache/dubbo/mcp/core/McpStreamableServiceImpl.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/core/McpStreamableServiceImpl.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.mcp.core; import org.apache.dubbo.common.resource.Disposable; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.mcp.transport.DubboMcpStreamableTransportProvider; import org.apache.dubbo.remoting.http12.message.ServerSentEvent; public class McpStreamableServiceImpl implements McpStreamableService, Disposable { private volatile DubboMcpStreamableTransportProvider transportProvider = null; @Override public void streamable(StreamObserver<ServerSentEvent<byte[]>> responseObserver) { if (transportProvider == null) { synchronized (this) { if (transportProvider == null) { transportProvider = getTransportProvider(); } } } transportProvider.handleRequest(responseObserver); } public DubboMcpStreamableTransportProvider getTransportProvider() { return McpApplicationDeployListener.getDubboMcpStreamableTransportProvider(); } @Override public void destroy() {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/core/McpServiceExportListener.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/core/McpServiceExportListener.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.mcp.core; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.ServiceListener; import org.apache.dubbo.mcp.tool.DubboServiceToolRegistry; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ProviderModel; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class McpServiceExportListener implements ServiceListener { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(McpServiceExportListener.class); private final Map<String, RegisteredServiceInfo> registeredServiceTools = new ConcurrentHashMap<>(); private static class RegisteredServiceInfo { final int toolCount; final String interfaceName; final ProviderModel providerModel; RegisteredServiceInfo(int toolCount, String interfaceName, ProviderModel providerModel) { this.toolCount = toolCount; this.interfaceName = interfaceName; this.providerModel = providerModel; } } @Override public void exported(ServiceConfig sc) { try { if (sc.getRef() == null) { return; } String serviceKey = sc.getUniqueServiceName(); ProviderModel providerModel = sc.getScopeModel().getServiceRepository().lookupExportedService(serviceKey); if (providerModel == null) { logger.warn( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "ProviderModel not found for service: " + sc.getInterface() + " with key: " + serviceKey); return; } DubboServiceToolRegistry toolRegistry = getToolRegistry(sc); if (toolRegistry == null) { return; } int registeredCount = toolRegistry.registerService(providerModel); if (registeredCount > 0) { registeredServiceTools.put( serviceKey, new RegisteredServiceInfo( registeredCount, providerModel.getServiceModel().getInterfaceName(), providerModel)); logger.info( "Dynamically registered {} MCP tools for exported service: {}", registeredCount, providerModel.getServiceModel().getInterfaceName()); } } catch (Exception e) { logger.error( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to register MCP tools for exported service: " + sc.getInterface(), e); } } @Override public void unexported(ServiceConfig sc) { try { if (sc.getRef() == null) { return; } String serviceKey = sc.getUniqueServiceName(); RegisteredServiceInfo serviceInfo = registeredServiceTools.remove(serviceKey); if (serviceInfo != null && serviceInfo.toolCount > 0) { DubboServiceToolRegistry toolRegistry = getToolRegistry(sc); if (toolRegistry == null) { return; } toolRegistry.unregisterService(serviceInfo.providerModel); logger.info( "Dynamically unregistered {} MCP tools for unexported service: {}", serviceInfo.toolCount, serviceInfo.interfaceName); } } catch (Exception e) { logger.error( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to unregister MCP tools for unexported service: " + sc.getInterface(), e); } } private DubboServiceToolRegistry getToolRegistry(ServiceConfig sc) { try { ApplicationModel applicationModel = sc.getScopeModel().getApplicationModel(); return applicationModel.getBeanFactory().getBean(DubboServiceToolRegistry.class); } catch (Exception e) { logger.warn( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to get DubboServiceToolRegistry from application context", e); 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-mcp/src/main/java/org/apache/dubbo/mcp/core/McpSseServiceImpl.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/core/McpSseServiceImpl.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.mcp.core; import org.apache.dubbo.common.resource.Disposable; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.mcp.transport.DubboMcpSseTransportProvider; import org.apache.dubbo.remoting.http12.message.ServerSentEvent; public class McpSseServiceImpl implements McpSseService, Disposable { private volatile DubboMcpSseTransportProvider transportProvider = null; @Override public void get(StreamObserver<ServerSentEvent<String>> responseObserver) { if (transportProvider == null) { synchronized (this) { if (transportProvider == null) { transportProvider = getTransportProvider(); } } } transportProvider.handleRequest(responseObserver); } @Override public void post() { if (transportProvider == null) { synchronized (this) { if (transportProvider == null) { transportProvider = getTransportProvider(); } } } transportProvider.handleRequest(null); } private DubboMcpSseTransportProvider getTransportProvider() { return McpApplicationDeployListener.getDubboMcpSseTransportProvider(); } @Override public void destroy() {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/core/McpSseService.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/core/McpSseService.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.mcp.core; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.remoting.http12.HttpMethods; import org.apache.dubbo.remoting.http12.message.ServerSentEvent; import org.apache.dubbo.remoting.http12.rest.Mapping; import static org.apache.dubbo.mcp.McpConstant.SETTINGS_MCP_PATHS_MESSAGE; import static org.apache.dubbo.mcp.McpConstant.SETTINGS_MCP_PATHS_SSE; @Mapping("") public interface McpSseService { @Mapping(value = "//${" + SETTINGS_MCP_PATHS_SSE + ":/mcp/sse}", method = HttpMethods.GET) void get(StreamObserver<ServerSentEvent<String>> responseObserver); @Mapping(value = "//${" + SETTINGS_MCP_PATHS_MESSAGE + ":/mcp/message}", method = HttpMethods.POST) void post(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/core/McpApplicationDeployListener.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/core/McpApplicationDeployListener.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.mcp.core; import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.deploy.ApplicationDeployListener; 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.CollectionUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.bootstrap.builders.InternalServiceConfigBuilder; import org.apache.dubbo.mcp.McpConstant; import org.apache.dubbo.mcp.tool.DubboMcpGenericCaller; import org.apache.dubbo.mcp.tool.DubboOpenApiToolConverter; import org.apache.dubbo.mcp.tool.DubboServiceToolRegistry; import org.apache.dubbo.mcp.transport.DubboMcpSseTransportProvider; import org.apache.dubbo.mcp.transport.DubboMcpStreamableTransportProvider; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.protocol.tri.rest.openapi.DefaultOpenAPIService; import java.util.Collection; import java.util.concurrent.ExecutorService; import com.fasterxml.jackson.databind.ObjectMapper; import io.modelcontextprotocol.server.McpAsyncServer; import io.modelcontextprotocol.server.McpServer; import io.modelcontextprotocol.spec.McpSchema; import static org.apache.dubbo.metadata.util.MetadataServiceVersionUtils.V1; public class McpApplicationDeployListener implements ApplicationDeployListener { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(McpApplicationDeployListener.class); private DubboServiceToolRegistry toolRegistry; private boolean mcpEnable = true; private volatile ServiceConfig<McpSseService> sseServiceConfig; private volatile ServiceConfig<McpStreamableService> streamableServiceConfig; private static DubboMcpSseTransportProvider dubboMcpSseTransportProvider; private static DubboMcpStreamableTransportProvider dubboMcpStreamableTransportProvider; private McpAsyncServer mcpAsyncServer; @Override public void onInitialize(ApplicationModel scopeModel) {} @Override public void onStarting(ApplicationModel applicationModel) {} public static DubboMcpSseTransportProvider getDubboMcpSseTransportProvider() { return dubboMcpSseTransportProvider; } public static DubboMcpStreamableTransportProvider getDubboMcpStreamableTransportProvider() { return dubboMcpStreamableTransportProvider; } @Override public void onStarted(ApplicationModel applicationModel) { Configuration globalConf = ConfigurationUtils.getGlobalConfiguration(applicationModel); mcpEnable = globalConf.getBoolean(McpConstant.SETTINGS_MCP_ENABLE, false); if (!mcpEnable) { logger.info("MCP service is disabled, skipping initialization"); return; } try { logger.info("Initializing MCP server and dynamic service registration"); // Initialize service filter McpServiceFilter mcpServiceFilter = new McpServiceFilter(applicationModel); String protocol = globalConf.getString(McpConstant.SETTINGS_MCP_PROTOCOL, "streamable"); McpSchema.ServerCapabilities.ToolCapabilities toolCapabilities = new McpSchema.ServerCapabilities.ToolCapabilities(true); McpSchema.ServerCapabilities serverCapabilities = new McpSchema.ServerCapabilities(null, null, null, null, null, toolCapabilities); Integer sessionTimeout = globalConf.getInt(McpConstant.SETTINGS_MCP_SESSION_TIMEOUT, McpConstant.DEFAULT_SESSION_TIMEOUT); if ("streamable".equals(protocol)) { dubboMcpStreamableTransportProvider = new DubboMcpStreamableTransportProvider(new ObjectMapper(), sessionTimeout); mcpAsyncServer = McpServer.async(getDubboMcpStreamableTransportProvider()) .capabilities(serverCapabilities) .build(); } else if ("sse".equals(protocol)) { dubboMcpSseTransportProvider = new DubboMcpSseTransportProvider(new ObjectMapper(), sessionTimeout); mcpAsyncServer = McpServer.async(getDubboMcpSseTransportProvider()) .capabilities(serverCapabilities) .build(); } else { logger.error( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "not support protocol " + protocol); } FrameworkModel frameworkModel = applicationModel.getFrameworkModel(); DefaultOpenAPIService defaultOpenAPIService = new DefaultOpenAPIService(frameworkModel); DubboOpenApiToolConverter toolConverter = new DubboOpenApiToolConverter(defaultOpenAPIService); DubboMcpGenericCaller genericCaller = new DubboMcpGenericCaller(applicationModel); toolRegistry = new DubboServiceToolRegistry(mcpAsyncServer, toolConverter, genericCaller, mcpServiceFilter); applicationModel.getBeanFactory().registerBean(toolRegistry); Collection<ProviderModel> providerModels = applicationModel.getApplicationServiceRepository().allProviderModels(); int registeredCount = 0; for (ProviderModel pm : providerModels) { int serviceRegisteredCount = toolRegistry.registerService(pm); registeredCount += serviceRegisteredCount; } if ("streamable".equals(protocol)) { exportMcpStreamableService(applicationModel); } else { exportMcpSSEService(applicationModel); } logger.info( "MCP server initialized successfully, {} existing tools registered, dynamic registration enabled", registeredCount); } catch (Exception e) { logger.error( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "MCP service initialization failed: " + e.getMessage(), e); } } @Override public void onStopping(ApplicationModel applicationModel) { if (toolRegistry != null) { logger.info("MCP server stopping, clearing tool registry"); toolRegistry.clearRegistry(); } } @Override public void onStopped(ApplicationModel applicationModel) { if (mcpEnable && mcpAsyncServer != null) { mcpAsyncServer.close(); } } @Override public void onFailure(ApplicationModel applicationModel, Throwable cause) {} private void exportMcpSSEService(ApplicationModel applicationModel) { McpSseServiceImpl mcpSseServiceImpl = applicationModel.getBeanFactory().getOrRegisterBean(McpSseServiceImpl.class); ExecutorService internalServiceExecutor = applicationModel .getFrameworkModel() .getBeanFactory() .getBean(FrameworkExecutorRepository.class) .getInternalServiceExecutor(); this.sseServiceConfig = InternalServiceConfigBuilder.<McpSseService>newBuilder(applicationModel) .interfaceClass(McpSseService.class) .protocol(CommonConstants.TRIPLE, McpConstant.MCP_SERVICE_PROTOCOL) .port(getRegisterPort(), String.valueOf(McpConstant.MCP_SERVICE_PORT)) .registryId("internal-mcp-registry") .executor(internalServiceExecutor) .ref(mcpSseServiceImpl) .version(V1) .build(); sseServiceConfig.export(); logger.info("MCP service exported on: {}", sseServiceConfig.getExportedUrls()); } private void exportMcpStreamableService(ApplicationModel applicationModel) { McpStreamableServiceImpl mcpStreamableServiceImpl = applicationModel.getBeanFactory().getOrRegisterBean(McpStreamableServiceImpl.class); ExecutorService internalServiceExecutor = applicationModel .getFrameworkModel() .getBeanFactory() .getBean(FrameworkExecutorRepository.class) .getInternalServiceExecutor(); this.streamableServiceConfig = InternalServiceConfigBuilder.<McpStreamableService>newBuilder(applicationModel) .interfaceClass(McpStreamableService.class) .protocol(CommonConstants.TRIPLE, McpConstant.MCP_SERVICE_PROTOCOL) .port(getRegisterPort(), String.valueOf(McpConstant.MCP_SERVICE_PORT)) .registryId("internal-mcp-registry") .executor(internalServiceExecutor) .ref(mcpStreamableServiceImpl) .version(V1) .build(); streamableServiceConfig.export(); logger.info("MCP service exported on: {}", streamableServiceConfig.getExportedUrls()); } /** * Get the Mcp service register port. * First, try to get config from user configuration, if not found, get from protocol config. * Second, try to get config from protocol config, if not found, get a random available port. */ private int getRegisterPort() { Configuration globalConf = ConfigurationUtils.getGlobalConfiguration(ApplicationModel.defaultModel()); int mcpPort = globalConf.getInt(McpConstant.SETTINGS_MCP_PORT, -1); if (mcpPort != -1) { return mcpPort; } ApplicationModel applicationModel = ApplicationModel.defaultModel(); Collection<ProtocolConfig> protocolConfigs = applicationModel.getApplicationConfigManager().getProtocols(); if (CollectionUtils.isNotEmpty(protocolConfigs)) { for (ProtocolConfig protocolConfig : protocolConfigs) { if (CommonConstants.TRIPLE.equals(protocolConfig.getName())) { return protocolConfig.getPort(); } } } return NetUtils.getAvailablePort(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/core/McpStreamableService.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/core/McpStreamableService.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.mcp.core; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.remoting.http12.message.ServerSentEvent; import org.apache.dubbo.remoting.http12.rest.Mapping; import static org.apache.dubbo.mcp.McpConstant.SETTINGS_MCP_PATHS_MESSAGE; @Mapping("") public interface McpStreamableService { @Mapping(value = "//${" + SETTINGS_MCP_PATHS_MESSAGE + ":/mcp/streamable/message}") void streamable(StreamObserver<ServerSentEvent<byte[]>> responseObserver); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/core/McpServiceFilter.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/core/McpServiceFilter.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.mcp.core; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.mcp.McpConstant; import org.apache.dubbo.mcp.annotations.McpTool; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ProviderModel; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; public class McpServiceFilter { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(McpServiceFilter.class); private final Configuration configuration; private final Pattern[] includePatterns; private final Pattern[] excludePatterns; private final boolean defaultEnabled; public McpServiceFilter(ApplicationModel applicationModel) { this.configuration = ConfigurationUtils.getGlobalConfiguration(applicationModel); this.defaultEnabled = configuration.getBoolean(McpConstant.SETTINGS_MCP_DEFAULT_ENABLED, true); String includeStr = configuration.getString(McpConstant.SETTINGS_MCP_INCLUDE_PATTERNS, ""); String excludeStr = configuration.getString(McpConstant.SETTINGS_MCP_EXCLUDE_PATTERNS, ""); this.includePatterns = parsePatterns(includeStr); this.excludePatterns = parsePatterns(excludeStr); } /** * Check if service should be exposed as MCP tool. * Priority: URL Parameters > Annotations > Configuration File > Default */ public boolean shouldExposeAsMcpTool(ProviderModel providerModel) { String interfaceName = providerModel.getServiceModel().getInterfaceName(); if (isMatchedByPatterns(interfaceName, excludePatterns)) { return false; } URL serviceUrl = getServiceUrl(providerModel); if (serviceUrl != null) { String urlValue = serviceUrl.getParameter(McpConstant.PARAM_MCP_ENABLED); if (urlValue != null && StringUtils.isNotEmpty(urlValue)) { return Boolean.parseBoolean(urlValue); } } Object serviceBean = providerModel.getServiceInstance(); if (serviceBean != null) { DubboService dubboService = serviceBean.getClass().getAnnotation(DubboService.class); if (dubboService != null && dubboService.mcpEnabled()) { return true; } } String serviceSpecificKey = McpConstant.SETTINGS_MCP_SERVICE_PREFIX + "." + interfaceName + ".enabled"; if (configuration.containsKey(serviceSpecificKey)) { return configuration.getBoolean(serviceSpecificKey, false); } if (configuration.containsKey(McpConstant.PARAM_MCP_ENABLED)) { return configuration.getBoolean(McpConstant.PARAM_MCP_ENABLED, false); } if (includePatterns.length > 0) { return isMatchedByPatterns(interfaceName, includePatterns); } return defaultEnabled; } /** * Check if specific method should be exposed as MCP tool. * Priority: @McpTool(enabled=false) > URL Parameters > @McpTool(enabled=true) > Configuration > Service-level */ public boolean shouldExposeMethodAsMcpTool(ProviderModel providerModel, Method method) { String interfaceName = providerModel.getServiceModel().getInterfaceName(); String methodName = method.getName(); if (isMatchedByPatterns(interfaceName, excludePatterns)) { return false; } McpTool methodMcpTool = getMethodMcpTool(providerModel, method); if (methodMcpTool != null && !methodMcpTool.enabled()) { return false; } URL serviceUrl = getServiceUrl(providerModel); if (serviceUrl != null) { String methodUrlValue = serviceUrl.getMethodParameter(methodName, McpConstant.PARAM_MCP_ENABLED); if (methodUrlValue != null && StringUtils.isNotEmpty(methodUrlValue)) { return Boolean.parseBoolean(methodUrlValue); } String serviceLevelValue = serviceUrl.getParameter(McpConstant.PARAM_MCP_ENABLED); if (serviceLevelValue != null && StringUtils.isNotEmpty(serviceLevelValue)) { return Boolean.parseBoolean(serviceLevelValue); } } if (methodMcpTool != null && methodMcpTool.enabled()) { return true; } String methodConfigKey = McpConstant.SETTINGS_MCP_SERVICE_PREFIX + "." + interfaceName + ".methods." + methodName + ".enabled"; if (configuration.containsKey(methodConfigKey)) { return configuration.getBoolean(methodConfigKey, false); } if (shouldExposeAsMcpTool(providerModel)) { return Modifier.isPublic(method.getModifiers()); } return false; } /** * Get @McpTool annotation from method, checking both interface and implementation class. */ private McpTool getMethodMcpTool(ProviderModel providerModel, Method method) { String methodName = method.getName(); Class<?>[] paramTypes = method.getParameterTypes(); Object serviceBean = providerModel.getServiceInstance(); if (serviceBean != null) { try { Method implMethod = serviceBean.getClass().getMethod(methodName, paramTypes); McpTool implMcpTool = implMethod.getAnnotation(McpTool.class); if (implMcpTool != null) { return implMcpTool; } } catch (NoSuchMethodException e) { // Method not found in implementation class logger.error( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Method not found in implementation class: " + methodName + " with parameters: " + Arrays.toString(paramTypes), e); } } McpTool interfaceMcpTool = method.getAnnotation(McpTool.class); if (interfaceMcpTool != null) { return interfaceMcpTool; } Class<?> serviceInterface = providerModel.getServiceModel().getServiceInterfaceClass(); if (serviceInterface != null) { try { Method interfaceMethod = serviceInterface.getMethod(methodName, paramTypes); return interfaceMethod.getAnnotation(McpTool.class); } catch (NoSuchMethodException e) { // Method not found in service interface } } return null; } public McpToolConfig getMcpToolConfig(ProviderModel providerModel, Method method) { String interfaceName = providerModel.getServiceModel().getInterfaceName(); McpToolConfig config = new McpToolConfig(); config.setToolName(method.getName()); McpTool mcpTool = getMethodMcpTool(providerModel, method); if (mcpTool != null) { if (StringUtils.isNotEmpty(mcpTool.name())) { config.setToolName(mcpTool.name()); } if (StringUtils.isNotEmpty(mcpTool.description())) { config.setDescription(mcpTool.description()); } if (mcpTool.tags().length > 0) { config.setTags(Arrays.asList(mcpTool.tags())); } config.setPriority(mcpTool.priority()); } String methodPrefix = McpConstant.SETTINGS_MCP_SERVICE_PREFIX + "." + interfaceName + ".methods." + method.getName() + "."; String configToolName = configuration.getString(methodPrefix + "name"); if (StringUtils.isNotEmpty(configToolName)) { config.setToolName(configToolName); } String configDescription = configuration.getString(methodPrefix + "description"); if (StringUtils.isNotEmpty(configDescription)) { config.setDescription(configDescription); } String configTags = configuration.getString(methodPrefix + "tags"); if (StringUtils.isNotEmpty(configTags)) { config.setTags(Arrays.asList(configTags.split(","))); } URL serviceUrl = getServiceUrl(providerModel); if (serviceUrl != null) { String urlToolName = serviceUrl.getMethodParameter(method.getName(), McpConstant.PARAM_MCP_TOOL_NAME); if (urlToolName != null && StringUtils.isNotEmpty(urlToolName)) { config.setToolName(urlToolName); } String urlDescription = serviceUrl.getMethodParameter(method.getName(), McpConstant.PARAM_MCP_DESCRIPTION); if (urlDescription != null && StringUtils.isNotEmpty(urlDescription)) { config.setDescription(urlDescription); } String urlTags = serviceUrl.getMethodParameter(method.getName(), McpConstant.PARAM_MCP_TAGS); if (urlTags != null && StringUtils.isNotEmpty(urlTags)) { config.setTags(Arrays.asList(urlTags.split(","))); } String urlPriority = serviceUrl.getMethodParameter(method.getName(), McpConstant.PARAM_MCP_PRIORITY); if (urlPriority != null && StringUtils.isNotEmpty(urlPriority)) { try { config.setPriority(Integer.parseInt(urlPriority)); } catch (NumberFormatException e) { logger.warn( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Invalid URL priority value: " + urlPriority + " for method: " + method.getName()); } } } return config; } public McpToolConfig getMcpToolConfig(ProviderModel providerModel) { String interfaceName = providerModel.getServiceModel().getInterfaceName(); McpToolConfig config = new McpToolConfig(); String servicePrefix = McpConstant.SETTINGS_MCP_SERVICE_PREFIX + "." + interfaceName + "."; String configToolName = configuration.getString(servicePrefix + "name"); if (StringUtils.isNotEmpty(configToolName)) { config.setToolName(configToolName); } String configDescription = configuration.getString(servicePrefix + "description"); if (StringUtils.isNotEmpty(configDescription)) { config.setDescription(configDescription); } String configTags = configuration.getString(servicePrefix + "tags"); if (StringUtils.isNotEmpty(configTags)) { config.setTags(Arrays.asList(configTags.split(","))); } URL serviceUrl = getServiceUrl(providerModel); if (serviceUrl != null) { String urlToolName = serviceUrl.getParameter(McpConstant.PARAM_MCP_TOOL_NAME); if (urlToolName != null && StringUtils.isNotEmpty(urlToolName)) { config.setToolName(urlToolName); } String urlDescription = serviceUrl.getParameter(McpConstant.PARAM_MCP_DESCRIPTION); if (urlDescription != null && StringUtils.isNotEmpty(urlDescription)) { config.setDescription(urlDescription); } String urlTags = serviceUrl.getParameter(McpConstant.PARAM_MCP_TAGS); if (urlTags != null && StringUtils.isNotEmpty(urlTags)) { config.setTags(Arrays.asList(urlTags.split(","))); } String urlPriority = serviceUrl.getParameter(McpConstant.PARAM_MCP_PRIORITY); if (urlPriority != null && StringUtils.isNotEmpty(urlPriority)) { try { config.setPriority(Integer.parseInt(urlPriority)); } catch (NumberFormatException e) { logger.warn( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Invalid URL priority value: " + urlPriority + " for service: " + interfaceName); } } } return config; } private URL getServiceUrl(ProviderModel providerModel) { List<URL> serviceUrls = providerModel.getServiceUrls(); if (serviceUrls != null && !serviceUrls.isEmpty()) { return serviceUrls.get(0); } return null; } private Pattern[] parsePatterns(String patternStr) { if (StringUtils.isEmpty(patternStr)) { return new Pattern[0]; } return Arrays.stream(patternStr.split(",")) .map(String::trim) .filter(StringUtils::isNotEmpty) .map(pattern -> Pattern.compile(pattern.replace("*", ".*"))) .toArray(Pattern[]::new); } private boolean isMatchedByPatterns(String text, Pattern[] patterns) { for (Pattern pattern : patterns) { if (pattern.matcher(text).matches()) { return true; } } return false; } public static class McpToolConfig { private String toolName; private String description; private List<String> tags; private int priority = 0; public String getToolName() { return toolName; } public void setToolName(String toolName) { this.toolName = toolName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<String> getTags() { return tags; } public void setTags(List<String> tags) { this.tags = tags; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/transport/DubboMcpSseTransportProvider.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/transport/DubboMcpSseTransportProvider.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.mcp.transport; import org.apache.dubbo.cache.support.expiring.ExpiringMap; import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.common.utils.IOUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.mcp.McpConstant; import org.apache.dubbo.remoting.http12.HttpMethods; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.HttpResult; import org.apache.dubbo.remoting.http12.HttpStatus; import org.apache.dubbo.remoting.http12.message.ServerSentEvent; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.model.ApplicationModel; import java.io.IOException; import java.nio.charset.StandardCharsets; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.modelcontextprotocol.spec.McpError; import io.modelcontextprotocol.spec.McpSchema; import io.modelcontextprotocol.spec.McpServerSession; import io.modelcontextprotocol.spec.McpServerTransport; import io.modelcontextprotocol.spec.McpServerTransportProvider; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; public class DubboMcpSseTransportProvider implements McpServerTransportProvider { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboMcpSseTransportProvider.class); /** * Event type for JSON-RPC messages sent through the SSE connection. */ public static final String MESSAGE_EVENT_TYPE = "message"; /** * Event type for sending the message endpoint URI to clients. */ public static final String ENDPOINT_EVENT_TYPE = "endpoint"; private McpServerSession.Factory sessionFactory; private final ObjectMapper objectMapper; /** * session cache, default expire time is 60 seconds */ private final ExpiringMap<String, McpServerSession> sessions; public DubboMcpSseTransportProvider(ObjectMapper objectMapper, Integer expireSeconds) { if (expireSeconds != null) { if (expireSeconds < 60) { expireSeconds = 60; } } else { expireSeconds = 60; } sessions = new ExpiringMap<>(expireSeconds, 30); this.objectMapper = objectMapper; sessions.getExpireThread().startExpiryIfNotStarted(); } public DubboMcpSseTransportProvider(ObjectMapper objectMapper) { this(objectMapper, 60); } @Override public void setSessionFactory(McpServerSession.Factory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public Mono<Void> notifyClients(String method, Object params) { if (sessions.isEmpty()) { return Mono.empty(); } return Flux.fromIterable(sessions.values()) .flatMap(session -> session.sendNotification(method, params) .doOnError(e -> logger.error( COMMON_UNEXPECTED_EXCEPTION, "", "", String.format( "Failed to send message to session %s: %s", session.getId(), e.getMessage()), e)) .onErrorComplete()) .then(); } @Override public Mono<Void> closeGracefully() { return Flux.fromIterable(sessions.values()) .flatMap(McpServerSession::closeGracefully) .then(); } public void handleRequest(StreamObserver<ServerSentEvent<String>> responseObserver) { // Handle the request and return the response HttpRequest request = RpcContext.getServiceContext().getRequest(HttpRequest.class); if (HttpMethods.isGet(request.method())) { handleSseConnection(responseObserver); } else if (HttpMethods.isPost(request.method())) { handleMessage(); } } public void handleMessage() { HttpRequest request = RpcContext.getServiceContext().getRequest(HttpRequest.class); String sessionId = request.parameter("sessionId"); HttpResponse response = RpcContext.getServiceContext().getResponse(HttpResponse.class); if (StringUtils.isBlank(sessionId)) { throw HttpResult.of(HttpStatus.BAD_REQUEST, new McpError("Session ID missing in message endpoint")) .toPayload(); } McpServerSession session = sessions.get(sessionId); if (session == null) { throw HttpResult.of(HttpStatus.NOT_FOUND, "Unknown sessionId: " + sessionId) .toPayload(); } refreshSessionExpire(session); try { McpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage( objectMapper, IOUtils.read(request.inputStream(), String.valueOf(StandardCharsets.UTF_8))); session.handle(message).block(); response.setStatus(HttpStatus.OK.getCode()); } catch (IOException e) { throw HttpResult.of(HttpStatus.INTERNAL_SERVER_ERROR, new McpError("Invalid message format")) .toPayload(); } } private void handleSseConnection(StreamObserver<ServerSentEvent<String>> responseObserver) { // Handle the SSE connection // This is where you would set up the SSE stream and send events to the client DubboMcpSessionTransport dubboMcpSessionTransport = new DubboMcpSessionTransport(responseObserver, objectMapper); McpServerSession mcpServerSession = sessionFactory.create(dubboMcpSessionTransport); sessions.put(mcpServerSession.getId(), mcpServerSession); Configuration conf = ConfigurationUtils.getGlobalConfiguration(ApplicationModel.defaultModel()); String messagePath = conf.getString(McpConstant.SETTINGS_MCP_PATHS_MESSAGE, "/mcp/message"); sendEvent(responseObserver, ENDPOINT_EVENT_TYPE, messagePath + "?sessionId=" + mcpServerSession.getId()); } private void refreshSessionExpire(McpServerSession session) { sessions.put(session.getId(), session); } private void sendEvent(StreamObserver<ServerSentEvent<String>> responseObserver, String eventType, String data) { responseObserver.onNext( ServerSentEvent.<String>builder().event(eventType).data(data).build()); } private static class DubboMcpSessionTransport implements McpServerTransport { private final ObjectMapper JSON; private final StreamObserver<ServerSentEvent<String>> responseObserver; public DubboMcpSessionTransport( StreamObserver<ServerSentEvent<String>> responseObserver, ObjectMapper objectMapper) { this.responseObserver = responseObserver; this.JSON = objectMapper; } @Override public void close() { responseObserver.onCompleted(); } @Override public Mono<Void> closeGracefully() { return Mono.fromRunnable(responseObserver::onCompleted); } @Override public Mono<Void> sendMessage(McpSchema.JSONRPCMessage message) { return Mono.fromRunnable(() -> { try { String jsonText = JSON.writeValueAsString(message); responseObserver.onNext(ServerSentEvent.<String>builder() .event(MESSAGE_EVENT_TYPE) .data(jsonText) .build()); } catch (Exception e) { responseObserver.onError(e); } }); } @Override public <T> T unmarshalFrom(Object data, TypeReference<T> typeRef) { return JSON.convertValue(data, typeRef); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/transport/DubboMcpStreamableTransportProvider.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/transport/DubboMcpStreamableTransportProvider.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.mcp.transport; import org.apache.dubbo.cache.support.expiring.ExpiringMap; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.IOUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.mcp.McpConstant; import org.apache.dubbo.remoting.http12.HttpMethods; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.HttpResult; import org.apache.dubbo.remoting.http12.HttpStatus; import org.apache.dubbo.remoting.http12.HttpUtils; import org.apache.dubbo.remoting.http12.message.MediaType; import org.apache.dubbo.remoting.http12.message.ServerSentEvent; import org.apache.dubbo.rpc.RpcContext; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.modelcontextprotocol.spec.McpError; import io.modelcontextprotocol.spec.McpSchema; import io.modelcontextprotocol.spec.McpStreamableServerSession; import io.modelcontextprotocol.spec.McpStreamableServerSession.Factory; import io.modelcontextprotocol.spec.McpStreamableServerTransport; import io.modelcontextprotocol.spec.McpStreamableServerTransportProvider; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * Implementation of {@link McpStreamableServerTransportProvider} for the Dubbo MCP transport. * This class provides methods to manage streamable server sessions and notify clients. */ public class DubboMcpStreamableTransportProvider implements McpStreamableServerTransportProvider { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboMcpStreamableTransportProvider.class); private Factory sessionFactory; private final ObjectMapper objectMapper; public static final String SESSION_ID_HEADER = "mcp-session-id"; private static final String LAST_EVENT_ID_HEADER = "Last-Event-ID"; /** * TODO: This design is suboptimal. A mechanism should be implemented to remove the session object upon connection closure or timeout. */ private final ExpiringMap<String, McpStreamableServerSession> sessions; public DubboMcpStreamableTransportProvider(ObjectMapper objectMapper) { this(objectMapper, McpConstant.DEFAULT_SESSION_TIMEOUT); } public DubboMcpStreamableTransportProvider(ObjectMapper objectMapper, Integer expireSeconds) { // Minimum expiration time is 60 seconds if (expireSeconds != null) { if (expireSeconds < 60) { expireSeconds = 60; } } else { expireSeconds = 60; } sessions = new ExpiringMap<>(expireSeconds, 30); this.objectMapper = objectMapper; sessions.getExpireThread().startExpiryIfNotStarted(); } @Override public void setSessionFactory(Factory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public Mono<Void> notifyClients(String method, Object params) { if (sessions.isEmpty()) { return Mono.empty(); } return Flux.fromIterable(sessions.values()) .flatMap(session -> session.sendNotification(method, params) .doOnError(e -> logger.error( COMMON_UNEXPECTED_EXCEPTION, "", "", String.format( "Failed to send message to session %s: %s", session.getId(), e.getMessage()), e)) .onErrorComplete()) .then(); } @Override public Mono<Void> closeGracefully() { return Flux.fromIterable(sessions.values()) .flatMap(McpStreamableServerSession::closeGracefully) .then(); } public void handleRequest(StreamObserver<ServerSentEvent<byte[]>> responseObserver) { HttpRequest request = RpcContext.getServiceContext().getRequest(HttpRequest.class); HttpResponse response = RpcContext.getServiceContext().getResponse(HttpResponse.class); if (HttpMethods.isGet(request.method())) { handleGet(responseObserver); } else if (HttpMethods.isPost(request.method())) { handlePost(responseObserver); } else if (HttpMethods.DELETE.name().equals(request.method())) { handleDelete(responseObserver); } else { // unSupport method response.setStatus(HttpStatus.METHOD_NOT_ALLOWED.getCode()); response.setBody(new McpError("Method not allowed: " + request.method()).getJsonRpcError()); if (responseObserver != null) { responseObserver.onError(HttpResult.builder() .status(HttpStatus.METHOD_NOT_ALLOWED.getCode()) .body(new McpError("Method not allowed: " + request.method()).getJsonRpcError()) .build() .toPayload()); responseObserver.onCompleted(); } } } private void handleGet(StreamObserver<ServerSentEvent<byte[]>> responseObserver) { HttpRequest request = RpcContext.getServiceContext().getRequest(HttpRequest.class); HttpResponse response = RpcContext.getServiceContext().getResponse(HttpResponse.class); List<String> badRequestErrors = new ArrayList<>(); // check Accept header List<String> accepts = HttpUtils.parseAccept(request.accept()); if (CollectionUtils.isEmpty(accepts) || (!accepts.contains(MediaType.TEXT_EVENT_STREAM.getName()) && !accepts.contains(MediaType.APPLICATION_JSON.getName()))) { badRequestErrors.add("text/event-stream or application/json required in Accept header"); } // check sessionId String sessionId = request.header(SESSION_ID_HEADER); if (StringUtils.isBlank(sessionId)) { badRequestErrors.add("Session ID required in mcp-session-id header"); } if (!badRequestErrors.isEmpty()) { String combinedMessage = String.join("; ", badRequestErrors); response.setStatus(HttpStatus.BAD_REQUEST.getCode()); response.setBody(new McpError(combinedMessage).getJsonRpcError()); if (responseObserver != null) { responseObserver.onError(HttpResult.builder() .status(HttpStatus.BAD_REQUEST.getCode()) .body(new McpError(combinedMessage).getJsonRpcError()) .build() .toPayload()); responseObserver.onCompleted(); } return; } // Find existing session McpStreamableServerSession session = sessions.get(sessionId); if (session == null) { response.setStatus(HttpStatus.NOT_FOUND.getCode()); response.setBody(new McpError("Session not found").getJsonRpcError()); if (responseObserver != null) { responseObserver.onError(HttpResult.builder() .status(HttpStatus.NOT_FOUND.getCode()) .body(new McpError("Session not found").getJsonRpcError()) .build() .toPayload()); responseObserver.onCompleted(); } return; } // Check if this is a replay request String lastEventId = request.header(LAST_EVENT_ID_HEADER); if (StringUtils.isNotBlank(lastEventId)) { // Handle replay request by calling session.replay() try { session.replay(lastEventId) .subscribe( message -> { if (responseObserver != null) { try { String jsonData = objectMapper.writeValueAsString(message); responseObserver.onNext(ServerSentEvent.<byte[]>builder() .event("message") .data(jsonData.getBytes(StandardCharsets.UTF_8)) .build()); } catch (Exception e) { logger.error( COMMON_UNEXPECTED_EXCEPTION, "", "", String.format( "Failed to serialize replay message for session %s: %s", sessionId, e.getMessage()), e); } } }, error -> { logger.error( COMMON_UNEXPECTED_EXCEPTION, "", "", String.format( "Failed to replay messages for session %s with lastEventId %s: %s", sessionId, lastEventId, error.getMessage()), error); response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.getCode()); response.setBody(new McpError("Failed to replay messages: " + error.getMessage()) .getJsonRpcError()); if (responseObserver != null) { responseObserver.onError(HttpResult.builder() .status(HttpStatus.INTERNAL_SERVER_ERROR.getCode()) .body(new McpError("Failed to replay messages: " + error.getMessage()) .getJsonRpcError()) .build() .toPayload()); responseObserver.onCompleted(); } }, () -> { if (responseObserver != null) { responseObserver.onCompleted(); } }); } catch (Exception e) { logger.error( COMMON_UNEXPECTED_EXCEPTION, "", "", String.format( "Failed to handle replay for session %s with lastEventId %s: %s", sessionId, lastEventId, e.getMessage()), e); response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.getCode()); response.setBody(new McpError("Failed to handle replay: " + e.getMessage()).getJsonRpcError()); if (responseObserver != null) { responseObserver.onError(HttpResult.builder() .status(HttpStatus.INTERNAL_SERVER_ERROR.getCode()) .body(new McpError("Failed to handle replay: " + e.getMessage()).getJsonRpcError()) .build() .toPayload()); responseObserver.onCompleted(); } } } else { // Send initial notification for new connection session.sendNotification("tools").subscribe(); } } private void handlePost(StreamObserver<ServerSentEvent<byte[]>> responseObserver) { HttpRequest request = RpcContext.getServiceContext().getRequest(HttpRequest.class); HttpResponse response = RpcContext.getServiceContext().getResponse(HttpResponse.class); List<String> badRequestErrors = new ArrayList<>(); McpStreamableServerSession session = null; try { // Check Accept header List<String> accepts = HttpUtils.parseAccept(request.accept()); if (CollectionUtils.isEmpty(accepts) || (!accepts.contains(MediaType.TEXT_EVENT_STREAM.getName()) && !accepts.contains(MediaType.APPLICATION_JSON.getName()))) { badRequestErrors.add("text/event-stream or application/json required in Accept header"); } // Read and deserialize JSON-RPC message from request body String requestBody = IOUtils.read(request.inputStream(), StandardCharsets.UTF_8.name()); McpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(objectMapper, requestBody); // Check if it's an initialization request if (message instanceof McpSchema.JSONRPCRequest && McpSchema.METHOD_INITIALIZE.equals(((McpSchema.JSONRPCRequest) message).method())) { // New initialization request if (!badRequestErrors.isEmpty()) { String combinedMessage = String.join("; ", badRequestErrors); response.setStatus(HttpStatus.BAD_REQUEST.getCode()); response.setBody(new McpError(combinedMessage).getJsonRpcError()); if (responseObserver != null) { responseObserver.onError(HttpResult.builder() .status(HttpStatus.BAD_REQUEST.getCode()) .body(new McpError(combinedMessage).getJsonRpcError()) .build() .toPayload()); responseObserver.onCompleted(); } return; } // Create new session McpSchema.InitializeRequest initializeRequest = objectMapper.convertValue( ((McpSchema.JSONRPCRequest) message).params(), new TypeReference<>() {}); McpStreamableServerSession.McpStreamableServerSessionInit init = sessionFactory.startSession(initializeRequest); session = init.session(); sessions.put(session.getId(), session); try { McpSchema.InitializeResult initResult = init.initResult().block(); response.setHeader("Content-Type", MediaType.APPLICATION_JSON.getName()); response.setHeader(SESSION_ID_HEADER, session.getId()); response.setStatus(HttpStatus.OK.getCode()); String jsonResponse = objectMapper.writeValueAsString(new McpSchema.JSONRPCResponse( McpSchema.JSONRPC_VERSION, ((McpSchema.JSONRPCRequest) message).id(), initResult, null)); if (responseObserver != null) { responseObserver.onNext(ServerSentEvent.<byte[]>builder() .event("message") .data(jsonResponse.getBytes(StandardCharsets.UTF_8)) .build()); responseObserver.onCompleted(); } return; } catch (Exception e) { response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.getCode()); response.setBody(new McpError("Failed to initialize session: " + e.getMessage()).getJsonRpcError()); if (responseObserver != null) { responseObserver.onError(HttpResult.builder() .status(HttpStatus.INTERNAL_SERVER_ERROR.getCode()) .body(new McpError("Failed to initialize session: " + e.getMessage()).getJsonRpcError()) .build() .toPayload()); responseObserver.onCompleted(); } return; } } // Non-initialization request requires sessionId String sessionId = request.header(SESSION_ID_HEADER); if (StringUtils.isBlank(sessionId)) { badRequestErrors.add("Session ID required in mcp-session-id header"); } if (!badRequestErrors.isEmpty()) { String combinedMessage = String.join("; ", badRequestErrors); response.setStatus(HttpStatus.BAD_REQUEST.getCode()); response.setBody(new McpError(combinedMessage).getJsonRpcError()); if (responseObserver != null) { responseObserver.onError(HttpResult.builder() .status(HttpStatus.BAD_REQUEST.getCode()) .body(new McpError(combinedMessage).getJsonRpcError()) .build() .toPayload()); responseObserver.onCompleted(); } return; } // Find existing session session = sessions.get(sessionId); if (session == null) { response.setStatus(HttpStatus.NOT_FOUND.getCode()); response.setBody(new McpError("Unknown sessionId: " + sessionId).getJsonRpcError()); if (responseObserver != null) { responseObserver.onError(HttpResult.builder() .status(HttpStatus.NOT_FOUND.getCode()) .body(new McpError("Unknown sessionId: " + sessionId).getJsonRpcError()) .build() .toPayload()); responseObserver.onCompleted(); } return; } // Refresh session expiration time refreshSessionExpire(session); if (message instanceof McpSchema.JSONRPCResponse) { session.accept((McpSchema.JSONRPCResponse) message).block(); response.setStatus(HttpStatus.ACCEPTED.getCode()); if (responseObserver != null) { responseObserver.onNext(ServerSentEvent.<byte[]>builder() .event("response") .data("{\"status\":\"accepted\"}".getBytes(StandardCharsets.UTF_8)) .build()); responseObserver.onCompleted(); } } else if (message instanceof McpSchema.JSONRPCNotification) { session.accept((McpSchema.JSONRPCNotification) message).block(); response.setStatus(HttpStatus.ACCEPTED.getCode()); if (responseObserver != null) { responseObserver.onNext(ServerSentEvent.<byte[]>builder() .event("response") .data("{\"status\":\"accepted\"}".getBytes(StandardCharsets.UTF_8)) .build()); responseObserver.onCompleted(); } } else if (message instanceof McpSchema.JSONRPCRequest) { // For streaming responses, we need to return SSE response.setHeader("Content-Type", MediaType.TEXT_EVENT_STREAM.getName()); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Connection", "keep-alive"); response.setHeader("Access-Control-Allow-Origin", "*"); // Handle request stream DubboMcpSessionTransport sessionTransport = new DubboMcpSessionTransport(responseObserver, objectMapper); session.responseStream((McpSchema.JSONRPCRequest) message, sessionTransport) .block(); } else { response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.getCode()); response.setBody(new McpError("Unknown message type").getJsonRpcError()); if (responseObserver != null) { responseObserver.onError(HttpResult.builder() .status(HttpStatus.INTERNAL_SERVER_ERROR.getCode()) .body(new McpError("Unknown message type").getJsonRpcError()) .build() .toPayload()); responseObserver.onCompleted(); } } } catch (IOException e) { response.setStatus(HttpStatus.BAD_REQUEST.getCode()); response.setBody(new McpError("Invalid message format: " + e.getMessage()).getJsonRpcError()); if (responseObserver != null) { responseObserver.onError(HttpResult.builder() .status(HttpStatus.BAD_REQUEST.getCode()) .body(new McpError("Invalid message format: " + e.getMessage()).getJsonRpcError()) .build() .toPayload()); responseObserver.onCompleted(); } } catch (Exception e) { response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.getCode()); response.setBody(new McpError("Internal server error: " + e.getMessage()).getJsonRpcError()); if (responseObserver != null) { responseObserver.onError(HttpResult.builder() .status(HttpStatus.INTERNAL_SERVER_ERROR.getCode()) .body(new McpError("Internal server error: " + e.getMessage()).getJsonRpcError()) .build() .toPayload()); responseObserver.onCompleted(); } } } private void handleDelete(StreamObserver<ServerSentEvent<byte[]>> responseObserver) { HttpRequest request = RpcContext.getServiceContext().getRequest(HttpRequest.class); HttpResponse response = RpcContext.getServiceContext().getResponse(HttpResponse.class); String sessionId = request.header(SESSION_ID_HEADER); if (StringUtils.isBlank(sessionId)) { response.setStatus(HttpStatus.BAD_REQUEST.getCode()); response.setBody(new McpError("Session ID required in mcp-session-id header").getJsonRpcError()); if (responseObserver != null) { responseObserver.onError(HttpResult.builder() .status(HttpStatus.BAD_REQUEST.getCode()) .body(new McpError("Session ID required in mcp-session-id header").getJsonRpcError()) .build() .toPayload()); responseObserver.onCompleted(); } return; } McpStreamableServerSession session = sessions.get(sessionId); if (session == null) { response.setStatus(HttpStatus.NOT_FOUND.getCode()); if (responseObserver != null) { responseObserver.onCompleted(); } return; } try { session.delete().block(); sessions.remove(sessionId); response.setStatus(HttpStatus.OK.getCode()); if (responseObserver != null) { responseObserver.onNext(ServerSentEvent.<byte[]>builder() .event("response") .data("{\"status\":\"deleted\"}".getBytes(StandardCharsets.UTF_8)) .build()); responseObserver.onCompleted(); } } catch (Exception e) { response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.getCode()); response.setBody(new McpError(e.getMessage()).getJsonRpcError()); if (responseObserver != null) { responseObserver.onError(HttpResult.builder() .status(HttpStatus.INTERNAL_SERVER_ERROR.getCode()) .body(new McpError(e.getMessage()).getJsonRpcError()) .build() .toPayload()); responseObserver.onCompleted(); } } } private void refreshSessionExpire(McpStreamableServerSession session) { sessions.put(session.getId(), session); } private static class DubboMcpSessionTransport implements McpStreamableServerTransport { private final ObjectMapper JSON; private final StreamObserver<ServerSentEvent<byte[]>> responseObserver; public DubboMcpSessionTransport( StreamObserver<ServerSentEvent<byte[]>> responseObserver, ObjectMapper objectMapper) { this.responseObserver = responseObserver; this.JSON = objectMapper; } @Override public void close() { if (responseObserver != null) { responseObserver.onCompleted(); } } @Override public Mono<Void> closeGracefully() { return Mono.fromRunnable(this::close); } @Override public Mono<Void> sendMessage(McpSchema.JSONRPCMessage message) { return Mono.fromRunnable(() -> { try { if (responseObserver != null) { String jsonText = JSON.writeValueAsString(message); responseObserver.onNext(ServerSentEvent.<byte[]>builder() .event("message") .data(jsonText.getBytes(StandardCharsets.UTF_8)) .build()); } } catch (Exception e) { responseObserver.onError(e); } }); } @Override public Mono<Void> sendMessage(McpSchema.JSONRPCMessage message, String messageId) { return Mono.fromRunnable(() -> { try { if (responseObserver != null) { String jsonText = JSON.writeValueAsString(message); ServerSentEvent<byte[]> event = ServerSentEvent.<byte[]>builder() .event("message") .data(jsonText.getBytes(StandardCharsets.UTF_8)) .id(messageId) .build(); responseObserver.onNext(event); } } catch (Exception e) { responseObserver.onError(e); } }); } @Override public <T> T unmarshalFrom(Object data, TypeReference<T> typeRef) { return JSON.convertValue(data, typeRef); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/tool/DubboServiceToolRegistry.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/tool/DubboServiceToolRegistry.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.mcp.tool; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.mcp.JsonSchemaType; import org.apache.dubbo.mcp.McpConstant; import org.apache.dubbo.mcp.annotations.McpToolParam; import org.apache.dubbo.mcp.core.McpServiceFilter; import org.apache.dubbo.mcp.util.TypeSchemaUtils; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ServiceMeta; import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Operation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiFunction; import com.fasterxml.jackson.databind.ObjectMapper; import io.modelcontextprotocol.server.McpAsyncServer; import io.modelcontextprotocol.server.McpAsyncServerExchange; import io.modelcontextprotocol.server.McpServerFeatures; import io.modelcontextprotocol.spec.McpSchema; import reactor.core.publisher.Mono; public class DubboServiceToolRegistry { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboServiceToolRegistry.class); private final McpAsyncServer mcpServer; private final DubboOpenApiToolConverter toolConverter; private final DubboMcpGenericCaller genericCaller; private final McpServiceFilter mcpServiceFilter; private final Map<String, McpServerFeatures.AsyncToolSpecification> registeredTools = new ConcurrentHashMap<>(); private final Map<String, Set<String>> serviceToToolsMapping = new ConcurrentHashMap<>(); private final ObjectMapper objectMapper; public DubboServiceToolRegistry( McpAsyncServer mcpServer, DubboOpenApiToolConverter toolConverter, DubboMcpGenericCaller genericCaller, McpServiceFilter mcpServiceFilter) { this.mcpServer = mcpServer; this.toolConverter = toolConverter; this.genericCaller = genericCaller; this.mcpServiceFilter = mcpServiceFilter; this.objectMapper = new ObjectMapper(); } public int registerService(ProviderModel providerModel) { ServiceDescriptor serviceDescriptor = providerModel.getServiceModel(); List<URL> statedURLs = providerModel.getServiceUrls(); if (statedURLs == null || statedURLs.isEmpty()) { return 0; } try { URL url = statedURLs.get(0); int registeredCount = 0; String serviceKey = getServiceKey(providerModel); Set<String> toolNames = new HashSet<>(); Class<?> serviceInterface = serviceDescriptor.getServiceInterfaceClass(); if (serviceInterface == null) { return 0; } Method[] methods = serviceInterface.getDeclaredMethods(); boolean shouldRegisterServiceLevel = mcpServiceFilter.shouldExposeAsMcpTool(providerModel); for (Method method : methods) { if (mcpServiceFilter.shouldExposeMethodAsMcpTool(providerModel, method)) { McpServiceFilter.McpToolConfig toolConfig = mcpServiceFilter.getMcpToolConfig(providerModel, method); String toolName = registerMethodAsTool(providerModel, method, url, toolConfig); if (toolName != null) { toolNames.add(toolName); registeredCount++; } } } if (registeredCount == 0 && shouldRegisterServiceLevel) { Set<String> serviceToolNames = registerServiceLevelTools(providerModel, url); toolNames.addAll(serviceToolNames); registeredCount = serviceToolNames.size(); } if (registeredCount > 0) { serviceToToolsMapping.put(serviceKey, toolNames); logger.info( "Registered {} MCP tools for service: {}", registeredCount, serviceDescriptor.getInterfaceName()); } return registeredCount; } catch (Exception e) { logger.error( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to register service as MCP tools: " + serviceDescriptor.getInterfaceName(), e); return 0; } } public void unregisterService(ProviderModel providerModel) { String serviceKey = getServiceKey(providerModel); Set<String> toolNames = serviceToToolsMapping.remove(serviceKey); if (toolNames == null || toolNames.isEmpty()) { return; } int unregisteredCount = 0; for (String toolName : toolNames) { try { McpServerFeatures.AsyncToolSpecification toolSpec = registeredTools.remove(toolName); if (toolSpec != null) { mcpServer.removeTool(toolName).block(); unregisteredCount++; } } catch (Exception e) { logger.error( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to unregister MCP tool: " + toolName, e); } } if (unregisteredCount > 0) { logger.info( "Unregistered {} MCP tools for service: {}", unregisteredCount, providerModel.getServiceModel().getInterfaceName()); } } private String getServiceKey(ProviderModel providerModel) { return providerModel.getServiceKey(); } private String registerMethodAsTool( ProviderModel providerModel, Method method, URL url, McpServiceFilter.McpToolConfig toolConfig) { try { String toolName = toolConfig.getToolName(); if (toolName == null || toolName.isEmpty()) { toolName = method.getName(); } if (registeredTools.containsKey(toolName)) { return null; } String description = toolConfig.getDescription(); if (description == null || description.isEmpty()) { description = generateDefaultDescription(method, providerModel); } McpSchema.Tool mcpTool = new McpSchema.Tool(toolName, description, generateToolSchema(method)); McpServerFeatures.AsyncToolSpecification toolSpec = createMethodToolSpecification(mcpTool, providerModel, method, url); mcpServer.addTool(toolSpec).block(); registeredTools.put(toolName, toolSpec); return toolName; } catch (Exception e) { logger.error( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to register method as MCP tool: " + method.getName(), e); return null; } } private Set<String> registerServiceLevelTools(ProviderModel providerModel, URL url) { ServiceDescriptor serviceDescriptor = providerModel.getServiceModel(); Set<String> toolNames = new HashSet<>(); McpServiceFilter.McpToolConfig serviceConfig = mcpServiceFilter.getMcpToolConfig(providerModel); Map<String, McpSchema.Tool> tools = toolConverter.convertToTools(serviceDescriptor, url, serviceConfig); if (tools.isEmpty()) { return toolNames; } for (Map.Entry<String, McpSchema.Tool> entry : tools.entrySet()) { McpSchema.Tool tool = entry.getValue(); String toolId = tool.name(); if (registeredTools.containsKey(toolId)) { continue; } try { Operation operation = toolConverter.getOperationByToolName(toolId); if (operation == null) { logger.error( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Could not find Operation metadata for tool: " + tool + ". Skipping registration"); continue; } McpServerFeatures.AsyncToolSpecification toolSpec = createServiceToolSpecification(tool, operation, url); mcpServer.addTool(toolSpec).block(); registeredTools.put(toolId, toolSpec); toolNames.add(toolId); } catch (Exception e) { logger.error( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to register MCP tool: " + toolId, e); } } return toolNames; } private McpServerFeatures.AsyncToolSpecification createMethodToolSpecification( McpSchema.Tool mcpTool, ProviderModel providerModel, Method method, URL url) { final String interfaceName = providerModel.getServiceModel().getInterfaceName(); final String methodName = method.getName(); final Class<?>[] parameterClasses = method.getParameterTypes(); final List<String> orderedJavaParameterNames = getStrings(method); final String group = url.getGroup(); final String version = url.getVersion(); return getAsyncToolSpecification( mcpTool, interfaceName, methodName, parameterClasses, orderedJavaParameterNames, group, version); } private McpServerFeatures.AsyncToolSpecification getAsyncToolSpecification( McpSchema.Tool mcpTool, String interfaceName, String methodName, Class<?>[] parameterClasses, List<String> orderedJavaParameterNames, String group, String version) { BiFunction<McpAsyncServerExchange, Map<String, Object>, Mono<McpSchema.CallToolResult>> callFunction = (exchange, mcpProvidedParameters) -> { try { Object result = genericCaller.execute( interfaceName, methodName, orderedJavaParameterNames, parameterClasses, mcpProvidedParameters, group, version); String resultJson = (result != null) ? result.toString() : "null"; return Mono.just(new McpSchema.CallToolResult(resultJson, true)); } catch (Exception e) { logger.error( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", String.format( "Error executing tool %s (interface: %s, method: %s): %s", mcpTool.name(), interfaceName, methodName, e.getMessage()), e); return Mono.just( new McpSchema.CallToolResult("Tool execution failed: " + e.getMessage(), false)); } }; return new McpServerFeatures.AsyncToolSpecification(mcpTool, callFunction); } private static List<String> getStrings(Method method) { final List<String> orderedJavaParameterNames = new ArrayList<>(); java.lang.reflect.Parameter[] parameters = method.getParameters(); for (int i = 0; i < parameters.length; i++) { java.lang.reflect.Parameter parameter = parameters[i]; String paramName; McpToolParam mcpToolParam = parameter.getAnnotation(McpToolParam.class); if (mcpToolParam != null && !mcpToolParam.name().isEmpty()) { paramName = mcpToolParam.name(); } else if (parameter.isNamePresent()) { paramName = parameter.getName(); } else { paramName = McpConstant.DEFAULT_TOOL_NAME_PREFIX + i; } orderedJavaParameterNames.add(paramName); } return orderedJavaParameterNames; } private McpServerFeatures.AsyncToolSpecification createServiceToolSpecification( McpSchema.Tool mcpTool, Operation operation, URL url) { final MethodMeta methodMeta = operation.getMeta(); if (methodMeta == null) { throw new IllegalStateException("MethodMeta not found in Operation for tool: " + mcpTool.name()); } final ServiceMeta serviceMeta = methodMeta.getServiceMeta(); final String interfaceName = serviceMeta.getServiceInterface(); final String methodName = methodMeta.getMethod().getName(); final Class<?>[] parameterClasses = methodMeta.getMethod().getParameterTypes(); final List<String> orderedJavaParameterNames = new ArrayList<>(); if (methodMeta.getParameters() != null) { for (ParameterMeta javaParamMeta : methodMeta.getParameters()) { orderedJavaParameterNames.add(javaParamMeta.getName()); } } final String group = serviceMeta.getUrl() != null ? serviceMeta.getUrl().getGroup() : (url != null ? url.getGroup() : null); final String version = serviceMeta.getUrl() != null ? serviceMeta.getUrl().getVersion() : (url != null ? url.getVersion() : null); return getAsyncToolSpecification( mcpTool, interfaceName, methodName, parameterClasses, orderedJavaParameterNames, group, version); } private String generateDefaultDescription(Method method, ProviderModel providerModel) { return String.format( McpConstant.DEFAULT_TOOL_DESCRIPTION_TEMPLATE, method.getName(), providerModel.getServiceModel().getInterfaceName()); } private String generateToolSchema(Method method) { Map<String, Object> schemaMap = new HashMap<>(); schemaMap.put(McpConstant.SCHEMA_PROPERTY_TYPE, JsonSchemaType.OBJECT_SCHEMA.getJsonSchemaType()); Map<String, Object> properties = new HashMap<>(); List<String> requiredParams = new ArrayList<>(); generateSchemaFromMethodSignature(method, properties, requiredParams); schemaMap.put(McpConstant.SCHEMA_PROPERTY_PROPERTIES, properties); if (!requiredParams.isEmpty()) { schemaMap.put(McpConstant.SCHEMA_PROPERTY_REQUIRED, requiredParams); } try { return objectMapper.writeValueAsString(schemaMap); } catch (Exception e) { logger.error( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to generate tool schema for method " + method.getName() + ": " + e.getMessage(), e); return "{\"type\":\"object\",\"properties\":{}}"; } } private void generateSchemaFromMethodSignature( Method method, Map<String, Object> properties, List<String> requiredParams) { Class<?>[] paramTypes = method.getParameterTypes(); java.lang.reflect.Type[] genericTypes = method.getGenericParameterTypes(); java.lang.annotation.Annotation[][] parameterAnnotations = method.getParameterAnnotations(); for (int i = 0; i < paramTypes.length; i++) { String paramName = null; String paramDescription = null; boolean isRequired = false; for (java.lang.annotation.Annotation annotation : parameterAnnotations[i]) { if (annotation instanceof McpToolParam mcpToolParam) { if (!mcpToolParam.name().isEmpty()) { paramName = mcpToolParam.name(); } if (!mcpToolParam.description().isEmpty()) { paramDescription = mcpToolParam.description(); } isRequired = mcpToolParam.required(); break; } } if (paramName == null) { paramName = getParameterName(method, i); if (paramName == null || paramName.isEmpty()) { paramName = McpConstant.DEFAULT_TOOL_NAME_PREFIX + i; } } if (paramDescription == null) { paramDescription = String.format( McpConstant.DEFAULT_PARAMETER_DESCRIPTION_TEMPLATE, i, paramTypes[i].getSimpleName()); } TypeSchemaUtils.TypeSchemaInfo schemaInfo = TypeSchemaUtils.resolveTypeSchema(paramTypes[i], genericTypes[i], paramDescription); properties.put(paramName, TypeSchemaUtils.toSchemaMap(schemaInfo)); if (isRequired) { requiredParams.add(paramName); } } } private String getParameterName(Method method, int index) { if (method.getParameters().length > index) { return method.getParameters()[index].getName(); } return null; } public void clearRegistry() { for (String toolId : registeredTools.keySet()) { try { mcpServer.removeTool(toolId).block(); } catch (Exception e) { logger.error( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to unregister MCP tool: " + toolId, e); } } registeredTools.clear(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/tool/DubboOpenApiToolConverter.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/tool/DubboOpenApiToolConverter.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.mcp.tool; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.PojoUtils; import org.apache.dubbo.mcp.JsonSchemaType; import org.apache.dubbo.mcp.McpConstant; import org.apache.dubbo.mcp.core.McpServiceFilter; import org.apache.dubbo.mcp.util.TypeSchemaUtils; import org.apache.dubbo.remoting.http12.HttpMethods; import org.apache.dubbo.remoting.http12.rest.OpenAPIRequest; import org.apache.dubbo.remoting.http12.rest.ParamType; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.openapi.DefaultOpenAPIService; import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI; import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Operation; import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Parameter; import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.PathItem; import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Schema; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.fasterxml.jackson.databind.ObjectMapper; import io.modelcontextprotocol.spec.McpSchema; public class DubboOpenApiToolConverter { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboOpenApiToolConverter.class); private final DefaultOpenAPIService openApiService; private final ObjectMapper objectMapper = new ObjectMapper(); private final Map<String, Operation> opCache = new ConcurrentHashMap<>(); public DubboOpenApiToolConverter(DefaultOpenAPIService openApiService) { this.openApiService = openApiService; } public Map<String, McpSchema.Tool> convertToTools( ServiceDescriptor svcDesc, URL svcUrl, McpServiceFilter.McpToolConfig toolConfig) { opCache.clear(); OpenAPIRequest req = new OpenAPIRequest(); String intfName = svcDesc.getInterfaceName(); req.setService(new String[] {intfName}); OpenAPI openApiDef = openApiService.getOpenAPI(req); if (openApiDef == null || openApiDef.getPaths() == null) { return new HashMap<>(); } Map<String, McpSchema.Tool> mcpTools = new HashMap<>(); for (Map.Entry<String, PathItem> pathEntry : openApiDef.getPaths().entrySet()) { String path = pathEntry.getKey(); PathItem item = pathEntry.getValue(); if (item.getOperations() != null) { for (Map.Entry<HttpMethods, Operation> opEntry : item.getOperations().entrySet()) { HttpMethods httpMethod = opEntry.getKey(); Operation op = opEntry.getValue(); if (op == null || op.getOperationId() == null) { continue; } String opId = op.getOperationId(); McpServiceFilter.McpToolConfig methodConfig = getMethodConfig(op, toolConfig); McpSchema.Tool mcpTool = convertOperationToMcpTool(path, httpMethod, op, methodConfig); mcpTools.put(opId, mcpTool); opCache.put(opId, op); } } } return mcpTools; } public Operation getOperationByToolName(String toolName) { return opCache.get(toolName); } private McpSchema.Tool convertOperationToMcpTool( String path, HttpMethods method, Operation op, McpServiceFilter.McpToolConfig toolConfig) { String opId = op.getOperationId(); String toolName = generateToolName(op, toolConfig); String desc = generateToolDescription(op, toolConfig, path, method); Map<String, Object> paramsSchemaMap = extractParameterSchema(op); String schemaJson; try { schemaJson = objectMapper.writeValueAsString(paramsSchemaMap); } catch (Exception e) { logger.error( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "Failed to serialize parameter schema for tool {}: {}", opId, e.getMessage(), e); schemaJson = "{\"type\":\"object\",\"properties\":{}}"; } return new McpSchema.Tool(toolName, desc, schemaJson); } private String generateToolName(Operation op, McpServiceFilter.McpToolConfig toolConfig) { String opId = op.getOperationId(); if (toolConfig != null && toolConfig.getToolName() != null && !toolConfig.getToolName().isEmpty()) { return toolConfig.getToolName(); } return opId; } private String generateToolDescription( Operation op, McpServiceFilter.McpToolConfig toolConfig, String path, HttpMethods method) { if (toolConfig != null && toolConfig.getDescription() != null && !toolConfig.getDescription().isEmpty()) { return toolConfig.getDescription(); } String desc = op.getSummary(); if (desc == null || desc.isEmpty()) { desc = op.getDescription(); } if (desc == null || desc.isEmpty()) { desc = "Executes operation '" + op.getOperationId() + "' which corresponds to a " + method.name() + " request on path " + path + "."; } return desc; } private Map<String, Object> extractParameterSchema(Operation op) { Map<String, Object> schema = new HashMap<>(); Map<String, Object> props = new HashMap<>(); schema.put(McpConstant.SCHEMA_PROPERTY_TYPE, JsonSchemaType.OBJECT_SCHEMA.getJsonSchemaType()); if (op.getParameters() != null) { for (Parameter apiParam : op.getParameters()) { if (McpConstant.PARAM_TRIPLE_SERVICE_GROUP.equals(apiParam.getName())) { continue; } if (apiParam.getSchema() != null) { props.put( apiParam.getName(), convertOpenApiSchemaToMcpMap(apiParam.getSchema(), apiParam.getName())); } } } if (op.getRequestBody() != null && op.getRequestBody().getContents() != null) { op.getRequestBody().getContents().values().stream().findFirst().ifPresent(mediaType -> { if (mediaType.getSchema() != null) { Schema bodySchema = mediaType.getSchema(); MethodMeta methodMeta = op.getMeta(); if (methodMeta != null && methodMeta.getParameters() != null) { ParameterMeta[] methodParams = methodMeta.getParameters(); boolean shouldCreateIndividualParams = methodParams.length > 1 && allParamsArePrimitive(methodParams); if (shouldCreateIndividualParams) { for (int i = 0; i < methodParams.length; i++) { ParameterMeta param = methodParams[i]; String paramName = param.getName(); if (paramName == null || paramName.startsWith(McpConstant.DEFAULT_TOOL_NAME_PREFIX)) { paramName = param.getType().getSimpleName().toLowerCase() + "_" + (i + 1); logger.warn( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Operation '" + op.getOperationId() + "': Parameter " + i + " has default name '" + param.getName() + "', using generated name '" + paramName + "'. Ensure '-parameters' compiler flag is enabled."); } Map<String, Object> paramSchema = new HashMap<>(); Class<?> paramType = param.getType(); if (paramType == Double.class || paramType == double.class) { paramSchema.put( McpConstant.SCHEMA_PROPERTY_TYPE, JsonSchemaType.NUMBER_SCHEMA.getJsonSchemaType()); paramSchema.put( McpConstant.SCHEMA_PROPERTY_DESCRIPTION, McpConstant.PARAM_DESCRIPTION_DOUBLE); } else if (paramType == Integer.class || paramType == int.class) { paramSchema.put( McpConstant.SCHEMA_PROPERTY_TYPE, JsonSchemaType.INTEGER_SCHEMA.getJsonSchemaType()); paramSchema.put( McpConstant.SCHEMA_PROPERTY_DESCRIPTION, McpConstant.PARAM_DESCRIPTION_INTEGER); } else if (paramType == String.class) { paramSchema.put( McpConstant.SCHEMA_PROPERTY_TYPE, JsonSchemaType.STRING_SCHEMA.getJsonSchemaType()); paramSchema.put( McpConstant.SCHEMA_PROPERTY_DESCRIPTION, McpConstant.PARAM_DESCRIPTION_STRING); } else if (paramType == Boolean.class || paramType == boolean.class) { paramSchema.put( McpConstant.SCHEMA_PROPERTY_TYPE, JsonSchemaType.BOOLEAN_SCHEMA.getJsonSchemaType()); paramSchema.put( McpConstant.SCHEMA_PROPERTY_DESCRIPTION, McpConstant.PARAM_DESCRIPTION_BOOLEAN); } else { paramSchema = convertOpenApiSchemaToMcpMap(bodySchema.getItems(), paramName); } props.put(paramName, paramSchema); } } else { String inferredBodyParamName = McpConstant.PARAM_REQUEST_BODY_PAYLOAD; ParameterMeta requestBodyJavaParam = null; if (methodParams.length == 1) { ParameterMeta singleParam = methodParams[0]; if (singleParam.getNamedValueMeta().paramType() == null || singleParam.getNamedValueMeta().paramType() == ParamType.Body) { requestBodyJavaParam = singleParam; } } else { for (ParameterMeta pMeta : methodParams) { if (pMeta.getNamedValueMeta().paramType() == ParamType.Body) { requestBodyJavaParam = pMeta; break; } } if (requestBodyJavaParam == null) { for (ParameterMeta pMeta : methodParams) { if (pMeta.getNamedValueMeta().paramType() == null && PojoUtils.isPojo(pMeta.getType())) { requestBodyJavaParam = pMeta; break; } } } } if (requestBodyJavaParam != null) { String actualParamName = requestBodyJavaParam.getName(); if (actualParamName != null && !actualParamName.startsWith(McpConstant.DEFAULT_TOOL_NAME_PREFIX) && !actualParamName.isEmpty()) { inferredBodyParamName = actualParamName; } else { logger.warn( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Operation '" + op.getOperationId() + "': Could not get a meaningful name for request body param from MethodMeta (actual name was '" + (actualParamName != null ? actualParamName : "null") + "'). Using default '" + inferredBodyParamName + "'. Ensure '-parameters' compiler flag is enabled."); } } else { logger.warn( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Operation '" + op.getOperationId() + "': Could not identify a specific method parameter for the request body via MethodMeta. Using default name '" + inferredBodyParamName + " ' for schema type '" + bodySchema.getType() + "'"); } props.put( inferredBodyParamName, convertOpenApiSchemaToMcpMap(bodySchema, inferredBodyParamName)); } } else { logger.warn( LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION, "", "", "Operation '" + op.getOperationId() + "': MethodMeta not available for request body parameter name inference. Using default name 'requestBodyPayload' for schema type '" + bodySchema.getType() + "'."); props.put( McpConstant.PARAM_REQUEST_BODY_PAYLOAD, convertOpenApiSchemaToMcpMap(bodySchema, McpConstant.PARAM_REQUEST_BODY_PAYLOAD)); } } }); } schema.put(McpConstant.SCHEMA_PROPERTY_PROPERTIES, props); return schema; } private Map<String, Object> convertOpenApiSchemaToMcpMap(Schema openApiSchema) { return convertOpenApiSchemaToMcpMap(openApiSchema, null); } private Map<String, Object> convertOpenApiSchemaToMcpMap(Schema openApiSchema, String propertyName) { Map<String, Object> mcpMap = new HashMap<>(); if (openApiSchema == null) { return mcpMap; } if (openApiSchema.getRef() != null) { mcpMap.put(McpConstant.SCHEMA_PROPERTY_REF, openApiSchema.getRef()); } if (openApiSchema.getType() != null) { mcpMap.put( McpConstant.SCHEMA_PROPERTY_TYPE, openApiSchema.getType().toString().toLowerCase()); } if (openApiSchema.getFormat() != null) { mcpMap.put(McpConstant.SCHEMA_PROPERTY_FORMAT, openApiSchema.getFormat()); } if (openApiSchema.getDescription() != null && !openApiSchema.getDescription().isEmpty()) { mcpMap.put(McpConstant.SCHEMA_PROPERTY_DESCRIPTION, openApiSchema.getDescription()); } else { String defaultParamDesc = getParamDesc(openApiSchema, propertyName); mcpMap.put(McpConstant.SCHEMA_PROPERTY_DESCRIPTION, defaultParamDesc); } if (openApiSchema.getEnumeration() != null && !openApiSchema.getEnumeration().isEmpty()) { mcpMap.put(McpConstant.SCHEMA_PROPERTY_ENUM, openApiSchema.getEnumeration()); } if (openApiSchema.getDefaultValue() != null) { mcpMap.put(McpConstant.SCHEMA_PROPERTY_DEFAULT, openApiSchema.getDefaultValue()); } if (Schema.Type.OBJECT.equals(openApiSchema.getType()) && openApiSchema.getProperties() != null) { Map<String, Object> nestedProps = new HashMap<>(); openApiSchema .getProperties() .forEach((name, propSchema) -> nestedProps.put(name, convertOpenApiSchemaToMcpMap(propSchema, name))); mcpMap.put(McpConstant.SCHEMA_PROPERTY_PROPERTIES, nestedProps); } if (Schema.Type.ARRAY.equals(openApiSchema.getType()) && openApiSchema.getItems() != null) { mcpMap.put( McpConstant.SCHEMA_PROPERTY_ITEMS, convertOpenApiSchemaToMcpMap( openApiSchema.getItems(), propertyName != null ? propertyName + "_item" : null)); } return mcpMap; } private static String getParamDesc(Schema openApiSchema, String propertyName) { String typeOrRefString = ""; if (openApiSchema.getRef() != null && !openApiSchema.getRef().isEmpty()) { String ref = openApiSchema.getRef(); String componentName = ref.substring(ref.lastIndexOf('/') + 1); typeOrRefString = " referencing '" + componentName + "';"; // Indicates it's a reference if (openApiSchema.getType() != null) { typeOrRefString += " (which is of type '" + openApiSchema.getType().toString().toLowerCase() + "')"; } } else if (openApiSchema.getType() != null) { typeOrRefString = " of type '" + openApiSchema.getType().toString().toLowerCase() + "';"; if (openApiSchema.getFormat() != null) { typeOrRefString += " with format '" + openApiSchema.getFormat() + "';"; } } String namePrefix; if (propertyName != null && !propertyName.isEmpty()) { namePrefix = "Parameter '" + propertyName + "';"; } else { namePrefix = typeOrRefString.isEmpty() ? "Parameter" : "Schema"; } return namePrefix + typeOrRefString + "."; } private boolean allParamsArePrimitive(ParameterMeta[] methodParams) { for (ParameterMeta param : methodParams) { Class<?> paramType = param.getType(); if (!TypeSchemaUtils.isPrimitiveOrWrapper(paramType)) { return false; } } return true; } private McpServiceFilter.McpToolConfig getMethodConfig(Operation op, McpServiceFilter.McpToolConfig defaultConfig) { // Try to get method-specific configuration from operation metadata // This would need integration with the service filter to get method-level config // For now, return the default config return defaultConfig; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/tool/DubboMcpGenericCaller.java
dubbo-plugin/dubbo-mcp/src/main/java/org/apache/dubbo/mcp/tool/DubboMcpGenericCaller.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.mcp.tool; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.service.GenericService; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; public class DubboMcpGenericCaller { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboMcpGenericCaller.class); private final ApplicationConfig applicationConfig; private final Map<String, GenericService> serviceCache = new ConcurrentHashMap<>(); public DubboMcpGenericCaller(ApplicationModel applicationModel) { if (applicationModel == null) { logger.error( COMMON_UNEXPECTED_EXCEPTION, "", "", "ApplicationModel cannot be null for DubboMcpGenericCaller."); throw new IllegalArgumentException("ApplicationModel cannot be null."); } this.applicationConfig = applicationModel.getCurrentConfig(); if (this.applicationConfig == null) { String errMsg = "ApplicationConfig is null in the provided ApplicationModel. Application Name: " + (applicationModel.getApplicationName() != null ? applicationModel.getApplicationName() : "N/A"); logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", errMsg); throw new IllegalStateException(errMsg); } } public Object execute( String interfaceName, String methodName, List<String> orderedJavaParameterNames, Class<?>[] parameterJavaTypes, Map<String, Object> mcpProvidedParameters, String group, String version) { String cacheKey = interfaceName + ":" + (group == null ? "" : group) + ":" + (version == null ? "" : version); GenericService genericService = serviceCache.get(cacheKey); if (genericService == null) { ReferenceConfig<GenericService> reference = new ReferenceConfig<>(); reference.setApplication(this.applicationConfig); reference.setInterface(interfaceName); reference.setGeneric("true"); // Defaults to 'bean' or 'true' for POJO generalization. reference.setScope("local"); if (group != null && !group.isEmpty()) { reference.setGroup(group); } if (version != null && !version.isEmpty()) { reference.setVersion(version); } try { genericService = reference.get(); if (genericService != null) { serviceCache.put(cacheKey, genericService); } else { String errorMessage = "Failed to obtain GenericService instance for " + interfaceName + (group != null ? " group " + group : "") + (version != null ? " version " + version : ""); logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", errorMessage); throw new IllegalStateException(errorMessage); } } catch (Exception e) { String errorMessage = "Error obtaining GenericService for " + interfaceName + ": " + e.getMessage(); logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", errorMessage, e); throw new RuntimeException(errorMessage, e); } } String[] invokeParameterTypes = new String[parameterJavaTypes.length]; for (int i = 0; i < parameterJavaTypes.length; i++) { invokeParameterTypes[i] = parameterJavaTypes[i].getName(); } Object[] invokeArgs = new Object[orderedJavaParameterNames.size()]; for (int i = 0; i < orderedJavaParameterNames.size(); i++) { String paramName = orderedJavaParameterNames.get(i); if (mcpProvidedParameters.containsKey(paramName)) { invokeArgs[i] = mcpProvidedParameters.get(paramName); } else { invokeArgs[i] = null; logger.warn( COMMON_UNEXPECTED_EXCEPTION, "", "", "Parameter '" + paramName + "' not found in MCP provided parameters for method '" + methodName + "' of interface '" + interfaceName + "'. Will use null."); } } try { return genericService.$invoke(methodName, invokeParameterTypes, invokeArgs); } catch (Exception e) { String errorMessage = "GenericService $invoke failed for method '" + methodName + "' on interface '" + interfaceName + "': " + e.getMessage(); logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", errorMessage, e); throw new RuntimeException(errorMessage, e); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-triple-websocket/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/TripleEndpoint.java
dubbo-plugin/dubbo-triple-websocket/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/TripleEndpoint.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.websocket; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.io.StreamUtils; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.nested.TripleConfig; import org.apache.dubbo.remoting.http12.HttpHeaderNames; import org.apache.dubbo.remoting.http12.HttpHeaders; import org.apache.dubbo.remoting.http12.HttpMethods; import org.apache.dubbo.remoting.http12.HttpStatus; import org.apache.dubbo.remoting.http12.h2.Http2Header; import org.apache.dubbo.remoting.http12.h2.Http2InputMessage; import org.apache.dubbo.remoting.http12.h2.Http2InputMessageFrame; import org.apache.dubbo.remoting.http12.h2.Http2MetadataFrame; import org.apache.dubbo.remoting.http12.message.DefaultHttpHeaders; import org.apache.dubbo.remoting.websocket.WebSocketTransportListener; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.tri.ServletExchanger; import javax.websocket.CloseReason; import javax.websocket.CloseReason.CloseCodes; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; import javax.websocket.Session; import static org.apache.dubbo.rpc.protocol.tri.websocket.WebSocketConstants.TRIPLE_WEBSOCKET_LISTENER; public class TripleEndpoint extends Endpoint { @Override public void onOpen(Session session, EndpointConfig config) { String path = session.getRequestURI().getPath(); HttpHeaders httpHeaders = new DefaultHttpHeaders(); httpHeaders.set(HttpHeaderNames.PATH.getName(), path); httpHeaders.set(HttpHeaderNames.METHOD.getName(), HttpMethods.POST.name()); Http2Header http2Header = new Http2MetadataFrame(httpHeaders); URL url = ServletExchanger.getUrl(); TripleConfig tripleConfig = ConfigManager.getProtocolOrDefault(url).getTripleOrDefault(); WebSocketStreamChannel webSocketStreamChannel = new WebSocketStreamChannel(session, tripleConfig); WebSocketTransportListener webSocketTransportListener = DefaultWebSocketServerTransportListenerFactory.INSTANCE.newInstance( webSocketStreamChannel, url, FrameworkModel.defaultModel()); webSocketTransportListener.onMetadata(http2Header); session.addMessageHandler(new TripleTextMessageHandler(webSocketTransportListener)); session.addMessageHandler(new TripleBinaryMessageHandler(webSocketTransportListener)); session.getUserProperties().put(TRIPLE_WEBSOCKET_LISTENER, webSocketTransportListener); } @Override public void onClose(Session session, CloseReason closeReason) { super.onClose(session, closeReason); WebSocketTransportListener webSocketTransportListener = (WebSocketTransportListener) session.getUserProperties().get(TRIPLE_WEBSOCKET_LISTENER); if (webSocketTransportListener == null) { return; } if (closeReason.getCloseCode().getCode() == CloseCodes.NORMAL_CLOSURE.getCode()) { Http2InputMessage http2InputMessage = new Http2InputMessageFrame(StreamUtils.EMPTY, true); webSocketTransportListener.onData(http2InputMessage); return; } webSocketTransportListener.cancelByRemote(closeReason.getCloseCode().getCode()); } @Override public void onError(Session session, Throwable thr) { super.onError(session, thr); WebSocketTransportListener webSocketTransportListener = (WebSocketTransportListener) session.getUserProperties().get(TRIPLE_WEBSOCKET_LISTENER); if (webSocketTransportListener == null) { return; } webSocketTransportListener.cancelByRemote(HttpStatus.INTERNAL_SERVER_ERROR.getCode()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-triple-websocket/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/TripleWebSocketFilter.java
dubbo-plugin/dubbo-triple-websocket/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/TripleWebSocketFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.websocket; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.remoting.http12.HttpMethods; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.websocket.server.ServerContainer; import javax.websocket.server.ServerEndpointConfig; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Set; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; import static org.apache.dubbo.rpc.protocol.tri.TripleConstants.UPGRADE_HEADER_KEY; import static org.apache.dubbo.rpc.protocol.tri.websocket.WebSocketConstants.TRIPLE_WEBSOCKET_REMOTE_ADDRESS; import static org.apache.dubbo.rpc.protocol.tri.websocket.WebSocketConstants.TRIPLE_WEBSOCKET_UPGRADE_HEADER_VALUE; public class TripleWebSocketFilter implements Filter { private static final ErrorTypeAwareLogger LOG = LoggerFactory.getErrorTypeAwareLogger(TripleWebSocketFilter.class); private transient ServerContainer sc; private final Set<String> existed = new ConcurrentHashSet<>(); @Override public void init(FilterConfig filterConfig) { sc = (ServerContainer) filterConfig.getServletContext().getAttribute(ServerContainer.class.getName()); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!isWebSocketUpgradeRequest(request, response)) { chain.doFilter(request, response); return; } HttpServletRequest hRequest = (HttpServletRequest) request; HttpServletResponse hResponse = (HttpServletResponse) response; String path; String pathInfo = hRequest.getPathInfo(); if (pathInfo == null) { path = hRequest.getServletPath(); } else { path = hRequest.getServletPath() + pathInfo; } Map<String, String[]> copiedMap = new HashMap<>(hRequest.getParameterMap()); copiedMap.put( TRIPLE_WEBSOCKET_REMOTE_ADDRESS, new String[] {hRequest.getRemoteHost(), String.valueOf(hRequest.getRemotePort())}); HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(hRequest) { @Override public Map<String, String[]> getParameterMap() { return copiedMap; } }; if (existed.contains(path)) { chain.doFilter(wrappedRequest, hResponse); return; } ServerEndpointConfig serverEndpointConfig = ServerEndpointConfig.Builder.create(TripleEndpoint.class, path).build(); try { sc.addEndpoint(serverEndpointConfig); existed.add(path); } catch (Exception e) { LOG.error(PROTOCOL_FAILED_REQUEST, "", "", "Failed to add endpoint", e); hResponse.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } chain.doFilter(wrappedRequest, hResponse); } @Override public void destroy() {} public boolean isWebSocketUpgradeRequest(ServletRequest request, ServletResponse response) { return ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse) && headerContainsToken( (HttpServletRequest) request, UPGRADE_HEADER_KEY, TRIPLE_WEBSOCKET_UPGRADE_HEADER_VALUE) && HttpMethods.GET.name().equals(((HttpServletRequest) request).getMethod())); } private boolean headerContainsToken(HttpServletRequest req, String headerName, String target) { Enumeration<String> headers = req.getHeaders(headerName); while (headers.hasMoreElements()) { String header = headers.nextElement(); String[] tokens = header.split(","); for (String token : tokens) { if (target.equalsIgnoreCase(token.trim())) { 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-triple-websocket/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/TripleBinaryMessageHandler.java
dubbo-plugin/dubbo-triple-websocket/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/TripleBinaryMessageHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.websocket; import org.apache.dubbo.remoting.http12.h2.Http2InputMessage; import org.apache.dubbo.remoting.http12.h2.Http2InputMessageFrame; import org.apache.dubbo.remoting.websocket.FinalFragmentByteArrayInputStream; import org.apache.dubbo.remoting.websocket.WebSocketTransportListener; import javax.websocket.MessageHandler; import java.nio.ByteBuffer; public class TripleBinaryMessageHandler implements MessageHandler.Partial<ByteBuffer> { private final WebSocketTransportListener webSocketTransportListener; public TripleBinaryMessageHandler(WebSocketTransportListener webSocketTransportListener) { this.webSocketTransportListener = webSocketTransportListener; } @Override public void onMessage(ByteBuffer messagePart, boolean last) { Http2InputMessage http2InputMessage = new Http2InputMessageFrame(new FinalFragmentByteArrayInputStream(messagePart.array(), last), false); webSocketTransportListener.onData(http2InputMessage); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-triple-websocket/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/WebSocketConstants.java
dubbo-plugin/dubbo-triple-websocket/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/WebSocketConstants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.websocket; public interface WebSocketConstants { String TRIPLE_WEBSOCKET_UPGRADE_HEADER_VALUE = "websocket"; String TRIPLE_WEBSOCKET_REMOTE_ADDRESS = "tri.websocket.remote.address"; String TRIPLE_WEBSOCKET_LISTENER = "tri.websocket.listener"; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-triple-websocket/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/WebSocketStreamChannel.java
dubbo-plugin/dubbo-triple-websocket/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/WebSocketStreamChannel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.websocket; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.config.nested.TripleConfig; import org.apache.dubbo.remoting.http12.HttpHeaderNames; import org.apache.dubbo.remoting.http12.HttpHeaders; import org.apache.dubbo.remoting.http12.HttpMetadata; import org.apache.dubbo.remoting.http12.HttpOutputMessage; import org.apache.dubbo.remoting.http12.HttpStatus; import org.apache.dubbo.remoting.http12.LimitedByteArrayOutputStream; import org.apache.dubbo.remoting.http12.h2.H2StreamChannel; import org.apache.dubbo.remoting.http12.h2.Http2Header; import org.apache.dubbo.remoting.http12.h2.Http2OutputMessage; import org.apache.dubbo.remoting.http12.h2.Http2OutputMessageFrame; import org.apache.dubbo.remoting.websocket.WebSocketHeaderNames; import javax.websocket.CloseReason; import javax.websocket.Session; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import static org.apache.dubbo.rpc.protocol.tri.websocket.WebSocketConstants.TRIPLE_WEBSOCKET_REMOTE_ADDRESS; public class WebSocketStreamChannel implements H2StreamChannel { private final Session session; private final TripleConfig tripleConfig; private final InetSocketAddress remoteAddress; private final InetSocketAddress localAddress; public WebSocketStreamChannel(Session session, TripleConfig tripleConfig) { this.session = session; this.tripleConfig = tripleConfig; Map<String, List<String>> requestParameterMap = session.getRequestParameterMap(); List<String> remoteAddressData = requestParameterMap.get(TRIPLE_WEBSOCKET_REMOTE_ADDRESS); this.remoteAddress = InetSocketAddress.createUnresolved( remoteAddressData.get(0), Integer.parseInt(remoteAddressData.get(1))); this.localAddress = InetSocketAddress.createUnresolved( session.getRequestURI().getHost(), session.getRequestURI().getPort()); } @Override public CompletableFuture<Void> writeResetFrame(long errorCode) { CompletableFuture<Void> completableFuture = new CompletableFuture<>(); try { session.close(); completableFuture.complete(null); } catch (IOException e) { completableFuture.completeExceptionally(e); } return completableFuture; } @Override public Http2OutputMessage newOutputMessage(boolean endStream) { return new Http2OutputMessageFrame( new LimitedByteArrayOutputStream(256, tripleConfig.getMaxResponseBodySizeOrDefault()), endStream); } @Override public CompletableFuture<Void> writeHeader(HttpMetadata httpMetadata) { Http2Header http2Header = (Http2Header) httpMetadata; CompletableFuture<Void> completableFuture = new CompletableFuture<>(); if (http2Header.isEndStream()) { try { session.close(encodeCloseReason(http2Header)); completableFuture.complete(null); } catch (IOException e) { completableFuture.completeExceptionally(e); } } return completableFuture; } @Override public CompletableFuture<Void> writeMessage(HttpOutputMessage httpOutputMessage) { ByteArrayOutputStream body = (ByteArrayOutputStream) httpOutputMessage.getBody(); CompletableFuture<Void> completableFuture = new CompletableFuture<>(); try { session.getBasicRemote().sendBinary(ByteBuffer.wrap(body.toByteArray())); completableFuture.complete(null); } catch (IOException e) { completableFuture.completeExceptionally(e); } return completableFuture; } @Override public SocketAddress remoteAddress() { return remoteAddress; } @Override public SocketAddress localAddress() { return localAddress; } @Override public void flush() {} private CloseReason encodeCloseReason(Http2Header http2Header) { HttpHeaders headers = http2Header.headers(); List<String> statusHeaders = headers.remove(HttpHeaderNames.STATUS.getName()); CloseReason closeReason; if (CollectionUtils.isNotEmpty(statusHeaders) && !HttpStatus.OK.getStatusString().equals(statusHeaders.get(0))) { List<String> messageHeaders = headers.remove(WebSocketHeaderNames.WEBSOCKET_MESSAGE.getName()); closeReason = new CloseReason( CloseReason.CloseCodes.UNEXPECTED_CONDITION, CollectionUtils.isNotEmpty(messageHeaders) ? messageHeaders.get(0) : "Internal server error"); } else { closeReason = new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Bye"); } return closeReason; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-triple-websocket/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/TripleTextMessageHandler.java
dubbo-plugin/dubbo-triple-websocket/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/TripleTextMessageHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.websocket; import org.apache.dubbo.remoting.http12.h2.Http2InputMessage; import org.apache.dubbo.remoting.http12.h2.Http2InputMessageFrame; import org.apache.dubbo.remoting.websocket.FinalFragmentByteArrayInputStream; import org.apache.dubbo.remoting.websocket.WebSocketTransportListener; import javax.websocket.MessageHandler; import java.nio.charset.StandardCharsets; public class TripleTextMessageHandler implements MessageHandler.Partial<String> { private final WebSocketTransportListener webSocketTransportListener; public TripleTextMessageHandler(WebSocketTransportListener webSocketTransportListener) { this.webSocketTransportListener = webSocketTransportListener; } @Override public void onMessage(String messagePart, boolean last) { Http2InputMessage http2InputMessage = new Http2InputMessageFrame( new FinalFragmentByteArrayInputStream(messagePart.getBytes(StandardCharsets.UTF_8), last), false); webSocketTransportListener.onData(http2InputMessage); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-plugin-loom/src/test/java/org/apache/dubbo/common/threadpool/support/loom/VirtualThreadPoolTest.java
dubbo-plugin/dubbo-plugin-loom/src/test/java/org/apache/dubbo/common/threadpool/support/loom/VirtualThreadPoolTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.common.threadpool.support.loom; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadpool.ThreadPool; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledForJreRange; import org.junit.jupiter.api.condition.JRE; import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.startsWith; import static org.junit.jupiter.api.Assertions.assertTrue; public class VirtualThreadPoolTest { @Test @EnabledForJreRange(min = JRE.JAVA_21) void getExecutor1() throws Exception { URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY + "=demo"); ThreadPool threadPool = new VirtualThreadPool(); Executor executor = threadPool.getExecutor(url); final CountDownLatch latch = new CountDownLatch(1); executor.execute(() -> { Thread thread = Thread.currentThread(); assertTrue(thread.isVirtual()); assertThat(thread.getName(), startsWith("demo")); latch.countDown(); }); latch.await(); assertThat(latch.getCount(), is(0L)); } @Test @EnabledForJreRange(min = JRE.JAVA_21) void getExecutor2() { URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + QUEUES_KEY + "=1"); ThreadPool threadPool = new VirtualThreadPool(); assertThat( threadPool.getExecutor(url).getClass().getName(), Matchers.is("java.util.concurrent.ThreadPerTaskExecutor")); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-plugin-loom/src/main/java/org/apache/dubbo/common/threadpool/support/loom/VirtualThreadPool.java
dubbo-plugin/dubbo-plugin-loom/src/main/java/org/apache/dubbo/common/threadpool/support/loom/VirtualThreadPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.common.threadpool.support.loom; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadpool.ThreadPool; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; /** * Creates a thread pool that use virtual thread * * @see Executors#newVirtualThreadPerTaskExecutor() */ public class VirtualThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { String name = url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); return Executors.newThreadPerTaskExecutor( Thread.ofVirtual().name(name, 1).factory()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/servlet/ServletStreamChannel.java
dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/servlet/ServletStreamChannel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.servlet; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.http12.HttpConstants; import org.apache.dubbo.remoting.http12.HttpHeaderNames; import org.apache.dubbo.remoting.http12.HttpHeaders; import org.apache.dubbo.remoting.http12.HttpMetadata; import org.apache.dubbo.remoting.http12.HttpOutputMessage; import org.apache.dubbo.remoting.http12.exception.HttpStatusException; import org.apache.dubbo.remoting.http12.h2.H2StreamChannel; import org.apache.dubbo.remoting.http12.h2.Http2Header; import org.apache.dubbo.remoting.http12.h2.Http2OutputMessage; import org.apache.dubbo.remoting.http12.h2.Http2OutputMessageFrame; import org.apache.dubbo.rpc.TriRpcStatus; import org.apache.dubbo.rpc.TriRpcStatus.Code; import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum; import javax.servlet.AsyncContext; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; final class ServletStreamChannel implements H2StreamChannel { private static final Logger LOGGER = LoggerFactory.getLogger(ServletStreamChannel.class); private final Queue<Object> writeQueue = new ConcurrentLinkedQueue<>(); private final AtomicBoolean writeable = new AtomicBoolean(); private final HttpServletRequest request; private final HttpServletResponse response; private final AsyncContext context; private boolean isGrpc; ServletStreamChannel(HttpServletRequest request, HttpServletResponse response, AsyncContext context) { this.request = request; this.response = response; this.context = context; } public void setGrpc(boolean isGrpc) { this.isGrpc = isGrpc; } public void writeError(int code, Throwable throwable) { if (response.isCommitted() && code == Code.DEADLINE_EXCEEDED.code) { return; } try { if (isGrpc) { response.setTrailerFields(() -> { Map<String, String> map = new HashMap<>(); map.put(TripleHeaderEnum.STATUS_KEY.getName(), String.valueOf(code)); return map; }); return; } try { if (throwable instanceof HttpStatusException) { response.setStatus(((HttpStatusException) throwable).getStatusCode()); response.getOutputStream().close(); } else { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } catch (Throwable t) { LOGGER.info("Failed to send response", t); } } finally { context.complete(); } } public void onWritePossible() { if (writeable.compareAndSet(false, true)) { flushQueue(); } } private void flushQueue() { if (writeQueue.isEmpty()) { return; } synchronized (writeQueue) { Object obj; while ((obj = writeQueue.poll()) != null) { if (obj instanceof HttpMetadata) { writeHeaderInternal((HttpMetadata) obj); } else if (obj instanceof HttpOutputMessage) { writeMessageInternal((HttpOutputMessage) obj); } } } } @Override public CompletableFuture<Void> writeResetFrame(long errorCode) { if (isGrpc) { writeError(TriRpcStatus.httpStatusToGrpcCode((int) errorCode).code, null); return completed(); } try { if (errorCode == 0L) { response.getOutputStream().close(); return completed(); } if (response.isCommitted()) { return completed(); } if (errorCode >= 300 && errorCode < 600) { response.sendError((int) errorCode); } else { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } catch (Throwable t) { LOGGER.info("Failed to close response", t); } finally { context.complete(); } return completed(); } @Override public Http2OutputMessage newOutputMessage(boolean endStream) { return new Http2OutputMessageFrame(new ByteArrayOutputStream(256), endStream); } @Override public CompletableFuture<Void> writeHeader(HttpMetadata httpMetadata) { if (writeable.get()) { flushQueue(); writeHeaderInternal(httpMetadata); } else { writeQueue.add(httpMetadata); } return completed(); } private void writeHeaderInternal(HttpMetadata httpMetadata) { boolean endStream = false; boolean isHttp1 = true; if (httpMetadata instanceof Http2Header) { endStream = ((Http2Header) httpMetadata).isEndStream(); isHttp1 = false; } try { HttpHeaders headers = httpMetadata.headers(); if (endStream) { response.setTrailerFields(() -> { Map<String, String> map = new HashMap<>(); for (Entry<CharSequence, String> entry : headers) { map.put(entry.getKey().toString(), entry.getValue()); } return map; }); return; } if (response.isCommitted()) { return; } for (Entry<CharSequence, String> entry : headers) { String key = entry.getKey().toString(); String value = entry.getValue(); if (HttpHeaderNames.STATUS.getName().equals(key)) { response.setStatus(Integer.parseInt(value)); continue; } if (isHttp1 && HttpHeaderNames.TRANSFER_ENCODING.getName().equals(key) && HttpConstants.CHUNKED.equals(value)) { continue; } response.addHeader(key, value); } } catch (Throwable t) { LOGGER.info("Failed to write header", t); } finally { if (endStream) { context.complete(); } } } @Override public CompletableFuture<Void> writeMessage(HttpOutputMessage httpOutputMessage) { if (writeable.get()) { flushQueue(); writeMessageInternal(httpOutputMessage); } else { writeQueue.add(httpOutputMessage); } return completed(); } private void writeMessageInternal(HttpOutputMessage httpOutputMessage) { boolean endStream = false; if (httpOutputMessage instanceof Http2OutputMessage) { endStream = ((Http2OutputMessage) httpOutputMessage).isEndStream(); } else if (httpOutputMessage == HttpOutputMessage.EMPTY_MESSAGE) { endStream = true; } try { ByteArrayOutputStream bos = (ByteArrayOutputStream) httpOutputMessage.getBody(); ServletOutputStream out = response.getOutputStream(); bos.writeTo(out); out.flush(); } catch (Throwable t) { LOGGER.info("Failed to write message", t); } finally { if (endStream) { context.complete(); } } } @Override public SocketAddress remoteAddress() { return InetSocketAddress.createUnresolved(request.getRemoteAddr(), request.getRemotePort()); } @Override public SocketAddress localAddress() { return InetSocketAddress.createUnresolved(request.getLocalAddr(), request.getLocalPort()); } @Override public void flush() {} private static CompletableFuture<Void> completed() { return CompletableFuture.completedFuture(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-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/servlet/TripleFilter.java
dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/servlet/TripleFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.servlet; import org.apache.dubbo.common.io.StreamUtils; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.http12.HttpVersion; import org.apache.dubbo.remoting.http12.h1.Http1InputMessage; import org.apache.dubbo.remoting.http12.h1.Http1ServerTransportListener; import org.apache.dubbo.remoting.http12.h2.Http2InputMessageFrame; import org.apache.dubbo.remoting.http12.h2.Http2ServerTransportListenerFactory; import org.apache.dubbo.remoting.http12.h2.Http2TransportListener; import org.apache.dubbo.rpc.PathResolver; import org.apache.dubbo.rpc.TriRpcStatus.Code; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.tri.RequestPath; import org.apache.dubbo.rpc.protocol.tri.ServletExchanger; import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum; import org.apache.dubbo.rpc.protocol.tri.h12.grpc.GrpcHeaderNames; import org.apache.dubbo.rpc.protocol.tri.h12.grpc.GrpcHttp2ServerTransportListener; import org.apache.dubbo.rpc.protocol.tri.h12.grpc.GrpcUtils; import org.apache.dubbo.rpc.protocol.tri.h12.http1.DefaultHttp11ServerTransportListenerFactory; import org.apache.dubbo.rpc.protocol.tri.h12.http2.GenericHttp2ServerTransportListenerFactory; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.DefaultRequestMappingRegistry; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMappingRegistry; import javax.servlet.AsyncContext; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ReadListener; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.WriteListener; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Set; import static org.apache.dubbo.rpc.protocol.tri.TripleConstants.UPGRADE_HEADER_KEY; public class TripleFilter implements Filter { private static final Logger LOGGER = LoggerFactory.getLogger(TripleFilter.class); private PathResolver pathResolver; private RequestMappingRegistry mappingRegistry; @Override public void init(FilterConfig config) { FrameworkModel frameworkModel = FrameworkModel.defaultModel(); pathResolver = frameworkModel.getDefaultExtension(PathResolver.class); mappingRegistry = frameworkModel.getOrRegisterBean(DefaultRequestMappingRegistry.class); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; boolean isHttp2 = HttpVersion.HTTP2.getProtocol().equals(request.getProtocol()); if (isHttp2) { if (hasGrpcMapping(request) || mappingRegistry.exists(request.getRequestURI(), request.getMethod())) { handleHttp2(request, response); return; } } else { if (notUpgradeRequest(request) && mappingRegistry.exists(request.getRequestURI(), request.getMethod())) { handleHttp1(request, response); return; } } chain.doFilter(request, response); } private void handleHttp2(HttpServletRequest request, HttpServletResponse response) { AsyncContext context = request.startAsync(request, response); ServletStreamChannel channel = new ServletStreamChannel(request, response, context); try { Http2TransportListener listener = determineHttp2ServerTransportListenerFactory(request.getContentType()) .newInstance(channel, ServletExchanger.getUrl(), FrameworkModel.defaultModel()); boolean isGrpc = listener instanceof GrpcHttp2ServerTransportListener; channel.setGrpc(isGrpc); context.setTimeout(resolveTimeout(request, isGrpc)); context.addListener(new TripleAsyncListener(channel)); ServletInputStream is = request.getInputStream(); is.setReadListener(new TripleReadListener(listener, channel, is)); response.getOutputStream().setWriteListener(new TripleWriteListener(channel)); listener.onMetadata(new HttpMetadataAdapter(request)); } catch (Throwable t) { LOGGER.info("Failed to process request", t); channel.writeError(Code.UNKNOWN.code, t); } } private void handleHttp1(HttpServletRequest request, HttpServletResponse response) { AsyncContext context = request.startAsync(request, response); ServletStreamChannel channel = new ServletStreamChannel(request, response, context); try { Http1ServerTransportListener listener = DefaultHttp11ServerTransportListenerFactory.INSTANCE.newInstance( channel, ServletExchanger.getUrl(), FrameworkModel.defaultModel()); channel.setGrpc(false); context.setTimeout(resolveTimeout(request, false)); ServletInputStream is = request.getInputStream(); response.getOutputStream().setWriteListener(new TripleWriteListener(channel)); listener.onMetadata(new HttpMetadataAdapter(request)); listener.onData(new Http1InputMessage( is.available() == 0 ? StreamUtils.EMPTY : new ByteArrayInputStream(StreamUtils.readBytes(is)))); } catch (Throwable t) { LOGGER.info("Failed to process request", t); channel.writeError(Code.UNKNOWN.code, t); } } @Override public void destroy() {} private boolean hasGrpcMapping(HttpServletRequest request) { if (!GrpcUtils.isGrpcRequest(request.getContentType())) { return false; } RequestPath path = RequestPath.parse(request.getRequestURI()); if (path == null) { return false; } String group = request.getHeader(TripleHeaderEnum.SERVICE_GROUP.getName()); String version = request.getHeader(TripleHeaderEnum.SERVICE_VERSION.getName()); return pathResolver.resolve(path.getPath(), group, version) != null; } private boolean notUpgradeRequest(HttpServletRequest request) { return request.getHeader(UPGRADE_HEADER_KEY) == null; } private Http2ServerTransportListenerFactory determineHttp2ServerTransportListenerFactory(String contentType) { Set<Http2ServerTransportListenerFactory> http2ServerTransportListenerFactories = FrameworkModel.defaultModel() .getExtensionLoader(Http2ServerTransportListenerFactory.class) .getSupportedExtensionInstances(); for (Http2ServerTransportListenerFactory factory : http2ServerTransportListenerFactories) { if (factory.supportContentType(contentType)) { return factory; } } return GenericHttp2ServerTransportListenerFactory.INSTANCE; } private static int resolveTimeout(HttpServletRequest request, boolean isGrpc) { try { if (isGrpc) { String timeoutString = request.getHeader(GrpcHeaderNames.GRPC_TIMEOUT.getName()); if (timeoutString != null) { Long timeout = GrpcUtils.parseTimeoutToMills(timeoutString); if (timeout != null) { return timeout.intValue() + 2000; } } } else { String timeoutString = request.getHeader(TripleHeaderEnum.SERVICE_TIMEOUT.getName()); if (timeoutString != null) { return Integer.parseInt(timeoutString) + 2000; } } } catch (Throwable ignored) { } return 0; } private static final class TripleAsyncListener implements AsyncListener { private final ServletStreamChannel streamChannel; TripleAsyncListener(ServletStreamChannel streamChannel) { this.streamChannel = streamChannel; } @Override public void onComplete(AsyncEvent event) {} @Override public void onTimeout(AsyncEvent event) { streamChannel.writeError(Code.DEADLINE_EXCEEDED.code, event.getThrowable()); } @Override public void onError(AsyncEvent event) { streamChannel.writeError(Code.CANCELLED.code, event.getThrowable()); } @Override public void onStartAsync(AsyncEvent event) {} } private static final class TripleReadListener implements ReadListener { private final Http2TransportListener listener; private final ServletStreamChannel channel; private final ServletInputStream input; private final byte[] buffer = new byte[4 * 1024]; TripleReadListener(Http2TransportListener listener, ServletStreamChannel channel, ServletInputStream input) { this.listener = listener; this.channel = channel; this.input = input; } @Override public void onDataAvailable() throws IOException { while (input.isReady()) { int length = input.read(buffer); if (length == -1) { return; } byte[] copy = Arrays.copyOf(buffer, length); listener.onData(new Http2InputMessageFrame(new ByteArrayInputStream(copy), false)); } } @Override public void onAllDataRead() { listener.onData(new Http2InputMessageFrame(StreamUtils.EMPTY, true)); } @Override public void onError(Throwable t) { channel.writeError(Code.CANCELLED.code, t); } } private static final class TripleWriteListener implements WriteListener { private final ServletStreamChannel channel; TripleWriteListener(ServletStreamChannel channel) { this.channel = channel; } @Override public void onWritePossible() { channel.onWritePossible(); } @Override public void onError(Throwable t) { channel.writeError(Code.CANCELLED.code, 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-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/servlet/HttpMetadataAdapter.java
dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/servlet/HttpMetadataAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.servlet; import org.apache.dubbo.remoting.http12.HttpHeaders; import org.apache.dubbo.remoting.http12.h2.Http2Header; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; import io.netty.handler.codec.http2.Http2Headers.PseudoHeaderName; public final class HttpMetadataAdapter implements Http2Header { private final HttpServletRequest request; private HttpHeaders headers; HttpMetadataAdapter(HttpServletRequest request) { this.request = request; } public HttpServletRequest getRequest() { return request; } @Override public HttpHeaders headers() { HttpHeaders headers = this.headers; if (headers == null) { headers = HttpHeaders.create(); Enumeration<String> en = request.getHeaderNames(); while (en.hasMoreElements()) { String key = en.nextElement(); Enumeration<String> ven = request.getHeaders(key); while (ven.hasMoreElements()) { headers.add(key, ven.nextElement()); } } headers.add(PseudoHeaderName.METHOD.value(), method()); headers.add(PseudoHeaderName.SCHEME.value(), request.getScheme()); headers.add(PseudoHeaderName.AUTHORITY.value(), request.getServerName()); headers.add(PseudoHeaderName.PROTOCOL.value(), request.getProtocol()); this.headers = headers; } return headers; } @Override public String method() { return request.getMethod(); } @Override public String path() { String query = request.getQueryString(); return query == null ? request.getRequestURI() : request.getRequestURI() + '?' + query; } @Override public long id() { return -1L; } @Override public boolean isEndStream() { 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-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/ServletHttpMessageAdapterFactory.java
dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/ServletHttpMessageAdapterFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.servlet; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http12.HttpChannel; import org.apache.dubbo.remoting.http12.HttpMetadata; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.message.HttpMessageAdapterFactory; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestExtension; import javax.servlet.ServletContext; @Activate(order = -100, onClass = "javax.servlet.http.HttpServletRequest") public final class ServletHttpMessageAdapterFactory implements HttpMessageAdapterFactory<ServletHttpRequestAdapter, HttpMetadata, Void> { private final FrameworkModel frameworkModel; private final ServletContext servletContext; private final HttpSessionFactory httpSessionFactory; public ServletHttpMessageAdapterFactory(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; servletContext = (ServletContext) createDummyServletContext(frameworkModel); httpSessionFactory = getHttpSessionFactory(frameworkModel); } private HttpSessionFactory getHttpSessionFactory(FrameworkModel frameworkModel) { for (RestExtension extension : frameworkModel.getActivateExtensions(RestExtension.class)) { if (extension instanceof HttpSessionFactory) { return (HttpSessionFactory) extension; } } return null; } @Override public ServletHttpRequestAdapter adaptRequest(HttpMetadata rawRequest, HttpChannel channel) { return new ServletHttpRequestAdapter(rawRequest, channel, servletContext, httpSessionFactory); } @Override public HttpResponse adaptResponse(ServletHttpRequestAdapter request, HttpMetadata rawRequest, Void rawResponse) { return new ServletHttpResponseAdapter(); } public Object adaptFilterConfig(String filterName) { return new DummyFilterConfig(filterName, frameworkModel, servletContext); } private Object createDummyServletContext(FrameworkModel frameworkModel) { return new DummyServletContext(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-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/DummyFilterConfig.java
dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/DummyFilterConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.servlet; import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import java.util.Collections; import java.util.Enumeration; final class DummyFilterConfig implements FilterConfig { private final String filterName; private final FrameworkModel frameworkModel; private final ServletContext servletContext; public DummyFilterConfig(String filterName, FrameworkModel frameworkModel, ServletContext servletContext) { this.filterName = filterName; this.frameworkModel = frameworkModel; this.servletContext = servletContext; } @Override public String getFilterName() { return filterName; } @Override public ServletContext getServletContext() { return servletContext; } @Override public String getInitParameter(String name) { String prefix = RestConstants.CONFIG_PREFIX + "filter-config."; Configuration conf = ConfigurationUtils.getGlobalConfiguration(frameworkModel.defaultApplication()); String value = conf.getString(prefix + filterName + "." + name); if (value == null) { value = conf.getString(prefix + name); } return value; } @Override public Enumeration<String> getInitParameterNames() { return Collections.emptyEnumeration(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/ServletArgumentResolver.java
dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/ServletArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.servlet; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.rpc.protocol.tri.rest.RestException; import org.apache.dubbo.rpc.protocol.tri.rest.argument.ArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.HashSet; import java.util.Set; @Activate(onClass = "javax.servlet.http.HttpServletRequest") public class ServletArgumentResolver implements ArgumentResolver { private static final Set<Class<?>> SUPPORTED_TYPES = new HashSet<>(); static { SUPPORTED_TYPES.add(ServletRequest.class); SUPPORTED_TYPES.add(HttpServletRequest.class); SUPPORTED_TYPES.add(ServletResponse.class); SUPPORTED_TYPES.add(HttpServletResponse.class); SUPPORTED_TYPES.add(HttpSession.class); SUPPORTED_TYPES.add(Cookie.class); SUPPORTED_TYPES.add(Cookie[].class); SUPPORTED_TYPES.add(Reader.class); SUPPORTED_TYPES.add(Writer.class); } @Override public boolean accept(ParameterMeta parameter) { return SUPPORTED_TYPES.contains(parameter.getActualType()); } @Override public Object resolve(ParameterMeta parameter, HttpRequest request, HttpResponse response) { Class<?> type = parameter.getActualType(); if (type == ServletRequest.class || type == HttpServletRequest.class) { return request; } if (type == ServletResponse.class || type == HttpServletResponse.class) { return response; } if (type == HttpSession.class) { return ((HttpServletRequest) request).getSession(); } if (type == Cookie.class) { return Helper.convert(request.cookie(parameter.getRequiredName())); } if (type == Cookie[].class) { return ((HttpServletRequest) request).getCookies(); } if (type == Reader.class) { try { return ((HttpServletRequest) request).getReader(); } catch (IOException e) { throw new RestException(e); } } if (type == Writer.class) { try { return ((HttpServletResponse) response).getWriter(); } catch (IOException e) { throw new RestException(e); } } 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-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/FileUploadPart.java
dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/FileUploadPart.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.servlet; import org.apache.dubbo.common.io.StreamUtils; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.rpc.protocol.tri.rest.RestException; import javax.servlet.http.Part; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Collections; public final class FileUploadPart implements Part { private final HttpRequest.FileUpload fileUpload; public FileUploadPart(HttpRequest.FileUpload fileUpload) { this.fileUpload = fileUpload; } @Override public InputStream getInputStream() { return fileUpload.inputStream(); } @Override public String getContentType() { return fileUpload.contentType(); } @Override public String getName() { return fileUpload.name(); } @Override public String getSubmittedFileName() { return fileUpload.filename(); } @Override public long getSize() { return fileUpload.size(); } @Override public void write(String fileName) { try (FileOutputStream fos = new FileOutputStream(fileName)) { StreamUtils.copy(fileUpload.inputStream(), fos); } catch (IOException e) { throw new RestException(e); } } @Override public void delete() {} @Override public String getHeader(String name) { return null; } @Override public Collection<String> getHeaders(String name) { return null; } @Override public Collection<String> getHeaderNames() { return Collections.emptyList(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/FilterAdapter.java
dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/FilterAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.servlet; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.message.HttpMessageAdapterFactory; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.tri.rest.RestException; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestExtensionAdapter; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter; import org.apache.dubbo.rpc.protocol.tri.rest.util.RestUtils; import javax.servlet.Filter; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.io.IOException; import java.util.Arrays; @Activate(onClass = "javax.servlet.Filter") public final class FilterAdapter implements RestExtensionAdapter<Filter> { private final ServletHttpMessageAdapterFactory adapterFactory; public FilterAdapter(FrameworkModel frameworkModel) { adapterFactory = (ServletHttpMessageAdapterFactory) frameworkModel.getExtension(HttpMessageAdapterFactory.class, "servlet"); } @Override public boolean accept(Object extension) { return extension instanceof Filter; } @Override public RestFilter adapt(Filter extension) { try { String filterName = extension.getClass().getSimpleName(); extension.init((FilterConfig) adapterFactory.adaptFilterConfig(filterName)); } catch (ServletException e) { throw new RestException(e); } return new FilterRestFilter(extension); } private static final class FilterRestFilter implements RestFilter { private final Filter filter; @Override public int getPriority() { return RestUtils.getPriority(filter); } @Override public String[] getPatterns() { return RestUtils.getPattens(filter); } public FilterRestFilter(Filter filter) { this.filter = filter; } @Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws Exception { filter.doFilter((ServletRequest) request, (ServletResponse) response, (q, p) -> { try { chain.doFilter(request, response); } catch (RuntimeException | IOException | ServletException e) { throw e; } catch (Exception e) { throw new ServletException(e); } }); } @Override public String toString() { StringBuilder sb = new StringBuilder("RestFilter{filter="); sb.append(filter); int priority = getPriority(); if (priority != 0) { sb.append(", priority=").append(priority); } String[] patterns = getPatterns(); if (patterns != null) { sb.append(", patterns=").append(Arrays.toString(patterns)); } return sb.append('}').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-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/DummyServletContext.java
dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/DummyServletContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.servlet; import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants; import javax.servlet.Filter; import javax.servlet.FilterRegistration; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; import javax.servlet.ServletRegistration.Dynamic; import javax.servlet.SessionCookieConfig; import javax.servlet.SessionTrackingMode; import javax.servlet.descriptor.JspConfigDescriptor; import java.io.InputStream; import java.net.URL; import java.util.Collections; import java.util.Enumeration; import java.util.EventListener; import java.util.HashMap; import java.util.Map; import java.util.Set; final class DummyServletContext implements ServletContext { private final FrameworkModel frameworkModel; private final Map<String, Object> attributes = new HashMap<>(); private final Map<String, String> initParameters = new HashMap<>(); public DummyServletContext(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } @Override public String getContextPath() { return "/"; } @Override public ServletContext getContext(String uripath) { return this; } @Override public int getMajorVersion() { return 3; } @Override public int getMinorVersion() { return 1; } @Override public int getEffectiveMajorVersion() { return 3; } @Override public int getEffectiveMinorVersion() { return 1; } @Override public String getMimeType(String file) { return null; } @Override public Set<String> getResourcePaths(String path) { return null; } @Override public URL getResource(String path) { return null; } @Override public InputStream getResourceAsStream(String path) { return null; } @Override public RequestDispatcher getRequestDispatcher(String path) { return null; } @Override public RequestDispatcher getNamedDispatcher(String name) { return null; } public Servlet getServlet(String name) { throw new UnsupportedOperationException(); } public Enumeration<Servlet> getServlets() { throw new UnsupportedOperationException(); } public Enumeration<String> getServletNames() { throw new UnsupportedOperationException(); } @Override public void log(String msg) { LoggerFactory.getLogger(DummyServletContext.class).info(msg); } public void log(Exception exception, String msg) { LoggerFactory.getLogger(DummyServletContext.class).info(msg, exception); } @Override public void log(String message, Throwable throwable) { LoggerFactory.getLogger(DummyServletContext.class).info(message, throwable); } @Override public String getRealPath(String path) { throw new UnsupportedOperationException(); } @Override public String getServerInfo() { return "Dubbo Rest Server/1.0"; } @Override public String getInitParameter(String name) { String value = initParameters.get(name); if (value != null) { return value; } Configuration conf = ConfigurationUtils.getGlobalConfiguration(frameworkModel.defaultApplication()); return conf.getString(RestConstants.CONFIG_PREFIX + "servlet-context." + name); } @Override public Enumeration<String> getInitParameterNames() { return Collections.enumeration(initParameters.keySet()); } @Override public boolean setInitParameter(String name, String value) { return initParameters.putIfAbsent(name, value) == null; } @Override public Object getAttribute(String name) { return attributes.get(name); } @Override public Enumeration<String> getAttributeNames() { return Collections.enumeration(attributes.keySet()); } @Override public void setAttribute(String name, Object object) { attributes.put(name, object); } @Override public void removeAttribute(String name) { attributes.remove(name); } @Override public String getServletContextName() { return ""; } @Override public ServletRegistration.Dynamic addServlet(String servletName, String className) { throw new UnsupportedOperationException(); } @Override public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) { throw new UnsupportedOperationException(); } @Override public ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) { throw new UnsupportedOperationException(); } @Override public Dynamic addJspFile(String servletName, String jspFile) { return null; } @Override public <T extends Servlet> T createServlet(Class<T> clazz) { throw new UnsupportedOperationException(); } @Override public ServletRegistration getServletRegistration(String servletName) { throw new UnsupportedOperationException(); } @Override public Map<String, ? extends ServletRegistration> getServletRegistrations() { throw new UnsupportedOperationException(); } @Override public FilterRegistration.Dynamic addFilter(String filterName, String className) { throw new UnsupportedOperationException(); } @Override public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) { throw new UnsupportedOperationException(); } @Override public FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) { throw new UnsupportedOperationException(); } @Override public <T extends Filter> T createFilter(Class<T> clazz) { throw new UnsupportedOperationException(); } @Override public FilterRegistration getFilterRegistration(String filterName) { throw new UnsupportedOperationException(); } @Override public Map<String, ? extends FilterRegistration> getFilterRegistrations() { throw new UnsupportedOperationException(); } @Override public SessionCookieConfig getSessionCookieConfig() { throw new UnsupportedOperationException(); } @Override public void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes) { throw new UnsupportedOperationException(); } @Override public Set<SessionTrackingMode> getDefaultSessionTrackingModes() { throw new UnsupportedOperationException(); } @Override public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() { throw new UnsupportedOperationException(); } @Override public void addListener(String className) { throw new UnsupportedOperationException(); } @Override public <T extends EventListener> void addListener(T t) { throw new UnsupportedOperationException(); } @Override public void addListener(Class<? extends EventListener> listenerClass) { throw new UnsupportedOperationException(); } @Override public <T extends EventListener> T createListener(Class<T> clazz) { throw new UnsupportedOperationException(); } @Override public JspConfigDescriptor getJspConfigDescriptor() { throw new UnsupportedOperationException(); } @Override public ClassLoader getClassLoader() { return getClass().getClassLoader(); } @Override public void declareRoles(String... roleNames) { throw new UnsupportedOperationException(); } @Override public String getVirtualServerName() { throw new UnsupportedOperationException(); } @Override public int getSessionTimeout() { throw new UnsupportedOperationException(); } @Override public void setSessionTimeout(int i) { throw new UnsupportedOperationException(); } @Override public String getRequestCharacterEncoding() { throw new UnsupportedOperationException(); } @Override public void setRequestCharacterEncoding(String encoding) { throw new UnsupportedOperationException(); } @Override public String getResponseCharacterEncoding() { throw new UnsupportedOperationException(); } @Override public void setResponseCharacterEncoding(String encoding) { throw new UnsupportedOperationException(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/ServletHttpRequestAdapter.java
dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/ServletHttpRequestAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.servlet; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.remoting.http12.HttpChannel; import org.apache.dubbo.remoting.http12.HttpConstants; import org.apache.dubbo.remoting.http12.HttpMetadata; import org.apache.dubbo.remoting.http12.HttpVersion; import org.apache.dubbo.remoting.http12.message.DefaultHttpRequest; import javax.servlet.AsyncContext; import javax.servlet.DispatcherType; import javax.servlet.ReadListener; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletInputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpUpgradeHandler; import javax.servlet.http.Part; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.security.Principal; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Locale; import java.util.Map; public class ServletHttpRequestAdapter extends DefaultHttpRequest implements HttpServletRequest { private final ServletContext servletContext; private final HttpSessionFactory sessionFactory; private ServletInputStream sis; private BufferedReader reader; public ServletHttpRequestAdapter( HttpMetadata metadata, HttpChannel channel, ServletContext servletContext, HttpSessionFactory sessionFactory) { super(metadata, channel); this.servletContext = servletContext; this.sessionFactory = sessionFactory; } @Override public String getAuthType() { return header("www-authenticate"); } @Override public Cookie[] getCookies() { return Helper.convertCookies(cookies()); } @Override public long getDateHeader(String name) { Date date = dateHeader(name); return date == null ? -1L : date.getTime(); } @Override public String getHeader(String name) { return header(name); } @Override public Enumeration<String> getHeaders(String name) { return Collections.enumeration(headerValues(name)); } @Override public Enumeration<String> getHeaderNames() { return Collections.enumeration(headerNames()); } @Override public int getIntHeader(String name) { String headerValue = getHeader(name); try { return Integer.parseInt(headerValue); } catch (NumberFormatException e) { return -1; } } @Override public String getMethod() { return method(); } @Override public String getPathInfo() { return null; } @Override public String getPathTranslated() { return null; } @Override public String getContextPath() { return "/"; } @Override public String getQueryString() { return query(); } @Override public String getRemoteUser() { throw new UnsupportedOperationException(); } @Override public boolean isUserInRole(String role) { throw new UnsupportedOperationException(); } @Override public Principal getUserPrincipal() { throw new UnsupportedOperationException(); } @Override public String getRequestedSessionId() { throw new UnsupportedOperationException(); } @Override public String getRequestURI() { return path(); } @Override public StringBuffer getRequestURL() { StringBuffer url = new StringBuffer(32); String scheme = getScheme(); int port = getServerPort(); url.append(scheme).append("://").append(getServerName()); if (HttpConstants.HTTP.equals(scheme) && port != 80 || HttpConstants.HTTPS.equals(scheme) && port != 443) { url.append(':'); url.append(port); } url.append(path()); return url; } @Override public String getServletPath() { return path(); } @Override public HttpSession getSession(boolean create) { if (sessionFactory == null) { throw new UnsupportedOperationException("No HttpSessionFactory found"); } return sessionFactory.getSession(this, create); } @Override public HttpSession getSession() { return getSession(true); } @Override public String changeSessionId() { return null; } @Override public boolean isRequestedSessionIdValid() { return true; } @Override public boolean isRequestedSessionIdFromCookie() { return true; } @Override public boolean isRequestedSessionIdFromURL() { return false; } public boolean isRequestedSessionIdFromUrl() { return false; } @Override public boolean authenticate(HttpServletResponse response) { throw new UnsupportedOperationException(); } @Override public void login(String username, String password) { throw new UnsupportedOperationException(); } @Override public void logout() { throw new UnsupportedOperationException(); } @Override public Collection<Part> getParts() { return Helper.convertParts(parts()); } @Override public FileUploadPart getPart(String name) { return Helper.convert(part(name)); } @Override public <T extends HttpUpgradeHandler> T upgrade(Class<T> handlerClass) { throw new UnsupportedOperationException(); } @Override public Object getAttribute(String name) { return attribute(name); } @Override public Enumeration<String> getAttributeNames() { return Collections.enumeration(attributeNames()); } @Override public String getCharacterEncoding() { return charset(); } @Override public void setCharacterEncoding(String env) { setCharset(env); } @Override public int getContentLength() { return contentLength(); } @Override public long getContentLengthLong() { return contentLength(); } @Override public String getContentType() { return contentType(); } @Override public ServletInputStream getInputStream() { if (sis == null) { sis = new HttpInputStream(inputStream()); } return sis; } @Override public String getParameter(String name) { return parameter(name); } @Override public Enumeration<String> getParameterNames() { return Collections.enumeration(parameterNames()); } @Override public String[] getParameterValues(String name) { List<String> values = parameterValues(name); return values == null ? null : values.toArray(new String[0]); } @Override public Map<String, String[]> getParameterMap() { Collection<String> paramNames = parameterNames(); if (paramNames.isEmpty()) { return Collections.emptyMap(); } Map<String, String[]> result = CollectionUtils.newLinkedHashMap(paramNames.size()); for (String paramName : paramNames) { result.put(paramName, getParameterValues(paramName)); } return result; } @Override public String getProtocol() { return isHttp2() ? HttpVersion.HTTP2.getProtocol() : HttpVersion.HTTP1.getProtocol(); } @Override public String getScheme() { return scheme(); } @Override public String getServerName() { return serverName(); } @Override public int getServerPort() { return serverPort(); } @Override public BufferedReader getReader() { if (reader == null) { reader = new BufferedReader(new InputStreamReader(inputStream(), charsetOrDefault())); } return reader; } @Override public String getRemoteAddr() { return remoteAddr(); } @Override public String getRemoteHost() { return String.valueOf(remotePort()); } @Override public Locale getLocale() { return locale(); } @Override public Enumeration<Locale> getLocales() { return Collections.enumeration(locales()); } @Override public boolean isSecure() { return HttpConstants.HTTPS.equals(scheme()); } @Override public RequestDispatcher getRequestDispatcher(String path) { throw new UnsupportedOperationException(); } public String getRealPath(String path) { return null; } @Override public int getRemotePort() { return remotePort(); } @Override public String getLocalName() { return localHost(); } @Override public String getLocalAddr() { return localAddr(); } @Override public int getLocalPort() { return localPort(); } @Override public ServletContext getServletContext() { return servletContext; } @Override public AsyncContext startAsync() throws IllegalStateException { throw new IllegalStateException(); } @Override public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException { throw new IllegalStateException(); } @Override public boolean isAsyncStarted() { return false; } @Override public boolean isAsyncSupported() { return false; } @Override public AsyncContext getAsyncContext() { throw new IllegalStateException(); } @Override public DispatcherType getDispatcherType() { return DispatcherType.REQUEST; } /* jakarta placeholder */ @Override public String toString() { return "ServletHttpRequestAdapter{" + fieldToString() + '}'; } private static final class HttpInputStream extends ServletInputStream { private final InputStream is; HttpInputStream(InputStream is) { this.is = is; } @Override public int read() throws IOException { return is.read(); } @Override public int read(byte[] b) throws IOException { return is.read(b); } @Override public void close() throws IOException { is.close(); } @Override public int readLine(byte[] b, int off, int len) throws IOException { return is.read(b, off, len); } @Override public boolean isFinished() { try { return is.available() == 0; } catch (IOException e) { return false; } } @Override public boolean isReady() { return true; } @Override public void setReadListener(ReadListener readListener) { throw new UnsupportedOperationException(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/HttpSessionFactory.java
dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/HttpSessionFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.servlet; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestExtension; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; public interface HttpSessionFactory extends RestExtension { HttpSession getSession(HttpServletRequest request, boolean create); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/ServletHttpResponseAdapter.java
dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/ServletHttpResponseAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.servlet; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.remoting.http12.HttpUtils; import org.apache.dubbo.remoting.http12.message.DefaultHttpResponse; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import javax.servlet.ServletOutputStream; import javax.servlet.WriteListener; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Date; import java.util.Locale; public class ServletHttpResponseAdapter extends DefaultHttpResponse implements HttpServletResponse { private ServletOutputStream sos; private PrintWriter writer; @Override public void addCookie(Cookie cookie) { addCookie(Helper.convert(cookie)); } @Override public boolean containsHeader(String name) { return hasHeader(name); } @Override public String encodeURL(String url) { return RequestUtils.encodeURL(url); } @Override public String encodeRedirectURL(String url) { return RequestUtils.encodeURL(url); } public String encodeUrl(String url) { return RequestUtils.encodeURL(url); } public String encodeRedirectUrl(String url) { return RequestUtils.encodeURL(url); } public void sendRedirect(String location, int sc, boolean clearBuffer) { sendRedirect(location); } @Override public void setDateHeader(String name, long date) { setHeader(name, new Date(date)); } @Override public void addDateHeader(String name, long date) { addHeader(name, new Date(date)); } @Override public void setHeader(String name, String value) { super.setHeader(name, value); } @Override public void addHeader(String name, String value) { super.addHeader(name, value); } @Override public void setIntHeader(String name, int value) { setHeader(name, String.valueOf(value)); } @Override public void addIntHeader(String name, int value) { addHeader(name, String.valueOf(value)); } public void setStatus(int sc, String sm) { setStatus(sc); setBody(sm); } @Override public int getStatus() { return status(); } @Override public String getHeader(String name) { return header(name); } @Override public Collection<String> getHeaders(String name) { return headerValues(name); } @Override public Collection<String> getHeaderNames() { return headerNames(); } @Override public String getCharacterEncoding() { return charset(); } @Override public String getContentType() { return contentType(); } @Override public ServletOutputStream getOutputStream() { if (sos == null) { sos = new HttpOutputStream(outputStream()); } return sos; } @Override public PrintWriter getWriter() { if (writer == null) { String ce = getCharacterEncoding(); Charset charset = ce == null ? StandardCharsets.UTF_8 : Charset.forName(ce); writer = new PrintWriter(new OutputStreamWriter(outputStream(), charset), true); } return writer; } @Override public void setCharacterEncoding(String charset) { setCharset(charset); } @Override public void setContentLength(int len) {} @Override public void setContentLengthLong(long len) {} @Override public void setBufferSize(int size) {} @Override public int getBufferSize() { return 0; } @Override public void flushBuffer() throws IOException { //noinspection resource OutputStream os = outputStream(); if (os instanceof BufferedOutputStream) { os.flush(); } } @Override public void setLocale(Locale loc) { setLocale(loc.toLanguageTag()); } @Override public Locale getLocale() { Locale locale = CollectionUtils.first(HttpUtils.parseContentLanguage(locale())); return locale == null ? Locale.getDefault() : locale; } @Override public String toString() { return "ServletHttpResponseAdapter{" + fieldToString() + '}'; } private static final class HttpOutputStream extends ServletOutputStream { private final OutputStream outputStream; private HttpOutputStream(OutputStream outputStream) { this.outputStream = outputStream; } @Override public void write(int b) throws IOException { outputStream.write(b); } @Override public void write(byte[] b) throws IOException { outputStream.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { outputStream.write(b, off, len); } @Override public boolean isReady() { return true; } @Override public void setWriteListener(WriteListener writeListener) { throw new UnsupportedOperationException(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/Helper.java
dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/Helper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.servlet; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.remoting.http12.HttpCookie; import org.apache.dubbo.remoting.http12.HttpRequest.FileUpload; import javax.servlet.http.Part; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; final class Helper { private Helper() {} static javax.servlet.http.Cookie[] convertCookies(Collection<HttpCookie> hCookies) { javax.servlet.http.Cookie[] cookies = new javax.servlet.http.Cookie[hCookies.size()]; int i = 0; for (HttpCookie cookie : hCookies) { cookies[i++] = convert(cookie); } return cookies; } static javax.servlet.http.Cookie convert(HttpCookie hCookie) { javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(hCookie.name(), hCookie.value()); if (hCookie.domain() != null) { cookie.setDomain(hCookie.domain()); } cookie.setMaxAge((int) hCookie.maxAge()); cookie.setHttpOnly(hCookie.httpOnly()); cookie.setPath(hCookie.path()); cookie.setSecure(hCookie.secure()); return cookie; } static HttpCookie convert(javax.servlet.http.Cookie sCookie) { HttpCookie cookie = new HttpCookie(sCookie.getName(), sCookie.getValue()); cookie.setDomain(sCookie.getDomain()); cookie.setMaxAge(sCookie.getMaxAge()); cookie.setHttpOnly(sCookie.isHttpOnly()); cookie.setPath(sCookie.getPath()); cookie.setSecure(sCookie.getSecure()); return cookie; } public static FileUploadPart convert(FileUpload part) { return new FileUploadPart(part); } public static Collection<Part> convertParts(Collection<FileUpload> parts) { if (CollectionUtils.isEmpty(parts)) { return Collections.emptyList(); } List<Part> result = new ArrayList<>(parts.size()); for (FileUpload part : parts) { result.add(convert(part)); } return result; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-autoconfigure-compatible/src/test/java/org/apache/dubbo/spring/boot/TestSuite.java
dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-autoconfigure-compatible/src/test/java/org/apache/dubbo/spring/boot/TestSuite.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.spring.boot; import org.apache.dubbo.spring.boot.autoconfigure.RelaxedDubboConfigBinderTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ RelaxedDubboConfigBinderTest.class, }) public class TestSuite {}
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-autoconfigure-compatible/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/TestBeansConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-autoconfigure-compatible/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/TestBeansConfiguration.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.spring.boot.autoconfigure; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConsumerConfig; 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.RegistryConfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class TestBeansConfiguration { @Bean ApplicationConfig application1() { ApplicationConfig config = new ApplicationConfig(); config.setId("application1"); return config; } @Bean ModuleConfig module1() { ModuleConfig config = new ModuleConfig(); config.setId("module1"); return config; } @Bean RegistryConfig registry1() { RegistryConfig config = new RegistryConfig(); config.setId("registry1"); return config; } @Bean MonitorConfig monitor1() { MonitorConfig config = new MonitorConfig(); config.setId("monitor1"); return config; } @Bean ProtocolConfig protocol1() { ProtocolConfig config = new ProtocolConfig(); config.setId("protocol1"); return config; } @Bean ConsumerConfig consumer1() { ConsumerConfig config = new ConsumerConfig(); config.setId("consumer1"); return config; } @Bean ProviderConfig provider1() { ProviderConfig config = new ProviderConfig(); config.setId("provider1"); return config; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-autoconfigure-compatible/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/RelaxedDubboConfigBinderTest.java
dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-autoconfigure-compatible/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/RelaxedDubboConfigBinderTest.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.spring.boot.autoconfigure; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.context.config.ConfigurationBeanBinder; import java.util.Map; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import static org.apache.dubbo.config.spring.util.PropertySourcesUtils.getSubProperties; /** * {@link RelaxedDubboConfigBinder} Test */ @RunWith(SpringRunner.class) @TestPropertySource( properties = { "dubbo.application.NAME=hello", "dubbo.application.owneR=world", "dubbo.registry.Address=10.20.153.17", "dubbo.protocol.pORt=20881", "dubbo.service.invoke.timeout=2000", }) @ContextConfiguration(classes = RelaxedDubboConfigBinder.class) public class RelaxedDubboConfigBinderTest { @Autowired private ConfigurationBeanBinder dubboConfigBinder; @Autowired private ConfigurableEnvironment environment; @Before public void init() { DubboBootstrap.reset(); } @After public void destroy() { DubboBootstrap.reset(); } @Test public void testBinder() { ApplicationConfig applicationConfig = new ApplicationConfig(); Map<String, Object> properties = getSubProperties(environment.getPropertySources(), "dubbo.application"); dubboConfigBinder.bind(properties, true, true, applicationConfig); Assert.assertEquals("hello", applicationConfig.getName()); Assert.assertEquals("world", applicationConfig.getOwner()); RegistryConfig registryConfig = new RegistryConfig(); properties = getSubProperties(environment.getPropertySources(), "dubbo.registry"); dubboConfigBinder.bind(properties, true, true, registryConfig); Assert.assertEquals("10.20.153.17", registryConfig.getAddress()); ProtocolConfig protocolConfig = new ProtocolConfig(); properties = getSubProperties(environment.getPropertySources(), "dubbo.protocol"); dubboConfigBinder.bind(properties, true, true, protocolConfig); Assert.assertEquals(Integer.valueOf(20881), protocolConfig.getPort()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-autoconfigure-compatible/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBindingAutoConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-autoconfigure-compatible/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBindingAutoConfiguration.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.spring.boot.autoconfigure; import org.apache.dubbo.config.spring.context.config.ConfigurationBeanBinder; import java.util.Set; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertyResolver; import static java.util.Collections.emptySet; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_BEAN_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_PROPERTY_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SCAN_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME; import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE; /** * Dubbo Relaxed Binding Auto-{@link Configuration} for Spring Boot 1.x */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @ConditionalOnClass(name = "org.springframework.boot.bind.RelaxedPropertyResolver") @Configuration public class DubboRelaxedBindingAutoConfiguration { public PropertyResolver dubboScanBasePackagesPropertyResolver(Environment environment) { return new RelaxedPropertyResolver(environment, DUBBO_SCAN_PREFIX); } /** * The bean is used to scan the packages of Dubbo Service classes * * @param environment {@link Environment} instance * @return non-null {@link Set} * @since 2.7.8 */ @ConditionalOnMissingBean(name = BASE_PACKAGES_BEAN_NAME) @Bean(name = BASE_PACKAGES_BEAN_NAME) public Set<String> dubboBasePackages(Environment environment) { PropertyResolver propertyResolver = dubboScanBasePackagesPropertyResolver(environment); return propertyResolver.getProperty(BASE_PACKAGES_PROPERTY_NAME, Set.class, emptySet()); } @ConditionalOnMissingBean(name = RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME, value = ConfigurationBeanBinder.class) @Bean(RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME) @Scope(scopeName = SCOPE_PROTOTYPE) public ConfigurationBeanBinder relaxedDubboConfigBinder() { return new RelaxedDubboConfigBinder(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-autoconfigure-compatible/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/RelaxedDubboConfigBinder.java
dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-autoconfigure-compatible/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/RelaxedDubboConfigBinder.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.spring.boot.autoconfigure; import org.apache.dubbo.config.spring.context.config.ConfigurationBeanBinder; import org.apache.dubbo.config.spring.context.properties.DubboConfigBinder; import java.util.Map; import org.springframework.beans.MutablePropertyValues; import org.springframework.boot.bind.RelaxedDataBinder; /** * Spring Boot Relaxed {@link DubboConfigBinder} implementation * * @since 2.7.0 */ class RelaxedDubboConfigBinder implements ConfigurationBeanBinder { @Override public void bind( Map<String, Object> configurationProperties, boolean ignoreUnknownFields, boolean ignoreInvalidFields, Object configurationBean) { RelaxedDataBinder relaxedDataBinder = new RelaxedDataBinder(configurationBean); // Set ignored* relaxedDataBinder.setIgnoreInvalidFields(ignoreInvalidFields); relaxedDataBinder.setIgnoreUnknownFields(ignoreUnknownFields); // Get properties under specified prefix from PropertySources // Convert Map to MutablePropertyValues MutablePropertyValues propertyValues = new MutablePropertyValues(configurationProperties); // Bind relaxedDataBinder.bind(propertyValues); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-actuator-autoconfigure-compatible/src/test/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAutoConfigurationTest.java
dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-actuator-autoconfigure-compatible/src/test/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAutoConfigurationTest.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.spring.boot.actuate.autoconfigure; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboConfigsMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboPropertiesMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboReferencesMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboServicesMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboShutdownMetadata; import java.util.Map; import java.util.SortedMap; import java.util.function.Supplier; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; /** * {@link DubboEndpointAutoConfiguration} Test * * @since 2.7.0 */ @RunWith(SpringRunner.class) @SpringBootTest( classes = {DubboEndpointAutoConfiguration.class, DubboEndpointAutoConfigurationTest.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { "dubbo.service.version = 1.0.0", "dubbo.application.id = my-application", "dubbo.application.name = dubbo-demo-application", "dubbo.module.id = my-module", "dubbo.module.name = dubbo-demo-module", "dubbo.registry.id = my-registry", "dubbo.registry.address = N/A", "dubbo.protocol.id=my-protocol", "dubbo.protocol.name=dubbo", "dubbo.protocol.port=20880", "dubbo.provider.id=my-provider", "dubbo.provider.host=127.0.0.1", "dubbo.scan.basePackages=org.apache.dubbo.spring.boot.actuate.autoconfigure", "endpoints.enabled = true", "management.security.enabled = false", "management.contextPath = /actuator", "endpoints.dubbo.enabled = true", "endpoints.dubbo.sensitive = false", "endpoints.dubboshutdown.enabled = true", "endpoints.dubboconfigs.enabled = true", "endpoints.dubboservices.enabled = true", "endpoints.dubboreferences.enabled = true", "endpoints.dubboproperties.enabled = true", }) @EnableAutoConfiguration @Ignore public class DubboEndpointAutoConfigurationTest { @Autowired private DubboEndpoint dubboEndpoint; @Autowired private DubboConfigsMetadata dubboConfigsMetadata; @Autowired private DubboPropertiesMetadata dubboProperties; @Autowired private DubboReferencesMetadata dubboReferencesMetadata; @Autowired private DubboServicesMetadata dubboServicesMetadata; @Autowired private DubboShutdownMetadata dubboShutdownMetadata; private RestTemplate restTemplate = new RestTemplate(); @Autowired private ObjectMapper objectMapper; @Value("http://127.0.0.1:${local.management.port}${management.contextPath:}") private String actuatorBaseURL; @Test public void testShutdown() throws Exception { Map<String, Object> value = dubboShutdownMetadata.shutdown(); Map<String, Object> shutdownCounts = (Map<String, Object>) value.get("shutdown.count"); Assert.assertEquals(0, shutdownCounts.get("registries")); Assert.assertEquals(1, shutdownCounts.get("protocols")); Assert.assertEquals(1, shutdownCounts.get("services")); Assert.assertEquals(0, shutdownCounts.get("references")); } @Test public void testConfigs() { Map<String, Map<String, Map<String, Object>>> configsMap = dubboConfigsMetadata.configs(); Map<String, Map<String, Object>> beansMetadata = configsMap.get("ApplicationConfig"); Assert.assertEquals( "dubbo-demo-application", beansMetadata.get("my-application").get("name")); beansMetadata = configsMap.get("ConsumerConfig"); Assert.assertTrue(beansMetadata.isEmpty()); beansMetadata = configsMap.get("MethodConfig"); Assert.assertTrue(beansMetadata.isEmpty()); beansMetadata = configsMap.get("ModuleConfig"); Assert.assertEquals("dubbo-demo-module", beansMetadata.get("my-module").get("name")); beansMetadata = configsMap.get("MonitorConfig"); Assert.assertTrue(beansMetadata.isEmpty()); beansMetadata = configsMap.get("ProtocolConfig"); Assert.assertEquals("dubbo", beansMetadata.get("my-protocol").get("name")); beansMetadata = configsMap.get("ProviderConfig"); Assert.assertEquals("127.0.0.1", beansMetadata.get("my-provider").get("host")); beansMetadata = configsMap.get("ReferenceConfig"); Assert.assertTrue(beansMetadata.isEmpty()); beansMetadata = configsMap.get("RegistryConfig"); Assert.assertEquals("N/A", beansMetadata.get("my-registry").get("address")); beansMetadata = configsMap.get("ServiceConfig"); Assert.assertFalse(beansMetadata.isEmpty()); } @Test public void testServices() { Map<String, Map<String, Object>> services = dubboServicesMetadata.services(); Assert.assertEquals(1, services.size()); Map<String, Object> demoServiceMeta = services.get( "ServiceBean:org.apache.dubbo.spring.boot.actuate.autoconfigure.DubboEndpointAutoConfigurationTest$DemoService:1.0.0:"); Assert.assertEquals("1.0.0", demoServiceMeta.get("version")); } @Test public void testReferences() { Map<String, Map<String, Object>> references = dubboReferencesMetadata.references(); Assert.assertTrue(references.isEmpty()); } @Test public void testProperties() { SortedMap<String, Object> properties = dubboProperties.properties(); Assert.assertEquals("my-application", properties.get("dubbo.application.id")); Assert.assertEquals("dubbo-demo-application", properties.get("dubbo.application.name")); Assert.assertEquals("my-module", properties.get("dubbo.module.id")); Assert.assertEquals("dubbo-demo-module", properties.get("dubbo.module.name")); Assert.assertEquals("my-registry", properties.get("dubbo.registry.id")); Assert.assertEquals("N/A", properties.get("dubbo.registry.address")); Assert.assertEquals("my-protocol", properties.get("dubbo.protocol.id")); Assert.assertEquals("dubbo", properties.get("dubbo.protocol.name")); Assert.assertEquals("20880", properties.get("dubbo.protocol.port")); Assert.assertEquals("my-provider", properties.get("dubbo.provider.id")); Assert.assertEquals("127.0.0.1", properties.get("dubbo.provider.host")); Assert.assertEquals( "org.apache.dubbo.spring.boot.actuate.autoconfigure", properties.get("dubbo.scan.basePackages")); } @Test public void testHttpEndpoints() throws JsonProcessingException { // testHttpEndpoint("/dubbo", dubboEndpoint::invoke); testHttpEndpoint("/dubbo/configs", dubboConfigsMetadata::configs); testHttpEndpoint("/dubbo/services", dubboServicesMetadata::services); testHttpEndpoint("/dubbo/references", dubboReferencesMetadata::references); testHttpEndpoint("/dubbo/properties", dubboProperties::properties); } private void testHttpEndpoint(String actuatorURI, Supplier<Map> resultsSupplier) throws JsonProcessingException { String actuatorURL = actuatorBaseURL + actuatorURI; String response = restTemplate.getForObject(actuatorURL, String.class); Assert.assertEquals(objectMapper.writeValueAsString(resultsSupplier.get()), response); } interface DemoService { String sayHello(String name); } @DubboService( version = "${dubbo.service.version}", application = "${dubbo.application.id}", protocol = "${dubbo.protocol.id}", registry = "${dubbo.registry.id}") static class DefaultDemoService implements DemoService { public String sayHello(String name) { return "Hello, " + name + " (from Spring Boot)"; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-actuator-autoconfigure-compatible/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboMvcEndpointManagementContextConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-actuator-autoconfigure-compatible/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboMvcEndpointManagementContextConfiguration.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.spring.boot.actuate.autoconfigure; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.mvc.DubboMvcEndpoint; import org.springframework.boot.actuate.autoconfigure.ManagementContextConfiguration; import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.context.annotation.Bean; /** * Dubbo {@link MvcEndpoint} {@link ManagementContextConfiguration} for Spring Boot 1.x * * @since 2.7.0 */ @ManagementContextConfiguration @ConditionalOnClass(name = {"org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter"}) @ConditionalOnWebApplication public class DubboMvcEndpointManagementContextConfiguration { @Bean @ConditionalOnBean(DubboEndpoint.class) @ConditionalOnMissingBean public DubboMvcEndpoint dubboMvcEndpoint(DubboEndpoint dubboEndpoint) { return new DubboMvcEndpoint(dubboEndpoint); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-actuator-autoconfigure-compatible/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAutoConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-actuator-autoconfigure-compatible/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAutoConfiguration.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.spring.boot.actuate.autoconfigure; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboEndpoint; import org.apache.dubbo.spring.boot.autoconfigure.DubboAutoConfiguration; import org.apache.dubbo.spring.boot.autoconfigure.DubboRelaxedBindingAutoConfiguration; import org.springframework.boot.actuate.condition.ConditionalOnEnabledEndpoint; import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * Dubbo {@link Endpoint} Auto Configuration is compatible with Spring Boot Actuator 1.x * * @since 2.7.0 */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @Configuration @ConditionalOnClass( name = {"org.springframework.boot.actuate.endpoint.Endpoint" // Spring Boot 1.x }) @AutoConfigureAfter(value = {DubboAutoConfiguration.class, DubboRelaxedBindingAutoConfiguration.class}) @EnableConfigurationProperties(DubboEndpoint.class) public class DubboEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnEnabledEndpoint(value = "dubbo") public DubboEndpoint dubboEndpoint() { return new DubboEndpoint(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-actuator-autoconfigure-compatible/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboEndpoint.java
dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-actuator-autoconfigure-compatible/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboEndpoint.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.spring.boot.actuate.endpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboMetadata; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.AbstractEndpoint; import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Actuator {@link Endpoint} to expose Dubbo Meta Data * * @see Endpoint * @since 2.7.0 */ @ConfigurationProperties(prefix = "endpoints.dubbo", ignoreUnknownFields = false) public class DubboEndpoint extends AbstractEndpoint<Map<String, Object>> { @Autowired private DubboMetadata dubboMetadata; public DubboEndpoint() { super("dubbo", true, false); } @Override public Map<String, Object> invoke() { return dubboMetadata.invoke(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-actuator-autoconfigure-compatible/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/mvc/DubboMvcEndpoint.java
dubbo-spring-boot-project/dubbo-spring-boot-compatible/dubbo-spring-boot-actuator-autoconfigure-compatible/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/mvc/DubboMvcEndpoint.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.spring.boot.actuate.endpoint.mvc; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboConfigsMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboPropertiesMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboReferencesMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboServicesMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboShutdownMetadata; import java.util.Map; import java.util.SortedMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter; import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.async.DeferredResult; /** * {@link MvcEndpoint} to expose Dubbo Metadata * * @see MvcEndpoint * @since 2.7.0 */ public class DubboMvcEndpoint extends EndpointMvcAdapter { public static final String DUBBO_SHUTDOWN_ENDPOINT_URI = "/shutdown"; public static final String DUBBO_CONFIGS_ENDPOINT_URI = "/configs"; public static final String DUBBO_SERVICES_ENDPOINT_URI = "/services"; public static final String DUBBO_REFERENCES_ENDPOINT_URI = "/references"; public static final String DUBBO_PROPERTIES_ENDPOINT_URI = "/properties"; private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private DubboShutdownMetadata dubboShutdownMetadata; @Autowired private DubboConfigsMetadata dubboConfigsMetadata; @Autowired private DubboServicesMetadata dubboServicesMetadata; @Autowired private DubboReferencesMetadata dubboReferencesMetadata; @Autowired private DubboPropertiesMetadata dubboPropertiesMetadata; public DubboMvcEndpoint(DubboEndpoint dubboEndpoint) { super(dubboEndpoint); } @RequestMapping( value = DUBBO_SHUTDOWN_ENDPOINT_URI, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public DeferredResult shutdown() throws Exception { Map<String, Object> shutdownCountData = dubboShutdownMetadata.shutdown(); return new DeferredResult(null, shutdownCountData); } @RequestMapping( value = DUBBO_CONFIGS_ENDPOINT_URI, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map<String, Map<String, Map<String, Object>>> configs() { return dubboConfigsMetadata.configs(); } @RequestMapping( value = DUBBO_SERVICES_ENDPOINT_URI, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map<String, Map<String, Object>> services() { return dubboServicesMetadata.services(); } @RequestMapping( value = DUBBO_REFERENCES_ENDPOINT_URI, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map<String, Map<String, Object>> references() { return dubboReferencesMetadata.references(); } @RequestMapping( value = DUBBO_PROPERTIES_ENDPOINT_URI, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public SortedMap<String, Object> properties() { return dubboPropertiesMetadata.properties(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-3-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/SpringBoot3Condition.java
dubbo-spring-boot-project/dubbo-spring-boot-3-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/SpringBoot3Condition.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.spring.boot.autoconfigure; import org.springframework.boot.SpringBootVersion; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class SpringBoot3Condition implements Condition { public static boolean IS_SPRING_BOOT_3 = SpringBootVersion.getVersion().charAt(0) >= '3'; @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return IS_SPRING_BOOT_3; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-3-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboTriple3AutoConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-3-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboTriple3AutoConfiguration.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.spring.boot.autoconfigure; import org.apache.dubbo.rpc.protocol.tri.ServletExchanger; import org.apache.dubbo.rpc.protocol.tri.servlet.jakarta.TripleFilter; import org.apache.dubbo.rpc.protocol.tri.websocket.jakarta.TripleWebSocketFilter; import jakarta.servlet.Filter; import org.apache.coyote.ProtocolHandler; import org.apache.coyote.UpgradeProtocol; import org.apache.coyote.http2.Http2Protocol; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; import org.springframework.boot.web.embedded.tomcat.ConfigurableTomcatWebServerFactory; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) @Conditional(SpringBoot3Condition.class) public class DubboTriple3AutoConfiguration { public static final String SERVLET_PREFIX = "dubbo.protocol.triple.servlet"; public static final String WEBSOCKET_PREFIX = "dubbo.protocol.triple.websocket"; @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Filter.class) @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnProperty(prefix = SERVLET_PREFIX, name = "enabled", havingValue = "true") public static class TripleServletConfiguration { @Bean public FilterRegistrationBean<TripleFilter> tripleProtocolFilter( @Value("${" + SERVLET_PREFIX + ".filter-url-patterns:/*}") String[] urlPatterns, @Value("${" + SERVLET_PREFIX + ".filter-order:-1000000}") int order, @Value("${server.port:8080}") int serverPort) { ServletExchanger.bindServerPort(serverPort); FilterRegistrationBean<TripleFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(new TripleFilter()); registrationBean.addUrlPatterns(urlPatterns); registrationBean.setOrder(order); return registrationBean; } @Bean @ConditionalOnClass(Http2Protocol.class) @ConditionalOnProperty(prefix = SERVLET_PREFIX, name = "max-concurrent-streams") public WebServerFactoryCustomizer<ConfigurableTomcatWebServerFactory> tripleTomcatHttp2Customizer( @Value("${" + SERVLET_PREFIX + ".max-concurrent-streams}") int maxConcurrentStreams) { return factory -> factory.addConnectorCustomizers(connector -> { ProtocolHandler handler = connector.getProtocolHandler(); for (UpgradeProtocol upgradeProtocol : handler.findUpgradeProtocols()) { if (upgradeProtocol instanceof Http2Protocol) { Http2Protocol protocol = (Http2Protocol) upgradeProtocol; int value = maxConcurrentStreams <= 0 ? Integer.MAX_VALUE : maxConcurrentStreams; protocol.setMaxConcurrentStreams(value); protocol.setMaxConcurrentStreamExecution(value); } } }); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Filter.class) @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnProperty(prefix = WEBSOCKET_PREFIX, name = "enabled", havingValue = "true") public static class TripleWebSocketConfiguration { @Bean public FilterRegistrationBean<TripleWebSocketFilter> tripleWebSocketFilter( @Value("${" + WEBSOCKET_PREFIX + ".filter-url-patterns:/*}") String[] urlPatterns, @Value("${" + WEBSOCKET_PREFIX + ".filter-order:-1000000}") int order, @Value("${server.port:8080}") int serverPort) { ServletExchanger.bindServerPort(serverPort); FilterRegistrationBean<TripleWebSocketFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(new TripleWebSocketFilter()); registrationBean.addUrlPatterns(urlPatterns); registrationBean.setOrder(order); return registrationBean; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/test/java/org/apache/dubbo/spring/boot/util/DubboUtilsTest.java
dubbo-spring-boot-project/dubbo-spring-boot/src/test/java/org/apache/dubbo/spring/boot/util/DubboUtilsTest.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.spring.boot.util; import org.junit.jupiter.api.Test; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_PROPERTY_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE; import static org.apache.dubbo.spring.boot.util.DubboUtils.DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_APPLICATION_ID_PROPERTY; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_APPLICATION_NAME_PROPERTY; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_APPLICATION_QOS_ENABLE_PROPERTY; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_CONFIG_MULTIPLE_PROPERTY; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_CONFIG_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_GITHUB_URL; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_MAILING_LIST; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SCAN_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SPRING_BOOT_GITHUB_URL; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SPRING_BOOT_GIT_URL; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SPRING_BOOT_ISSUES_URL; import static org.apache.dubbo.spring.boot.util.DubboUtils.MULTIPLE_CONFIG_PROPERTY_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.OVERRIDE_CONFIG_FULL_PROPERTY_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.SPRING_APPLICATION_NAME_PROPERTY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link DubboUtils} Test * * @see DubboUtils * @since 2.7.0 */ class DubboUtilsTest { @Test void testConstants() { assertEquals("dubbo", DUBBO_PREFIX); assertEquals("dubbo.scan.", DUBBO_SCAN_PREFIX); assertEquals("base-packages", BASE_PACKAGES_PROPERTY_NAME); assertEquals("dubbo.config.", DUBBO_CONFIG_PREFIX); assertEquals("multiple", MULTIPLE_CONFIG_PROPERTY_NAME); assertEquals("dubbo.config.override", OVERRIDE_CONFIG_FULL_PROPERTY_NAME); assertEquals("https://github.com/apache/dubbo/tree/3.0/dubbo-spring-boot", DUBBO_SPRING_BOOT_GITHUB_URL); assertEquals("https://github.com/apache/dubbo.git", DUBBO_SPRING_BOOT_GIT_URL); assertEquals("https://github.com/apache/dubbo/issues", DUBBO_SPRING_BOOT_ISSUES_URL); assertEquals("https://github.com/apache/dubbo", DUBBO_GITHUB_URL); assertEquals("dev@dubbo.apache.org", DUBBO_MAILING_LIST); assertEquals("spring.application.name", SPRING_APPLICATION_NAME_PROPERTY); assertEquals("dubbo.application.id", DUBBO_APPLICATION_ID_PROPERTY); assertEquals("dubbo.application.name", DUBBO_APPLICATION_NAME_PROPERTY); assertEquals("dubbo.application.qos-enable", DUBBO_APPLICATION_QOS_ENABLE_PROPERTY); assertEquals("dubbo.config.multiple", DUBBO_CONFIG_MULTIPLE_PROPERTY); assertTrue(DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE); assertTrue(DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/test/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessorTest.java
dubbo-spring-boot-project/dubbo-spring-boot/src/test/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessorTest.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.spring.boot.env; import java.util.HashMap; import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; import org.springframework.core.Ordered; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.mock.env.MockEnvironment; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * {@link DubboDefaultPropertiesEnvironmentPostProcessor} Test */ class DubboDefaultPropertiesEnvironmentPostProcessorTest { private DubboDefaultPropertiesEnvironmentPostProcessor instance = new DubboDefaultPropertiesEnvironmentPostProcessor(); private SpringApplication springApplication = new SpringApplication(); @Test void testOrder() { assertEquals(Ordered.LOWEST_PRECEDENCE, instance.getOrder()); } @Test void testPostProcessEnvironment() { MockEnvironment environment = new MockEnvironment(); // Case 1 : Not Any property instance.postProcessEnvironment(environment, springApplication); // Get PropertySources MutablePropertySources propertySources = environment.getPropertySources(); // Nothing to change PropertySource defaultPropertySource = propertySources.get("defaultProperties"); assertNotNull(defaultPropertySource); assertEquals("true", defaultPropertySource.getProperty("dubbo.config.multiple")); // assertEquals("true", defaultPropertySource.getProperty("dubbo.application.qos-enable")); // Case 2 : Only set property "spring.application.name" environment.setProperty("spring.application.name", "demo-dubbo-application"); instance.postProcessEnvironment(environment, springApplication); defaultPropertySource = propertySources.get("defaultProperties"); Object dubboApplicationName = defaultPropertySource.getProperty("dubbo.application.name"); assertEquals("demo-dubbo-application", dubboApplicationName); // Case 3 : Only set property "dubbo.application.name" // Reset environment environment = new MockEnvironment(); propertySources = environment.getPropertySources(); environment.setProperty("dubbo.application.name", "demo-dubbo-application"); instance.postProcessEnvironment(environment, springApplication); defaultPropertySource = propertySources.get("defaultProperties"); assertNotNull(defaultPropertySource); dubboApplicationName = environment.getProperty("dubbo.application.name"); assertEquals("demo-dubbo-application", dubboApplicationName); // Case 4 : If "defaultProperties" PropertySource is present in PropertySources // Reset environment environment = new MockEnvironment(); propertySources = environment.getPropertySources(); propertySources.addLast(new MapPropertySource("defaultProperties", new HashMap<String, Object>())); environment.setProperty("spring.application.name", "demo-dubbo-application"); instance.postProcessEnvironment(environment, springApplication); defaultPropertySource = propertySources.get("defaultProperties"); dubboApplicationName = defaultPropertySource.getProperty("dubbo.application.name"); assertEquals("demo-dubbo-application", dubboApplicationName); // Case 5 : Reset dubbo.config.multiple and dubbo.application.qos-enable environment = new MockEnvironment(); propertySources = environment.getPropertySources(); propertySources.addLast(new MapPropertySource("defaultProperties", new HashMap<String, Object>())); environment.setProperty("dubbo.config.multiple", "false"); environment.setProperty("dubbo.application.qos-enable", "false"); instance.postProcessEnvironment(environment, springApplication); assertEquals("false", environment.getProperty("dubbo.config.multiple")); assertEquals("false", environment.getProperty("dubbo.application.qos-enable")); // Case 6 : Test virtual thread property when spring.threads.virtual.enabled=true environment = new MockEnvironment(); propertySources = environment.getPropertySources(); propertySources.addLast(new MapPropertySource("defaultProperties", new HashMap<String, Object>())); environment.setProperty("spring.threads.virtual.enabled", "true"); instance.postProcessEnvironment(environment, springApplication); defaultPropertySource = propertySources.get("defaultProperties"); assertNotNull(defaultPropertySource); assertEquals("virtual", defaultPropertySource.getProperty("dubbo.protocol.threadpool")); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/test/java/org/apache/dubbo/spring/boot/context/event/WelcomeLogoApplicationListenerTest.java
dubbo-spring-boot-project/dubbo-spring-boot/src/test/java/org/apache/dubbo/spring/boot/context/event/WelcomeLogoApplicationListenerTest.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.spring.boot.context.event; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * {@link WelcomeLogoApplicationListener} Test * * @see WelcomeLogoApplicationListener * @since 2.7.0 */ @ExtendWith(SpringExtension.class) @SpringBootTest(classes = {WelcomeLogoApplicationListener.class}) class WelcomeLogoApplicationListenerTest { @Autowired private WelcomeLogoApplicationListener welcomeLogoApplicationListener; @Test void testOnApplicationEvent() { assertNotNull(welcomeLogoApplicationListener.buildBannerText()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/test/java/org/apache/dubbo/spring/boot/context/event/DubboNetInterfaceConfigApplicationListenerTest.java
dubbo-spring-boot-project/dubbo-spring-boot/src/test/java/org/apache/dubbo/spring/boot/context/event/DubboNetInterfaceConfigApplicationListenerTest.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.spring.boot.context.event; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; import org.springframework.context.ApplicationListener; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_NETWORK_IGNORED_INTERFACE; import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_PREFERRED_NETWORK_INTERFACE; import static org.junit.jupiter.api.Assertions.assertEquals; /** * @since 3.3 */ public class DubboNetInterfaceConfigApplicationListenerTest { private static final String USE_NETWORK_INTERFACE_NAME = "eth0"; private static final String IGNORED_NETWORK_INTERFACE_NAME = "eth1"; @Test public void testOnApplicationEvent() { SpringApplicationBuilder builder = new SpringApplicationBuilder(DubboNetInterfaceConfigApplicationListenerTest.class); builder.listeners(new NetworkInterfaceApplicationListener()); builder.web(WebApplicationType.NONE); SpringApplication application = builder.build(); application.run(); String preferredNetworkInterface = SystemPropertyConfigUtils.getSystemProperty(DUBBO_PREFERRED_NETWORK_INTERFACE); String ignoredNetworkInterface = SystemPropertyConfigUtils.getSystemProperty(DUBBO_NETWORK_IGNORED_INTERFACE); assertEquals(USE_NETWORK_INTERFACE_NAME, preferredNetworkInterface); assertEquals(IGNORED_NETWORK_INTERFACE_NAME, ignoredNetworkInterface); } static class NetworkInterfaceApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> { @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent applicationEnvironmentPreparedEvent) { ConfigurableEnvironment environment = applicationEnvironmentPreparedEvent.getEnvironment(); MutablePropertySources propertySources = environment.getPropertySources(); Map<String, Object> map = new HashMap<>(); map.put(DUBBO_PREFERRED_NETWORK_INTERFACE, USE_NETWORK_INTERFACE_NAME); map.put(DUBBO_NETWORK_IGNORED_INTERFACE, IGNORED_NETWORK_INTERFACE_NAME); propertySources.addLast(new MapPropertySource("networkInterfaceConfig", map)); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/test/java/org/apache/dubbo/spring/boot/context/event/AwaitingNonWebApplicationListenerTest.java
dubbo-spring-boot-project/dubbo-spring-boot/src/test/java/org/apache/dubbo/spring/boot/context/event/AwaitingNonWebApplicationListenerTest.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.spring.boot.context.event; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; /** * {@link AwaitingNonWebApplicationListener} Test */ @Disabled class AwaitingNonWebApplicationListenerTest { @BeforeEach void before() { DubboBootstrap.reset(); } @AfterEach void after() { DubboBootstrap.reset(); } // @Test // void init() { // AtomicBoolean awaited = AwaitingNonWebApplicationListener.getAwaited(); // awaited.set(false); // } // // @Test // void testSingleContextNonWebApplication() { // new SpringApplicationBuilder(Object.class) // .web(false) // .run() // .close(); // // ShutdownHookCallbacks.INSTANCE.addCallback(() -> { // AtomicBoolean awaited = AwaitingNonWebApplicationListener.getAwaited(); // assertTrue(awaited.get()); // System.out.println("Callback..."); // }); // } // // @Test // void testMultipleContextNonWebApplication() { // new SpringApplicationBuilder(Object.class) // .parent(Object.class) // .web(false) // .run().close(); // AtomicBoolean awaited = AwaitingNonWebApplicationListener.getAwaited(); // assertFalse(awaited.get()); // } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/test/java/org/apache/dubbo/spring/boot/context/event/DubboConfigBeanDefinitionConflictApplicationListenerTest.java
dubbo-spring-boot-project/dubbo-spring-boot/src/test/java/org/apache/dubbo/spring/boot/context/event/DubboConfigBeanDefinitionConflictApplicationListenerTest.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.spring.boot.context.event; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.PropertySource; import static org.junit.jupiter.api.Assertions.assertEquals; /** * {@link DubboConfigBeanDefinitionConflictApplicationListener} Test * * @since 2.7.5 */ class DubboConfigBeanDefinitionConflictApplicationListenerTest { @BeforeEach void init() { DubboBootstrap.reset(); // context.addApplicationListener(new DubboConfigBeanDefinitionConflictApplicationListener()); } @AfterEach void destroy() { DubboBootstrap.reset(); } // @Test void testNormalCase() { System.setProperty("dubbo.application.name", "test-dubbo-application"); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DubboConfig.class); try { context.start(); ApplicationConfig applicationConfig = context.getBean(ApplicationConfig.class); assertEquals("test-dubbo-application", applicationConfig.getName()); } finally { System.clearProperty("dubbo.application.name"); context.close(); } } @Test void testDuplicatedConfigsCase() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PropertySourceConfig.class, DubboConfig.class, XmlConfig.class); try { context.start(); Map<String, ApplicationConfig> beansMap = context.getBeansOfType(ApplicationConfig.class); ApplicationConfig applicationConfig = beansMap.get("dubbo-consumer-2.7.x"); assertEquals(1, beansMap.size()); assertEquals("dubbo-consumer-2.7.x", applicationConfig.getName()); } finally { context.close(); } } @EnableDubboConfig static class DubboConfig {} @PropertySource("classpath:/META-INF/dubbo.properties") static class PropertySourceConfig {} @ImportResource("classpath:/META-INF/spring/dubbo-context.xml") static class XmlConfig {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/util/DubboUtils.java
dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/util/DubboUtils.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.spring.boot.util; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; import org.apache.dubbo.config.spring.context.properties.DubboConfigBinder; import java.util.Set; import org.springframework.boot.context.ContextIdApplicationContextInitializer; import org.springframework.core.env.PropertyResolver; import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.SYSTEM_LINE_SEPARATOR; /** * The utilities class for Dubbo * * @since 2.7.0 */ public abstract class DubboUtils { /** * line separator */ public static final String LINE_SEPARATOR = SystemPropertyConfigUtils.getSystemProperty(SYSTEM_LINE_SEPARATOR); /** * The separator of property name */ public static final String PROPERTY_NAME_SEPARATOR = "."; /** * The prefix of property name of Dubbo */ public static final String DUBBO_PREFIX = "dubbo"; /** * The prefix of property name for Dubbo scan */ public static final String DUBBO_SCAN_PREFIX = DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR + "scan" + PROPERTY_NAME_SEPARATOR; /** * The prefix of property name for Dubbo Config */ public static final String DUBBO_CONFIG_PREFIX = DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR + "config" + PROPERTY_NAME_SEPARATOR; /** * The property name of base packages to scan * <p> * The default value is empty set. */ public static final String BASE_PACKAGES_PROPERTY_NAME = "base-packages"; /** * The property name of multiple properties binding from externalized configuration * <p> * The default value is {@link #DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE} * * @deprecated 2.7.8 It will be remove in the future, {@link EnableDubboConfig} instead */ @Deprecated public static final String MULTIPLE_CONFIG_PROPERTY_NAME = "multiple"; /** * The default value of multiple properties binding from externalized configuration * * @deprecated 2.7.8 It will be remove in the future */ @Deprecated public static final boolean DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE = true; /** * The property name of override Dubbo config * <p> * The default value is {@link #DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE} */ public static final String OVERRIDE_CONFIG_FULL_PROPERTY_NAME = DUBBO_CONFIG_PREFIX + "override"; /** * The default property value of override Dubbo config */ public static final boolean DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE = true; /** * The github URL of Dubbo Spring Boot */ public static final String DUBBO_SPRING_BOOT_GITHUB_URL = "https://github.com/apache/dubbo/tree/3.0/dubbo-spring-boot"; /** * The git URL of Dubbo Spring Boot */ public static final String DUBBO_SPRING_BOOT_GIT_URL = "https://github.com/apache/dubbo.git"; /** * The issues of Dubbo Spring Boot */ public static final String DUBBO_SPRING_BOOT_ISSUES_URL = "https://github.com/apache/dubbo/issues"; /** * The github URL of Dubbo */ public static final String DUBBO_GITHUB_URL = "https://github.com/apache/dubbo"; /** * The google group URL of Dubbo */ public static final String DUBBO_MAILING_LIST = "dev@dubbo.apache.org"; /** * The bean name of Relaxed-binding {@link DubboConfigBinder} */ public static final String RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME = "relaxedDubboConfigBinder"; /** * The bean name of {@link PropertyResolver} for {@link ServiceAnnotationPostProcessor}'s base-packages * * @deprecated 2.7.8 It will be remove in the future, please use {@link #BASE_PACKAGES_BEAN_NAME} */ @Deprecated public static final String BASE_PACKAGES_PROPERTY_RESOLVER_BEAN_NAME = "dubboScanBasePackagesPropertyResolver"; /** * The bean name of {@link Set} presenting {@link ServiceAnnotationPostProcessor}'s base-packages * * @since 2.7.8 */ public static final String BASE_PACKAGES_BEAN_NAME = "dubbo-service-class-base-packages"; /** * The property name of Spring Application * * @see ContextIdApplicationContextInitializer * @since 2.7.1 */ public static final String SPRING_APPLICATION_NAME_PROPERTY = "spring.application.name"; /** * The property id of {@link ApplicationConfig} Bean * * @see EnableDubboConfig * @since 2.7.1 */ public static final String DUBBO_APPLICATION_ID_PROPERTY = "dubbo.application.id"; /** * The property name of {@link ApplicationConfig} * * @see EnableDubboConfig * @since 2.7.1 */ public static final String DUBBO_APPLICATION_NAME_PROPERTY = "dubbo.application.name"; /** * The property name of {@link ApplicationConfig#getQosEnable() application's QOS enable} * * @since 2.7.1 */ public static final String DUBBO_APPLICATION_QOS_ENABLE_PROPERTY = "dubbo.application.qos-enable"; /** * The property name of {@link EnableDubboConfig#multiple() @EnableDubboConfig.multiple()} * * @since 2.7.1 */ public static final String DUBBO_CONFIG_MULTIPLE_PROPERTY = "dubbo.config.multiple"; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessor.java
dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessor.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.spring.boot.env; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.springframework.boot.SpringApplication; import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.Ordered; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_APPLICATION_NAME_PROPERTY; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_CONFIG_MULTIPLE_PROPERTY; import static org.apache.dubbo.spring.boot.util.DubboUtils.SPRING_APPLICATION_NAME_PROPERTY; /** * The lowest precedence {@link EnvironmentPostProcessor} processes * {@link SpringApplication#setDefaultProperties(Properties) Spring Boot default properties} for Dubbo * as late as possible before {@link ConfigurableApplicationContext#refresh() application context refresh}. */ public class DubboDefaultPropertiesEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { /** * The name of default {@link PropertySource} defined in SpringApplication#configurePropertySources method. */ public static final String PROPERTY_SOURCE_NAME = "defaultProperties"; /** * The property name of "spring.main.allow-bean-definition-overriding". * Please refer to: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.1-Release-Notes#bean-overriding */ public static final String ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY = "spring.main.allow-bean-definition-overriding"; public static final String DUBBO_THREAD_POOL_PROPERTY = "dubbo.protocol.threadpool"; public static final String VIRTUAL_THREAD = "virtual"; public static final String SPRING_THREAD_POOL_PROPERTY = "spring.threads.virtual.enabled"; private static final String ENABLED_VALUE = "true"; @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { MutablePropertySources propertySources = environment.getPropertySources(); Map<String, Object> defaultProperties = createDefaultProperties(environment); if (!CollectionUtils.isEmpty(defaultProperties)) { addOrReplace(propertySources, defaultProperties); } } @Override public int getOrder() { return LOWEST_PRECEDENCE; } private Map<String, Object> createDefaultProperties(ConfigurableEnvironment environment) { Map<String, Object> defaultProperties = new HashMap<>(); setDubboApplicationNameProperty(environment, defaultProperties); setDubboConfigMultipleProperty(defaultProperties); setDubboVirtualThreadsProperty(environment, defaultProperties); return defaultProperties; } private void setDubboVirtualThreadsProperty(Environment environment, Map<String, Object> defaultProperties) { String virtualEnabled = environment.getProperty(SPRING_THREAD_POOL_PROPERTY); if (ENABLED_VALUE.equals(virtualEnabled)) { defaultProperties.put(DUBBO_THREAD_POOL_PROPERTY, VIRTUAL_THREAD); } } private void setDubboApplicationNameProperty(Environment environment, Map<String, Object> defaultProperties) { String springApplicationName = environment.getProperty(SPRING_APPLICATION_NAME_PROPERTY); if (StringUtils.hasLength(springApplicationName) && !environment.containsProperty(DUBBO_APPLICATION_NAME_PROPERTY)) { defaultProperties.put(DUBBO_APPLICATION_NAME_PROPERTY, springApplicationName); } } private void setDubboConfigMultipleProperty(Map<String, Object> defaultProperties) { defaultProperties.put(DUBBO_CONFIG_MULTIPLE_PROPERTY, Boolean.TRUE.toString()); } /** * Set {@link #ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY "spring.main.allow-bean-definition-overriding"} to be * <code>true</code> as default. * * @param defaultProperties the default {@link Properties properties} * @see #ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY * @since 2.7.1 */ private void setAllowBeanDefinitionOverriding(Map<String, Object> defaultProperties) { defaultProperties.put(ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY, Boolean.TRUE.toString()); } /** * Copy from BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map) * * @param propertySources {@link MutablePropertySources} * @param map Default Dubbo Properties */ private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) { MapPropertySource target = null; if (propertySources.contains(PROPERTY_SOURCE_NAME)) { PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME); if (source instanceof MapPropertySource) { target = (MapPropertySource) source; for (Map.Entry<String, Object> entry : map.entrySet()) { String key = entry.getKey(); if (!target.containsProperty(key)) { target.getSource().put(key, entry.getValue()); } } } } if (target == null) { target = new MapPropertySource(PROPERTY_SOURCE_NAME, map); } if (!propertySources.contains(PROPERTY_SOURCE_NAME)) { propertySources.addLast(target); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/interceptor/DubboTagHeaderOrParameterInterceptor.java
dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/interceptor/DubboTagHeaderOrParameterInterceptor.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.spring.boot.interceptor; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.rpc.RpcContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; public class DubboTagHeaderOrParameterInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String tag = request.getHeader(CommonConstants.DUBBO_TAG_HEADER); if (tag == null) { tag = request.getParameter(CommonConstants.TAG_KEY); } if (tag != null) { RpcContext.getClientAttachment().setAttachment(CommonConstants.TAG_KEY, tag); } return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { RpcContext.getClientAttachment().removeAttachment(CommonConstants.TAG_KEY); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/interceptor/DubboTagCookieInterceptor.java
dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/interceptor/DubboTagCookieInterceptor.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.spring.boot.interceptor; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.rpc.RpcContext; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; public class DubboTagCookieInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String tag = getSingleCookieValue(request.getCookies(), CommonConstants.TAG_KEY); RpcContext.getClientAttachment().setAttachment(CommonConstants.TAG_KEY, tag); return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { RpcContext.getClientAttachment().removeAttachment(CommonConstants.TAG_KEY); } private static String getSingleCookieValue(Cookie[] cookies, String name) { if (cookies == null || cookies.length == 0) { return null; } for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return cookie.getValue(); } } return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/config/ServiceBeanIdConflictProcessor.java
dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/config/ServiceBeanIdConflictProcessor.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.spring.boot.config; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.config.spring.reference.ReferenceAttributes; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import org.springframework.beans.BeansException; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor; import org.springframework.core.Ordered; import org.springframework.core.PriorityOrdered; import static org.apache.dubbo.config.spring.util.SpringCompatUtils.getPropertyValue; import static org.springframework.util.ClassUtils.getUserClass; import static org.springframework.util.ClassUtils.isAssignable; /** * The post-processor for resolving the id conflict of {@link ServiceBean} when an interface is * implemented by multiple services with different groups or versions that are exported on one provider * <p> * Current implementation is a temporary resolution, and will be removed in the future. * * @see CommonAnnotationBeanPostProcessor * @since 2.7.7 * @deprecated */ public class ServiceBeanIdConflictProcessor implements MergedBeanDefinitionPostProcessor, DisposableBean, PriorityOrdered { /** * The key is the class names of interfaces that were exported by {@link ServiceBean} * The value is bean names of {@link ServiceBean} or {@link ServiceConfig}. */ private Map<String, String> interfaceNamesToBeanNames = new HashMap<>(); /** * Holds the bean names of {@link ServiceBean} or {@link ServiceConfig}. */ private Set<String> conflictedBeanNames = new HashSet<>(); @Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) { // Get raw bean type Class<?> rawBeanType = getUserClass(beanType); if (isAssignable(ServiceConfig.class, rawBeanType)) { // ServiceConfig type or sub-type String interfaceName = getPropertyValue(beanDefinition.getPropertyValues(), ReferenceAttributes.INTERFACE); String mappedBeanName = interfaceNamesToBeanNames.putIfAbsent(interfaceName, beanName); // If mapped bean name exists and does not equal current bean name if (mappedBeanName != null && !mappedBeanName.equals(beanName)) { // conflictedBeanNames will record current bean name. conflictedBeanNames.add(beanName); } } } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (conflictedBeanNames.contains(beanName) && bean instanceof ServiceConfig) { ServiceConfig serviceConfig = (ServiceConfig) bean; if (isConflictedServiceConfig(serviceConfig)) { // Set id as the bean name serviceConfig.setId(beanName); } } return bean; } private boolean isConflictedServiceConfig(ServiceConfig serviceConfig) { return Objects.equals(serviceConfig.getId(), serviceConfig.getInterface()); } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } /** * Keep the order being higher than {@link CommonAnnotationBeanPostProcessor#getOrder()} that is * {@link Ordered#LOWEST_PRECEDENCE} * * @return {@link Ordered#LOWEST_PRECEDENCE} +1 */ @Override public int getOrder() { return LOWEST_PRECEDENCE + 1; } @Override public void destroy() throws Exception { interfaceNamesToBeanNames.clear(); conflictedBeanNames.clear(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/context/DubboApplicationContextInitializer.java
dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/context/DubboApplicationContextInitializer.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.spring.boot.context; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.Ordered; /** * Dubbo {@link ApplicationContextInitializer} implementation * * @see ApplicationContextInitializer * @since 2.7.1 */ public class DubboApplicationContextInitializer implements ApplicationContextInitializer, Ordered { @Override public void initialize(ConfigurableApplicationContext applicationContext) { overrideBeanDefinitions(applicationContext); } private void overrideBeanDefinitions(ConfigurableApplicationContext applicationContext) { // @since 2.7.8 OverrideBeanDefinitionRegistryPostProcessor has been removed // applicationContext.addBeanFactoryPostProcessor(new OverrideBeanDefinitionRegistryPostProcessor()); // @since 2.7.5 DubboConfigBeanDefinitionConflictProcessor has been removed // @see {@link DubboConfigBeanDefinitionConflictApplicationListener} // applicationContext.addBeanFactoryPostProcessor(new DubboConfigBeanDefinitionConflictProcessor()); // TODO Add some components in the future ( after 2.7.8 ) } @Override public int getOrder() { return HIGHEST_PRECEDENCE; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/context/event/AwaitingNonWebApplicationListener.java
dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/context/event/AwaitingNonWebApplicationListener.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.spring.boot.context.event; import org.apache.dubbo.common.lang.ShutdownHookCallbacks; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.event.ApplicationFailedEvent; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.SmartApplicationListener; import org.springframework.util.ClassUtils; import static java.util.concurrent.Executors.newSingleThreadExecutor; import static org.springframework.util.ObjectUtils.containsElement; /** * Awaiting Non-Web Spring Boot {@link ApplicationListener} * * @since 2.7.0 */ public class AwaitingNonWebApplicationListener implements SmartApplicationListener { private static final String[] WEB_APPLICATION_CONTEXT_CLASSES = new String[] { "org.springframework.web.context.WebApplicationContext", "org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext" }; private static final Logger logger = LoggerFactory.getLogger(AwaitingNonWebApplicationListener.class); private static final Class<? extends ApplicationEvent>[] SUPPORTED_APPLICATION_EVENTS = of(ApplicationReadyEvent.class, ContextClosedEvent.class); private final AtomicBoolean awaited = new AtomicBoolean(false); private static final Integer UNDEFINED_ID = Integer.valueOf(-1); /** * Target the application id */ private final AtomicInteger applicationContextId = new AtomicInteger(UNDEFINED_ID); private final Lock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); private final ExecutorService executorService = newSingleThreadExecutor(); private static <T> T[] of(T... values) { return values; } AtomicBoolean getAwaited() { return awaited; } @Override public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) { return containsElement(SUPPORTED_APPLICATION_EVENTS, eventType); } @Override public boolean supportsSourceType(Class<?> sourceType) { return true; } @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationReadyEvent) { onApplicationReadyEvent((ApplicationReadyEvent) event); } if (event instanceof ApplicationFailedEvent) { awaitAndRelease(((ApplicationFailedEvent) event).getApplicationContext()); } } @Override public int getOrder() { return LOWEST_PRECEDENCE; } protected void onApplicationReadyEvent(ApplicationReadyEvent event) { final ConfigurableApplicationContext applicationContext = event.getApplicationContext(); if (!isRootApplicationContext(applicationContext) || isWebApplication(applicationContext)) { return; } if (applicationContextId.compareAndSet(UNDEFINED_ID, applicationContext.hashCode())) { awaitAndRelease(event.getApplicationContext()); } } private void awaitAndRelease(ConfigurableApplicationContext applicationContext) { await(); releaseOnExit(applicationContext); } /** * @param applicationContext * @since 2.7.8 */ private void releaseOnExit(ConfigurableApplicationContext applicationContext) { ApplicationModel applicationModel = DubboBeanUtils.getApplicationModel(applicationContext); if (applicationModel == null) { return; } ShutdownHookCallbacks shutdownHookCallbacks = applicationModel.getBeanFactory().getBean(ShutdownHookCallbacks.class); if (shutdownHookCallbacks != null) { shutdownHookCallbacks.addCallback(this::release); } } private boolean isRootApplicationContext(ApplicationContext applicationContext) { return applicationContext.getParent() == null; } private boolean isWebApplication(ApplicationContext applicationContext) { boolean webApplication = false; for (String contextClass : WEB_APPLICATION_CONTEXT_CLASSES) { if (isAssignable(contextClass, applicationContext.getClass(), applicationContext.getClassLoader())) { webApplication = true; break; } } return webApplication; } private static boolean isAssignable(String target, Class<?> type, ClassLoader classLoader) { try { return ClassUtils.resolveClassName(target, classLoader).isAssignableFrom(type); } catch (Throwable ex) { return false; } } protected void await() { // has been waited, return immediately if (awaited.get()) { return; } if (!executorService.isShutdown()) { executorService.execute(() -> executeMutually(() -> { while (!awaited.get()) { if (logger.isInfoEnabled()) { logger.info(" [Dubbo] Current Spring Boot Application is await..."); } try { condition.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } })); } } protected void release() { executeMutually(() -> { while (awaited.compareAndSet(false, true)) { if (logger.isInfoEnabled()) { logger.info(" [Dubbo] Current Spring Boot Application is about to shutdown..."); } condition.signalAll(); // @since 2.7.8 method shutdown() is combined into the method release() shutdown(); } }); } private void shutdown() { if (!executorService.isShutdown()) { // Shutdown executorService executorService.shutdown(); } } private void executeMutually(Runnable runnable) { try { lock.lock(); runnable.run(); } finally { lock.unlock(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/context/event/DubboOpenAPIExportListener.java
dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/context/event/DubboOpenAPIExportListener.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.spring.boot.context.event; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import org.apache.dubbo.remoting.http12.rest.OpenAPIService; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.concurrent.atomic.AtomicBoolean; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; /** * OpenAPI Export Listener * <p> * This class exports OpenAPI specifications for Dubbo services * when the Spring Boot application is fully started and ready. */ public class DubboOpenAPIExportListener implements ApplicationListener<ApplicationReadyEvent> { private final AtomicBoolean exported = new AtomicBoolean(false); @Override public void onApplicationEvent(ApplicationReadyEvent event) { if (!exported.compareAndSet(false, true)) { return; } ApplicationModel applicationModel = DubboBeanUtils.getApplicationModel(event.getApplicationContext()); if (applicationModel == null) { return; } OpenAPIService openAPIService = applicationModel.getBean(OpenAPIService.class); if (openAPIService != null) { openAPIService.export(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/context/event/WelcomeLogoApplicationListener.java
dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/context/event/WelcomeLogoApplicationListener.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.spring.boot.context.event; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.concurrent.atomic.AtomicBoolean; import org.springframework.boot.context.event.ApplicationContextInitializedEvent; import org.springframework.context.ApplicationListener; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_GITHUB_URL; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_MAILING_LIST; import static org.apache.dubbo.spring.boot.util.DubboUtils.LINE_SEPARATOR; /** * Dubbo Welcome Logo {@link ApplicationListener} * * @see ApplicationListener * @since 2.7.0 */ @Order(Ordered.HIGHEST_PRECEDENCE + 20 + 1) // After LoggingApplicationListener#DEFAULT_ORDER public class WelcomeLogoApplicationListener implements ApplicationListener<ApplicationContextInitializedEvent> { private static AtomicBoolean processed = new AtomicBoolean(false); @Override public void onApplicationEvent(ApplicationContextInitializedEvent event) { // Skip if processed before, prevent duplicated execution in Hierarchical ApplicationContext if (processed.get()) { return; } /** * Gets Logger After LoggingSystem configuration ready * @see LoggingApplicationListener */ final Logger logger = LoggerFactory.getLogger(getClass()); String bannerText = buildBannerText(); if (logger.isInfoEnabled()) { logger.info(bannerText); } // mark processed to be true processed.compareAndSet(false, true); } String buildBannerText() { StringBuilder bannerTextBuilder = new StringBuilder(); bannerTextBuilder .append(LINE_SEPARATOR) .append(LINE_SEPARATOR) .append(" :: Dubbo (v") .append(Version.getVersion()) .append(") : ") .append(DUBBO_GITHUB_URL) .append(LINE_SEPARATOR) .append(" :: Discuss group : ") .append(DUBBO_MAILING_LIST) .append(LINE_SEPARATOR); return bannerTextBuilder.toString(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/context/event/DubboNetInterfaceConfigApplicationListener.java
dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/context/event/DubboNetInterfaceConfigApplicationListener.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.spring.boot.context.event; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.StringUtils; import org.springframework.boot.context.event.ApplicationContextInitializedEvent; import org.springframework.context.ApplicationListener; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.core.env.ConfigurableEnvironment; /** * @since 3.3 */ @Order(Ordered.HIGHEST_PRECEDENCE + 20) // After LoggingApplicationListener#DEFAULT_ORDER public class DubboNetInterfaceConfigApplicationListener implements ApplicationListener<ApplicationContextInitializedEvent> { @Override public void onApplicationEvent(ApplicationContextInitializedEvent event) { ConfigurableEnvironment environment = event.getApplicationContext().getEnvironment(); String preferredNetworkInterface = System.getProperty(CommonConstants.DubboProperty.DUBBO_PREFERRED_NETWORK_INTERFACE); if (StringUtils.isBlank(preferredNetworkInterface)) { preferredNetworkInterface = environment.getProperty(CommonConstants.DubboProperty.DUBBO_PREFERRED_NETWORK_INTERFACE); if (StringUtils.isNotBlank(preferredNetworkInterface)) { System.setProperty( CommonConstants.DubboProperty.DUBBO_PREFERRED_NETWORK_INTERFACE, preferredNetworkInterface); } } String ignoredNetworkInterface = System.getProperty(CommonConstants.DubboProperty.DUBBO_NETWORK_IGNORED_INTERFACE); if (StringUtils.isBlank(ignoredNetworkInterface)) { ignoredNetworkInterface = environment.getProperty(CommonConstants.DubboProperty.DUBBO_NETWORK_IGNORED_INTERFACE); if (StringUtils.isNotBlank(ignoredNetworkInterface)) { System.setProperty( CommonConstants.DubboProperty.DUBBO_NETWORK_IGNORED_INTERFACE, ignoredNetworkInterface); } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/context/event/DubboConfigBeanDefinitionConflictApplicationListener.java
dubbo-spring-boot-project/dubbo-spring-boot/src/main/java/org/apache/dubbo/spring/boot/context/event/DubboConfigBeanDefinitionConflictApplicationListener.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.spring.boot.context.event; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.core.Ordered; import org.springframework.core.env.Environment; import static org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors; import static org.springframework.context.ConfigurableApplicationContext.ENVIRONMENT_BEAN_NAME; /** * The {@link ApplicationListener} class for Dubbo Config {@link BeanDefinition Bean Definition} to resolve conflict * * @see BeanDefinition * @see ApplicationListener * @since 2.7.5 */ public class DubboConfigBeanDefinitionConflictApplicationListener implements ApplicationListener<ContextRefreshedEvent>, Ordered { private final Logger logger = LoggerFactory.getLogger(getClass()); @Override public void onApplicationEvent(ContextRefreshedEvent event) { ApplicationContext applicationContext = event.getApplicationContext(); BeanDefinitionRegistry registry = getBeanDefinitionRegistry(applicationContext); resolveUniqueApplicationConfigBean(registry, applicationContext); } private BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext applicationContext) { AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory(); if (beanFactory instanceof BeanDefinitionRegistry) { return (BeanDefinitionRegistry) beanFactory; } throw new IllegalStateException( "The BeanFactory in the ApplicationContext must bea subclass of BeanDefinitionRegistry"); } /** * Resolve the unique {@link ApplicationConfig} Bean * * @param registry {@link BeanDefinitionRegistry} instance * @param beanFactory {@link ConfigurableListableBeanFactory} instance * @see EnableDubboConfig */ private void resolveUniqueApplicationConfigBean(BeanDefinitionRegistry registry, ListableBeanFactory beanFactory) { String[] beansNames = beanNamesForTypeIncludingAncestors(beanFactory, ApplicationConfig.class); if (beansNames.length < 2) { // If the number of ApplicationConfig beans is less than two, return immediately. return; } Environment environment = beanFactory.getBean(ENVIRONMENT_BEAN_NAME, Environment.class); // Remove ApplicationConfig Beans that are configured by "dubbo.application.*" Stream.of(beansNames) .filter(beansName -> isConfiguredApplicationConfigBeanName(environment, beansName)) .forEach(registry::removeBeanDefinition); beansNames = beanNamesForTypeIncludingAncestors(beanFactory, ApplicationConfig.class); if (beansNames.length > 1) { throw new IllegalStateException(String.format( "There are more than one instances of %s, whose bean definitions : %s", ApplicationConfig.class.getSimpleName(), Stream.of(beansNames).map(registry::getBeanDefinition).collect(Collectors.toList()))); } } private boolean isConfiguredApplicationConfigBeanName(Environment environment, String beanName) { boolean removed = BeanFactoryUtils.isGeneratedBeanName(beanName) // Dubbo ApplicationConfig id as bean name || Objects.equals(beanName, environment.getProperty("dubbo.application.id")); if (removed && logger.isDebugEnabled()) { logger.debug( "The {} bean [ name : {} ] has been removed!", ApplicationConfig.class.getSimpleName(), beanName); } return removed; } @Override public int getOrder() { return LOWEST_PRECEDENCE; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessorTest.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessorTest.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.spring.boot.env; import java.util.HashMap; import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; import org.springframework.core.Ordered; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.mock.env.MockEnvironment; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * {@link DubboDefaultPropertiesEnvironmentPostProcessor} Test */ class DubboDefaultPropertiesEnvironmentPostProcessorTest { private DubboDefaultPropertiesEnvironmentPostProcessor instance = new DubboDefaultPropertiesEnvironmentPostProcessor(); private SpringApplication springApplication = new SpringApplication(); @Test void testOrder() { assertEquals(Ordered.LOWEST_PRECEDENCE, instance.getOrder()); } @Test void testPostProcessEnvironment() { MockEnvironment environment = new MockEnvironment(); // Case 1 : Not Any property instance.postProcessEnvironment(environment, springApplication); // Get PropertySources MutablePropertySources propertySources = environment.getPropertySources(); // Nothing to change PropertySource defaultPropertySource = propertySources.get("defaultProperties"); assertNotNull(defaultPropertySource); assertEquals("true", defaultPropertySource.getProperty("dubbo.config.multiple")); // assertEquals("true", defaultPropertySource.getProperty("dubbo.application.qos-enable")); // Case 2 : Only set property "spring.application.name" environment.setProperty("spring.application.name", "demo-dubbo-application"); instance.postProcessEnvironment(environment, springApplication); defaultPropertySource = propertySources.get("defaultProperties"); Object dubboApplicationName = defaultPropertySource.getProperty("dubbo.application.name"); assertEquals("demo-dubbo-application", dubboApplicationName); // Case 3 : Only set property "dubbo.application.name" // Reset environment environment = new MockEnvironment(); propertySources = environment.getPropertySources(); environment.setProperty("dubbo.application.name", "demo-dubbo-application"); instance.postProcessEnvironment(environment, springApplication); defaultPropertySource = propertySources.get("defaultProperties"); assertNotNull(defaultPropertySource); dubboApplicationName = environment.getProperty("dubbo.application.name"); assertEquals("demo-dubbo-application", dubboApplicationName); // Case 4 : If "defaultProperties" PropertySource is present in PropertySources // Reset environment environment = new MockEnvironment(); propertySources = environment.getPropertySources(); propertySources.addLast(new MapPropertySource("defaultProperties", new HashMap<String, Object>())); environment.setProperty("spring.application.name", "demo-dubbo-application"); instance.postProcessEnvironment(environment, springApplication); defaultPropertySource = propertySources.get("defaultProperties"); dubboApplicationName = defaultPropertySource.getProperty("dubbo.application.name"); assertEquals("demo-dubbo-application", dubboApplicationName); // Case 5 : Reset dubbo.config.multiple and dubbo.application.qos-enable environment = new MockEnvironment(); propertySources = environment.getPropertySources(); propertySources.addLast(new MapPropertySource("defaultProperties", new HashMap<String, Object>())); environment.setProperty("dubbo.config.multiple", "false"); environment.setProperty("dubbo.application.qos-enable", "false"); instance.postProcessEnvironment(environment, springApplication); assertEquals("false", environment.getProperty("dubbo.config.multiple")); assertEquals("false", environment.getProperty("dubbo.application.qos-enable")); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/CompatibleDubboAutoConfigurationTestWithoutProperties.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/CompatibleDubboAutoConfigurationTestWithoutProperties.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.spring.boot.autoconfigure; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; /** * {@link DubboAutoConfiguration} Test * * @see DubboAutoConfiguration */ @ExtendWith(SpringExtension.class) @SpringBootTest( classes = CompatibleDubboAutoConfigurationTestWithoutProperties.class, properties = {"dubbo.application.name=demo"}) @EnableAutoConfiguration class CompatibleDubboAutoConfigurationTestWithoutProperties { @Autowired(required = false) private ServiceAnnotationPostProcessor serviceAnnotationPostProcessor; @Autowired private ApplicationContext applicationContext; @BeforeEach void init() { DubboBootstrap.reset(); } @AfterEach void destroy() { DubboBootstrap.reset(); } @Test void testBeans() { assertNull(serviceAnnotationPostProcessor); ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor = DubboBeanUtils.getReferenceAnnotationBeanPostProcessor(applicationContext); assertNotNull(referenceAnnotationBeanPostProcessor); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/BinderDubboConfigBinderTest.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/BinderDubboConfigBinderTest.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.spring.boot.autoconfigure; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.spring.context.config.ConfigurationBeanBinder; import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.apache.dubbo.config.spring.util.PropertySourcesUtils.getSubProperties; import static org.junit.jupiter.api.Assertions.assertEquals; /** * {@link BinderDubboConfigBinder} Test * * @since 2.7.0 */ @ExtendWith(SpringExtension.class) @TestPropertySource(locations = "classpath:/dubbo.properties") @ContextConfiguration(classes = BinderDubboConfigBinder.class) class BinderDubboConfigBinderTest { @Autowired private ConfigurationBeanBinder dubboConfigBinder; @Autowired private ConfigurableEnvironment environment; @Test void testBinder() { ApplicationConfig applicationConfig = new ApplicationConfig(); Map<String, Object> properties = getSubProperties(environment.getPropertySources(), "dubbo.application"); dubboConfigBinder.bind(properties, true, true, applicationConfig); assertEquals("hello", applicationConfig.getName()); assertEquals("world", applicationConfig.getOwner()); RegistryConfig registryConfig = new RegistryConfig(); properties = getSubProperties(environment.getPropertySources(), "dubbo.registry"); dubboConfigBinder.bind(properties, true, true, registryConfig); assertEquals("10.20.153.17", registryConfig.getAddress()); ProtocolConfig protocolConfig = new ProtocolConfig(); properties = getSubProperties(environment.getPropertySources(), "dubbo.protocol"); dubboConfigBinder.bind(properties, true, true, protocolConfig); assertEquals(Integer.valueOf(20881), protocolConfig.getPort()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/CompatibleDubboAutoConfigurationTest.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/CompatibleDubboAutoConfigurationTest.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.spring.boot.autoconfigure; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.PropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * {@link DubboAutoConfiguration} Test * @see DubboAutoConfiguration */ @ExtendWith(SpringExtension.class) @SpringBootTest( classes = {CompatibleDubboAutoConfigurationTest.class}, properties = {"dubbo.scan.base-packages = org.apache.dubbo.spring.boot.autoconfigure"}) @EnableAutoConfiguration @PropertySource(value = "classpath:/META-INF/dubbo.properties") class CompatibleDubboAutoConfigurationTest { @Autowired private ObjectProvider<ServiceAnnotationPostProcessor> serviceAnnotationPostProcessor; @Autowired private ApplicationContext applicationContext; @Test void testBeans() { assertNotNull(serviceAnnotationPostProcessor); assertNotNull(serviceAnnotationPostProcessor.getIfAvailable()); ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor = DubboBeanUtils.getReferenceAnnotationBeanPostProcessor(applicationContext); assertNotNull(referenceAnnotationBeanPostProcessor); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBinding2AutoConfigurationTest.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBinding2AutoConfigurationTest.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.spring.boot.autoconfigure; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.context.config.ConfigurationBeanBinder; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.util.ClassUtils; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_BEAN_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link DubboRelaxedBinding2AutoConfiguration} Test */ @ExtendWith(SpringExtension.class) @SpringBootTest( classes = DubboRelaxedBinding2AutoConfigurationTest.class, properties = {"dubbo.scan.basePackages = org.apache.dubbo.spring.boot.autoconfigure"}) @EnableAutoConfiguration @PropertySource(value = "classpath:/dubbo.properties") class DubboRelaxedBinding2AutoConfigurationTest { @Autowired @Qualifier(BASE_PACKAGES_BEAN_NAME) private Set<String> packagesToScan; @Autowired @Qualifier(RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME) private ConfigurationBeanBinder dubboConfigBinder; @Autowired private ObjectProvider<ServiceAnnotationPostProcessor> serviceAnnotationPostProcessor; @Autowired private Environment environment; @Autowired private Map<String, Environment> environments; @Autowired private ApplicationContext applicationContext; @Test void testBeans() { assertTrue(ClassUtils.isAssignableValue(BinderDubboConfigBinder.class, dubboConfigBinder)); assertNotNull(serviceAnnotationPostProcessor); assertNotNull(serviceAnnotationPostProcessor.getIfAvailable()); ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor = DubboBeanUtils.getReferenceAnnotationBeanPostProcessor(applicationContext); assertNotNull(referenceAnnotationBeanPostProcessor); assertNotNull(environment); assertNotNull(environments); assertEquals(1, environments.size()); assertTrue(environments.containsValue(environment)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/base/DubboAutoConfigurationOnMultipleConfigTest.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/base/DubboAutoConfigurationOnMultipleConfigTest.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.spring.boot.autoconfigure.base; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConsumerConfig; 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.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.spring.boot.autoconfigure.DubboAutoConfiguration; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.junit.jupiter.api.Assertions.assertEquals; /** * {@link DubboAutoConfiguration} Test On multiple Dubbo Configuration * * @since 2.7.0 */ @ExtendWith(SpringExtension.class) @TestPropertySource( properties = { "dubbo.applications.application1.name=dubbo-demo-multi-application", "dubbo.modules.module1.name=dubbo-demo-module", "dubbo.registries.registry1.address=test://192.168.99.100:32770", "dubbo.protocols.protocol1.name=dubbo", "dubbo.protocols.protocol1.port=20880", "dubbo.monitors.monitor1.address=test://127.0.0.1:32770", "dubbo.providers.provider1.host=127.0.0.1", "dubbo.consumers.consumer1.client=netty", "dubbo.config.multiple=true", "dubbo.scan.basePackages=org.apache.dubbo.spring.boot.dubbo, org.apache.dubbo.spring.boot.condition" }) @SpringBootTest(classes = {DubboAutoConfigurationOnMultipleConfigTest.class}) @EnableAutoConfiguration @ComponentScan class DubboAutoConfigurationOnMultipleConfigTest { /** * @see TestBeansConfiguration */ @Autowired @Qualifier("application1") ApplicationConfig application; @Autowired @Qualifier("module1") ModuleConfig module; @Autowired @Qualifier("registry1") RegistryConfig registry; @Autowired @Qualifier("monitor1") MonitorConfig monitor; @Autowired @Qualifier("protocol1") ProtocolConfig protocol; @Autowired @Qualifier("consumer1") ConsumerConfig consumer; @Autowired @Qualifier("provider1") ProviderConfig provider; @BeforeEach void init() { DubboBootstrap.reset(); } @AfterEach void destroy() { DubboBootstrap.reset(); } @Test void testMultiConfig() { // application assertEquals("dubbo-demo-multi-application", application.getName()); // module assertEquals("dubbo-demo-module", module.getName()); // registry assertEquals("test://192.168.99.100:32770", registry.getAddress()); assertEquals("test", registry.getProtocol()); assertEquals(Integer.valueOf(32770), registry.getPort()); // monitor assertEquals("test://127.0.0.1:32770", monitor.getAddress()); // protocol assertEquals("dubbo", protocol.getName()); assertEquals(Integer.valueOf(20880), protocol.getPort()); // consumer assertEquals("netty", consumer.getClient()); // provider assertEquals("127.0.0.1", provider.getHost()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/base/TestBeansConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/base/TestBeansConfiguration.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.spring.boot.autoconfigure.base; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConsumerConfig; 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.RegistryConfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class TestBeansConfiguration { @Bean ApplicationConfig application1() { ApplicationConfig config = new ApplicationConfig(); config.setId("application1"); return config; } @Bean ModuleConfig module1() { ModuleConfig config = new ModuleConfig(); config.setId("module1"); return config; } @Bean RegistryConfig registry1() { RegistryConfig config = new RegistryConfig(); config.setId("registry1"); return config; } @Bean MonitorConfig monitor1() { MonitorConfig config = new MonitorConfig(); config.setId("monitor1"); return config; } @Bean ProtocolConfig protocol1() { ProtocolConfig config = new ProtocolConfig(); config.setId("protocol1"); return config; } @Bean ConsumerConfig consumer1() { ConsumerConfig config = new ConsumerConfig(); config.setId("consumer1"); return config; } @Bean ProviderConfig provider1() { ProviderConfig config = new ProviderConfig(); config.setId("provider1"); return config; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/base/DubboAutoConfigurationOnSingleConfigTest.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/base/DubboAutoConfigurationOnSingleConfigTest.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.spring.boot.autoconfigure.base; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConsumerConfig; 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.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.spring.boot.autoconfigure.DubboAutoConfiguration; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.junit.jupiter.api.Assertions.assertEquals; /** * {@link DubboAutoConfiguration} Test On single Dubbo Configuration * * @since 2.7.0 */ @ExtendWith(SpringExtension.class) @TestPropertySource( properties = { "dubbo.application.name = dubbo-demo-single-application", "dubbo.module.name = dubbo-demo-module", "dubbo.registry.address = test://192.168.99.100:32770", "dubbo.protocol.name=dubbo", "dubbo.protocol.port=20880", "dubbo.monitor.address=test://127.0.0.1:32770", "dubbo.provider.host=127.0.0.1", "dubbo.consumer.client=netty" }) @SpringBootTest(classes = {DubboAutoConfigurationOnSingleConfigTest.class}) @EnableAutoConfiguration @ComponentScan class DubboAutoConfigurationOnSingleConfigTest { @Autowired private ApplicationConfig applicationConfig; @Autowired private ModuleConfig moduleConfig; @Autowired private RegistryConfig registryConfig; @Autowired private MonitorConfig monitorConfig; @Autowired private ProviderConfig providerConfig; @Autowired private ConsumerConfig consumerConfig; @Autowired private ProtocolConfig protocolConfig; @BeforeEach void init() { DubboBootstrap.reset(); } @AfterEach void destroy() { DubboBootstrap.reset(); } @Test void testSingleConfig() { // application assertEquals("dubbo-demo-single-application", applicationConfig.getName()); // module assertEquals("dubbo-demo-module", moduleConfig.getName()); // registry assertEquals("test://192.168.99.100:32770", registryConfig.getAddress()); // monitor assertEquals("test://127.0.0.1:32770", monitorConfig.getAddress()); // protocol assertEquals("dubbo", protocolConfig.getName()); assertEquals(Integer.valueOf(20880), protocolConfig.getPort()); // consumer assertEquals("netty", consumerConfig.getClient()); // provider assertEquals("127.0.0.1", providerConfig.getHost()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/observability/DubboMicrometerTracingAutoConfigurationTests.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/observability/DubboMicrometerTracingAutoConfigurationTests.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.spring.boot.autoconfigure.observability; import java.util.List; import java.util.stream.Collectors; import io.micrometer.tracing.Tracer; import io.micrometer.tracing.handler.DefaultTracingObservationHandler; import io.micrometer.tracing.handler.PropagatingReceiverTracingObservationHandler; import io.micrometer.tracing.handler.PropagatingSenderTracingObservationHandler; import io.micrometer.tracing.handler.TracingObservationHandler; import io.micrometer.tracing.propagation.Propagator; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.FilteredClassLoader; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** * Tests for {@link DubboMicrometerTracingAutoConfiguration} */ class DubboMicrometerTracingAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DubboMicrometerTracingAutoConfiguration.class)) .withPropertyValues("dubbo.tracing.enabled=true"); @Test void shouldSupplyBeans() { this.contextRunner .withUserConfiguration(TracerConfiguration.class, PropagatorConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(DefaultTracingObservationHandler.class); assertThat(context).hasSingleBean(PropagatingReceiverTracingObservationHandler.class); assertThat(context).hasSingleBean(PropagatingSenderTracingObservationHandler.class); }); } @Test @SuppressWarnings("rawtypes") void shouldSupplyBeansInCorrectOrder() { this.contextRunner .withUserConfiguration(TracerConfiguration.class, PropagatorConfiguration.class) .run((context) -> { List<TracingObservationHandler> tracingObservationHandlers = context.getBeanProvider( TracingObservationHandler.class) .orderedStream() .collect(Collectors.toList()); assertThat(tracingObservationHandlers).hasSize(3); assertThat(tracingObservationHandlers.get(0)) .isInstanceOf(PropagatingReceiverTracingObservationHandler.class); assertThat(tracingObservationHandlers.get(1)) .isInstanceOf(PropagatingSenderTracingObservationHandler.class); assertThat(tracingObservationHandlers.get(2)).isInstanceOf(DefaultTracingObservationHandler.class); }); } @Test void shouldBackOffOnCustomBeans() { this.contextRunner.withUserConfiguration(CustomConfiguration.class).run((context) -> { assertThat(context).hasBean("customDefaultTracingObservationHandler"); assertThat(context).hasSingleBean(DefaultTracingObservationHandler.class); assertThat(context).hasBean("customPropagatingReceiverTracingObservationHandler"); assertThat(context).hasSingleBean(PropagatingReceiverTracingObservationHandler.class); assertThat(context).hasBean("customPropagatingSenderTracingObservationHandler"); assertThat(context).hasSingleBean(PropagatingSenderTracingObservationHandler.class); }); } @Test void shouldNotSupplyBeansIfMicrometerIsMissing() { this.contextRunner .withClassLoader(new FilteredClassLoader("io.micrometer")) .run((context) -> { assertThat(context).doesNotHaveBean(DefaultTracingObservationHandler.class); assertThat(context).doesNotHaveBean(PropagatingReceiverTracingObservationHandler.class); assertThat(context).doesNotHaveBean(PropagatingSenderTracingObservationHandler.class); }); } @Test void shouldNotSupplyBeansIfTracerIsMissing() { this.contextRunner.withUserConfiguration(PropagatorConfiguration.class).run((context) -> { assertThat(context).doesNotHaveBean(DefaultTracingObservationHandler.class); assertThat(context).doesNotHaveBean(PropagatingReceiverTracingObservationHandler.class); assertThat(context).doesNotHaveBean(PropagatingSenderTracingObservationHandler.class); }); } @Test void shouldNotSupplyBeansIfPropagatorIsMissing() { this.contextRunner.withUserConfiguration(TracerConfiguration.class).run((context) -> { assertThat(context).doesNotHaveBean(PropagatingSenderTracingObservationHandler.class); assertThat(context).doesNotHaveBean(PropagatingReceiverTracingObservationHandler.class); }); } @Test void shouldNotSupplyBeansIfTracingIsDisabled() { this.contextRunner .withUserConfiguration(TracerConfiguration.class, PropagatorConfiguration.class) .withPropertyValues("dubbo.tracing.enabled=false") .run((context) -> { assertThat(context).doesNotHaveBean(DefaultTracingObservationHandler.class); assertThat(context).doesNotHaveBean(PropagatingReceiverTracingObservationHandler.class); assertThat(context).doesNotHaveBean(PropagatingSenderTracingObservationHandler.class); }); } @Configuration(proxyBeanMethods = false) private static class TracerConfiguration { @Bean Tracer tracer() { return mock(Tracer.class); } } @Configuration(proxyBeanMethods = false) private static class PropagatorConfiguration { @Bean Propagator propagator() { return mock(Propagator.class); } } @Configuration(proxyBeanMethods = false) private static class CustomConfiguration { @Bean DefaultTracingObservationHandler customDefaultTracingObservationHandler() { return mock(DefaultTracingObservationHandler.class); } @Bean PropagatingReceiverTracingObservationHandler<?> customPropagatingReceiverTracingObservationHandler() { return mock(PropagatingReceiverTracingObservationHandler.class); } @Bean PropagatingSenderTracingObservationHandler<?> customPropagatingSenderTracingObservationHandler() { return mock(PropagatingSenderTracingObservationHandler.class); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboSpringBoot3DependencyCheckAutoConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboSpringBoot3DependencyCheckAutoConfiguration.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.spring.boot.autoconfigure; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) @Conditional(SpringBoot3Condition.class) public class DubboSpringBoot3DependencyCheckAutoConfiguration { public static final String SERVLET_PREFIX = "dubbo.protocol.triple.servlet"; public static final String WEBSOCKET_PREFIX = "dubbo.protocol.triple.websocket"; public static final String JAKARATA_SERVLET_FILTER = "jakarta.servlet.Filter"; public static final String DUBBO_TRIPLE_3_AUTOCONFIGURATION = "org.apache.dubbo.spring.boot.autoconfigure.DubboTriple3AutoConfiguration"; private static final String SPRING_BOOT_3_DEPENDENCY_CHECK_WARNING = "Couldn't enable servlet support for triple at SpringBoot3: Missing dubbo-spring-boot-3-autoconfigure"; @Configuration(proxyBeanMethods = false) @ConditionalOnClass(name = JAKARATA_SERVLET_FILTER) @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnProperty(prefix = SERVLET_PREFIX, name = "enabled", havingValue = "true") @ConditionalOnMissingClass(DUBBO_TRIPLE_3_AUTOCONFIGURATION) public static class tripleProtocolFilterDependencyCheckConfiguration { @Bean public Object tripleProtocolFilterDependencyCheck() { throw new IllegalStateException(SPRING_BOOT_3_DEPENDENCY_CHECK_WARNING); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(name = JAKARATA_SERVLET_FILTER) @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnProperty(prefix = WEBSOCKET_PREFIX, name = "enabled", havingValue = "true") @ConditionalOnMissingClass(DUBBO_TRIPLE_3_AUTOCONFIGURATION) public static class tripleWebSocketFilterDependencyCheckConfiguration { @Bean public Object tripleWebSocketFilterDependencyCheck() { throw new IllegalStateException(SPRING_BOOT_3_DEPENDENCY_CHECK_WARNING); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboMetadataGenerateAutoConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboMetadataGenerateAutoConfiguration.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.spring.boot.autoconfigure; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; @Configuration @EnableConfigurationProperties(DubboConfigurationProperties.class) public class DubboMetadataGenerateAutoConfiguration {}
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/SpringBoot3Condition.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/SpringBoot3Condition.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.spring.boot.autoconfigure; import org.springframework.boot.SpringBootVersion; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class SpringBoot3Condition implements Condition { public static boolean IS_SPRING_BOOT_3 = SpringBootVersion.getVersion().charAt(0) >= '3'; @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return IS_SPRING_BOOT_3; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/BinderDubboConfigBinder.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/BinderDubboConfigBinder.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.spring.boot.autoconfigure; import org.apache.dubbo.config.spring.context.config.ConfigurationBeanBinder; import org.apache.dubbo.config.spring.context.properties.DubboConfigBinder; import java.util.Map; import org.springframework.boot.context.properties.bind.BindHandler; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.context.properties.bind.PropertySourcesPlaceholdersResolver; import org.springframework.boot.context.properties.bind.handler.IgnoreErrorsBindHandler; import org.springframework.boot.context.properties.bind.handler.NoUnboundElementsBindHandler; import org.springframework.boot.context.properties.source.ConfigurationPropertySource; import org.springframework.boot.context.properties.source.UnboundElementsSourceFilter; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.PropertySource; import static java.util.Arrays.asList; import static org.springframework.boot.context.properties.source.ConfigurationPropertySources.from; /** * Spring Boot Relaxed {@link DubboConfigBinder} implementation * see org.springframework.boot.context.properties.ConfigurationPropertiesBinder * * @since 2.7.0 */ class BinderDubboConfigBinder implements ConfigurationBeanBinder { @Override public void bind( Map<String, Object> configurationProperties, boolean ignoreUnknownFields, boolean ignoreInvalidFields, Object configurationBean) { Iterable<PropertySource<?>> propertySources = asList(new MapPropertySource("internal", configurationProperties)); // Converts ConfigurationPropertySources Iterable<ConfigurationPropertySource> configurationPropertySources = from(propertySources); // Wrap Bindable from DubboConfig instance Bindable bindable = Bindable.ofInstance(configurationBean); Binder binder = new Binder(configurationPropertySources, new PropertySourcesPlaceholdersResolver(propertySources)); // Get BindHandler BindHandler bindHandler = getBindHandler(ignoreUnknownFields, ignoreInvalidFields); // Bind binder.bind("", bindable, bindHandler); } private BindHandler getBindHandler(boolean ignoreUnknownFields, boolean ignoreInvalidFields) { BindHandler handler = BindHandler.DEFAULT; if (ignoreInvalidFields) { handler = new IgnoreErrorsBindHandler(handler); } if (!ignoreUnknownFields) { UnboundElementsSourceFilter filter = new UnboundElementsSourceFilter(); handler = new NoUnboundElementsBindHandler(handler, filter); } return handler; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboTripleAutoConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboTripleAutoConfiguration.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.spring.boot.autoconfigure; import org.apache.dubbo.rpc.protocol.tri.ServletExchanger; import org.apache.dubbo.rpc.protocol.tri.servlet.TripleFilter; import org.apache.dubbo.rpc.protocol.tri.websocket.TripleWebSocketFilter; import javax.servlet.Filter; import org.apache.coyote.ProtocolHandler; import org.apache.coyote.UpgradeProtocol; import org.apache.coyote.http2.Http2Protocol; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; import org.springframework.boot.web.embedded.tomcat.ConfigurableTomcatWebServerFactory; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) @Conditional(SpringBoot12Condition.class) public class DubboTripleAutoConfiguration { public static final String SERVLET_PREFIX = "dubbo.protocol.triple.servlet"; public static final String WEBSOCKET_PREFIX = "dubbo.protocol.triple.websocket"; @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Filter.class) @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnProperty(prefix = SERVLET_PREFIX, name = "enabled", havingValue = "true") public static class TripleServletConfiguration { @Bean public FilterRegistrationBean<TripleFilter> tripleProtocolFilter( @Value("${" + SERVLET_PREFIX + ".filter-url-patterns:/*}") String[] urlPatterns, @Value("${" + SERVLET_PREFIX + ".filter-order:-1000000}") int order, @Value("${server.port:8080}") int serverPort) { ServletExchanger.bindServerPort(serverPort); FilterRegistrationBean<TripleFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(new TripleFilter()); registrationBean.addUrlPatterns(urlPatterns); registrationBean.setOrder(order); return registrationBean; } @Bean @ConditionalOnClass(Http2Protocol.class) @ConditionalOnProperty(prefix = SERVLET_PREFIX, name = "max-concurrent-streams") public WebServerFactoryCustomizer<ConfigurableTomcatWebServerFactory> tripleTomcatHttp2Customizer( @Value("${" + SERVLET_PREFIX + ".max-concurrent-streams}") int maxConcurrentStreams) { return factory -> factory.addConnectorCustomizers(connector -> { ProtocolHandler handler = connector.getProtocolHandler(); for (UpgradeProtocol upgradeProtocol : handler.findUpgradeProtocols()) { if (upgradeProtocol instanceof Http2Protocol) { Http2Protocol protocol = (Http2Protocol) upgradeProtocol; int value = maxConcurrentStreams <= 0 ? Integer.MAX_VALUE : maxConcurrentStreams; protocol.setMaxConcurrentStreams(value); protocol.setMaxConcurrentStreamExecution(value); } } }); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Filter.class) @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnProperty(prefix = WEBSOCKET_PREFIX, name = "enabled", havingValue = "true") public static class TripleWebSocketConfiguration { @Bean public FilterRegistrationBean<TripleWebSocketFilter> tripleWebSocketFilter( @Value("${" + WEBSOCKET_PREFIX + ".filter-url-patterns:/*}") String[] urlPatterns, @Value("${" + WEBSOCKET_PREFIX + ".filter-order:-1000000}") int order, @Value("${server.port:8080}") int serverPort) { ServletExchanger.bindServerPort(serverPort); FilterRegistrationBean<TripleWebSocketFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(new TripleWebSocketFilter()); registrationBean.addUrlPatterns(urlPatterns); registrationBean.setOrder(order); return registrationBean; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/SpringBoot12Condition.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/SpringBoot12Condition.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.spring.boot.autoconfigure; import org.springframework.boot.SpringBootVersion; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class SpringBoot12Condition implements Condition { public static boolean IS_SPRING_BOOT_12 = SpringBootVersion.getVersion().charAt(0) < '3'; @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return IS_SPRING_BOOT_12; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboConfigurationProperties.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboConfigurationProperties.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.spring.boot.autoconfigure; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.ConfigKeys; 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.RegistryConfig; import org.apache.dubbo.config.SslConfig; import org.apache.dubbo.config.TracingConfig; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * Dubbo {@link ConfigurationProperties Config Properties} only used to generate JSON metadata (non-public class) * * @see ConfigKeys * @since 2.7.1 */ @ConfigurationProperties(DUBBO_PREFIX) public class DubboConfigurationProperties { /** * Configuration properties for the application. */ @NestedConfigurationProperty private ApplicationConfig application = new ApplicationConfig(); /** * Configuration properties for the module. */ @NestedConfigurationProperty private ModuleConfig module = new ModuleConfig(); /** * Configuration properties for the registry. */ @NestedConfigurationProperty private RegistryConfig registry = new RegistryConfig(); /** * Configuration properties for the protocol. */ @NestedConfigurationProperty private ProtocolConfig protocol = new ProtocolConfig(); /** * Configuration properties for the monitor. */ @NestedConfigurationProperty private MonitorConfig monitor = new MonitorConfig(); /** * Configuration properties for the provider. */ @NestedConfigurationProperty private ProviderConfig provider = new ProviderConfig(); /** * Configuration properties for the consumer. */ @NestedConfigurationProperty private ConsumerConfig consumer = new ConsumerConfig(); /** * Configuration properties for the config center. */ @NestedConfigurationProperty private ConfigCenterConfig configCenter = new ConfigCenterConfig(); /** * Configuration properties for the metadata report. */ @NestedConfigurationProperty private MetadataReportConfig metadataReport = new MetadataReportConfig(); /** * Configuration properties for metrics. */ @NestedConfigurationProperty private MetricsConfig metrics = new MetricsConfig(); /** * Configuration properties for tracing. */ @NestedConfigurationProperty private TracingConfig tracing = new TracingConfig(); /** * Configuration properties for ssl. */ @NestedConfigurationProperty private SslConfig ssl = new SslConfig(); // Multiple Config Bindings /** * Multiple configurations for Module. */ private Map<String, ModuleConfig> modules = new LinkedHashMap<>(); /** * Multiple configurations for Registry. */ private Map<String, RegistryConfig> registries = new LinkedHashMap<>(); /** * Multiple configurations for Protocol. */ private Map<String, ProtocolConfig> protocols = new LinkedHashMap<>(); /** * Multiple configurations for Monitor. */ private Map<String, MonitorConfig> monitors = new LinkedHashMap<>(); /** * Multiple configurations for Provider. */ private Map<String, ProviderConfig> providers = new LinkedHashMap<>(); /** * Multiple configurations for Consumer. */ private Map<String, ConsumerConfig> consumers = new LinkedHashMap<>(); /** * Multiple configurations for ConfigCenterBean. */ private Map<String, ConfigCenterConfig> configCenters = new LinkedHashMap<>(); /** * Multiple configurations for MetadataReportConfig. */ private Map<String, MetadataReportConfig> metadataReports = new LinkedHashMap<>(); /** * Multiple configurations for MetricsConfig. */ private Map<String, MetricsConfig> metricses = new LinkedHashMap<>(); /** * Multiple configurations for TracingConfig. */ private Map<String, TracingConfig> tracings = new LinkedHashMap<>(); public ApplicationConfig getApplication() { return application; } public void setApplication(ApplicationConfig application) { this.application = application; } public ModuleConfig getModule() { return module; } public void setModule(ModuleConfig module) { this.module = module; } public RegistryConfig getRegistry() { return registry; } public void setRegistry(RegistryConfig registry) { this.registry = registry; } public ProtocolConfig getProtocol() { return protocol; } public void setProtocol(ProtocolConfig protocol) { this.protocol = protocol; } public MonitorConfig getMonitor() { return monitor; } public void setMonitor(MonitorConfig monitor) { this.monitor = monitor; } public ProviderConfig getProvider() { return provider; } public void setProvider(ProviderConfig provider) { this.provider = provider; } public ConsumerConfig getConsumer() { return consumer; } public void setConsumer(ConsumerConfig consumer) { this.consumer = consumer; } public ConfigCenterConfig getConfigCenter() { return configCenter; } public void setConfigCenter(ConfigCenterConfig configCenter) { this.configCenter = configCenter; } public MetadataReportConfig getMetadataReport() { return metadataReport; } public void setMetadataReport(MetadataReportConfig metadataReport) { this.metadataReport = metadataReport; } public MetricsConfig getMetrics() { return metrics; } public void setMetrics(MetricsConfig metrics) { this.metrics = metrics; } public TracingConfig getTracing() { return tracing; } public void setTracing(TracingConfig tracing) { this.tracing = tracing; } public SslConfig getSsl() { return ssl; } public void setSsl(SslConfig ssl) { this.ssl = ssl; } public Map<String, ModuleConfig> getModules() { return modules; } public void setModules(Map<String, ModuleConfig> modules) { this.modules = modules; } public Map<String, RegistryConfig> getRegistries() { return registries; } public void setRegistries(Map<String, RegistryConfig> registries) { this.registries = registries; } public Map<String, ProtocolConfig> getProtocols() { return protocols; } public void setProtocols(Map<String, ProtocolConfig> protocols) { this.protocols = protocols; } public Map<String, MonitorConfig> getMonitors() { return monitors; } public void setMonitors(Map<String, MonitorConfig> monitors) { this.monitors = monitors; } public Map<String, ProviderConfig> getProviders() { return providers; } public void setProviders(Map<String, ProviderConfig> providers) { this.providers = providers; } public Map<String, ConsumerConfig> getConsumers() { return consumers; } public void setConsumers(Map<String, ConsumerConfig> consumers) { this.consumers = consumers; } public Map<String, ConfigCenterConfig> getConfigCenters() { return configCenters; } public void setConfigCenters(Map<String, ConfigCenterConfig> configCenters) { this.configCenters = configCenters; } public Map<String, MetadataReportConfig> getMetadataReports() { return metadataReports; } public void setMetadataReports(Map<String, MetadataReportConfig> metadataReports) { this.metadataReports = metadataReports; } public Map<String, MetricsConfig> getMetricses() { return metricses; } public void setMetricses(Map<String, MetricsConfig> metricses) { this.metricses = metricses; } public Map<String, TracingConfig> getTracings() { return tracings; } public void setTracings(Map<String, TracingConfig> tracings) { this.tracings = tracings; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBinding2AutoConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBinding2AutoConfiguration.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.spring.boot.autoconfigure; import org.apache.dubbo.config.spring.context.config.ConfigurationBeanBinder; import org.apache.dubbo.config.spring.util.PropertySourcesUtils; import java.util.Map; import java.util.Set; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.source.ConfigurationPropertySources; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import org.springframework.core.env.AbstractEnvironment; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertyResolver; import static java.util.Collections.emptySet; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_BEAN_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_PROPERTY_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SCAN_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME; import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE; /** * Dubbo Relaxed Binding Auto-{@link Configuration} for Spring Boot 2.0 * * @see DubboRelaxedBindingAutoConfiguration * @since 2.7.0 */ @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @ConditionalOnClass(name = "org.springframework.boot.context.properties.bind.Binder") @AutoConfigureBefore(DubboRelaxedBindingAutoConfiguration.class) public class DubboRelaxedBinding2AutoConfiguration { public PropertyResolver dubboScanBasePackagesPropertyResolver(ConfigurableEnvironment environment) { ConfigurableEnvironment propertyResolver = new AbstractEnvironment() { @Override protected void customizePropertySources(MutablePropertySources propertySources) { Map<String, Object> dubboScanProperties = PropertySourcesUtils.getSubProperties(environment.getPropertySources(), DUBBO_SCAN_PREFIX); propertySources.addLast(new MapPropertySource("dubboScanProperties", dubboScanProperties)); } }; ConfigurationPropertySources.attach(propertyResolver); return propertyResolver; } /** * The bean is used to scan the packages of Dubbo Service classes * * @param environment {@link Environment} instance * @return non-null {@link Set} * @since 2.7.8 */ @ConditionalOnMissingBean(name = BASE_PACKAGES_BEAN_NAME) @Bean(name = BASE_PACKAGES_BEAN_NAME) public Set<String> dubboBasePackages(ConfigurableEnvironment environment) { PropertyResolver propertyResolver = dubboScanBasePackagesPropertyResolver(environment); return propertyResolver.getProperty(BASE_PACKAGES_PROPERTY_NAME, Set.class, emptySet()); } @ConditionalOnMissingBean(name = RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME, value = ConfigurationBeanBinder.class) @Bean(RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME) @Scope(scopeName = SCOPE_PROTOTYPE) public ConfigurationBeanBinder relaxedDubboConfigBinder() { return new BinderDubboConfigBinder(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboListenerAutoConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboListenerAutoConfiguration.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.spring.boot.autoconfigure; import org.apache.dubbo.rpc.Constants; import org.apache.dubbo.spring.boot.context.event.AwaitingNonWebApplicationListener; import org.apache.dubbo.spring.boot.context.event.DubboConfigBeanDefinitionConflictApplicationListener; import org.apache.dubbo.spring.boot.context.event.DubboOpenAPIExportListener; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * Dubbo Listener Auto-{@link Configuration} * * @since 3.0.4 */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @Configuration public class DubboListenerAutoConfiguration { @ConditionalOnMissingBean @Bean public DubboConfigBeanDefinitionConflictApplicationListener dubboConfigBeanDefinitionConflictApplicationListener() { return new DubboConfigBeanDefinitionConflictApplicationListener(); } @ConditionalOnMissingBean @Bean public AwaitingNonWebApplicationListener awaitingNonWebApplicationListener() { return new AwaitingNonWebApplicationListener(); } @ConditionalOnMissingBean @Bean @ConditionalOnProperty(prefix = Constants.H2_SETTINGS_OPENAPI_PREFIX, name = "enabled", havingValue = "true") public DubboOpenAPIExportListener dubboOpenAPIExportListener() { return new DubboOpenAPIExportListener(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfiguration.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.spring.boot.autoconfigure; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; import org.apache.dubbo.config.spring.util.SpringCompatUtils; import java.util.Collection; import java.util.Set; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_BEAN_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_PROPERTY_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SCAN_PREFIX; /** * Dubbo Auto {@link Configuration} * * @see DubboReference * @see DubboService * @see ServiceAnnotationPostProcessor * @see ReferenceAnnotationBeanPostProcessor * @since 2.7.0 */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @Configuration @AutoConfigureAfter(DubboRelaxedBindingAutoConfiguration.class) @EnableDubboConfig public class DubboAutoConfiguration { /** * Creates {@link ServiceAnnotationPostProcessor} Bean * * @param packagesToScan the packages to scan * @return {@link ServiceAnnotationPostProcessor} */ @ConditionalOnProperty(prefix = DUBBO_SCAN_PREFIX, name = BASE_PACKAGES_PROPERTY_NAME) @ConditionalOnBean(name = BASE_PACKAGES_BEAN_NAME) @Bean public static ServiceAnnotationPostProcessor serviceAnnotationBeanProcessor( @Qualifier(BASE_PACKAGES_BEAN_NAME) Set<String> packagesToScan) { ServiceAnnotationPostProcessor serviceAnnotationPostProcessor; try { serviceAnnotationPostProcessor = (ServiceAnnotationPostProcessor) SpringCompatUtils.serviceAnnotationPostProcessor() .getDeclaredConstructor(Collection.class) .newInstance(packagesToScan); } catch (Exception e) { throw new RuntimeException(e); } return serviceAnnotationPostProcessor; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/ObservationHandlerGrouping.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/ObservationHandlerGrouping.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.spring.boot.autoconfigure.observability; import java.util.ArrayList; import java.util.Collections; import java.util.List; import io.micrometer.observation.ObservationHandler; import io.micrometer.observation.ObservationRegistry; import org.springframework.util.CollectionUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; /** * Groups {@link ObservationHandler ObservationHandlers} by type. * copy from {@link org.springframework.boot.actuate.autoconfigure.observation.ObservationHandlerGrouping} * this class is available starting from Boot 3.0. It's not available if you're using Boot < 3.0 */ class ObservationHandlerGrouping { private final List<Class<? extends ObservationHandler>> categories; ObservationHandlerGrouping(Class<? extends ObservationHandler> category) { this(Collections.singletonList(category)); } ObservationHandlerGrouping(List<Class<? extends ObservationHandler>> categories) { this.categories = categories; } void apply(List<ObservationHandler<?>> handlers, ObservationRegistry.ObservationConfig config) { MultiValueMap<Class<? extends ObservationHandler>, ObservationHandler<?>> groupings = new LinkedMultiValueMap<>(); List<ObservationHandler<?>> handlersWithoutCategory = new ArrayList<>(); for (ObservationHandler<?> handler : handlers) { Class<? extends ObservationHandler> category = findCategory(handler); if (category != null) { groupings.add(category, handler); } else { handlersWithoutCategory.add(handler); } } for (Class<? extends ObservationHandler> category : this.categories) { List<ObservationHandler<?>> handlerGroup = groupings.get(category); if (!CollectionUtils.isEmpty(handlerGroup)) { config.observationHandler( new ObservationHandler.FirstMatchingCompositeObservationHandler(handlerGroup)); } } for (ObservationHandler<?> observationHandler : handlersWithoutCategory) { config.observationHandler(observationHandler); } } private Class<? extends ObservationHandler> findCategory(ObservationHandler<?> handler) { for (Class<? extends ObservationHandler> category : this.categories) { if (category.isInstance(handler)) { return category; } } return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/DubboObservationAutoConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/DubboObservationAutoConfiguration.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.spring.boot.autoconfigure.observability; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.spring.context.event.DubboConfigInitEvent; import org.apache.dubbo.qos.protocol.QosProtocolWrapper; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.spring.boot.autoconfigure.observability.annotation.ConditionalOnDubboTracingEnable; import java.util.Arrays; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.observation.DefaultMeterObservationHandler; import io.micrometer.core.instrument.observation.MeterObservationHandler; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationRegistry; import io.micrometer.tracing.Tracer; import io.micrometer.tracing.handler.TracingAwareMeterObservationHandler; import io.micrometer.tracing.handler.TracingObservationHandler; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * Register observationRegistry to ApplicationModel. * Create observationRegistry when you are using Boot <3.0 or you are not using spring-boot-starter-actuator */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @AutoConfiguration( after = DubboMicrometerTracingAutoConfiguration.class, afterName = "org.springframework.boot.actuate.autoconfigure.observation.ObservationAutoConfiguration") @ConditionalOnDubboTracingEnable @ConditionalOnClass(name = {"io.micrometer.observation.Observation", "io.micrometer.tracing.Tracer"}) public class DubboObservationAutoConfiguration implements BeanFactoryAware, ApplicationListener<DubboConfigInitEvent>, Ordered { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(QosProtocolWrapper.class); public DubboObservationAutoConfiguration(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } private final ApplicationModel applicationModel; private BeanFactory beanFactory; @Bean @ConditionalOnMissingBean @ConditionalOnClass(name = "io.micrometer.observation.ObservationRegistry") ObservationRegistry observationRegistry() { return ObservationRegistry.create(); } @Bean @ConditionalOnMissingBean( type = "org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryPostProcessor") @ConditionalOnClass(name = "io.micrometer.observation.ObservationHandler") public ObservationRegistryPostProcessor dubboObservationRegistryPostProcessor( ObjectProvider<ObservationHandlerGrouping> observationHandlerGrouping, ObjectProvider<io.micrometer.observation.ObservationHandler<?>> observationHandlers) { return new ObservationRegistryPostProcessor(observationHandlerGrouping, observationHandlers); } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } @Override public void onApplicationEvent(DubboConfigInitEvent event) { try { applicationModel .getBeanFactory() .registerBean(beanFactory.getBean(io.micrometer.observation.ObservationRegistry.class)); applicationModel.getBeanFactory().registerBean(beanFactory.getBean(io.micrometer.tracing.Tracer.class)); applicationModel .getBeanFactory() .registerBean(beanFactory.getBean(io.micrometer.tracing.propagation.Propagator.class)); } catch (NoSuchBeanDefinitionException e) { logger.info("Please use a version of micrometer higher than 1.10.0: " + e.getMessage()); } } @Override public int getOrder() { return HIGHEST_PRECEDENCE; } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(MeterRegistry.class) @ConditionalOnMissingClass("io.micrometer.tracing.Tracer") @ConditionalOnMissingBean( type = "org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryPostProcessor") static class OnlyMetricsConfiguration { @Bean @ConditionalOnClass(name = "io.micrometer.core.instrument.observation.MeterObservationHandler") ObservationHandlerGrouping metricsObservationHandlerGrouping() { return new ObservationHandlerGrouping(MeterObservationHandler.class); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(io.micrometer.tracing.Tracer.class) @ConditionalOnMissingClass("io.micrometer.core.instrument.MeterRegistry") @ConditionalOnMissingBean( type = "org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryPostProcessor") static class OnlyTracingConfiguration { @Bean @ConditionalOnClass(name = "io.micrometer.tracing.handler.TracingObservationHandler") ObservationHandlerGrouping tracingObservationHandlerGrouping() { return new ObservationHandlerGrouping(TracingObservationHandler.class); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({MeterRegistry.class, io.micrometer.tracing.Tracer.class}) @ConditionalOnMissingBean( type = "org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryPostProcessor") static class MetricsWithTracingConfiguration { @Bean @ConditionalOnClass( name = { "io.micrometer.tracing.handler.TracingObservationHandler", "io.micrometer.core.instrument.observation.MeterObservationHandler" }) ObservationHandlerGrouping metricsAndTracingObservationHandlerGrouping() { return new ObservationHandlerGrouping( Arrays.asList(TracingObservationHandler.class, MeterObservationHandler.class)); } } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(MeterRegistry.class) @ConditionalOnMissingBean(MeterObservationHandler.class) static class MeterObservationHandlerConfiguration { @ConditionalOnMissingBean(type = "io.micrometer.tracing.Tracer") @Configuration(proxyBeanMethods = false) static class OnlyMetricsMeterObservationHandlerConfiguration { @Bean @ConditionalOnClass(name = {"io.micrometer.core.instrument.observation.DefaultMeterObservationHandler"}) DefaultMeterObservationHandler defaultMeterObservationHandler(MeterRegistry meterRegistry) { return new DefaultMeterObservationHandler(meterRegistry); } } @ConditionalOnBean(io.micrometer.tracing.Tracer.class) @Configuration(proxyBeanMethods = false) static class TracingAndMetricsObservationHandlerConfiguration { @Bean @ConditionalOnClass( name = { "io.micrometer.tracing.handler.TracingAwareMeterObservationHandler", "io.micrometer.tracing.Tracer", "io.micrometer.core.instrument.MeterRegistry" }) TracingAwareMeterObservationHandler<Observation.Context> tracingAwareMeterObservationHandler( MeterRegistry meterRegistry, Tracer tracer) { DefaultMeterObservationHandler delegate = new DefaultMeterObservationHandler(meterRegistry); return new TracingAwareMeterObservationHandler<>(delegate, tracer); } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/ObservabilityUtils.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/ObservabilityUtils.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.spring.boot.autoconfigure.observability; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.PROPERTY_NAME_SEPARATOR; /** * The utilities class for Dubbo Observability * * @since 3.2.0 */ public class ObservabilityUtils { public static final String DUBBO_TRACING_PREFIX = DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR + "tracing"; public static final String DUBBO_TRACING_PROPAGATION = DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "propagation"; public static final String DUBBO_TRACING_BAGGAGE = DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "baggage"; public static final String DUBBO_TRACING_BAGGAGE_CORRELATION = DUBBO_TRACING_BAGGAGE + PROPERTY_NAME_SEPARATOR + "correlation"; public static final String DUBBO_TRACING_BAGGAGE_ENABLED = DUBBO_TRACING_BAGGAGE + PROPERTY_NAME_SEPARATOR + "enabled"; public static final String DUBBO_TRACING_ZIPKIN_CONFIG_PREFIX = DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "tracing-exporter.zipkin-config"; public static final String DUBBO_TRACING_OTLP_CONFIG_PREFIX = DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "tracing-exporter.otlp-config"; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/DubboMicrometerTracingAutoConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/DubboMicrometerTracingAutoConfiguration.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.spring.boot.autoconfigure.observability; import org.apache.dubbo.spring.boot.autoconfigure.DubboAutoConfiguration; import org.apache.dubbo.spring.boot.autoconfigure.observability.annotation.ConditionalOnDubboTracingEnable; import org.apache.dubbo.tracing.handler.DubboClientTracingObservationHandler; import org.apache.dubbo.tracing.handler.DubboServerTracingObservationHandler; import io.micrometer.tracing.Tracer; import io.micrometer.tracing.handler.PropagatingReceiverTracingObservationHandler; import io.micrometer.tracing.handler.PropagatingSenderTracingObservationHandler; import io.micrometer.tracing.propagation.Propagator; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.core.annotation.Order; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * copy from {@link org.springframework.boot.actuate.autoconfigure.tracing.MicrometerTracingAutoConfiguration} * this class is available starting from Boot 3.0. It's not available if you're using Boot < 3.0 */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @ConditionalOnDubboTracingEnable @ConditionalOnClass( name = { "io.micrometer.observation.Observation", "io.micrometer.tracing.Tracer", "io.micrometer.tracing.propagation.Propagator" }) @AutoConfigureAfter( name = "org.springframework.boot.actuate.autoconfigure.tracing.MicrometerTracingAutoConfiguration", value = DubboAutoConfiguration.class) public class DubboMicrometerTracingAutoConfiguration { /** * {@code @Order} value of * {@link #propagatingReceiverTracingObservationHandler(io.micrometer.tracing.Tracer, io.micrometer.tracing.propagation.Propagator)}. */ public static final int RECEIVER_TRACING_OBSERVATION_HANDLER_ORDER = 1000; /** * {@code @Order} value of * {@link #propagatingSenderTracingObservationHandler(io.micrometer.tracing.Tracer, io.micrometer.tracing.propagation.Propagator)}. */ public static final int SENDER_TRACING_OBSERVATION_HANDLER_ORDER = 2000; @Bean @ConditionalOnMissingBean @ConditionalOnBean(io.micrometer.tracing.Tracer.class) public io.micrometer.tracing.handler.DefaultTracingObservationHandler defaultTracingObservationHandler( io.micrometer.tracing.Tracer tracer) { return new io.micrometer.tracing.handler.DefaultTracingObservationHandler(tracer); } @Bean @ConditionalOnMissingBean @ConditionalOnBean({io.micrometer.tracing.Tracer.class, io.micrometer.tracing.propagation.Propagator.class}) @Order(SENDER_TRACING_OBSERVATION_HANDLER_ORDER) public PropagatingSenderTracingObservationHandler<?> propagatingSenderTracingObservationHandler( Tracer tracer, Propagator propagator) { return new PropagatingSenderTracingObservationHandler<>(tracer, propagator); } @Bean @ConditionalOnMissingBean @ConditionalOnBean({io.micrometer.tracing.Tracer.class, io.micrometer.tracing.propagation.Propagator.class}) @Order(RECEIVER_TRACING_OBSERVATION_HANDLER_ORDER) public PropagatingReceiverTracingObservationHandler<?> propagatingReceiverTracingObservationHandler( Tracer tracer, Propagator propagator) { return new PropagatingReceiverTracingObservationHandler<>(tracer, propagator); } @Bean @ConditionalOnMissingBean @ConditionalOnBean({io.micrometer.tracing.Tracer.class}) @Order(SENDER_TRACING_OBSERVATION_HANDLER_ORDER) public DubboClientTracingObservationHandler<?> dubboClientTracingObservationHandler( io.micrometer.tracing.Tracer tracer) { return new DubboClientTracingObservationHandler<>(tracer); } @Bean @ConditionalOnMissingBean @ConditionalOnBean({io.micrometer.tracing.Tracer.class}) @Order(RECEIVER_TRACING_OBSERVATION_HANDLER_ORDER) public DubboServerTracingObservationHandler<?> dubboServerTracingObservationHandler( io.micrometer.tracing.Tracer tracer) { return new DubboServerTracingObservationHandler<>(tracer); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/ObservationRegistryPostProcessor.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/ObservationRegistryPostProcessor.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.spring.boot.autoconfigure.observability; import java.util.List; import java.util.stream.Collectors; import io.micrometer.observation.ObservationHandler; import io.micrometer.observation.ObservationRegistry; import org.springframework.beans.BeansException; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.config.BeanPostProcessor; /** * registry observationHandlers to observationConfig */ public class ObservationRegistryPostProcessor implements BeanPostProcessor { private final ObjectProvider<ObservationHandlerGrouping> observationHandlerGrouping; private final ObjectProvider<ObservationHandler<?>> observationHandlers; public ObservationRegistryPostProcessor( ObjectProvider<ObservationHandlerGrouping> observationHandlerGrouping, ObjectProvider<ObservationHandler<?>> observationHandlers) { this.observationHandlerGrouping = observationHandlerGrouping; this.observationHandlers = observationHandlers; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof ObservationRegistry) { ObservationRegistry observationRegistry = (ObservationRegistry) bean; List<ObservationHandler<?>> observationHandlerList = observationHandlers.orderedStream().collect(Collectors.toList()); observationHandlerGrouping.ifAvailable(grouping -> { grouping.apply(observationHandlerList, observationRegistry.observationConfig()); }); } return bean; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/brave/BraveAutoConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/brave/BraveAutoConfiguration.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.spring.boot.autoconfigure.observability.brave; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.spring.boot.autoconfigure.DubboConfigurationProperties; import org.apache.dubbo.spring.boot.autoconfigure.observability.DubboMicrometerTracingAutoConfiguration; import org.apache.dubbo.spring.boot.autoconfigure.observability.ObservabilityUtils; import org.apache.dubbo.spring.boot.autoconfigure.observability.annotation.ConditionalOnDubboTracingEnable; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.core.env.Environment; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * provider Brave when you are using Boot <3.0 or you are not using spring-boot-starter-actuator */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @AutoConfiguration( before = DubboMicrometerTracingAutoConfiguration.class, afterName = "org.springframework.boot.actuate.autoconfigure.tracing.BraveAutoConfiguration") @ConditionalOnClass( name = { "io.micrometer.tracing.Tracer", "io.micrometer.tracing.brave.bridge.BraveTracer", "io.micrometer.tracing.brave.bridge.BraveBaggageManager", "brave.Tracing" }) @EnableConfigurationProperties(DubboConfigurationProperties.class) @ConditionalOnDubboTracingEnable public class BraveAutoConfiguration { private static final io.micrometer.tracing.brave.bridge.BraveBaggageManager BRAVE_BAGGAGE_MANAGER = new io.micrometer.tracing.brave.bridge.BraveBaggageManager(); /** * Default value for application name if {@code spring.application.name} is not set. */ private static final String DEFAULT_APPLICATION_NAME = "unknown_dubbo_service"; private final DubboConfigurationProperties dubboConfigProperties; public BraveAutoConfiguration(DubboConfigurationProperties dubboConfigProperties) { this.dubboConfigProperties = dubboConfigProperties; } @Bean @ConditionalOnMissingBean @Order(Ordered.HIGHEST_PRECEDENCE) io.micrometer.tracing.brave.bridge.CompositeSpanHandler compositeSpanHandler( ObjectProvider<io.micrometer.tracing.exporter.SpanExportingPredicate> predicates, ObjectProvider<io.micrometer.tracing.exporter.SpanReporter> reporters, ObjectProvider<io.micrometer.tracing.exporter.SpanFilter> filters) { return new io.micrometer.tracing.brave.bridge.CompositeSpanHandler( predicates.orderedStream().collect(Collectors.toList()), reporters.orderedStream().collect(Collectors.toList()), filters.orderedStream().collect(Collectors.toList())); } @Bean @ConditionalOnMissingBean public brave.Tracing braveTracing( Environment environment, List<brave.handler.SpanHandler> spanHandlers, List<brave.TracingCustomizer> tracingCustomizers, brave.propagation.CurrentTraceContext currentTraceContext, brave.propagation.Propagation.Factory propagationFactory, brave.sampler.Sampler sampler) { String applicationName = dubboConfigProperties.getApplication().getName(); if (StringUtils.isBlank(applicationName)) { applicationName = environment.getProperty("spring.application.name", DEFAULT_APPLICATION_NAME); } brave.Tracing.Builder builder = brave.Tracing.newBuilder() .currentTraceContext(currentTraceContext) .traceId128Bit(true) .supportsJoin(false) .propagationFactory(propagationFactory) .sampler(sampler) .localServiceName(applicationName); spanHandlers.forEach(builder::addSpanHandler); for (brave.TracingCustomizer tracingCustomizer : tracingCustomizers) { tracingCustomizer.customize(builder); } return builder.build(); } @Bean @ConditionalOnMissingBean public brave.Tracer braveTracer(brave.Tracing tracing) { return tracing.tracer(); } @Bean @ConditionalOnMissingBean public brave.propagation.CurrentTraceContext braveCurrentTraceContext( List<brave.propagation.CurrentTraceContext.ScopeDecorator> scopeDecorators, List<brave.propagation.CurrentTraceContextCustomizer> currentTraceContextCustomizers) { brave.propagation.ThreadLocalCurrentTraceContext.Builder builder = brave.propagation.ThreadLocalCurrentTraceContext.newBuilder(); scopeDecorators.forEach(builder::addScopeDecorator); for (brave.propagation.CurrentTraceContextCustomizer currentTraceContextCustomizer : currentTraceContextCustomizers) { currentTraceContextCustomizer.customize(builder); } return builder.build(); } @Bean @ConditionalOnMissingBean public brave.sampler.Sampler braveSampler(DubboConfigurationProperties properties) { return brave.sampler.Sampler.create( properties.getTracing().getSampling().getProbability()); } @Bean @ConditionalOnMissingBean(io.micrometer.tracing.Tracer.class) io.micrometer.tracing.brave.bridge.BraveTracer braveTracerBridge( brave.Tracer tracer, brave.propagation.CurrentTraceContext currentTraceContext) { return new io.micrometer.tracing.brave.bridge.BraveTracer( tracer, new io.micrometer.tracing.brave.bridge.BraveCurrentTraceContext(currentTraceContext), BRAVE_BAGGAGE_MANAGER); } @Bean @ConditionalOnMissingBean io.micrometer.tracing.brave.bridge.BravePropagator bravePropagator(brave.Tracing tracing) { return new io.micrometer.tracing.brave.bridge.BravePropagator(tracing); } @Bean @ConditionalOnMissingBean(brave.SpanCustomizer.class) brave.CurrentSpanCustomizer currentSpanCustomizer(brave.Tracing tracing) { return brave.CurrentSpanCustomizer.create(tracing); } @Bean @ConditionalOnMissingBean(io.micrometer.tracing.SpanCustomizer.class) io.micrometer.tracing.brave.bridge.BraveSpanCustomizer braveSpanCustomizer(brave.SpanCustomizer spanCustomizer) { return new io.micrometer.tracing.brave.bridge.BraveSpanCustomizer(spanCustomizer); } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(value = ObservabilityUtils.DUBBO_TRACING_BAGGAGE_ENABLED, havingValue = "false") static class BraveNoBaggageConfiguration { @Bean @ConditionalOnMissingBean brave.propagation.Propagation.Factory propagationFactory(DubboConfigurationProperties tracing) { String type = tracing.getTracing().getPropagation().getType(); switch (type) { case org.apache.dubbo.config.nested.PropagationConfig.B3: return brave.propagation.B3Propagation.newFactoryBuilder() .injectFormat(brave.propagation.B3Propagation.Format.SINGLE_NO_PARENT) .build(); case org.apache.dubbo.config.nested.PropagationConfig.W3C: return new io.micrometer.tracing.brave.bridge.W3CPropagation(); default: throw new IllegalArgumentException("UnSupport propagation type"); } } } @ConditionalOnProperty(value = ObservabilityUtils.DUBBO_TRACING_BAGGAGE_ENABLED, matchIfMissing = true) @Configuration(proxyBeanMethods = false) static class BraveBaggageConfiguration { private final DubboConfigurationProperties dubboConfigProperties; public BraveBaggageConfiguration(DubboConfigurationProperties dubboConfigProperties) { this.dubboConfigProperties = dubboConfigProperties; } @Bean @ConditionalOnMissingBean @ConditionalOnProperty( prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, value = "type", havingValue = "B3") brave.baggage.BaggagePropagation.FactoryBuilder b3PropagationFactoryBuilder( ObjectProvider<brave.baggage.BaggagePropagationCustomizer> baggagePropagationCustomizers) { brave.propagation.Propagation.Factory delegate = brave.propagation.B3Propagation.newFactoryBuilder() .injectFormat(brave.propagation.B3Propagation.Format.SINGLE_NO_PARENT) .build(); brave.baggage.BaggagePropagation.FactoryBuilder builder = brave.baggage.BaggagePropagation.newFactoryBuilder(delegate); baggagePropagationCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder; } @Bean @ConditionalOnMissingBean @ConditionalOnProperty( prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, value = "type", havingValue = "W3C", matchIfMissing = true) brave.baggage.BaggagePropagation.FactoryBuilder w3cPropagationFactoryBuilder( ObjectProvider<brave.baggage.BaggagePropagationCustomizer> baggagePropagationCustomizers) { brave.propagation.Propagation.Factory delegate = new io.micrometer.tracing.brave.bridge.W3CPropagation( BRAVE_BAGGAGE_MANAGER, Collections.emptyList()); brave.baggage.BaggagePropagation.FactoryBuilder builder = brave.baggage.BaggagePropagation.newFactoryBuilder(delegate); baggagePropagationCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder; } @Bean @ConditionalOnMissingBean @Order(0) brave.baggage.BaggagePropagationCustomizer remoteFieldsBaggagePropagationCustomizer() { return (builder) -> { List<String> remoteFields = dubboConfigProperties.getTracing().getBaggage().getRemoteFields(); for (String fieldName : remoteFields) { builder.add(brave.baggage.BaggagePropagationConfig.SingleBaggageField.remote( brave.baggage.BaggageField.create(fieldName))); } }; } @Bean @ConditionalOnMissingBean brave.propagation.Propagation.Factory propagationFactory( brave.baggage.BaggagePropagation.FactoryBuilder factoryBuilder) { return factoryBuilder.build(); } @Bean @ConditionalOnMissingBean brave.baggage.CorrelationScopeDecorator.Builder mdcCorrelationScopeDecoratorBuilder( ObjectProvider<brave.baggage.CorrelationScopeCustomizer> correlationScopeCustomizers) { brave.baggage.CorrelationScopeDecorator.Builder builder = brave.context.slf4j.MDCScopeDecorator.newBuilder(); correlationScopeCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder; } @Bean @Order(0) @ConditionalOnProperty( prefix = ObservabilityUtils.DUBBO_TRACING_BAGGAGE_CORRELATION, name = "enabled", matchIfMissing = true) @ConditionalOnMissingBean brave.baggage.CorrelationScopeCustomizer correlationFieldsCorrelationScopeCustomizer() { return (builder) -> { List<String> correlationFields = this.dubboConfigProperties .getTracing() .getBaggage() .getCorrelation() .getFields(); for (String field : correlationFields) { builder.add(brave.baggage.CorrelationScopeConfig.SingleCorrelationField.newBuilder( brave.baggage.BaggageField.create(field)) .flushOnUpdate() .build()); } }; } @Bean @ConditionalOnMissingBean(brave.propagation.CurrentTraceContext.ScopeDecorator.class) brave.propagation.CurrentTraceContext.ScopeDecorator correlationScopeDecorator( brave.baggage.CorrelationScopeDecorator.Builder builder) { return builder.build(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/otlp/OtlpAutoConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/otlp/OtlpAutoConfiguration.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.spring.boot.autoconfigure.observability.otlp; import org.apache.dubbo.config.nested.ExporterConfig.OtlpConfig; import org.apache.dubbo.spring.boot.autoconfigure.DubboConfigurationProperties; import org.apache.dubbo.spring.boot.autoconfigure.observability.annotation.ConditionalOnDubboTracingEnable; import java.util.Map; import io.micrometer.tracing.otel.bridge.OtelTracer; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder; import io.opentelemetry.sdk.trace.SdkTracerProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import static org.apache.dubbo.spring.boot.autoconfigure.observability.ObservabilityUtils.DUBBO_TRACING_OTLP_CONFIG_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * @since 3.2.2 */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @AutoConfiguration @ConditionalOnClass({OtelTracer.class, SdkTracerProvider.class, OpenTelemetry.class, OtlpGrpcSpanExporter.class}) @ConditionalOnDubboTracingEnable @EnableConfigurationProperties(DubboConfigurationProperties.class) public class OtlpAutoConfiguration { @Bean @ConditionalOnProperty(prefix = DUBBO_TRACING_OTLP_CONFIG_PREFIX, name = "endpoint") @ConditionalOnMissingBean( value = OtlpGrpcSpanExporter.class, type = "io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter") OtlpGrpcSpanExporter otlpGrpcSpanExporter(DubboConfigurationProperties properties) { OtlpConfig cfg = properties.getTracing().getTracingExporter().getOtlpConfig(); OtlpGrpcSpanExporterBuilder builder = OtlpGrpcSpanExporter.builder() .setEndpoint(cfg.getEndpoint()) .setTimeout(cfg.getTimeout()) .setCompression(cfg.getCompressionMethod()); for (Map.Entry<String, String> entry : cfg.getHeaders().entrySet()) { builder.addHeader(entry.getKey(), entry.getValue()); } return builder.build(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/annotation/ConditionalOnDubboTracingEnable.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/annotation/ConditionalOnDubboTracingEnable.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.spring.boot.autoconfigure.observability.annotation; import org.apache.dubbo.spring.boot.autoconfigure.observability.ObservabilityUtils; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; /** * Checks whether tracing is enabled. * It matches if the value of the {@code dubbo.tracing.enabled} property is {@code true} or if it * is not configured. * * @since 3.2.0 */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_PREFIX, name = "enabled") public @interface ConditionalOnDubboTracingEnable {}
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/otel/OpenTelemetryAutoConfiguration.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/otel/OpenTelemetryAutoConfiguration.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.spring.boot.autoconfigure.observability.otel; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.spring.boot.autoconfigure.DubboConfigurationProperties; import org.apache.dubbo.spring.boot.autoconfigure.observability.DubboMicrometerTracingAutoConfiguration; import org.apache.dubbo.spring.boot.autoconfigure.observability.ObservabilityUtils; import org.apache.dubbo.spring.boot.autoconfigure.observability.annotation.ConditionalOnDubboTracingEnable; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import io.opentelemetry.api.common.AttributeKey; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * provider OpenTelemetry when you are using Boot <3.0 or you are not using spring-boot-starter-actuator */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @AutoConfiguration( before = DubboMicrometerTracingAutoConfiguration.class, afterName = "org.springframework.boot.actuate.autoconfigure.tracing.OpenTelemetryAutoConfiguration") @ConditionalOnDubboTracingEnable @ConditionalOnClass( name = { "io.micrometer.tracing.otel.bridge.OtelTracer", "io.opentelemetry.sdk.trace.SdkTracerProvider", "io.opentelemetry.api.OpenTelemetry", "io.micrometer.tracing.SpanCustomizer" }) @EnableConfigurationProperties(DubboConfigurationProperties.class) public class OpenTelemetryAutoConfiguration { /** * Default value for application name if {@code spring.application.name} is not set. */ private static final String DEFAULT_APPLICATION_NAME = "unknown_dubbo_service"; private final DubboConfigurationProperties dubboConfigProperties; OpenTelemetryAutoConfiguration(DubboConfigurationProperties dubboConfigProperties) { this.dubboConfigProperties = dubboConfigProperties; } @Bean @ConditionalOnMissingBean io.opentelemetry.api.OpenTelemetry openTelemetry( io.opentelemetry.sdk.trace.SdkTracerProvider sdkTracerProvider, io.opentelemetry.context.propagation.ContextPropagators contextPropagators) { return io.opentelemetry.sdk.OpenTelemetrySdk.builder() .setTracerProvider(sdkTracerProvider) .setPropagators(contextPropagators) .build(); } @Bean @ConditionalOnMissingBean io.opentelemetry.sdk.trace.SdkTracerProvider otelSdkTracerProvider( Environment environment, ObjectProvider<io.opentelemetry.sdk.trace.SpanProcessor> spanProcessors, io.opentelemetry.sdk.trace.samplers.Sampler sampler) { String applicationName = dubboConfigProperties.getApplication().getName(); if (StringUtils.isBlank(applicationName)) { applicationName = environment.getProperty("spring.application.name", DEFAULT_APPLICATION_NAME); } // Due to https://github.com/micrometer-metrics/tracing/issues/343 String RESOURCE_ATTRIBUTES_CLASS_NAME = "io.opentelemetry.semconv.ResourceAttributes"; boolean isLowVersion = !ClassUtils.isPresent( RESOURCE_ATTRIBUTES_CLASS_NAME, Thread.currentThread().getContextClassLoader()); AttributeKey<String> serviceNameAttributeKey = AttributeKey.stringKey("service.name"); String SERVICE_NAME = "SERVICE_NAME"; if (isLowVersion) { RESOURCE_ATTRIBUTES_CLASS_NAME = "io.opentelemetry.semconv.resource.attributes.ResourceAttributes"; } try { serviceNameAttributeKey = (AttributeKey<String>) ClassUtils.resolveClass( RESOURCE_ATTRIBUTES_CLASS_NAME, Thread.currentThread().getContextClassLoader()) .getDeclaredField(SERVICE_NAME) .get(null); } catch (Throwable ignored) { } io.opentelemetry.sdk.trace.SdkTracerProviderBuilder builder = io.opentelemetry.sdk.trace.SdkTracerProvider.builder() .setSampler(sampler) .setResource(io.opentelemetry.sdk.resources.Resource.create( io.opentelemetry.api.common.Attributes.of(serviceNameAttributeKey, applicationName))); spanProcessors.orderedStream().forEach(builder::addSpanProcessor); return builder.build(); } @Bean @ConditionalOnMissingBean io.opentelemetry.context.propagation.ContextPropagators otelContextPropagators( ObjectProvider<io.opentelemetry.context.propagation.TextMapPropagator> textMapPropagators) { return io.opentelemetry.context.propagation.ContextPropagators.create( io.opentelemetry.context.propagation.TextMapPropagator.composite( textMapPropagators.orderedStream().collect(Collectors.toList()))); } @Bean @ConditionalOnMissingBean io.opentelemetry.sdk.trace.samplers.Sampler otelSampler() { io.opentelemetry.sdk.trace.samplers.Sampler rootSampler = io.opentelemetry.sdk.trace.samplers.Sampler.traceIdRatioBased( this.dubboConfigProperties.getTracing().getSampling().getProbability()); return io.opentelemetry.sdk.trace.samplers.Sampler.parentBased(rootSampler); } @Bean @ConditionalOnMissingBean io.opentelemetry.sdk.trace.SpanProcessor otelSpanProcessor( ObjectProvider<io.opentelemetry.sdk.trace.export.SpanExporter> spanExporters, ObjectProvider<io.micrometer.tracing.exporter.SpanExportingPredicate> spanExportingPredicates, ObjectProvider<io.micrometer.tracing.exporter.SpanReporter> spanReporters, ObjectProvider<io.micrometer.tracing.exporter.SpanFilter> spanFilters) { return io.opentelemetry.sdk.trace.export.BatchSpanProcessor.builder( new io.micrometer.tracing.otel.bridge.CompositeSpanExporter( spanExporters.orderedStream().collect(Collectors.toList()), spanExportingPredicates.orderedStream().collect(Collectors.toList()), spanReporters.orderedStream().collect(Collectors.toList()), spanFilters.orderedStream().collect(Collectors.toList()))) .build(); } @Bean @ConditionalOnMissingBean io.opentelemetry.api.trace.Tracer otelTracer(io.opentelemetry.api.OpenTelemetry openTelemetry) { return openTelemetry.getTracer("org.apache.dubbo", Version.getVersion()); } @Bean @ConditionalOnMissingBean(io.micrometer.tracing.Tracer.class) io.micrometer.tracing.otel.bridge.OtelTracer micrometerOtelTracer( io.opentelemetry.api.trace.Tracer tracer, io.micrometer.tracing.otel.bridge.OtelTracer.EventPublisher eventPublisher, io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext otelCurrentTraceContext) { return new io.micrometer.tracing.otel.bridge.OtelTracer( tracer, otelCurrentTraceContext, eventPublisher, new io.micrometer.tracing.otel.bridge.OtelBaggageManager( otelCurrentTraceContext, this.dubboConfigProperties.getTracing().getBaggage().getRemoteFields(), Collections.emptyList())); } @Bean @ConditionalOnMissingBean io.micrometer.tracing.otel.bridge.OtelPropagator otelPropagator( io.opentelemetry.context.propagation.ContextPropagators contextPropagators, io.opentelemetry.api.trace.Tracer tracer) { return new io.micrometer.tracing.otel.bridge.OtelPropagator(contextPropagators, tracer); } @Bean @ConditionalOnMissingBean io.micrometer.tracing.otel.bridge.OtelTracer.EventPublisher otelTracerEventPublisher( List<io.micrometer.tracing.otel.bridge.EventListener> eventListeners) { return new OTelEventPublisher(eventListeners); } @Bean @ConditionalOnMissingBean io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext otelCurrentTraceContext( io.micrometer.tracing.otel.bridge.OtelTracer.EventPublisher publisher) { io.opentelemetry.context.ContextStorage.addWrapper( new io.micrometer.tracing.otel.bridge.EventPublishingContextWrapper(publisher)); return new io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext(); } @Bean @ConditionalOnMissingBean io.micrometer.tracing.otel.bridge.Slf4JEventListener otelSlf4JEventListener() { return new io.micrometer.tracing.otel.bridge.Slf4JEventListener(); } @Bean @ConditionalOnMissingBean(io.micrometer.tracing.SpanCustomizer.class) io.micrometer.tracing.otel.bridge.OtelSpanCustomizer otelSpanCustomizer() { return new io.micrometer.tracing.otel.bridge.OtelSpanCustomizer(); } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_BAGGAGE, name = "enabled", matchIfMissing = true) static class BaggageConfiguration { private final DubboConfigurationProperties dubboConfigProperties; BaggageConfiguration(DubboConfigurationProperties dubboConfigProperties) { this.dubboConfigProperties = dubboConfigProperties; } @Bean @ConditionalOnMissingBean @ConditionalOnProperty( prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, name = "type", havingValue = "W3C", matchIfMissing = true) @ConditionalOnClass(name = {"io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext"}) io.opentelemetry.context.propagation.TextMapPropagator w3cTextMapPropagatorWithBaggage( io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext otelCurrentTraceContext) { List<String> remoteFields = this.dubboConfigProperties.getTracing().getBaggage().getRemoteFields(); return io.opentelemetry.context.propagation.TextMapPropagator.composite( io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator.getInstance(), io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator.getInstance(), new io.micrometer.tracing.otel.propagation.BaggageTextMapPropagator( remoteFields, new io.micrometer.tracing.otel.bridge.OtelBaggageManager( otelCurrentTraceContext, remoteFields, Collections.emptyList()))); } @Bean @ConditionalOnMissingBean @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, name = "type", havingValue = "B3") io.opentelemetry.context.propagation.TextMapPropagator b3BaggageTextMapPropagator( io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext otelCurrentTraceContext) { List<String> remoteFields = this.dubboConfigProperties.getTracing().getBaggage().getRemoteFields(); return io.opentelemetry.context.propagation.TextMapPropagator.composite( io.opentelemetry.extension.trace.propagation.B3Propagator.injectingSingleHeader(), new io.micrometer.tracing.otel.propagation.BaggageTextMapPropagator( remoteFields, new io.micrometer.tracing.otel.bridge.OtelBaggageManager( otelCurrentTraceContext, remoteFields, Collections.emptyList()))); } @Bean @ConditionalOnMissingBean @ConditionalOnProperty( prefix = ObservabilityUtils.DUBBO_TRACING_BAGGAGE_CORRELATION, name = "enabled", matchIfMissing = true) io.micrometer.tracing.otel.bridge.Slf4JBaggageEventListener otelSlf4JBaggageEventListener() { return new io.micrometer.tracing.otel.bridge.Slf4JBaggageEventListener(this.dubboConfigProperties .getTracing() .getBaggage() .getCorrelation() .getFields()); } } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_BAGGAGE, name = "enabled", havingValue = "false") static class NoBaggageConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, name = "type", havingValue = "B3") io.opentelemetry.extension.trace.propagation.B3Propagator b3TextMapPropagator() { return io.opentelemetry.extension.trace.propagation.B3Propagator.injectingSingleHeader(); } @Bean @ConditionalOnMissingBean @ConditionalOnProperty( prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, name = "type", havingValue = "W3C", matchIfMissing = true) io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator w3cTextMapPropagatorWithoutBaggage() { return io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator.getInstance(); } } static class OTelEventPublisher implements io.micrometer.tracing.otel.bridge.OtelTracer.EventPublisher { private final List<io.micrometer.tracing.otel.bridge.EventListener> listeners; OTelEventPublisher(List<io.micrometer.tracing.otel.bridge.EventListener> listeners) { this.listeners = listeners; } @Override public void publishEvent(Object event) { for (io.micrometer.tracing.otel.bridge.EventListener listener : this.listeners) { listener.onEvent(event); } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/zipkin/ZipkinWebClientSender.java
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/zipkin/ZipkinWebClientSender.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.spring.boot.autoconfigure.observability.zipkin; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import zipkin2.reporter.Call; import zipkin2.reporter.Callback; class ZipkinWebClientSender extends HttpSender { private final String endpoint; private final WebClient webClient; ZipkinWebClientSender(String endpoint, WebClient webClient) { this.endpoint = endpoint; this.webClient = webClient; } @Override public HttpPostCall sendSpans(byte[] batchedEncodedSpans) { return new WebClientHttpPostCall(this.endpoint, batchedEncodedSpans, this.webClient); } private static class WebClientHttpPostCall extends HttpPostCall { private final String endpoint; private final WebClient webClient; WebClientHttpPostCall(String endpoint, byte[] body, WebClient webClient) { super(body); this.endpoint = endpoint; this.webClient = webClient; } @Override public Call<Void> clone() { return new WebClientHttpPostCall(this.endpoint, getUncompressedBody(), this.webClient); } @Override protected Void doExecute() { sendRequest().block(); return null; } @Override protected void doEnqueue(Callback<Void> callback) { sendRequest().subscribe((entity) -> callback.onSuccess(null), callback::onError); } private Mono<ResponseEntity<Void>> sendRequest() { return this.webClient .post() .uri(this.endpoint) .headers(this::addDefaultHeaders) .bodyValue(getBody()) .retrieve() .toBodilessEntity(); } private void addDefaultHeaders(HttpHeaders headers) { headers.addAll(getDefaultHeaders()); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false