repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/TraceTelnetHandler.java
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/TraceTelnetHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.telnet.TelnetHandler; import org.apache.dubbo.remoting.telnet.support.Help; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import org.apache.dubbo.rpc.protocol.dubbo.filter.TraceFilter; import java.lang.reflect.Method; @Activate @Help(parameter = "[service] [method] [times]", summary = "Trace the service.", detail = "Trace the service.") public class TraceTelnetHandler implements TelnetHandler { @Override public String telnet(Channel channel, String message) { String service = (String) channel.getAttribute(ChangeTelnetHandler.SERVICE_KEY); if ((StringUtils.isEmpty(service)) && (StringUtils.isEmpty(message))) { return "Please input service name, eg: \r\ntrace XxxService\r\ntrace XxxService xxxMethod\r\ntrace XxxService xxxMethod 10\r\nor \"cd XxxService\" firstly."; } String[] parts = message.split("\\s+"); String method; String times; // message like : XxxService , XxxService 10 , XxxService xxxMethod , XxxService xxxMethod 10 if (StringUtils.isEmpty(service)) { service = parts.length > 0 ? parts[0] : null; method = parts.length > 1 ? parts[1] : null; times = parts.length > 2 ? parts[2] : "1"; } else { // message like : xxxMethod, xxxMethod 10 method = parts.length > 0 ? parts[0] : null; times = parts.length > 1 ? parts[1] : "1"; } if (StringUtils.isNumber(method)) { times = method; method = null; } if (!StringUtils.isNumber(times)) { return "Illegal times " + times + ", must be integer."; } Invoker<?> invoker = null; for (Exporter<?> exporter : DubboProtocol.getDubboProtocol().getExporters()) { if (service.equals(exporter.getInvoker().getInterface().getSimpleName()) || service.equals(exporter.getInvoker().getInterface().getName()) || service.equals(exporter.getInvoker().getUrl().getPath())) { invoker = exporter.getInvoker(); break; } } if (invoker != null) { if (StringUtils.isNotEmpty(method)) { boolean found = false; for (Method m : invoker.getInterface().getMethods()) { if (m.getName().equals(method)) { found = true; break; } } if (!found) { return "No such method " + method + " in class " + invoker.getInterface().getName(); } } TraceFilter.addTracer(invoker.getInterface(), method, channel, Integer.parseInt(times)); } else { return "No such service " + service; } return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/QosBindException.java
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/QosBindException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server; /** * Indicate that if Qos Start failed */ public class QosBindException extends RuntimeException { public QosBindException(String message, Throwable cause) { super(message, cause); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/Server.java
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/Server.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server; 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.qos.api.PermissionLevel; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.qos.server.handler.QosProcessHandler; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.concurrent.atomic.AtomicBoolean; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.util.concurrent.DefaultThreadFactory; /** * A server serves for both telnet access and http access * <ul> * <li>static initialize server</li> * <li>start server and bind port</li> * <li>close server</li> * </ul> */ public class Server { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Server.class); private String host; private int port; private boolean acceptForeignIp = true; private String acceptForeignIpWhitelist = StringUtils.EMPTY_STRING; private String anonymousAccessPermissionLevel = PermissionLevel.NONE.name(); private String anonymousAllowCommands = StringUtils.EMPTY_STRING; private EventLoopGroup boss; private EventLoopGroup worker; private FrameworkModel frameworkModel; public Server(FrameworkModel frameworkModel) { this.welcome = DubboLogo.DUBBO; this.frameworkModel = frameworkModel; } private String welcome; private AtomicBoolean started = new AtomicBoolean(); /** * welcome message */ public void setWelcome(String welcome) { this.welcome = welcome; } public int getPort() { return port; } /** * start server, bind port */ public void start() throws Throwable { if (!started.compareAndSet(false, true)) { return; } boss = new NioEventLoopGroup(1, new DefaultThreadFactory("qos-boss", true)); worker = new NioEventLoopGroup(0, new DefaultThreadFactory("qos-worker", true)); ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(boss, worker); serverBootstrap.channel(NioServerSocketChannel.class); serverBootstrap.option(ChannelOption.SO_REUSEADDR, true); serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true); serverBootstrap.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline() .addLast(new QosProcessHandler( frameworkModel, QosConfiguration.builder() .welcome(welcome) .acceptForeignIp(acceptForeignIp) .acceptForeignIpWhitelist(acceptForeignIpWhitelist) .anonymousAccessPermissionLevel(anonymousAccessPermissionLevel) .anonymousAllowCommands(anonymousAllowCommands) .build())); } }); try { if (StringUtils.isBlank(host)) { serverBootstrap.bind(port).sync(); } else { serverBootstrap.bind(host, port).sync(); } logger.info("qos-server bind localhost:" + port); } catch (Throwable throwable) { throw new QosBindException("qos-server can not bind localhost:" + port, throwable); } } /** * close server */ public void stop() { logger.info("qos-server stopped."); if (boss != null) { boss.shutdownGracefully(); } if (worker != null) { worker.shutdownGracefully(); } started.set(false); } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public void setPort(int port) { this.port = port; } public boolean isAcceptForeignIp() { return acceptForeignIp; } public void setAcceptForeignIp(boolean acceptForeignIp) { this.acceptForeignIp = acceptForeignIp; } public void setAcceptForeignIpWhitelist(String acceptForeignIpWhitelist) { this.acceptForeignIpWhitelist = acceptForeignIpWhitelist; } public void setAnonymousAccessPermissionLevel(String anonymousAccessPermissionLevel) { this.anonymousAccessPermissionLevel = anonymousAccessPermissionLevel; } public void setAnonymousAllowCommands(String anonymousAllowCommands) { this.anonymousAllowCommands = anonymousAllowCommands; } public String getWelcome() { return welcome; } public boolean isStarted() { return started.get(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/DubboLogo.java
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/DubboLogo.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server; public class DubboLogo { public static final String DUBBO = " ___ __ __ ___ ___ ____ " + System.lineSeparator() + " / _ \\ / / / // _ ) / _ ) / __ \\ " + System.lineSeparator() + " / // // /_/ // _ |/ _ |/ /_/ / " + System.lineSeparator() + "/____/ \\____//____//____/ \\____/ " + System.lineSeparator(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/HttpProcessHandler.java
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/HttpProcessHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.qos.command.CommandExecutor; import org.apache.dubbo.qos.command.DefaultCommandExecutor; import org.apache.dubbo.qos.command.decoder.HttpCommandDecoder; import org.apache.dubbo.qos.command.exception.NoSuchCommandException; import org.apache.dubbo.qos.command.exception.PermissionDenyException; import org.apache.dubbo.rpc.model.FrameworkModel; import java.nio.charset.StandardCharsets; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_COMMAND_NOT_FOUND; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PERMISSION_DENY_EXCEPTION; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_UNEXPECTED_EXCEPTION; /** * Parse HttpRequest for uri and parameters * <p> * <ul> * <li>if command not found, return 404</li> * <li>if execution fails, return 500</li> * <li>if succeed, return 200</li> * </ul> * <p> * will disconnect after execution finishes */ public class HttpProcessHandler extends SimpleChannelInboundHandler<HttpRequest> { private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(HttpProcessHandler.class); private final CommandExecutor commandExecutor; private final QosConfiguration qosConfiguration; public HttpProcessHandler(FrameworkModel frameworkModel, QosConfiguration qosConfiguration) { this.commandExecutor = new DefaultCommandExecutor(frameworkModel); this.qosConfiguration = qosConfiguration; } private static FullHttpResponse http(int httpCode, String result) { FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(httpCode), Unpooled.wrappedBuffer(result.getBytes(StandardCharsets.UTF_8))); HttpHeaders httpHeaders = response.headers(); httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=utf-8"); httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); return response; } private static FullHttpResponse http(int httpCode) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(httpCode)); HttpHeaders httpHeaders = response.headers(); httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, "text/plain"); httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); return response; } @Override protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception { CommandContext commandContext = HttpCommandDecoder.decode(msg); // return 404 when fail to construct command context if (commandContext == null) { log.warn(QOS_UNEXPECTED_EXCEPTION, "", "", "can not found commandContext, url: " + msg.uri()); FullHttpResponse response = http(404); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { commandContext.setRemote(ctx.channel()); commandContext.setQosConfiguration(qosConfiguration); try { String result = commandExecutor.execute(commandContext); int httpCode = commandContext.getHttpCode(); FullHttpResponse response = http(httpCode, result); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (NoSuchCommandException ex) { log.error(QOS_COMMAND_NOT_FOUND, "", "", "can not find command: " + commandContext, ex); FullHttpResponse response = http(404); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (PermissionDenyException ex) { log.error( QOS_PERMISSION_DENY_EXCEPTION, "", "", "permission deny to access command: " + commandContext, ex); FullHttpResponse response = http(403); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (Exception qosEx) { log.error( QOS_UNEXPECTED_EXCEPTION, "", "", "execute commandContext: " + commandContext + " got exception", qosEx); FullHttpResponse response = http(500, qosEx.getMessage()); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandler.java
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.qos.command.CommandExecutor; import org.apache.dubbo.qos.command.DefaultCommandExecutor; import org.apache.dubbo.qos.command.decoder.TelnetCommandDecoder; import org.apache.dubbo.qos.command.exception.NoSuchCommandException; import org.apache.dubbo.qos.command.exception.PermissionDenyException; import org.apache.dubbo.qos.common.QosConstants; import org.apache.dubbo.rpc.model.FrameworkModel; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_COMMAND_NOT_FOUND; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PERMISSION_DENY_EXCEPTION; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_UNEXPECTED_EXCEPTION; /** * Telnet process handler */ public class TelnetProcessHandler extends SimpleChannelInboundHandler<String> { private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(TelnetProcessHandler.class); private final CommandExecutor commandExecutor; private final QosConfiguration qosConfiguration; public TelnetProcessHandler(FrameworkModel frameworkModel, QosConfiguration qosConfiguration) { this.commandExecutor = new DefaultCommandExecutor(frameworkModel); this.qosConfiguration = qosConfiguration; } @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { if (StringUtils.isBlank(msg)) { ctx.writeAndFlush(QosProcessHandler.PROMPT); } else { CommandContext commandContext = TelnetCommandDecoder.decode(msg); commandContext.setQosConfiguration(qosConfiguration); commandContext.setRemote(ctx.channel()); try { String result = commandExecutor.execute(commandContext); if (StringUtils.isEquals(QosConstants.CLOSE, result)) { ctx.writeAndFlush(getByeLabel()).addListener(ChannelFutureListener.CLOSE); } else { ctx.writeAndFlush(result + QosConstants.BR_STR + QosProcessHandler.PROMPT); } } catch (NoSuchCommandException ex) { ctx.writeAndFlush(msg + " :no such command"); ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.PROMPT); log.error(QOS_COMMAND_NOT_FOUND, "", "", "can not found command " + commandContext, ex); } catch (PermissionDenyException ex) { ctx.writeAndFlush(msg + " :permission deny"); ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.PROMPT); log.error( QOS_PERMISSION_DENY_EXCEPTION, "", "", "permission deny to access command " + commandContext, ex); } catch (Exception ex) { ctx.writeAndFlush(msg + " :fail to execute commandContext by " + ex.getMessage()); ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.PROMPT); log.error( QOS_UNEXPECTED_EXCEPTION, "", "", "execute commandContext got exception " + commandContext, ex); } } } private String getByeLabel() { return "BYE!\n"; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/ForeignHostPermitHandler.java
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/ForeignHostPermitHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.qos.common.QosConstants; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.function.Predicate; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; public class ForeignHostPermitHandler extends ChannelHandlerAdapter { // true means to accept foreign IP private final boolean acceptForeignIp; // the whitelist of foreign IP when acceptForeignIp = false, the delimiter is colon(,) // support specific ip and an ip range from CIDR specification private final String acceptForeignIpWhitelist; private final Predicate<String> whitelistPredicate; private final QosConfiguration qosConfiguration; public ForeignHostPermitHandler(QosConfiguration qosConfiguration) { this.qosConfiguration = qosConfiguration; this.acceptForeignIp = qosConfiguration.isAcceptForeignIp(); this.acceptForeignIpWhitelist = qosConfiguration.getAcceptForeignIpWhitelist(); this.whitelistPredicate = qosConfiguration.getAcceptForeignIpWhitelistPredicate(); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { if (acceptForeignIp) { return; } // the anonymous access is enabled by default, permission level is PUBLIC // if allow anonymous access, return if (qosConfiguration.isAllowAnonymousAccess()) { return; } final InetAddress inetAddress = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress(); // loopback address, return if (inetAddress.isLoopbackAddress()) { return; } // the ip is in the whitelist, return if (checkForeignIpInWhiteList(inetAddress)) { return; } ByteBuf cb = Unpooled.wrappedBuffer((QosConstants.BR_STR + "Foreign Ip Not Permitted, Consider Config It In Whitelist." + QosConstants.BR_STR) .getBytes(StandardCharsets.UTF_8)); ctx.writeAndFlush(cb).addListener(ChannelFutureListener.CLOSE); } private boolean checkForeignIpInWhiteList(InetAddress inetAddress) { if (StringUtils.isEmpty(acceptForeignIpWhitelist)) { return false; } final String foreignIp = inetAddress.getHostAddress(); return whitelistPredicate.test(foreignIp); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetIdleEventHandler.java
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetIdleEventHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.timeout.IdleStateEvent; public class TelnetIdleEventHandler extends ChannelDuplexHandler { private static final Logger log = LoggerFactory.getLogger(TelnetIdleEventHandler.class); @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { // server will close channel when server don't receive any request from client util timeout. if (evt instanceof IdleStateEvent) { Channel channel = ctx.channel(); log.info("IdleStateEvent triggered, close channel " + channel); channel.close(); } else { super.userEventTriggered(ctx, evt); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/CtrlCHandler.java
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/CtrlCHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.qos.common.QosConstants; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.util.CharsetUtil; import io.netty.util.ReferenceCountUtil; public class CtrlCHandler extends SimpleChannelInboundHandler<ByteBuf> { /** * When type 'Ctrl+C', telnet client will send the following sequence: * 'FF F4 FF FD 06', it can be divided into two parts: * <p> * 1. 'FF F4' is telnet interrupt process command. * <p> * 2. 'FF FD 06' is to suppress the output of the process that is to be * interrupted by the interrupt process command. * <p> * We need to response with 'FF FC 06' to ignore it and tell the client continue * display output. */ private byte[] CTRLC_BYTES_SEQUENCE = new byte[] {(byte) 0xff, (byte) 0xf4, (byte) 0xff, (byte) 0xfd, (byte) 0x06}; private byte[] RESPONSE_SEQUENCE = new byte[] {(byte) 0xff, (byte) 0xfc, 0x06}; public CtrlCHandler() { super(false); } @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception { // find ctrl+c final int readerIndex = buffer.readerIndex(); for (int i = readerIndex; i < buffer.writerIndex(); i++) { if (buffer.readableBytes() - i < CTRLC_BYTES_SEQUENCE.length) { break; } boolean match = true; for (int j = 0; j < CTRLC_BYTES_SEQUENCE.length; j++) { if (CTRLC_BYTES_SEQUENCE[j] != buffer.getByte(i + j)) { match = false; break; } } if (match) { buffer.readerIndex(readerIndex + buffer.readableBytes()); ctx.writeAndFlush(Unpooled.wrappedBuffer(RESPONSE_SEQUENCE)); ctx.writeAndFlush(Unpooled.wrappedBuffer( (QosConstants.BR_STR + QosProcessHandler.PROMPT).getBytes(CharsetUtil.UTF_8))); ReferenceCountUtil.release(buffer); return; } } ctx.fireChannelRead(buffer); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/QosProcessHandler.java
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/QosProcessHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.common.utils.ExecutorUtil; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.rpc.model.FrameworkModel; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.concurrent.TimeUnit; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.handler.timeout.IdleStateEvent; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.CharsetUtil; import io.netty.util.concurrent.ScheduledFuture; public class QosProcessHandler extends ByteToMessageDecoder { private ScheduledFuture<?> welcomeFuture; private final FrameworkModel frameworkModel; public static final String PROMPT = "dubbo>"; private final QosConfiguration qosConfiguration; public QosProcessHandler(FrameworkModel frameworkModel, QosConfiguration qosConfiguration) { this.frameworkModel = frameworkModel; this.qosConfiguration = qosConfiguration; } @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { welcomeFuture = ctx.executor() .schedule( () -> { final String welcome = qosConfiguration.getWelcome(); if (welcome != null) { ctx.write(Unpooled.wrappedBuffer(welcome.getBytes(StandardCharsets.UTF_8))); ctx.writeAndFlush(Unpooled.wrappedBuffer(PROMPT.getBytes(StandardCharsets.UTF_8))); } }, 500, TimeUnit.MILLISECONDS); } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() < 1) { return; } // read one byte to guess protocol final int magic = in.getByte(in.readerIndex()); ChannelPipeline p = ctx.pipeline(); p.addLast(new ForeignHostPermitHandler(qosConfiguration)); if (isHttp(magic)) { // no welcome output for http protocol if (welcomeFuture != null && welcomeFuture.isCancellable()) { welcomeFuture.cancel(false); } p.addLast(new HttpServerCodec()); p.addLast(new HttpObjectAggregator(1048576)); p.addLast(new HttpProcessHandler(frameworkModel, qosConfiguration)); p.remove(this); } else { p.addLast(new CtrlCHandler()); p.addLast(new LineBasedFrameDecoder(2048)); p.addLast(new StringDecoder(CharsetUtil.UTF_8)); p.addLast(new StringEncoder(CharsetUtil.UTF_8)); p.addLast(new IdleStateHandler(0, 0, 5 * 60)); p.addLast(new TelnetIdleEventHandler()); p.addLast(new TelnetProcessHandler(frameworkModel, qosConfiguration)); p.remove(this); } } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { ExecutorUtil.cancelScheduledFuture(welcomeFuture); ctx.close(); } } // G for GET, and P for POST private static boolean isHttp(int magic) { return magic == 'G' || magic == 'P'; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; 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.qos.api.PermissionLevel; import org.apache.dubbo.qos.common.QosConstants; import org.apache.dubbo.qos.server.Server; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeModelAware; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_FAILED_START_SERVER; import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP; import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP_WHITELIST; import static org.apache.dubbo.common.constants.QosConstants.ANONYMOUS_ACCESS_ALLOW_COMMANDS; import static org.apache.dubbo.common.constants.QosConstants.ANONYMOUS_ACCESS_PERMISSION_LEVEL; import static org.apache.dubbo.common.constants.QosConstants.QOS_CHECK; import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE; import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST; import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT; @Activate(order = 200) public class QosProtocolWrapper implements Protocol, ScopeModelAware { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(QosProtocolWrapper.class); private final AtomicBoolean hasStarted = new AtomicBoolean(false); private final Protocol protocol; private FrameworkModel frameworkModel; public QosProtocolWrapper(Protocol protocol) { if (protocol == null) { throw new IllegalArgumentException("protocol == null"); } this.protocol = protocol; } @Override public void setFrameworkModel(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } @Override public int getDefaultPort() { return protocol.getDefaultPort(); } @Override public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { startQosServer(invoker.getUrl(), true); return protocol.export(invoker); } @Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { startQosServer(url, false); return protocol.refer(type, url); } @Override public void destroy() { protocol.destroy(); stopServer(); } @Override public List<ProtocolServer> getServers() { return protocol.getServers(); } private void startQosServer(URL url, boolean isServer) throws RpcException { boolean qosCheck = url.getParameter(QOS_CHECK, false); try { if (!hasStarted.compareAndSet(false, true)) { return; } boolean qosEnable = url.getParameter(QOS_ENABLE, true); if (!qosEnable) { logger.info("qos won't be started because it is disabled. " + "Please check dubbo.application.qos.enable is configured either in system property, " + "dubbo.properties or XML/spring-boot configuration."); return; } String host = url.getParameter(QOS_HOST); int port = url.getParameter(QOS_PORT, QosConstants.DEFAULT_PORT); boolean acceptForeignIp = Boolean.parseBoolean(url.getParameter(ACCEPT_FOREIGN_IP, "false")); String acceptForeignIpWhitelist = url.getParameter(ACCEPT_FOREIGN_IP_WHITELIST, StringUtils.EMPTY_STRING); String anonymousAccessPermissionLevel = url.getParameter(ANONYMOUS_ACCESS_PERMISSION_LEVEL, PermissionLevel.PUBLIC.name()); String anonymousAllowCommands = url.getParameter(ANONYMOUS_ACCESS_ALLOW_COMMANDS, StringUtils.EMPTY_STRING); Server server = frameworkModel.getBeanFactory().getBean(Server.class); if (server.isStarted()) { return; } server.setHost(host); server.setPort(port); server.setAcceptForeignIp(acceptForeignIp); server.setAcceptForeignIpWhitelist(acceptForeignIpWhitelist); server.setAnonymousAccessPermissionLevel(anonymousAccessPermissionLevel); server.setAnonymousAllowCommands(anonymousAllowCommands); server.start(); } catch (Throwable throwable) { logger.warn(QOS_FAILED_START_SERVER, "", "", "Fail to start qos server: ", throwable); if (qosCheck) { try { // Stop QoS Server to support re-start if Qos-Check is enabled stopServer(); } catch (Throwable stop) { logger.warn(QOS_FAILED_START_SERVER, "", "", "Fail to stop qos server: ", stop); } if (isServer) { // Only throws exception when export services throw new RpcException(throwable); } } } } /*package*/ void stopServer() { if (hasStarted.compareAndSet(true, false)) { Server server = frameworkModel.getBeanFactory().getBean(Server.class); if (server.isStarted()) { server.stop(); } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/permission/DefaultAnonymousAccessPermissionChecker.java
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/permission/DefaultAnonymousAccessPermissionChecker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.permission; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.api.QosConfiguration; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.Optional; import io.netty.channel.Channel; public class DefaultAnonymousAccessPermissionChecker implements PermissionChecker { public static final DefaultAnonymousAccessPermissionChecker INSTANCE = new DefaultAnonymousAccessPermissionChecker(); @Override public boolean access(CommandContext commandContext, PermissionLevel defaultCmdRequiredPermissionLevel) { final InetAddress inetAddress = Optional.ofNullable(commandContext.getRemote()) .map(Channel::remoteAddress) .map(InetSocketAddress.class::cast) .map(InetSocketAddress::getAddress) .orElse(null); QosConfiguration qosConfiguration = commandContext.getQosConfiguration(); String anonymousAllowCommands = qosConfiguration.getAnonymousAllowCommands(); if (StringUtils.isNotEmpty(anonymousAllowCommands) && Arrays.stream(anonymousAllowCommands.split(",")) .filter(StringUtils::isNotEmpty) .map(String::trim) .anyMatch(cmd -> cmd.equals(commandContext.getCommandName()))) { return true; } PermissionLevel currentLevel = qosConfiguration.getAnonymousAccessPermissionLevel(); // Local has private permission if (inetAddress != null && inetAddress.isLoopbackAddress()) { currentLevel = PermissionLevel.PRIVATE; } else if (inetAddress != null && qosConfiguration.getAcceptForeignIpWhitelistPredicate().test(inetAddress.getHostAddress())) { currentLevel = PermissionLevel.PROTECTED; } return currentLevel.getLevel() >= defaultCmdRequiredPermissionLevel.getLevel(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/permission/PermissionChecker.java
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/permission/PermissionChecker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.permission; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.PermissionLevel; // qosPermissionChecker=xxx.xxx.xxxPermissionChecker @SPI(scope = ExtensionScope.FRAMEWORK) public interface PermissionChecker { boolean access(CommandContext commandContext, PermissionLevel defaultCmdPermissionLevel); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/DefaultAccessKeyStorageTest.java
dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/DefaultAccessKeyStorageTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth; import org.apache.dubbo.auth.model.AccessKeyPair; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock; class DefaultAccessKeyStorageTest { @Test void testGetAccessKey() { URL url = URL.valueOf("dubbo://10.10.10.10:2181") .addParameter(Constants.ACCESS_KEY_ID_KEY, "ak") .addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk"); DefaultAccessKeyStorage defaultAccessKeyStorage = new DefaultAccessKeyStorage(); AccessKeyPair accessKey = defaultAccessKeyStorage.getAccessKey(url, mock(Invocation.class)); assertNotNull(accessKey); assertEquals(accessKey.getAccessKey(), "ak"); assertEquals(accessKey.getSecretKey(), "sk"); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/AccessKeyAuthenticatorTest.java
dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/AccessKeyAuthenticatorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth; import org.apache.dubbo.auth.exception.RpcAuthenticationException; import org.apache.dubbo.auth.model.AccessKeyPair; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class AccessKeyAuthenticatorTest { @Test void testSignForRequest() { URL url = URL.valueOf("dubbo://10.10.10.10:2181") .addParameter(Constants.ACCESS_KEY_ID_KEY, "ak") .addParameter(CommonConstants.APPLICATION_KEY, "test") .addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk"); Invocation invocation = new RpcInvocation(); AccessKeyAuthenticator helper = mock(AccessKeyAuthenticator.class); doCallRealMethod().when(helper).sign(invocation, url); when(helper.getSignature(eq(url), eq(invocation), eq("sk"), anyString())) .thenReturn("dubbo"); AccessKeyPair accessKeyPair = mock(AccessKeyPair.class); when(accessKeyPair.getSecretKey()).thenReturn("sk"); when(helper.getAccessKeyPair(invocation, url)).thenReturn(accessKeyPair); helper.sign(invocation, url); assertEquals(String.valueOf(invocation.getAttachment(CommonConstants.CONSUMER)), url.getApplication()); assertNotNull(invocation.getAttachments().get(Constants.REQUEST_SIGNATURE_KEY)); assertEquals(invocation.getAttachments().get(Constants.REQUEST_SIGNATURE_KEY), "dubbo"); } @Test void testAuthenticateRequest() throws RpcAuthenticationException { URL url = URL.valueOf("dubbo://10.10.10.10:2181") .addParameter(Constants.ACCESS_KEY_ID_KEY, "ak") .addParameter(CommonConstants.APPLICATION_KEY, "test") .addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk"); Invocation invocation = new RpcInvocation(); invocation.setAttachment(Constants.ACCESS_KEY_ID_KEY, "ak"); invocation.setAttachment(Constants.REQUEST_SIGNATURE_KEY, "dubbo"); invocation.setAttachment(Constants.REQUEST_TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis())); invocation.setAttachment(CommonConstants.CONSUMER, "test"); AccessKeyAuthenticator helper = mock(AccessKeyAuthenticator.class); doCallRealMethod().when(helper).authenticate(invocation, url); when(helper.getSignature(eq(url), eq(invocation), eq("sk"), anyString())) .thenReturn("dubbo"); AccessKeyPair accessKeyPair = mock(AccessKeyPair.class); when(accessKeyPair.getSecretKey()).thenReturn("sk"); when(helper.getAccessKeyPair(invocation, url)).thenReturn(accessKeyPair); assertDoesNotThrow(() -> helper.authenticate(invocation, url)); } @Test void testAuthenticateRequestNoSignature() { URL url = URL.valueOf("dubbo://10.10.10.10:2181") .addParameter(Constants.ACCESS_KEY_ID_KEY, "ak") .addParameter(CommonConstants.APPLICATION_KEY, "test") .addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk"); Invocation invocation = new RpcInvocation(); AccessKeyAuthenticator helper = new AccessKeyAuthenticator(FrameworkModel.defaultModel()); assertThrows(RpcAuthenticationException.class, () -> helper.authenticate(invocation, url)); } @Test void testGetAccessKeyPairFailed() { URL url = URL.valueOf("dubbo://10.10.10.10:2181").addParameter(Constants.ACCESS_KEY_ID_KEY, "ak"); AccessKeyAuthenticator helper = new AccessKeyAuthenticator(FrameworkModel.defaultModel()); Invocation invocation = mock(Invocation.class); assertThrows(RuntimeException.class, () -> helper.getAccessKeyPair(invocation, url)); } @Test void testGetSignatureNoParameter() { URL url = mock(URL.class); Invocation invocation = mock(Invocation.class); String secretKey = "123456"; AccessKeyAuthenticator helper = new AccessKeyAuthenticator(FrameworkModel.defaultModel()); String signature = helper.getSignature(url, invocation, secretKey, String.valueOf(System.currentTimeMillis())); assertNotNull(signature); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/filter/ConsumerSignFilterTest.java
dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/filter/ConsumerSignFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth.filter; import org.apache.dubbo.auth.Constants; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.Test; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class ConsumerSignFilterTest { @Test void testAuthDisabled() { URL url = mock(URL.class); Invoker invoker = mock(Invoker.class); Invocation invocation = mock(Invocation.class); when(invoker.getUrl()).thenReturn(url); ConsumerSignFilter consumerSignFilter = new ConsumerSignFilter(FrameworkModel.defaultModel()); consumerSignFilter.invoke(invoker, invocation); verify(invocation, never()).setAttachment(eq(Constants.REQUEST_SIGNATURE_KEY), anyString()); } @Test void testAuthEnabled() { URL url = URL.valueOf("dubbo://10.10.10.10:2181") .addParameter(Constants.ACCESS_KEY_ID_KEY, "ak") .addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk") .addParameter(CommonConstants.APPLICATION_KEY, "test") .addParameter(Constants.AUTHENTICATOR_KEY, "accesskey") .addParameter(Constants.AUTH_KEY, true); Invoker invoker = mock(Invoker.class); Invocation invocation = mock(Invocation.class); when(invoker.getUrl()).thenReturn(url); ConsumerSignFilter consumerSignFilter = new ConsumerSignFilter(FrameworkModel.defaultModel()); consumerSignFilter.invoke(invoker, invocation); verify(invocation, times(1)).setAttachment(eq(Constants.REQUEST_SIGNATURE_KEY), anyString()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/filter/ProviderAuthFilterTest.java
dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/filter/ProviderAuthFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth.filter; import org.apache.dubbo.auth.Constants; import org.apache.dubbo.auth.exception.RpcAuthenticationException; import org.apache.dubbo.auth.utils.SignatureUtils; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class ProviderAuthFilterTest { @Test void testAuthDisabled() { URL url = mock(URL.class); Invoker invoker = mock(Invoker.class); Invocation invocation = mock(RpcInvocation.class); when(invoker.getUrl()).thenReturn(url); ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(FrameworkModel.defaultModel()); providerAuthFilter.invoke(invoker, invocation); verify(url, never()).getParameter(eq(Constants.AUTHENTICATOR_KEY), eq(Constants.DEFAULT_AUTHENTICATOR)); } @Test void testAuthEnabled() { URL url = URL.valueOf("dubbo://10.10.10.10:2181") .addParameter(Constants.ACCESS_KEY_ID_KEY, "ak") .addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk") .addParameter(CommonConstants.APPLICATION_KEY, "test") .addParameter(Constants.AUTHENTICATOR_KEY, "accesskey") .addParameter(Constants.AUTH_KEY, true); Invoker invoker = mock(Invoker.class); Invocation invocation = mock(RpcInvocation.class); when(invoker.getUrl()).thenReturn(url); ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(FrameworkModel.defaultModel()); providerAuthFilter.invoke(invoker, invocation); verify(invocation, atLeastOnce()).getAttachment(anyString()); } @Test void testAuthFailed() { URL url = URL.valueOf("dubbo://10.10.10.10:2181") .addParameter(Constants.ACCESS_KEY_ID_KEY, "ak") .addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk") .addParameter(CommonConstants.APPLICATION_KEY, "test") .addParameter(Constants.AUTHENTICATOR_KEY, "accesskey") .addParameter(Constants.AUTH_KEY, true); Invoker invoker = mock(Invoker.class); Invocation invocation = mock(RpcInvocation.class); when(invocation.getAttachment(Constants.REQUEST_SIGNATURE_KEY)).thenReturn(null); when(invoker.getUrl()).thenReturn(url); ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(FrameworkModel.defaultModel()); Result result = providerAuthFilter.invoke(invoker, invocation); assertTrue(result.hasException()); } @Test void testAuthFailedWhenNoSignature() { URL url = URL.valueOf("dubbo://10.10.10.10:2181") .addParameter(Constants.ACCESS_KEY_ID_KEY, "ak") .addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk") .addParameter(CommonConstants.APPLICATION_KEY, "test") .addParameter(Constants.AUTHENTICATOR_KEY, "accesskey") .addParameter(Constants.AUTH_KEY, true); Invoker invoker = mock(Invoker.class); Invocation invocation = mock(RpcInvocation.class); when(invocation.getAttachment(Constants.REQUEST_SIGNATURE_KEY)).thenReturn(null); when(invoker.getUrl()).thenReturn(url); ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(FrameworkModel.defaultModel()); Result result = providerAuthFilter.invoke(invoker, invocation); assertTrue(result.hasException()); } @Test void testAuthFailedWhenNoAccessKeyPair() { URL url = URL.valueOf("dubbo://10.10.10.10:2181") .addParameter(CommonConstants.APPLICATION_KEY, "test-provider") .addParameter(Constants.AUTHENTICATOR_KEY, "accesskey") .addParameter(Constants.AUTH_KEY, true); Invoker invoker = mock(Invoker.class); Invocation invocation = mock(RpcInvocation.class); when(invocation.getObjectAttachment(Constants.REQUEST_SIGNATURE_KEY)).thenReturn("dubbo"); when(invocation.getObjectAttachment(Constants.AK_KEY)).thenReturn("ak"); when(invocation.getObjectAttachment(CommonConstants.CONSUMER)).thenReturn("test-consumer"); when(invocation.getObjectAttachment(Constants.REQUEST_TIMESTAMP_KEY)).thenReturn(System.currentTimeMillis()); when(invoker.getUrl()).thenReturn(url); ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(FrameworkModel.defaultModel()); Result result = providerAuthFilter.invoke(invoker, invocation); assertTrue(result.hasException()); assertTrue(result.getException() instanceof RpcAuthenticationException); } @Test void testAuthFailedWhenParameterError() { String service = "org.apache.dubbo.DemoService"; String method = "test"; Object[] originalParams = new Object[] {"dubbo1", "dubbo2"}; long currentTimeMillis = System.currentTimeMillis(); URL url = URL.valueOf("dubbo://10.10.10.10:2181") .setServiceInterface(service) .addParameter(Constants.ACCESS_KEY_ID_KEY, "ak") .addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk") .addParameter(CommonConstants.APPLICATION_KEY, "test-provider") .addParameter(Constants.PARAMETER_SIGNATURE_ENABLE_KEY, true) .addParameter(Constants.AUTHENTICATOR_KEY, "accesskey") .addParameter(Constants.AUTH_KEY, true); Invoker invoker = mock(Invoker.class); Invocation invocation = mock(RpcInvocation.class); when(invocation.getObjectAttachment(Constants.AK_KEY)).thenReturn("ak"); when(invocation.getObjectAttachment(CommonConstants.CONSUMER)).thenReturn("test-consumer"); when(invocation.getObjectAttachment(Constants.REQUEST_TIMESTAMP_KEY)).thenReturn(currentTimeMillis); when(invocation.getMethodName()).thenReturn(method); Object[] fakeParams = new Object[] {"dubbo1", "dubbo3"}; when(invocation.getArguments()).thenReturn(fakeParams); when(invoker.getUrl()).thenReturn(url); String requestString = String.format( Constants.SIGNATURE_STRING_FORMAT, url.getColonSeparatedKey(), invocation.getMethodName(), "sk", currentTimeMillis); String sign = SignatureUtils.sign(originalParams, requestString, "sk"); when(invocation.getObjectAttachment(Constants.REQUEST_SIGNATURE_KEY)).thenReturn(sign); ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(FrameworkModel.defaultModel()); Result result = providerAuthFilter.invoke(invoker, invocation); assertTrue(result.hasException()); assertTrue(result.getException() instanceof RpcAuthenticationException); } @Test void testAuthSuccessfully() { String service = "org.apache.dubbo.DemoService"; String method = "test"; long currentTimeMillis = System.currentTimeMillis(); URL url = URL.valueOf("dubbo://10.10.10.10:2181") .setServiceInterface(service) .addParameter(Constants.ACCESS_KEY_ID_KEY, "ak") .addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk") .addParameter(CommonConstants.APPLICATION_KEY, "test-provider") .addParameter(Constants.AUTHENTICATOR_KEY, "accesskey") .addParameter(Constants.AUTH_KEY, true); Invoker invoker = mock(Invoker.class); Invocation invocation = mock(RpcInvocation.class); when(invocation.getAttachment(Constants.AK_KEY)).thenReturn("ak"); when(invocation.getAttachment(CommonConstants.CONSUMER)).thenReturn("test-consumer"); when(invocation.getAttachment(Constants.REQUEST_TIMESTAMP_KEY)).thenReturn(String.valueOf(currentTimeMillis)); when(invocation.getMethodName()).thenReturn(method); when(invoker.getUrl()).thenReturn(url); String requestString = String.format( Constants.SIGNATURE_STRING_FORMAT, url.getColonSeparatedKey(), invocation.getMethodName(), "sk", currentTimeMillis); String sign = SignatureUtils.sign(requestString, "sk"); when(invocation.getAttachment(Constants.REQUEST_SIGNATURE_KEY)).thenReturn(sign); ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(FrameworkModel.defaultModel()); Result result = providerAuthFilter.invoke(invoker, invocation); assertNull(result); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/utils/SignatureUtilsTest.java
dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/utils/SignatureUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth.utils; import java.util.ArrayList; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class SignatureUtilsTest { @Test void testEncryptWithObject() { Object[] objects = new Object[] {new ArrayList<>(), "temp"}; String encryptWithObject = SignatureUtils.sign(objects, "TestMethod#hello", "TOKEN"); Assertions.assertEquals(encryptWithObject, "t6c7PasKguovqSrVRcTQU4wTZt/ybl0jBCUMgAt/zQw="); } @Test void testEncryptWithNoParameters() { String encryptWithNoParams = SignatureUtils.sign(null, "TestMethod#hello", "TOKEN"); Assertions.assertEquals(encryptWithNoParams, "2DGkTcyXg4plU24rY8MZkEJwOMRW3o+wUP3HssRc3EE="); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/BasicAuthenticator.java
dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/BasicAuthenticator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth; import org.apache.dubbo.auth.exception.RpcAuthenticationException; import org.apache.dubbo.auth.spi.Authenticator; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Objects; public class BasicAuthenticator implements Authenticator { @Override public void sign(Invocation invocation, URL url) { String username = url.getParameter(Constants.USERNAME_KEY); String password = url.getParameter(Constants.PASSWORD_KEY); String auth = username + ":" + password; String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8)); String authHeaderValue = "Basic " + encodedAuth; invocation.setAttachment(Constants.AUTHORIZATION_HEADER_LOWER, authHeaderValue); } @Override public void authenticate(Invocation invocation, URL url) throws RpcAuthenticationException { String username = url.getParameter(Constants.USERNAME_KEY); String password = url.getParameter(Constants.PASSWORD_KEY); String auth = username + ":" + password; String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8)); String authHeaderValue = "Basic " + encodedAuth; if (!Objects.equals(authHeaderValue, invocation.getAttachment(Constants.AUTHORIZATION_HEADER)) && !Objects.equals(authHeaderValue, invocation.getAttachment(Constants.AUTHORIZATION_HEADER_LOWER))) { throw new RpcAuthenticationException("Failed to authenticate, maybe consumer side did not enable the auth"); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/AccessKeyAuthenticator.java
dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/AccessKeyAuthenticator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth; import org.apache.dubbo.auth.exception.AccessKeyNotFoundException; import org.apache.dubbo.auth.exception.RpcAuthenticationException; import org.apache.dubbo.auth.model.AccessKeyPair; import org.apache.dubbo.auth.spi.AccessKeyStorage; import org.apache.dubbo.auth.spi.Authenticator; import org.apache.dubbo.auth.utils.SignatureUtils; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.support.RpcUtils; public class AccessKeyAuthenticator implements Authenticator { private final FrameworkModel frameworkModel; public AccessKeyAuthenticator(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } @Override public void sign(Invocation invocation, URL url) { String currentTime = String.valueOf(System.currentTimeMillis()); AccessKeyPair accessKeyPair = getAccessKeyPair(invocation, url); invocation.setAttachment( Constants.REQUEST_SIGNATURE_KEY, getSignature(url, invocation, accessKeyPair.getSecretKey(), currentTime)); invocation.setAttachment(Constants.REQUEST_TIMESTAMP_KEY, currentTime); invocation.setAttachment(Constants.AK_KEY, accessKeyPair.getAccessKey()); invocation.setAttachment(CommonConstants.CONSUMER, url.getApplication()); } @Override public void authenticate(Invocation invocation, URL url) throws RpcAuthenticationException { String accessKeyId = String.valueOf(invocation.getAttachment(Constants.AK_KEY)); String requestTimestamp = String.valueOf(invocation.getAttachment(Constants.REQUEST_TIMESTAMP_KEY)); String originSignature = String.valueOf(invocation.getAttachment(Constants.REQUEST_SIGNATURE_KEY)); String consumer = String.valueOf(invocation.getAttachment(CommonConstants.CONSUMER)); if (StringUtils.isAnyEmpty(accessKeyId, consumer, requestTimestamp, originSignature)) { throw new RpcAuthenticationException("Failed to authenticate, maybe consumer side did not enable the auth"); } AccessKeyPair accessKeyPair; try { accessKeyPair = getAccessKeyPair(invocation, url); } catch (Exception e) { throw new RpcAuthenticationException("Failed to authenticate , can't load the accessKeyPair"); } String computeSignature = getSignature(url, invocation, accessKeyPair.getSecretKey(), requestTimestamp); boolean success = computeSignature.equals(originSignature); if (!success) { throw new RpcAuthenticationException("Failed to authenticate, signature is not correct"); } } AccessKeyPair getAccessKeyPair(Invocation invocation, URL url) { AccessKeyStorage accessKeyStorage = frameworkModel .getExtensionLoader(AccessKeyStorage.class) .getExtension(url.getParameter(Constants.ACCESS_KEY_STORAGE_KEY, Constants.DEFAULT_ACCESS_KEY_STORAGE)); AccessKeyPair accessKeyPair; try { accessKeyPair = accessKeyStorage.getAccessKey(url, invocation); if (accessKeyPair == null || StringUtils.isAnyEmpty(accessKeyPair.getAccessKey(), accessKeyPair.getSecretKey())) { throw new AccessKeyNotFoundException("AccessKeyId or secretAccessKey not found"); } } catch (Exception e) { throw new RuntimeException("Can't load the AccessKeyPair from accessKeyStorage"); } return accessKeyPair; } String getSignature(URL url, Invocation invocation, String secretKey, String time) { String requestString = String.format( Constants.SIGNATURE_STRING_FORMAT, url.getColonSeparatedKey(), RpcUtils.getMethodName(invocation), secretKey, time); return SignatureUtils.sign(requestString, secretKey); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/DefaultAccessKeyStorage.java
dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/DefaultAccessKeyStorage.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth; import org.apache.dubbo.auth.model.AccessKeyPair; import org.apache.dubbo.auth.spi.AccessKeyStorage; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; /** * The default implementation of {@link AccessKeyStorage} */ public class DefaultAccessKeyStorage implements AccessKeyStorage { @Override public AccessKeyPair getAccessKey(URL url, Invocation invocation) { AccessKeyPair accessKeyPair = new AccessKeyPair(); String accessKeyId = url.getParameter(Constants.ACCESS_KEY_ID_KEY); String secretAccessKey = url.getParameter(Constants.SECRET_ACCESS_KEY_KEY); accessKeyPair.setAccessKey(accessKeyId); accessKeyPair.setSecretKey(secretAccessKey); return accessKeyPair; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/Constants.java
dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/Constants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth; public interface Constants { String AUTH_KEY = "auth"; String AUTHENTICATOR_KEY = "authenticator"; String USERNAME_KEY = "username"; String PASSWORD_KEY = "password"; String DEFAULT_AUTHENTICATOR = "basic"; String DEFAULT_ACCESS_KEY_STORAGE = "urlstorage"; String ACCESS_KEY_STORAGE_KEY = "accessKey.storage"; // the key starting with "." shouldn't be output String ACCESS_KEY_ID_KEY = ".accessKeyId"; // the key starting with "." shouldn't be output String SECRET_ACCESS_KEY_KEY = ".secretAccessKey"; String REQUEST_TIMESTAMP_KEY = "timestamp"; String REQUEST_SIGNATURE_KEY = "signature"; String AK_KEY = "ak"; String SIGNATURE_STRING_FORMAT = "%s#%s#%s#%s"; String PARAMETER_SIGNATURE_ENABLE_KEY = "param.sign"; String AUTH_SUCCESS = "auth.success"; String AUTHORIZATION_HEADER_LOWER = "authorization"; String AUTHORIZATION_HEADER = "Authorization"; String REMOTE_ADDRESS_KEY = "tri.remote.address"; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/filter/ProviderAuthHeaderFilter.java
dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/filter/ProviderAuthHeaderFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth.filter; import org.apache.dubbo.auth.Constants; import org.apache.dubbo.auth.spi.Authenticator; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.HeaderFilter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.FrameworkModel; import static org.apache.dubbo.rpc.RpcException.AUTHORIZATION_EXCEPTION; @Activate(value = Constants.AUTH_KEY, order = -20000) public class ProviderAuthHeaderFilter implements HeaderFilter { private final FrameworkModel frameworkModel; public ProviderAuthHeaderFilter(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } @Override public RpcInvocation invoke(Invoker<?> invoker, RpcInvocation invocation) throws RpcException { URL url = invoker.getUrl(); boolean shouldAuth = url.getParameter(Constants.AUTH_KEY, false); if (shouldAuth) { Authenticator authenticator = frameworkModel .getExtensionLoader(Authenticator.class) .getExtension(url.getParameter(Constants.AUTHENTICATOR_KEY, Constants.DEFAULT_AUTHENTICATOR)); try { authenticator.authenticate(invocation, url); } catch (Exception e) { throw new RpcException(AUTHORIZATION_EXCEPTION, "No Auth."); } invocation.getAttributes().put(Constants.AUTH_SUCCESS, Boolean.TRUE); } return invocation; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/filter/ProviderAuthFilter.java
dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/filter/ProviderAuthFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth.filter; import org.apache.dubbo.auth.Constants; import org.apache.dubbo.auth.spi.Authenticator; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.FrameworkModel; @Activate(group = CommonConstants.PROVIDER, value = Constants.AUTH_KEY, order = -10000) public class ProviderAuthFilter implements Filter { private final FrameworkModel frameworkModel; public ProviderAuthFilter(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { URL url = invoker.getUrl(); boolean shouldAuth = url.getParameter(Constants.AUTH_KEY, false); if (shouldAuth) { if (Boolean.TRUE.equals(invocation.getAttributes().get(Constants.AUTH_SUCCESS))) { return invoker.invoke(invocation); } Authenticator authenticator = frameworkModel .getExtensionLoader(Authenticator.class) .getExtension(url.getParameter(Constants.AUTHENTICATOR_KEY, Constants.DEFAULT_AUTHENTICATOR)); try { authenticator.authenticate(invocation, url); } catch (Exception e) { return AsyncRpcResult.newDefaultAsyncResult(e, invocation); } } return invoker.invoke(invocation); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/filter/ConsumerSignFilter.java
dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/filter/ConsumerSignFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth.filter; import org.apache.dubbo.auth.Constants; import org.apache.dubbo.auth.spi.Authenticator; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.FrameworkModel; /** * The ConsumerSignFilter * * @see org.apache.dubbo.rpc.Filter */ @Activate(group = CommonConstants.CONSUMER, value = Constants.AUTH_KEY, order = -10000) public class ConsumerSignFilter implements Filter { private final FrameworkModel frameworkModel; public ConsumerSignFilter(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { URL url = invoker.getUrl(); boolean shouldAuth = url.getParameter(Constants.AUTH_KEY, false); if (shouldAuth) { Authenticator authenticator = frameworkModel .getExtensionLoader(Authenticator.class) .getExtension(url.getParameter(Constants.AUTHENTICATOR_KEY, Constants.DEFAULT_AUTHENTICATOR)); authenticator.sign(invocation, url); } return invoker.invoke(invocation); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/spi/Authenticator.java
dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/spi/Authenticator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth.spi; import org.apache.dubbo.auth.exception.RpcAuthenticationException; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.rpc.Invocation; @SPI(scope = ExtensionScope.FRAMEWORK, value = "basic") public interface Authenticator { /** * give a sign to request * * @param invocation * @param url */ void sign(Invocation invocation, URL url); /** * verify the signature of the request is valid or not * @param invocation * @param url * @throws RpcAuthenticationException when failed to authenticate current invocation */ void authenticate(Invocation invocation, URL url) throws RpcAuthenticationException; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/spi/AccessKeyStorage.java
dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/spi/AccessKeyStorage.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth.spi; import org.apache.dubbo.auth.model.AccessKeyPair; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.rpc.Invocation; /** * This SPI Extension support us to store our {@link AccessKeyPair} or load {@link AccessKeyPair} from other * storage, such as filesystem. */ @SPI(scope = ExtensionScope.FRAMEWORK) public interface AccessKeyStorage { /** * get AccessKeyPair of this request * * @param url * @param invocation * @return */ AccessKeyPair getAccessKey(URL url, Invocation invocation); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/model/AccessKeyPair.java
dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/model/AccessKeyPair.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth.model; /** * The model of AK/SK pair */ public class AccessKeyPair { private String accessKey; private String secretKey; private String consumerSide; private String providerSide; private String creator; private String options; public String getAccessKey() { return accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public String getConsumerSide() { return consumerSide; } public void setConsumerSide(String consumerSide) { this.consumerSide = consumerSide; } public String getProviderSide() { return providerSide; } public void setProviderSide(String providerSide) { this.providerSide = providerSide; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public String getOptions() { return options; } public void setOptions(String options) { this.options = options; } @Override public String toString() { return "AccessKeyPair{" + "accessKey='" + accessKey + '\'' + ", secretKey='" + secretKey + '\'' + ", consumerSide='" + consumerSide + '\'' + ", providerSide='" + providerSide + '\'' + ", creator='" + creator + '\'' + ", options='" + options + '\'' + '}'; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/exception/RpcAuthenticationException.java
dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/exception/RpcAuthenticationException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth.exception; public class RpcAuthenticationException extends Exception { public RpcAuthenticationException() {} public RpcAuthenticationException(String message) { super(message); } public RpcAuthenticationException(String message, Throwable cause) { super(message, cause); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/exception/AccessKeyNotFoundException.java
dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/exception/AccessKeyNotFoundException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth.exception; import org.apache.dubbo.auth.model.AccessKeyPair; /** * Signals that an attempt to get the {@link AccessKeyPair} has failed. */ public class AccessKeyNotFoundException extends Exception { private static final long serialVersionUID = 7106108446396804404L; public AccessKeyNotFoundException() {} public AccessKeyNotFoundException(String message) { super(message); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/utils/SignatureUtils.java
dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/utils/SignatureUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.auth.utils; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Base64; public class SignatureUtils { private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256"; public static String sign(String metadata, String key) throws RuntimeException { return sign(metadata.getBytes(StandardCharsets.UTF_8), key); } public static String sign(Object[] parameters, String metadata, String key) throws RuntimeException { if (parameters == null) { return sign(metadata, key); } for (int i = 0; i < parameters.length; i++) { if (!(parameters[i] instanceof Serializable)) { throw new IllegalArgumentException("The parameter [" + i + "] to be signed was not serializable."); } } Object[] includeMetadata = new Object[parameters.length + 1]; System.arraycopy(parameters, 0, includeMetadata, 0, parameters.length); includeMetadata[parameters.length] = metadata; byte[] includeMetadataBytes; try { includeMetadataBytes = toByteArray(includeMetadata); } catch (IOException e) { throw new RuntimeException("Failed to generate HMAC: " + e.getMessage()); } return sign(includeMetadataBytes, key); } private static String sign(byte[] data, String key) throws RuntimeException { Mac mac; try { mac = Mac.getInstance(HMAC_SHA256_ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Failed to generate HMAC: no such algorithm exception " + HMAC_SHA256_ALGORITHM); } SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), HMAC_SHA256_ALGORITHM); try { mac.init(signingKey); } catch (InvalidKeyException e) { throw new RuntimeException("Failed to generate HMAC: invalid key exception"); } byte[] rawHmac; try { // compute the hmac on input data bytes rawHmac = mac.doFinal(data); } catch (IllegalStateException e) { throw new RuntimeException("Failed to generate HMAC: " + e.getMessage()); } // base64-encode the hmac return Base64.getEncoder().encodeToString(rawHmac); } private static byte[] toByteArray(Object[] parameters) throws IOException { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) { out.writeObject(parameters); out.flush(); return bos.toByteArray(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/Cmd.java
dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/Cmd.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.api; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Command */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Cmd { /** * Command name * * @return command name */ String name(); /** * Command description * * @return command description */ String summary(); /** * Command example * * @return command example */ String[] example() default {}; /** * Command order in help * * @return command order in help */ int sort() default 0; /** * Command required access permission level * * @return command permission level */ PermissionLevel requiredPermissionLevel() default PermissionLevel.PROTECTED; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/CommandContext.java
dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/CommandContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.api; import java.util.Arrays; import java.util.Objects; import java.util.Optional; import io.netty.channel.Channel; public class CommandContext { private String commandName; private String[] args; private Channel remote; private boolean isHttp; private Object originRequest; private int httpCode = 200; private QosConfiguration qosConfiguration; public CommandContext(String commandName) { this.commandName = commandName; } public CommandContext(String commandName, String[] args, boolean isHttp) { this.commandName = commandName; this.args = args; this.isHttp = isHttp; } public String getCommandName() { return commandName; } public void setCommandName(String commandName) { this.commandName = commandName; } public String[] getArgs() { return args; } public void setArgs(String[] args) { this.args = args; } public Channel getRemote() { return remote; } public void setRemote(Channel remote) { this.remote = remote; } public boolean isHttp() { return isHttp; } public void setHttp(boolean http) { isHttp = http; } public Object getOriginRequest() { return originRequest; } public void setOriginRequest(Object originRequest) { this.originRequest = originRequest; } public int getHttpCode() { return httpCode; } public void setHttpCode(int httpCode) { this.httpCode = httpCode; } public void setQosConfiguration(QosConfiguration qosConfiguration) { this.qosConfiguration = qosConfiguration; } public QosConfiguration getQosConfiguration() { return qosConfiguration; } public boolean isAllowAnonymousAccess() { return this.qosConfiguration.isAllowAnonymousAccess(); } @Override public String toString() { return "CommandContext{" + "commandName='" + commandName + '\'' + ", args=" + Arrays.toString(args) + ", remote=" + Optional.ofNullable(remote) .map(Channel::remoteAddress) .map(Objects::toString) .orElse("unknown") + ", local=" + Optional.ofNullable(remote) .map(Channel::localAddress) .map(Objects::toString) .orElse("unknown") + ", isHttp=" + isHttp + ", httpCode=" + httpCode + ", qosConfiguration=" + qosConfiguration + '}'; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/QosConfiguration.java
dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/QosConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.api; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import java.net.UnknownHostException; import java.util.Arrays; import java.util.function.Predicate; public class QosConfiguration { private String welcome; private boolean acceptForeignIp; // the whitelist of foreign IP when acceptForeignIp = false, the delimiter is colon(,) // support specific ip and an ip range from CIDR specification private String acceptForeignIpWhitelist; private Predicate<String> acceptForeignIpWhitelistPredicate; // this permission level for anonymous access, it will ignore the acceptForeignIp and acceptForeignIpWhitelist // configurations // Access permission depends on the config anonymousAccessPermissionLevel and the cmd required permission level // the default value is Cmd.PermissionLevel.PUBLIC, can only access PUBLIC level cmd private PermissionLevel anonymousAccessPermissionLevel = PermissionLevel.PUBLIC; // the allow commands for anonymous access, the delimiter is colon(,) private String anonymousAllowCommands; private QosConfiguration() {} public QosConfiguration(Builder builder) { this.welcome = builder.getWelcome(); this.acceptForeignIp = builder.isAcceptForeignIp(); this.acceptForeignIpWhitelist = builder.getAcceptForeignIpWhitelist(); this.anonymousAccessPermissionLevel = builder.getAnonymousAccessPermissionLevel(); this.anonymousAllowCommands = builder.getAnonymousAllowCommands(); buildPredicate(); } private void buildPredicate() { if (StringUtils.isNotEmpty(acceptForeignIpWhitelist)) { this.acceptForeignIpWhitelistPredicate = Arrays.stream(acceptForeignIpWhitelist.split(",")) .map(String::trim) .filter(StringUtils::isNotEmpty) .map(foreignIpPattern -> (Predicate<String>) foreignIp -> { try { // hard code port to -1 return NetUtils.matchIpExpression(foreignIpPattern, foreignIp, -1); } catch (UnknownHostException ignore) { // ignore illegal CIDR specification } return false; }) .reduce(Predicate::or) .orElse(s -> false); } else { this.acceptForeignIpWhitelistPredicate = foreignIp -> false; } } public boolean isAllowAnonymousAccess() { return PermissionLevel.NONE != anonymousAccessPermissionLevel; } public String getWelcome() { return welcome; } public PermissionLevel getAnonymousAccessPermissionLevel() { return anonymousAccessPermissionLevel; } public String getAcceptForeignIpWhitelist() { return acceptForeignIpWhitelist; } public Predicate<String> getAcceptForeignIpWhitelistPredicate() { return acceptForeignIpWhitelistPredicate; } public boolean isAcceptForeignIp() { return acceptForeignIp; } public String getAnonymousAllowCommands() { return anonymousAllowCommands; } public static Builder builder() { return new Builder(); } public static class Builder { private String welcome; private boolean acceptForeignIp; private String acceptForeignIpWhitelist; private PermissionLevel anonymousAccessPermissionLevel = PermissionLevel.PUBLIC; private String anonymousAllowCommands; private Builder() {} public Builder welcome(String welcome) { this.welcome = welcome; return this; } public Builder acceptForeignIp(boolean acceptForeignIp) { this.acceptForeignIp = acceptForeignIp; return this; } public Builder acceptForeignIpWhitelist(String acceptForeignIpWhitelist) { this.acceptForeignIpWhitelist = acceptForeignIpWhitelist; return this; } public Builder anonymousAccessPermissionLevel(String anonymousAccessPermissionLevel) { this.anonymousAccessPermissionLevel = PermissionLevel.from(anonymousAccessPermissionLevel); return this; } public Builder anonymousAllowCommands(String anonymousAllowCommands) { this.anonymousAllowCommands = anonymousAllowCommands; return this; } public QosConfiguration build() { return new QosConfiguration(this); } public String getWelcome() { return welcome; } public boolean isAcceptForeignIp() { return acceptForeignIp; } public String getAcceptForeignIpWhitelist() { return acceptForeignIpWhitelist; } public PermissionLevel getAnonymousAccessPermissionLevel() { return anonymousAccessPermissionLevel; } public String getAnonymousAllowCommands() { return anonymousAllowCommands; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/PermissionLevel.java
dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/PermissionLevel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.api; import org.apache.dubbo.common.utils.StringUtils; import java.util.Arrays; public enum PermissionLevel { /** * the lowest permission level (default), can access with * anonymousAccessPermissionLevel=PUBLIC / anonymousAccessPermissionLevel=1 or higher */ PUBLIC(1), /** * the middle permission level, default permission for each cmd */ PROTECTED(2), /** * the highest permission level, suppose only the localhost can access this command */ PRIVATE(3), /** * It is the reserved anonymous permission level, can not access any command */ NONE(Integer.MIN_VALUE), ; private final int level; PermissionLevel(int level) { this.level = level; } public int getLevel() { return level; } // find the permission level by the level value, if not found, return default PUBLIC level public static PermissionLevel from(String permissionLevel) { if (StringUtils.isNumber(permissionLevel)) { return Arrays.stream(values()) .filter(p -> String.valueOf(p.getLevel()).equals(permissionLevel.trim())) .findFirst() .orElse(PUBLIC); } return Arrays.stream(values()) .filter(p -> p.name() .equalsIgnoreCase(String.valueOf(permissionLevel).trim())) .findFirst() .orElse(PUBLIC); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/BaseCommand.java
dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/BaseCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.api; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; @SPI(scope = ExtensionScope.FRAMEWORK) public interface BaseCommand { default boolean logResult() { return true; } String execute(CommandContext commandContext, String[] args); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring-security/src/test/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodecTest.java
dubbo-plugin/dubbo-spring-security/src/test/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodecTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.security.jackson; import java.time.Duration; import java.time.Instant; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.security.oauth2.core.OAuth2AccessToken; public class ObjectMapperCodecTest { private final ObjectMapperCodec mapper = new ObjectMapperCodec(); @Test public void testOAuth2AuthorizedClientCodec() { ClientRegistration clientRegistration = clientRegistration().build(); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, "principal-name", noScopes()); String content = mapper.serialize(authorizedClient); OAuth2AuthorizedClient deserialize = mapper.deserialize(content.getBytes(), OAuth2AuthorizedClient.class); Assertions.assertNotNull(deserialize); } public static ClientRegistration.Builder clientRegistration() { // @formatter:off return ClientRegistration.withRegistrationId("registration-id") .redirectUri("http://localhost/uua/oauth2/code/{registrationId}") .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .scope("read:user") .authorizationUri("https://example.com/login/oauth/authorize") .tokenUri("https://example.com/login/oauth/access_token") .jwkSetUri("https://example.com/oauth2/jwk") .issuerUri("https://example.com") .userInfoUri("https://api.example.com/user") .userNameAttributeName("id") .clientName("Client Name") .clientId("client-id") .clientSecret("client-secret"); // @formatter:on } public static OAuth2AccessToken noScopes() { return new OAuth2AccessToken( OAuth2AccessToken.TokenType.BEARER, "no-scopes", Instant.now(), Instant.now().plus(Duration.ofDays(1))); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderAuthenticationResolverFilter.java
dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderAuthenticationResolverFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.security.filter; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.spring.security.jackson.ObjectMapperCodec; import org.apache.dubbo.spring.security.utils.SecurityNames; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import static org.apache.dubbo.spring.security.utils.SecurityNames.CORE_JACKSON_2_MODULE_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.JAVA_TIME_MODULE_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.OBJECT_MAPPER_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.SECURITY_CONTEXT_HOLDER_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.SIMPLE_MODULE_CLASS_NAME; @Activate( group = CommonConstants.PROVIDER, order = -10000, onClass = { SECURITY_CONTEXT_HOLDER_CLASS_NAME, CORE_JACKSON_2_MODULE_CLASS_NAME, OBJECT_MAPPER_CLASS_NAME, JAVA_TIME_MODULE_CLASS_NAME, SIMPLE_MODULE_CLASS_NAME }) public class ContextHolderAuthenticationResolverFilter implements Filter { private final ObjectMapperCodec mapper; public ContextHolderAuthenticationResolverFilter(ApplicationModel applicationModel) { this.mapper = applicationModel.getBeanFactory().getBean(ObjectMapperCodec.class); } @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if (this.mapper != null) { getSecurityContext(invocation); } return invoker.invoke(invocation); } private void getSecurityContext(Invocation invocation) { String authenticationJSON = invocation.getAttachment(SecurityNames.SECURITY_AUTHENTICATION_CONTEXT_KEY); if (StringUtils.isBlank(authenticationJSON)) { return; } Authentication authentication = mapper.deserialize(authenticationJSON, Authentication.class); if (authentication == null) { return; } SecurityContextHolder.getContext().setAuthentication(authentication); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderParametersSelectedTransferFilter.java
dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderParametersSelectedTransferFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.security.filter; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.cluster.filter.ClusterFilter; import org.apache.dubbo.spring.security.utils.SecurityNames; import java.util.Map; import java.util.Objects; import static org.apache.dubbo.spring.security.utils.SecurityNames.SECURITY_AUTHENTICATION_CONTEXT_KEY; @Activate(group = CommonConstants.CONSUMER, order = -1) public class ContextHolderParametersSelectedTransferFilter implements ClusterFilter { @Override public Result invoke(Invoker<?> invoker, Invocation invocation) { this.setSecurityContextIfExists(invocation); return invoker.invoke(invocation); } private void setSecurityContextIfExists(Invocation invocation) { Map<String, Object> resultMap = RpcContext.getServerAttachment().getObjectAttachments(); Object authentication = resultMap.get(SECURITY_AUTHENTICATION_CONTEXT_KEY); if (Objects.isNull(authentication)) { return; } invocation.setObjectAttachment(SecurityNames.SECURITY_AUTHENTICATION_CONTEXT_KEY, authentication); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderAuthenticationPrepareFilter.java
dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderAuthenticationPrepareFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.security.filter; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.cluster.filter.ClusterFilter; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.spring.security.jackson.ObjectMapperCodec; import org.apache.dubbo.spring.security.utils.SecurityNames; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import static org.apache.dubbo.spring.security.utils.SecurityNames.CORE_JACKSON_2_MODULE_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.JAVA_TIME_MODULE_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.OBJECT_MAPPER_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.SECURITY_CONTEXT_HOLDER_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.SIMPLE_MODULE_CLASS_NAME; @Activate( group = CommonConstants.CONSUMER, order = -10000, onClass = { SECURITY_CONTEXT_HOLDER_CLASS_NAME, CORE_JACKSON_2_MODULE_CLASS_NAME, OBJECT_MAPPER_CLASS_NAME, JAVA_TIME_MODULE_CLASS_NAME, SIMPLE_MODULE_CLASS_NAME }) public class ContextHolderAuthenticationPrepareFilter implements ClusterFilter { private final Logger logger = LoggerFactory.getLogger(getClass()); private final ObjectMapperCodec mapper; public ContextHolderAuthenticationPrepareFilter(ApplicationModel applicationModel) { this.mapper = applicationModel.getBeanFactory().getBean(ObjectMapperCodec.class); } @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if (this.mapper != null) { setSecurityContext(invocation); } return invoker.invoke(invocation); } private void setSecurityContext(Invocation invocation) { SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); String content = mapper.serialize(authentication); if (StringUtils.isBlank(content)) { return; } invocation.setObjectAttachment(SecurityNames.SECURITY_AUTHENTICATION_CONTEXT_KEY, content); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/AuthenticationExceptionTranslatorFilter.java
dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/AuthenticationExceptionTranslatorFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.security.filter; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.AuthenticationException; import static org.apache.dubbo.rpc.RpcException.AUTHORIZATION_EXCEPTION; import static org.apache.dubbo.spring.security.utils.SecurityNames.CORE_JACKSON_2_MODULE_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.JAVA_TIME_MODULE_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.OBJECT_MAPPER_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.SECURITY_CONTEXT_HOLDER_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.SIMPLE_MODULE_CLASS_NAME; @Activate( group = CommonConstants.PROVIDER, order = Integer.MAX_VALUE, onClass = { SECURITY_CONTEXT_HOLDER_CLASS_NAME, CORE_JACKSON_2_MODULE_CLASS_NAME, OBJECT_MAPPER_CLASS_NAME, JAVA_TIME_MODULE_CLASS_NAME, SIMPLE_MODULE_CLASS_NAME }) public class AuthenticationExceptionTranslatorFilter implements Filter, Filter.Listener { @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { return invoker.invoke(invocation); } @Override public void onResponse(Result result, Invoker<?> invoker, Invocation invocation) { if (this.isTranslate(result)) { RpcException rpcException = new RpcException(result.getException().getMessage()); rpcException.setCode(AUTHORIZATION_EXCEPTION); result.setException(rpcException); } } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {} private boolean isTranslate(Result result) { Throwable exception = result.getException(); return result.hasException() && (exception instanceof AuthenticationException || exception instanceof AccessDeniedException); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/model/SecurityScopeModelInitializer.java
dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/model/SecurityScopeModelInitializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.security.model; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeModelInitializer; import org.apache.dubbo.spring.security.jackson.ObjectMapperCodec; import org.apache.dubbo.spring.security.jackson.ObjectMapperCodecCustomer; import java.util.Set; import static org.apache.dubbo.spring.security.utils.SecurityNames.CORE_JACKSON_2_MODULE_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.JAVA_TIME_MODULE_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.OBJECT_MAPPER_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.SECURITY_CONTEXT_HOLDER_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.SIMPLE_MODULE_CLASS_NAME; @Activate( onClass = { SECURITY_CONTEXT_HOLDER_CLASS_NAME, CORE_JACKSON_2_MODULE_CLASS_NAME, OBJECT_MAPPER_CLASS_NAME, JAVA_TIME_MODULE_CLASS_NAME, SIMPLE_MODULE_CLASS_NAME }) public class SecurityScopeModelInitializer implements ScopeModelInitializer { private final Logger logger = LoggerFactory.getLogger(getClass()); @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) { ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory(); try { ObjectMapperCodec objectMapperCodec = new ObjectMapperCodec(); Set<ObjectMapperCodecCustomer> objectMapperCodecCustomerList = frameworkModel .getExtensionLoader(ObjectMapperCodecCustomer.class) .getSupportedExtensionInstances(); for (ObjectMapperCodecCustomer objectMapperCodecCustomer : objectMapperCodecCustomerList) { objectMapperCodecCustomer.customize(objectMapperCodec); } beanFactory.registerBean(objectMapperCodec); } catch (Throwable t) { logger.info( "Failed to initialize ObjectMapperCodecCustomer and spring security related features are disabled.", 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-spring-security/src/main/java/org/apache/dubbo/spring/security/utils/SecurityNames.java
dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/utils/SecurityNames.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.security.utils; public final class SecurityNames { public static final String SECURITY_AUTHENTICATION_CONTEXT_KEY = "security_authentication_context"; public static final String SECURITY_CONTEXT_HOLDER_CLASS_NAME = "org.springframework.security.core.context.SecurityContextHolder"; public static final String CORE_JACKSON_2_MODULE_CLASS_NAME = "org.springframework.security.jackson2.CoreJackson2Module"; public static final String OBJECT_MAPPER_CLASS_NAME = "com.fasterxml.jackson.databind.ObjectMapper"; public static final String JAVA_TIME_MODULE_CLASS_NAME = "com.fasterxml.jackson.datatype.jsr310.JavaTimeModule"; public static final String SIMPLE_MODULE_CLASS_NAME = "com.fasterxml.jackson.databind.module.SimpleModule"; private SecurityNames() {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodec.java
dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.security.jackson; 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.ClassUtils; import org.apache.dubbo.common.utils.StringUtils; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.security.jackson2.CoreJackson2Module; public class ObjectMapperCodec { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ObjectMapperCodec.class); private final ObjectMapper mapper = new ObjectMapper(); public ObjectMapperCodec() { registerDefaultModule(); } public <T> T deserialize(byte[] bytes, Class<T> clazz) { try { if (bytes == null || bytes.length == 0) { return null; } return mapper.readValue(bytes, clazz); } catch (Exception exception) { logger.warn( LoggerCodeConstants.COMMON_JSON_CONVERT_EXCEPTION, "objectMapper! deserialize error, you can try to customize the ObjectMapperCodecCustomer.", "", "", exception); } return null; } public <T> T deserialize(String content, Class<T> clazz) { if (StringUtils.isBlank(content)) { return null; } return deserialize(content.getBytes(StandardCharsets.UTF_8), clazz); } public String serialize(Object object) { try { if (object == null) { return null; } return mapper.writeValueAsString(object); } catch (Exception ex) { logger.warn( LoggerCodeConstants.COMMON_JSON_CONVERT_EXCEPTION, "objectMapper! serialize error, you can try to customize the ObjectMapperCodecCustomer.", "", "", ex); } return null; } public ObjectMapperCodec addModule(SimpleModule simpleModule) { mapper.registerModule(simpleModule); return this; } public ObjectMapperCodec configureMapper(Consumer<ObjectMapper> objectMapperConfigure) { objectMapperConfigure.accept(this.mapper); return this; } private void registerDefaultModule() { mapper.registerModule(new CoreJackson2Module()); mapper.registerModule(new JavaTimeModule()); List<String> jacksonModuleClassNameList = new ArrayList<>(); jacksonModuleClassNameList.add( "org.springframework.security.oauth2.server.authorization.jackson2.OAuth2AuthorizationServerJackson2Module"); jacksonModuleClassNameList.add( "org.springframework.security.oauth2.client.jackson2.OAuth2ClientJackson2Module"); jacksonModuleClassNameList.add("org.springframework.security.web.server.jackson2.WebServerJackson2Module"); jacksonModuleClassNameList.add("com.fasterxml.jackson.module.paramnames.ParameterNamesModule"); jacksonModuleClassNameList.add("org.springframework.security.web.jackson2.WebServletJackson2Module"); jacksonModuleClassNameList.add("org.springframework.security.web.jackson2.WebJackson2Module"); jacksonModuleClassNameList.add("org.springframework.boot.jackson.JsonMixinModule"); jacksonModuleClassNameList.add("org.springframework.security.ldap.jackson2.LdapJackson2Module"); loadModuleIfPresent(jacksonModuleClassNameList); } private void loadModuleIfPresent(List<String> jacksonModuleClassNameList) { for (String moduleClassName : jacksonModuleClassNameList) { try { SimpleModule objectMapperModule = (SimpleModule) ClassUtils.forName(moduleClassName, ObjectMapperCodec.class.getClassLoader()) .getDeclaredConstructor() .newInstance(); mapper.registerModule(objectMapperModule); } catch (Throwable ex) { } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodecCustomer.java
dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodecCustomer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.security.jackson; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; @SPI(scope = ExtensionScope.FRAMEWORK) public interface ObjectMapperCodecCustomer { void customize(ObjectMapperCodec objectMapperCodec); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/AbstractGenerator.java
dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/AbstractGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.gen; import org.apache.dubbo.gen.utils.ProtoTypeMap; import javax.annotation.Nonnull; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.Mustache; import com.github.mustachejava.MustacheFactory; import com.google.api.AnnotationsProto; import com.google.api.HttpRule; import com.google.api.HttpRule.PatternCase; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.html.HtmlEscapers; import com.google.protobuf.DescriptorProtos.FileDescriptorProto; import com.google.protobuf.DescriptorProtos.FileOptions; import com.google.protobuf.DescriptorProtos.MethodDescriptorProto; import com.google.protobuf.DescriptorProtos.ServiceDescriptorProto; import com.google.protobuf.DescriptorProtos.SourceCodeInfo.Location; import com.google.protobuf.ExtensionRegistry; import com.google.protobuf.compiler.PluginProtos; public abstract class AbstractGenerator { private static final MustacheFactory MUSTACHE_FACTORY = new DefaultMustacheFactory(); private static final int SERVICE_NUMBER_OF_PATHS = 2; private static final int METHOD_NUMBER_OF_PATHS = 4; protected abstract String getClassPrefix(); protected abstract String getClassSuffix(); protected String getSingleTemplateFileName() { return getTemplateFileName(); } protected String getTemplateFileName() { return getClassPrefix() + getClassSuffix() + "Stub.mustache"; } protected String getInterfaceTemplateFileName() { return getClassPrefix() + getClassSuffix() + "InterfaceStub.mustache"; } private String getServiceJavaDocPrefix() { return ""; } private String getMethodJavaDocPrefix() { return " "; } public List<PluginProtos.CodeGeneratorResponse.File> generateFiles(PluginProtos.CodeGeneratorRequest request) { // 1. build ExtensionRegistry and registry ExtensionRegistry registry = ExtensionRegistry.newInstance(); AnnotationsProto.registerAllExtensions(registry); // 2. compile proto file List<FileDescriptorProto> protosToGenerate = request.getProtoFileList().stream() .filter(protoFile -> request.getFileToGenerateList().contains(protoFile.getName())) .map(protoFile -> parseWithExtensions(protoFile, registry)) .collect(Collectors.toList()); // 3. use compiled proto file build ProtoTypeMap final ProtoTypeMap typeMap = ProtoTypeMap.of(protosToGenerate); // 4. find and generate serviceContext List<ServiceContext> services = findServices(protosToGenerate, typeMap); return generateFiles(services); } private FileDescriptorProto parseWithExtensions(FileDescriptorProto protoFile, ExtensionRegistry registry) { try { return FileDescriptorProto.parseFrom(protoFile.toByteString(), registry); } catch (Exception e) { return protoFile; } } private List<ServiceContext> findServices(List<FileDescriptorProto> protos, ProtoTypeMap typeMap) { List<ServiceContext> contexts = new ArrayList<>(); protos.forEach(fileProto -> { for (int serviceNumber = 0; serviceNumber < fileProto.getServiceCount(); serviceNumber++) { ServiceContext serviceContext = buildServiceContext( fileProto.getService(serviceNumber), typeMap, fileProto.getSourceCodeInfo().getLocationList(), serviceNumber); serviceContext.protoName = fileProto.getName(); serviceContext.packageName = extractPackageName(fileProto); if (!Strings.isNullOrEmpty(fileProto.getOptions().getJavaOuterClassname())) { serviceContext.outerClassName = fileProto.getOptions().getJavaOuterClassname(); } else { serviceContext.outerClassName = ProtoTypeMap.getJavaOuterClassname(fileProto, fileProto.getOptions()); } serviceContext.commonPackageName = extractCommonPackageName(fileProto); serviceContext.multipleFiles = fileProto.getOptions().getJavaMultipleFiles(); contexts.add(serviceContext); } }); return contexts; } private String extractPackageName(FileDescriptorProto proto) { FileOptions options = proto.getOptions(); String javaPackage = options.getJavaPackage(); if (!Strings.isNullOrEmpty(javaPackage)) { return javaPackage; } return Strings.nullToEmpty(proto.getPackage()); } private String extractCommonPackageName(FileDescriptorProto proto) { return Strings.nullToEmpty(proto.getPackage()); } private ServiceContext buildServiceContext( ServiceDescriptorProto serviceProto, ProtoTypeMap typeMap, List<Location> locations, int serviceNumber) { ServiceContext serviceContext = new ServiceContext(); serviceContext.fileName = getClassPrefix() + serviceProto.getName() + getClassSuffix() + ".java"; serviceContext.className = getClassPrefix() + serviceProto.getName() + getClassSuffix(); serviceContext.interfaceFileName = serviceProto.getName() + ".java"; serviceContext.interfaceClassName = serviceProto.getName(); serviceContext.serviceName = serviceProto.getName(); serviceContext.deprecated = serviceProto.getOptions().getDeprecated(); List<Location> allLocationsForService = locations.stream() .filter(location -> location.getPathCount() >= 2 && location.getPath(0) == FileDescriptorProto.SERVICE_FIELD_NUMBER && location.getPath(1) == serviceNumber) .collect(Collectors.toList()); Location serviceLocation = allLocationsForService.stream() .filter(location -> location.getPathCount() == SERVICE_NUMBER_OF_PATHS) .findFirst() .orElseGet(Location::getDefaultInstance); serviceContext.javaDoc = getJavaDoc(getComments(serviceLocation), getServiceJavaDocPrefix()); for (int methodNumber = 0; methodNumber < serviceProto.getMethodCount(); methodNumber++) { MethodContext methodContext = buildMethodContext(serviceProto.getMethod(methodNumber), typeMap, locations, methodNumber); serviceContext.methods.add(methodContext); serviceContext.methodTypes.add(methodContext.inputType); serviceContext.methodTypes.add(methodContext.outputType); } return serviceContext; } private MethodContext buildMethodContext( MethodDescriptorProto methodProto, ProtoTypeMap typeMap, List<Location> locations, int methodNumber) { MethodContext methodContext = new MethodContext(); methodContext.originMethodName = methodProto.getName(); methodContext.methodName = lowerCaseFirst(methodProto.getName()); methodContext.inputType = typeMap.toJavaTypeName(methodProto.getInputType()); methodContext.outputType = typeMap.toJavaTypeName(methodProto.getOutputType()); methodContext.deprecated = methodProto.getOptions().getDeprecated(); methodContext.isManyInput = methodProto.getClientStreaming(); methodContext.isManyOutput = methodProto.getServerStreaming(); methodContext.methodNumber = methodNumber; // compile google.api.http option HttpRule httpRule = parseHttpRule(methodProto); if (httpRule != null) { PatternCase patternCase = httpRule.getPatternCase(); String path; switch (patternCase) { case GET: path = httpRule.getGet(); break; case PUT: path = httpRule.getPut(); break; case POST: path = httpRule.getPost(); break; case DELETE: path = httpRule.getDelete(); break; case PATCH: path = httpRule.getPatch(); break; default: path = ""; break; } if (!path.isEmpty()) { methodContext.httpMethod = patternCase.name(); methodContext.path = path; methodContext.body = httpRule.getBody(); methodContext.hasMapping = true; methodContext.needRequestAnnotation = !methodContext.body.isEmpty() || path.contains("{"); } } Location methodLocation = locations.stream() .filter(location -> location.getPathCount() == METHOD_NUMBER_OF_PATHS && location.getPath(METHOD_NUMBER_OF_PATHS - 1) == methodNumber) .findFirst() .orElseGet(Location::getDefaultInstance); methodContext.javaDoc = getJavaDoc(getComments(methodLocation), getMethodJavaDocPrefix()); if (!methodProto.getClientStreaming() && !methodProto.getServerStreaming()) { methodContext.reactiveCallsMethodName = "oneToOne"; methodContext.grpcCallsMethodName = "asyncUnaryCall"; } if (!methodProto.getClientStreaming() && methodProto.getServerStreaming()) { methodContext.reactiveCallsMethodName = "oneToMany"; methodContext.grpcCallsMethodName = "asyncServerStreamingCall"; } if (methodProto.getClientStreaming() && !methodProto.getServerStreaming()) { methodContext.reactiveCallsMethodName = "manyToOne"; methodContext.grpcCallsMethodName = "asyncClientStreamingCall"; } if (methodProto.getClientStreaming() && methodProto.getServerStreaming()) { methodContext.reactiveCallsMethodName = "manyToMany"; methodContext.grpcCallsMethodName = "asyncBidiStreamingCall"; } return methodContext; } private HttpRule parseHttpRule(MethodDescriptorProto methodProto) { HttpRule rule = null; // check methodProto have options if (methodProto.hasOptions()) { if (methodProto.getOptions().hasExtension(AnnotationsProto.http)) { rule = methodProto.getOptions().getExtension(AnnotationsProto.http); } } return rule; } private String lowerCaseFirst(String s) { return Character.toLowerCase(s.charAt(0)) + s.substring(1); } private List<PluginProtos.CodeGeneratorResponse.File> generateFiles(List<ServiceContext> services) { List<PluginProtos.CodeGeneratorResponse.File> allServiceFiles = new ArrayList<>(); for (ServiceContext context : services) { List<PluginProtos.CodeGeneratorResponse.File> files = buildFile(context); allServiceFiles.addAll(files); } return allServiceFiles; } protected boolean useMultipleTemplate(boolean multipleFiles) { return false; } private List<PluginProtos.CodeGeneratorResponse.File> buildFile(ServiceContext context) { List<PluginProtos.CodeGeneratorResponse.File> files = new ArrayList<>(); if (useMultipleTemplate(context.multipleFiles)) { String content = applyTemplate(getTemplateFileName(), context); String dir = absoluteDir(context); files.add(PluginProtos.CodeGeneratorResponse.File.newBuilder() .setName(getFileName(dir, context.fileName)) .setContent(content) .build()); content = applyTemplate(getInterfaceTemplateFileName(), context); files.add(PluginProtos.CodeGeneratorResponse.File.newBuilder() .setName(getFileName(dir, context.interfaceFileName)) .setContent(content) .build()); } else { String content = applyTemplate(getSingleTemplateFileName(), context); String dir = absoluteDir(context); files.add(PluginProtos.CodeGeneratorResponse.File.newBuilder() .setName(getFileName(dir, context.fileName)) .setContent(content) .build()); } return files; } protected String applyTemplate(@Nonnull String resourcePath, @Nonnull Object generatorContext) { Preconditions.checkNotNull(resourcePath, "resourcePath"); Preconditions.checkNotNull(generatorContext, "generatorContext"); InputStream resource = MustacheFactory.class.getClassLoader().getResourceAsStream(resourcePath); if (resource == null) { throw new RuntimeException("Could not find resource " + resourcePath); } else { InputStreamReader resourceReader = new InputStreamReader(resource, Charsets.UTF_8); Mustache template = MUSTACHE_FACTORY.compile(resourceReader, resourcePath); return template.execute(new StringWriter(), generatorContext).toString(); } } private String absoluteDir(ServiceContext ctx) { return ctx.packageName.replace('.', '/'); } private String getFileName(String dir, String fileName) { if (Strings.isNullOrEmpty(dir)) { return fileName; } return dir + "/" + fileName; } private String getComments(Location location) { return location.getLeadingComments().isEmpty() ? location.getTrailingComments() : location.getLeadingComments(); } private String getJavaDoc(String comments, String prefix) { if (!comments.isEmpty()) { StringBuilder builder = new StringBuilder("/**\n").append(prefix).append(" * <pre>\n"); Arrays.stream(HtmlEscapers.htmlEscaper().escape(comments).split("\n")) .map(line -> line.replace("*/", "&#42;&#47;").replace("*", "&#42;")) .forEach(line -> builder.append(prefix).append(" * ").append(line).append("\n")); builder.append(prefix).append(" * </pre>\n").append(prefix).append(" */"); return builder.toString(); } return null; } /** * Template class for proto Service objects. */ private class ServiceContext { // CHECKSTYLE DISABLE VisibilityModifier FOR 8 LINES public String fileName; public String interfaceFileName; public String protoName; public String packageName; public String commonPackageName; public String className; public String interfaceClassName; public String serviceName; public boolean deprecated; public String javaDoc; public boolean multipleFiles; public String outerClassName; public List<MethodContext> methods = new ArrayList<>(); public Set<String> methodTypes = new HashSet<>(); public List<MethodContext> unaryRequestMethods() { return methods.stream().filter(m -> !m.isManyInput).collect(Collectors.toList()); } public List<MethodContext> unaryMethods() { return methods.stream() .filter(m -> (!m.isManyInput && !m.isManyOutput)) .collect(Collectors.toList()); } public List<MethodContext> serverStreamingMethods() { return methods.stream() .filter(m -> !m.isManyInput && m.isManyOutput) .collect(Collectors.toList()); } public List<MethodContext> biStreamingMethods() { return methods.stream().filter(m -> m.isManyInput).collect(Collectors.toList()); } public List<MethodContext> biStreamingWithoutClientStreamMethods() { return methods.stream().filter(m -> m.isManyInput && m.isManyOutput).collect(Collectors.toList()); } public List<MethodContext> clientStreamingMethods() { return methods.stream() .filter(m -> m.isManyInput && !m.isManyOutput) .collect(Collectors.toList()); } public List<MethodContext> methods() { return methods; } } /** * Template class for proto RPC objects. */ private static class MethodContext { // CHECKSTYLE DISABLE VisibilityModifier FOR 10 LINES public String originMethodName; public String methodName; public String inputType; public String outputType; public boolean deprecated; public boolean isManyInput; public boolean isManyOutput; public String reactiveCallsMethodName; public String grpcCallsMethodName; public int methodNumber; public String javaDoc; /** * The HTTP request method */ public String httpMethod; /** * The HTTP request path */ public String path; /** * The message field that the HTTP request body mapping to */ public String body; /** * Whether the method has HTTP mapping */ public boolean hasMapping; /** * Whether the request body parameter need @GRequest annotation */ public boolean needRequestAnnotation; // This method mimics the upper-casing method ogf gRPC to ensure compatibility // See https://github.com/grpc/grpc-java/blob/v1.8.0/compiler/src/java_plugin/cpp/java_generator.cpp#L58 public String methodNameUpperUnderscore() { StringBuilder s = new StringBuilder(); for (int i = 0; i < methodName.length(); i++) { char c = methodName.charAt(i); s.append(Character.toUpperCase(c)); if ((i < methodName.length() - 1) && Character.isLowerCase(c) && Character.isUpperCase(methodName.charAt(i + 1))) { s.append('_'); } } return s.toString(); } public String methodNamePascalCase() { String mn = methodName.replace("_", ""); return String.valueOf(Character.toUpperCase(mn.charAt(0))) + mn.substring(1); } public String methodNameCamelCase() { String mn = methodName.replace("_", ""); return String.valueOf(Character.toLowerCase(mn.charAt(0))) + mn.substring(1); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/DubboGeneratorPlugin.java
dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/DubboGeneratorPlugin.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.gen; import java.io.IOException; import java.util.List; import com.google.protobuf.compiler.PluginProtos; public class DubboGeneratorPlugin { public static void generate(AbstractGenerator generator) { try { PluginProtos.CodeGeneratorRequest request = PluginProtos.CodeGeneratorRequest.parseFrom(System.in); List<PluginProtos.CodeGeneratorResponse.File> files = generator.generateFiles(request); PluginProtos.CodeGeneratorResponse.newBuilder() .addAllFile(files) .setSupportedFeatures( PluginProtos.CodeGeneratorResponse.Feature.FEATURE_PROTO3_OPTIONAL.getNumber()) .build() .writeTo(System.out); } catch (Exception e) { try { PluginProtos.CodeGeneratorResponse.newBuilder() .setError(e.getMessage()) .build() .writeTo(System.out); } catch (IOException var6) { exit(e); } } catch (Throwable var8) { exit(var8); } } public static void exit(Throwable e) { e.printStackTrace(System.err); System.exit(1); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/utils/ProtoTypeMap.java
dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/utils/ProtoTypeMap.java
/* * Copyright (c) 2019, Salesforce.com, Inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package org.apache.dubbo.gen.utils; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.protobuf.DescriptorProtos; import javax.annotation.Nonnull; import java.util.Collection; public final class ProtoTypeMap { private static final Joiner DOT_JOINER = Joiner.on('.').skipNulls(); private final ImmutableMap<String, String> types; private ProtoTypeMap(@Nonnull ImmutableMap<String, String> types) { Preconditions.checkNotNull(types, "types"); this.types = types; } public static ProtoTypeMap of(@Nonnull Collection<DescriptorProtos.FileDescriptorProto> fileDescriptorProtos) { Preconditions.checkNotNull(fileDescriptorProtos, "fileDescriptorProtos"); Preconditions.checkArgument(!fileDescriptorProtos.isEmpty(), "fileDescriptorProtos.isEmpty()"); ImmutableMap.Builder<String, String> types = ImmutableMap.builder(); for (DescriptorProtos.FileDescriptorProto fileDescriptor : fileDescriptorProtos) { DescriptorProtos.FileOptions fileOptions = fileDescriptor.getOptions(); String protoPackage = fileDescriptor.hasPackage() ? "." + fileDescriptor.getPackage() : ""; String javaPackage = Strings.emptyToNull(fileOptions.hasJavaPackage() ? fileOptions.getJavaPackage() : fileDescriptor.getPackage()); String enclosingClassName = fileOptions.getJavaMultipleFiles() ? null : getJavaOuterClassname(fileDescriptor, fileOptions); fileDescriptor.getEnumTypeList().forEach((e) -> { types.put(protoPackage + "." + e.getName(), DOT_JOINER.join(javaPackage, enclosingClassName, new Object[]{e.getName()})); }); fileDescriptor.getMessageTypeList().forEach((m) -> { recursivelyAddTypes(types, m, protoPackage, enclosingClassName, javaPackage); }); } return new ProtoTypeMap(types.build()); } private static void recursivelyAddTypes(ImmutableMap.Builder<String, String> types, DescriptorProtos.DescriptorProto m, String protoPackage, String enclosingClassName, String javaPackage) { String protoTypeName = protoPackage + "." + m.getName(); types.put(protoTypeName, DOT_JOINER.join(javaPackage, enclosingClassName, new Object[]{m.getName()})); m.getEnumTypeList().forEach((e) -> { types.put(protoPackage + "." + m.getName() + "." + e.getName(), DOT_JOINER.join(javaPackage, enclosingClassName, new Object[]{m.getName(), e.getName()})); }); m.getNestedTypeList().forEach((n) -> { recursivelyAddTypes(types, n, protoPackage + "." + m.getName(), DOT_JOINER.join(enclosingClassName, m.getName(), new Object[0]), javaPackage); }); } public String toJavaTypeName(@Nonnull String protoTypeName) { Preconditions.checkNotNull(protoTypeName, "protoTypeName"); return (String)this.types.get(protoTypeName); } public static String getJavaOuterClassname(DescriptorProtos.FileDescriptorProto fileDescriptor, DescriptorProtos.FileOptions fileOptions) { if (fileOptions.hasJavaOuterClassname()) { return fileOptions.getJavaOuterClassname(); } else { String filename = fileDescriptor.getName().substring(0, fileDescriptor.getName().length() - ".proto".length()); if (filename.contains("/")) { filename = filename.substring(filename.lastIndexOf(47) + 1); } filename = makeInvalidCharactersUnderscores(filename); filename = convertToCamelCase(filename); filename = appendOuterClassSuffix(filename, fileDescriptor); return filename; } } private static String appendOuterClassSuffix(String enclosingClassName, DescriptorProtos.FileDescriptorProto fd) { return !fd.getEnumTypeList().stream().anyMatch((enumProto) -> { return enumProto.getName().equals(enclosingClassName); }) && !fd.getMessageTypeList().stream().anyMatch((messageProto) -> { return messageProto.getName().equals(enclosingClassName); }) && !fd.getServiceList().stream().anyMatch((serviceProto) -> { return serviceProto.getName().equals(enclosingClassName); }) ? enclosingClassName : enclosingClassName + "OuterClass"; } private static String makeInvalidCharactersUnderscores(String filename) { char[] filechars = filename.toCharArray(); for(int i = 0; i < filechars.length; ++i) { char c = filechars[i]; if (!CharMatcher.inRange('0', '9').or(CharMatcher.inRange('A', 'Z')).or(CharMatcher.inRange('a', 'z')).matches(c)) { filechars[i] = '_'; } } return new String(filechars); } private static String convertToCamelCase(String name) { StringBuilder sb = new StringBuilder(); sb.append(Character.toUpperCase(name.charAt(0))); for(int i = 1; i < name.length(); ++i) { char c = name.charAt(i); char prev = name.charAt(i - 1); if (c != '_') { if (prev != '_' && !CharMatcher.inRange('0', '9').matches(prev)) { sb.append(c); } else { sb.append(Character.toUpperCase(c)); } } } return sb.toString(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/Dubbo3TripleGenerator.java
dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/Dubbo3TripleGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.gen.tri; import org.apache.dubbo.gen.AbstractGenerator; import org.apache.dubbo.gen.DubboGeneratorPlugin; public class Dubbo3TripleGenerator extends AbstractGenerator { public static void main(String[] args) { DubboGeneratorPlugin.generate(new Dubbo3TripleGenerator()); } @Override protected String getClassPrefix() { return "Dubbo"; } @Override protected String getClassSuffix() { return "Triple"; } @Override protected String getTemplateFileName() { return "Dubbo3TripleStub.mustache"; } @Override protected String getInterfaceTemplateFileName() { return "Dubbo3TripleInterfaceStub.mustache"; } @Override protected String getSingleTemplateFileName() { throw new IllegalStateException("Do not support single template!"); } @Override protected boolean useMultipleTemplate(boolean multipleFiles) { return true; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/reactive/ReactorDubbo3TripleGenerator.java
dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/reactive/ReactorDubbo3TripleGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.gen.tri.reactive; import org.apache.dubbo.gen.AbstractGenerator; import org.apache.dubbo.gen.DubboGeneratorPlugin; public class ReactorDubbo3TripleGenerator extends AbstractGenerator { public static void main(String[] args) { DubboGeneratorPlugin.generate(new ReactorDubbo3TripleGenerator()); } @Override protected String getClassPrefix() { return "Dubbo"; } @Override protected String getClassSuffix() { return "Triple"; } @Override protected String getTemplateFileName() { return "ReactorDubbo3TripleStub.mustache"; } @Override protected String getInterfaceTemplateFileName() { return "ReactorDubbo3TripleInterfaceStub.mustache"; } @Override protected String getSingleTemplateFileName() { throw new IllegalStateException("Do not support single template!"); } @Override protected boolean useMultipleTemplate(boolean multipleFiles) { return true; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/mutiny/MutinyDubbo3TripleGenerator.java
dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/mutiny/MutinyDubbo3TripleGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.gen.tri.mutiny; import org.apache.dubbo.gen.AbstractGenerator; import org.apache.dubbo.gen.DubboGeneratorPlugin; public class MutinyDubbo3TripleGenerator extends AbstractGenerator { public static void main(String[] args) { DubboGeneratorPlugin.generate(new MutinyDubbo3TripleGenerator()); } @Override protected String getClassPrefix() { return "Dubbo"; } @Override protected String getClassSuffix() { return "Triple"; } @Override protected String getTemplateFileName() { return "MutinyDubbo3TripleStub.mustache"; } @Override protected String getInterfaceTemplateFileName() { return "MutinyDubbo3TripleInterfaceStub.mustache"; } @Override protected String getSingleTemplateFileName() { throw new IllegalStateException("Do not support single template!"); } @Override protected boolean useMultipleTemplate(boolean multipleFiles) { return true; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/test/java/OneToOneMethodHandlerTest.java
dubbo-plugin/dubbo-mutiny/src/test/java/OneToOneMethodHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.dubbo.mutiny.handler.OneToOneMethodHandler; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Unit test for OneToOneMethodHandler */ public final class OneToOneMethodHandlerTest { @Test void testInvoke() throws ExecutionException, InterruptedException { String request = "request"; OneToOneMethodHandler<String, String> handler = new OneToOneMethodHandler<>(requestUni -> requestUni.map(r -> r + "Test")); CompletableFuture<?> future = handler.invoke(new Object[] {request}); assertEquals("requestTest", future.get()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/test/java/OneToManyMethodHandlerTest.java
dubbo-plugin/dubbo-mutiny/src/test/java/OneToManyMethodHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.dubbo.mutiny.handler.OneToManyMethodHandler; import java.util.concurrent.CompletableFuture; import io.smallrye.mutiny.Multi; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Unit test for OneToManyMethodHandler */ public final class OneToManyMethodHandlerTest { private CreateObserverAdapter creator; @BeforeEach void init() { creator = new CreateObserverAdapter(); } @Test void testInvoke() { String request = "1,2,3,4,5,6,7"; OneToManyMethodHandler<String, String> handler = new OneToManyMethodHandler<>(requestUni -> requestUni.onItem().transformToMulti(r -> Multi.createFrom().items(r.split(",")))); CompletableFuture<?> future = handler.invoke(new Object[] {request, creator.getResponseObserver()}); Assertions.assertTrue(future.isDone()); Assertions.assertEquals(7, creator.getNextCounter().get()); Assertions.assertEquals(0, creator.getErrorCounter().get()); Assertions.assertEquals(1, creator.getCompleteCounter().get()); } @Test void testError() { String request = "1,2,3,4,5,6,7"; OneToManyMethodHandler<String, String> handler = new OneToManyMethodHandler<>(requestUni -> Multi.createFrom().emitter(emitter -> { for (int i = 0; i < 10; i++) { if (i == 6) { emitter.fail(new Throwable()); return; } else { emitter.emit(String.valueOf(i)); } } emitter.complete(); })); CompletableFuture<?> future = handler.invoke(new Object[] {request, creator.getResponseObserver()}); Assertions.assertTrue(future.isDone()); Assertions.assertEquals(6, creator.getNextCounter().get()); Assertions.assertEquals(1, creator.getErrorCounter().get()); Assertions.assertEquals(0, creator.getCompleteCounter().get()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/test/java/ManyToManyMethodHandlerTest.java
dubbo-plugin/dubbo-mutiny/src/test/java/ManyToManyMethodHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.mutiny.handler.ManyToManyMethodHandler; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Unit test for ManyToManyMethodHandler */ public final class ManyToManyMethodHandlerTest { @Test void testInvoke() throws ExecutionException, InterruptedException { CreateObserverAdapter creator = new CreateObserverAdapter(); ManyToManyMethodHandler<String, String> handler = new ManyToManyMethodHandler<>(requestFlux -> requestFlux.map(r -> r + "0")); CompletableFuture<StreamObserver<String>> future = handler.invoke(new Object[] {creator.getResponseObserver()}); StreamObserver<String> requestObserver = future.get(); for (int i = 0; i < 10; i++) { requestObserver.onNext(String.valueOf(i)); } requestObserver.onCompleted(); Assertions.assertEquals(10, creator.getNextCounter().get()); Assertions.assertEquals(0, creator.getErrorCounter().get()); Assertions.assertEquals(1, creator.getCompleteCounter().get()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/test/java/CreateObserverAdapter.java
dubbo-plugin/dubbo-mutiny/src/test/java/CreateObserverAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.dubbo.rpc.protocol.tri.ServerStreamObserver; import java.util.concurrent.atomic.AtomicInteger; import org.mockito.Mockito; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; public class CreateObserverAdapter { private ServerStreamObserver<String> responseObserver; private AtomicInteger nextCounter; private AtomicInteger completeCounter; private AtomicInteger errorCounter; CreateObserverAdapter() { nextCounter = new AtomicInteger(); completeCounter = new AtomicInteger(); errorCounter = new AtomicInteger(); responseObserver = Mockito.mock(ServerStreamObserver.class); doAnswer(o -> nextCounter.incrementAndGet()).when(responseObserver).onNext(anyString()); doAnswer(o -> completeCounter.incrementAndGet()).when(responseObserver).onCompleted(); doAnswer(o -> errorCounter.incrementAndGet()).when(responseObserver).onError(any(Throwable.class)); } public AtomicInteger getCompleteCounter() { return completeCounter; } public AtomicInteger getNextCounter() { return nextCounter; } public AtomicInteger getErrorCounter() { return errorCounter; } public ServerStreamObserver<String> getResponseObserver() { return this.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-mutiny/src/test/java/ManyToOneMethodHandlerTest.java
dubbo-plugin/dubbo-mutiny/src/test/java/ManyToOneMethodHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.mutiny.handler.ManyToOneMethodHandler; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Unit test for ManyToOneMethodHandler */ public final class ManyToOneMethodHandlerTest { private StreamObserver<String> requestObserver; private CreateObserverAdapter creator; @BeforeEach void init() throws ExecutionException, InterruptedException { creator = new CreateObserverAdapter(); ManyToOneMethodHandler<String, String> handler = new ManyToOneMethodHandler<>(requestMulti -> requestMulti .map(Integer::valueOf) .collect() .asList() .map(list -> list.stream().reduce(Integer::sum)) .map(String::valueOf)); CompletableFuture<StreamObserver<String>> future = handler.invoke(new Object[] {creator.getResponseObserver()}); requestObserver = future.get(); } @Test void testInvoker() { for (int i = 0; i < 10; i++) { requestObserver.onNext(String.valueOf(i)); } requestObserver.onCompleted(); Assertions.assertEquals(1, creator.getNextCounter().get()); Assertions.assertEquals(0, creator.getErrorCounter().get()); Assertions.assertEquals(1, creator.getCompleteCounter().get()); } @Test void testError() { for (int i = 0; i < 10; i++) { if (i == 6) { requestObserver.onError(new Throwable()); } requestObserver.onNext(String.valueOf(i)); } requestObserver.onCompleted(); Assertions.assertEquals(0, creator.getNextCounter().get()); Assertions.assertEquals(1, creator.getErrorCounter().get()); Assertions.assertEquals(0, creator.getCompleteCounter().get()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/test/java/org/apache/dubbo/mutiny/MutinyClientCallsTest.java
dubbo-plugin/dubbo-mutiny/src/test/java/org/apache/dubbo/mutiny/MutinyClientCallsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.mutiny; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.mutiny.calls.MutinyClientCalls; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.StubMethodDescriptor; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import org.apache.dubbo.rpc.stub.StubInvocationUtil; import java.time.Duration; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; import io.smallrye.mutiny.helpers.test.AssertSubscriber; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; /** * Unit test for MutinyClientCalls */ public class MutinyClientCallsTest { @Test void testOneToOneSuccess() { Invoker<Object> invoker = Mockito.mock(Invoker.class); StubMethodDescriptor method = Mockito.mock(StubMethodDescriptor.class); try (MockedStatic<StubInvocationUtil> mocked = Mockito.mockStatic(StubInvocationUtil.class)) { mocked.when(() -> StubInvocationUtil.unaryCall( Mockito.eq(invoker), Mockito.eq(method), Mockito.eq("req"), Mockito.any())) .thenAnswer(invocation -> { StreamObserver<String> observer = invocation.getArgument(3); observer.onNext("resp"); observer.onCompleted(); return null; }); Uni<String> request = Uni.createFrom().item("req"); Uni<String> response = MutinyClientCalls.oneToOne(invoker, request, method); String result = response.await().indefinitely(); Assertions.assertEquals("resp", result); } } @Test void testOneToOneThrowsErrorWithMutinyAwait() { Invoker<Object> invoker = Mockito.mock(Invoker.class); StubMethodDescriptor method = Mockito.mock(StubMethodDescriptor.class); try (MockedStatic<StubInvocationUtil> mocked = Mockito.mockStatic(StubInvocationUtil.class)) { mocked.when(() -> StubInvocationUtil.unaryCall(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) .thenThrow(new RuntimeException("boom")); Uni<String> request = Uni.createFrom().item("req"); Uni<String> response = MutinyClientCalls.oneToOne(invoker, request, method); RuntimeException ex = Assertions.assertThrows(RuntimeException.class, () -> { response.await().indefinitely(); }); Assertions.assertTrue(ex.getMessage().contains("boom")); } } @Test void testOneToManyReturnsMultiAndEmitsItems() { Invoker<Object> invoker = Mockito.mock(Invoker.class); StubMethodDescriptor method = Mockito.mock(StubMethodDescriptor.class); try (MockedStatic<StubInvocationUtil> mocked = Mockito.mockStatic(StubInvocationUtil.class)) { AtomicBoolean stubCalled = new AtomicBoolean(false); CountDownLatch subscribed = new CountDownLatch(1); mocked.when(() -> StubInvocationUtil.serverStreamCall( Mockito.eq(invoker), Mockito.eq(method), Mockito.eq("testRequest"), Mockito.any())) .thenAnswer(invocation -> { stubCalled.set(true); ClientTripleMutinyPublisher<String> publisher = invocation.getArgument(3); CallStreamObserver<String> fakeSubscription = new CallStreamObserver<>() { @Override public void request(int n) { /* no-op */ } @Override public void setCompression(String compression) {} @Override public void disableAutoFlowControl() {} @Override public void onNext(String v) { publisher.onNext(v); } @Override public void onError(Throwable t) { publisher.onError(t); } @Override public void onCompleted() { publisher.onCompleted(); } }; publisher.onSubscribe(fakeSubscription); // Wait for downstream subscription to complete before emitting data new Thread(() -> { try { if (subscribed.await(5, TimeUnit.SECONDS)) { publisher.onNext("item1"); publisher.onNext("item2"); publisher.onCompleted(); } else { publisher.onError( new IllegalStateException("Downstream subscription timeout")); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); publisher.onError(e); } }) .start(); return null; }); Uni<String> uniRequest = Uni.createFrom().item("testRequest"); Multi<String> multiResponse = MutinyClientCalls.oneToMany(invoker, uniRequest, method); // Use AssertSubscriber to ensure proper subscription timing AssertSubscriber<String> subscriber = AssertSubscriber.create(Long.MAX_VALUE); multiResponse.subscribe().withSubscriber(subscriber); // Wait for subscription to be established subscriber.awaitSubscription(); subscribed.countDown(); // Signal that data emission can begin // Wait for completion subscriber.awaitCompletion(Duration.ofSeconds(5)); // Verify results Assertions.assertTrue(stubCalled.get(), "StubInvocationUtil.serverStreamCall should be called"); Assertions.assertEquals(List.of("item1", "item2"), subscriber.getItems()); subscriber.assertCompleted(); } } @Test void testManyToOneSuccess() { Invoker<Object> invoker = Mockito.mock(Invoker.class); StubMethodDescriptor method = Mockito.mock(StubMethodDescriptor.class); Multi<String> multiRequest = Multi.createFrom().items("a", "b", "c"); try (MockedStatic<StubInvocationUtil> mocked = Mockito.mockStatic(StubInvocationUtil.class)) { AtomicBoolean stubCalled = new AtomicBoolean(false); mocked.when(() -> StubInvocationUtil.biOrClientStreamCall( Mockito.eq(invoker), Mockito.eq(method), Mockito.any())) .thenAnswer(invocation -> { stubCalled.set(true); return null; }); Uni<String> uniResponse = MutinyClientCalls.manyToOne(invoker, multiRequest, method); AtomicReference<String> resultHolder = new AtomicReference<>(); AtomicReference<Throwable> errorHolder = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); uniResponse .subscribe() .with( item -> { resultHolder.set(item); latch.countDown(); }, failure -> { errorHolder.set(failure); latch.countDown(); }); try { latch.await(3, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } Assertions.assertTrue(stubCalled.get(), "StubInvocationUtil.biOrClientStreamCall should be called"); Assertions.assertNull(errorHolder.get(), "No error expected"); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/test/java/org/apache/dubbo/mutiny/TripleMutinyPublisherTest.java
dubbo-plugin/dubbo-mutiny/src/test/java/org/apache/dubbo/mutiny/TripleMutinyPublisherTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.mutiny; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Flow; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Unit test for AbstractTripleMutinyPublisher */ public class TripleMutinyPublisherTest { @Test public void testSubscribeAndRequest() { AtomicBoolean subscribed = new AtomicBoolean(false); AbstractTripleMutinyPublisher<String> publisher = new AbstractTripleMutinyPublisher<>() { @Override protected void onSubscribe(CallStreamObserver<?> subscription) { subscribed.set(true); this.subscription = Mockito.mock(CallStreamObserver.class); } }; publisher.onSubscribe(Mockito.mock(CallStreamObserver.class)); Flow.Subscriber<String> subscriber = new Flow.Subscriber<>() { @Override public void onSubscribe(Flow.Subscription s) { s.request(1); } @Override public void onNext(String item) {} @Override public void onError(Throwable t) {} @Override public void onComplete() {} }; publisher.subscribe(subscriber); assertTrue(subscribed.get()); } @Test public void testRequestBeforeStartRequest() { CallStreamObserver<?> mockObserver = Mockito.mock(CallStreamObserver.class); AbstractTripleMutinyPublisher<String> publisher = new AbstractTripleMutinyPublisher<>() {}; publisher.onSubscribe(mockObserver); publisher.request(5L); // should accumulate, not call request() Mockito.verify(mockObserver, Mockito.never()).request(Mockito.anyInt()); publisher.startRequest(); // now should flush request Mockito.verify(mockObserver).request(5); } @Test public void testCancelTriggersShutdownHook() { AtomicBoolean shutdown = new AtomicBoolean(false); AbstractTripleMutinyPublisher<String> publisher = new AbstractTripleMutinyPublisher<>(null, () -> shutdown.set(true)) {}; publisher.cancel(); assertTrue(publisher.isCancelled()); assertTrue(shutdown.get()); } @Test public void testOnNextAndComplete() { List<String> received = new ArrayList<>(); AtomicBoolean completed = new AtomicBoolean(); AbstractTripleMutinyPublisher<String> publisher = new AbstractTripleMutinyPublisher<>() {}; publisher.subscribe(new Flow.Subscriber<>() { @Override public void onSubscribe(Flow.Subscription s) {} @Override public void onNext(String item) { received.add(item); } @Override public void onError(Throwable t) {} @Override public void onComplete() { completed.set(true); } }); publisher.onNext("hello"); publisher.onNext("world"); publisher.onCompleted(); assertEquals(List.of("hello", "world"), received); assertTrue(completed.get()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/test/java/org/apache/dubbo/mutiny/MutinyServerCallsTest.java
dubbo-plugin/dubbo-mutiny/src/test/java/org/apache/dubbo/mutiny/MutinyServerCallsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.mutiny; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.mutiny.calls.MutinyServerCalls; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.function.Function; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * Unit test for MutinyServerCalls */ public class MutinyServerCallsTest { @Test void testOneToOne_success() { StreamObserver<String> responseObserver = mock(StreamObserver.class); Function<Uni<String>, Uni<String>> func = reqUni -> reqUni.onItem().transform(i -> i + "-resp"); MutinyServerCalls.oneToOne("req", responseObserver, func); // responseObserver verify(responseObserver, times(1)).onNext("req-resp"); verify(responseObserver, times(1)).onCompleted(); verify(responseObserver, never()).onError(any()); } @Test void testOneToOne_exception() { StreamObserver<String> responseObserver = mock(StreamObserver.class); // mock func error Function<Uni<String>, Uni<String>> func = reqUni -> { throw new RuntimeException("fail"); }; MutinyServerCalls.oneToOne("req", responseObserver, func); verify(responseObserver, times(1)).onError(any()); verify(responseObserver, never()).onNext(any()); verify(responseObserver, never()).onCompleted(); } @Test void testOneToMany_success() throws ExecutionException, InterruptedException { CallStreamObserver<String> responseObserver = mock(CallStreamObserver.class); // multi results Function<Uni<String>, Multi<String>> func = reqUni -> Multi.createFrom().items("a", "b", "c"); CompletableFuture<List<String>> future = MutinyServerCalls.oneToMany("req", responseObserver, func); List<String> results = future.get(); assertEquals(3, results.size()); // test responseObserver verify(responseObserver, atLeastOnce()).onNext(any()); verify(responseObserver, times(1)).onCompleted(); verify(responseObserver, never()).onError(any()); } @Test void testOneToMany_exception() { CallStreamObserver<String> responseObserver = mock(CallStreamObserver.class); Function<Uni<String>, Multi<String>> func = reqUni -> { throw new RuntimeException("fail"); }; CompletableFuture<List<String>> future = MutinyServerCalls.oneToMany("req", responseObserver, func); assertTrue(future.isCompletedExceptionally()); verify(responseObserver, times(1)).onError(any()); } @Test void testManyToOne_success() throws InterruptedException { CallStreamObserver<String> responseObserver = mock(CallStreamObserver.class); // return uni Function<Multi<String>, Uni<String>> func = multi -> multi.collect().asList().onItem().transform(list -> "size:" + list.size()); StreamObserver<String> requestObserver = MutinyServerCalls.manyToOne(responseObserver, func); // mock onNext/onCompleted requestObserver.onNext("a"); requestObserver.onNext("b"); requestObserver.onNext("c"); requestObserver.onCompleted(); Thread.sleep(200); verify(responseObserver, times(1)).onNext("size:3"); verify(responseObserver, times(1)).onCompleted(); verify(responseObserver, never()).onError(any()); } @Test void testManyToOne_funcThrows() { CallStreamObserver<String> responseObserver = mock(CallStreamObserver.class); Function<Multi<String>, Uni<String>> func = multi -> { throw new RuntimeException("fail"); }; StreamObserver<String> requestObserver = MutinyServerCalls.manyToOne(responseObserver, func); verify(responseObserver, times(1)).onError(any()); } @Test void testManyToMany_success() throws InterruptedException { CallStreamObserver<String> responseObserver = mock(CallStreamObserver.class); Function<Multi<String>, Multi<String>> func = multi -> multi.map(s -> s + "-resp"); StreamObserver<String> requestObserver = MutinyServerCalls.manyToMany(responseObserver, func); // mock onNext/onCompleted requestObserver.onNext("x"); requestObserver.onNext("y"); requestObserver.onCompleted(); Thread.sleep(200); verify(responseObserver, atLeastOnce()).onNext(any()); verify(responseObserver, times(1)).onCompleted(); verify(responseObserver, never()).onError(any()); } @Test void testManyToMany_funcThrows() { CallStreamObserver<String> responseObserver = mock(CallStreamObserver.class); Function<Multi<String>, Multi<String>> func = multi -> { throw new RuntimeException("fail"); }; StreamObserver<String> requestObserver = MutinyServerCalls.manyToMany(responseObserver, func); verify(responseObserver, times(1)).onError(any()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/test/java/org/apache/dubbo/mutiny/TripleMutinySubscriberTest.java
dubbo-plugin/dubbo-mutiny/src/test/java/org/apache/dubbo/mutiny/TripleMutinySubscriberTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.mutiny; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import java.util.concurrent.Flow; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Unit test for AbstractTripleMutinySubscriber */ public class TripleMutinySubscriberTest { @Test void testSubscribeBindsDownstreamAndRequests() { TestingSubscriber<String> subscriber = new TestingSubscriber<>(); Flow.Subscription subscription = Mockito.mock(Flow.Subscription.class); CallStreamObserver<String> downstream = Mockito.mock(CallStreamObserver.class); subscriber.onSubscribe(subscription); // bind subscription subscriber.subscribe(downstream); // bind downstream Mockito.verify(subscription).request(1); } @Test void testOnNextPassesItemAndRequestsNext() { TestingSubscriber<String> subscriber = new TestingSubscriber<>(); Flow.Subscription subscription = Mockito.mock(Flow.Subscription.class); CallStreamObserver<String> downstream = Mockito.mock(CallStreamObserver.class); subscriber.onSubscribe(subscription); subscriber.subscribe(downstream); subscriber.onNext("hello"); Mockito.verify(downstream).onNext("hello"); Mockito.verify(subscription, Mockito.times(2)).request(1); // 1st in subscribe, 2nd in onNext } @Test void testOnErrorMarksDoneAndPropagates() { TestingSubscriber<String> subscriber = new TestingSubscriber<>(); Flow.Subscription subscription = Mockito.mock(Flow.Subscription.class); CallStreamObserver<String> downstream = Mockito.mock(CallStreamObserver.class); RuntimeException error = new RuntimeException("boom"); subscriber.onSubscribe(subscription); subscriber.subscribe(downstream); subscriber.onError(error); Mockito.verify(downstream).onError(error); } @Test void testOnCompleteMarksDoneAndNotifies() { TestingSubscriber<String> subscriber = new TestingSubscriber<>(); Flow.Subscription subscription = Mockito.mock(Flow.Subscription.class); CallStreamObserver<String> downstream = Mockito.mock(CallStreamObserver.class); subscriber.onSubscribe(subscription); subscriber.subscribe(downstream); subscriber.onComplete(); Mockito.verify(downstream).onCompleted(); } @Test void testCancelCancelsSubscription() { TestingSubscriber<String> subscriber = new TestingSubscriber<>(); Flow.Subscription subscription = Mockito.mock(Flow.Subscription.class); subscriber.onSubscribe(subscription); subscriber.cancel(); assertTrue(subscriber.isCancelled()); Mockito.verify(subscription).cancel(); } @Test void testSubscribeTwiceDoesNotRebind() { TestingSubscriber<String> subscriber = new TestingSubscriber<>(); Flow.Subscription subscription = Mockito.mock(Flow.Subscription.class); CallStreamObserver<String> downstream1 = Mockito.mock(CallStreamObserver.class); CallStreamObserver<String> downstream2 = Mockito.mock(CallStreamObserver.class); subscriber.onSubscribe(subscription); subscriber.subscribe(downstream1); subscriber.subscribe(downstream2); subscriber.onNext("test"); Mockito.verify(downstream1).onNext("test"); Mockito.verify(downstream2, Mockito.never()).onNext(Mockito.any()); } @Test void testOnSubscribeTwiceCancelsSecond() { TestingSubscriber<String> subscriber = new TestingSubscriber<>(); Flow.Subscription sub1 = Mockito.mock(Flow.Subscription.class); Flow.Subscription sub2 = Mockito.mock(Flow.Subscription.class); subscriber.onSubscribe(sub1); subscriber.onSubscribe(sub2); // should cancel sub2 Mockito.verify(sub2).cancel(); Mockito.verify(sub1, Mockito.never()).cancel(); } @Test void testOnNextAfterDoneDoesNothing() { TestingSubscriber<String> subscriber = new TestingSubscriber<>(); Flow.Subscription subscription = Mockito.mock(Flow.Subscription.class); CallStreamObserver<String> downstream = Mockito.mock(CallStreamObserver.class); subscriber.onSubscribe(subscription); subscriber.subscribe(downstream); subscriber.onComplete(); subscriber.onNext("after-done"); // should be ignored Mockito.verify(downstream, Mockito.never()).onNext("after-done"); } static class TestingSubscriber<T> extends AbstractTripleMutinySubscriber<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-mutiny/src/main/java/org/apache/dubbo/mutiny/ServerTripleMutinyPublisher.java
dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/ServerTripleMutinyPublisher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.mutiny; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; /** * Used in ManyToOne and ManyToMany in server. <br> * It is a Publisher for user subscriber to subscribe. <br> * It is a StreamObserver for requestStream. <br> * It is a Subscription for user subscriber to request and pass request to responseStream. */ public class ServerTripleMutinyPublisher<T> extends AbstractTripleMutinyPublisher<T> { public ServerTripleMutinyPublisher(CallStreamObserver<?> callStreamObserver) { super.onSubscribe(callStreamObserver); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/ClientTripleMutinySubscriber.java
dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/ClientTripleMutinySubscriber.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.mutiny; import org.apache.dubbo.rpc.protocol.tri.observer.ClientCallToObserverAdapter; /** * The subscriber in client to subscribe user publisher and is subscribed by ClientStreamObserver. */ public class ClientTripleMutinySubscriber<T> extends AbstractTripleMutinySubscriber<T> { @Override public void cancel() { if (!isCancelled()) { super.cancel(); ((ClientCallToObserverAdapter<T>) downstream).cancel(new Exception("Cancelled")); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/ServerTripleMutinySubscriber.java
dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/ServerTripleMutinySubscriber.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.mutiny; import org.apache.dubbo.rpc.CancellationContext; import org.apache.dubbo.rpc.protocol.tri.CancelableStreamObserver; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; /** * The Subscriber in server to passing the data produced by user publisher to responseStream. */ public class ServerTripleMutinySubscriber<T> extends AbstractTripleMutinySubscriber<T> { /** * The execution future of the current task, in order to be returned to stubInvoker */ private final CompletableFuture<List<T>> executionFuture = new CompletableFuture<>(); /** * The result elements collected by the current task. * This class is a multi subscriber, which usually means there will be multiple elements, so it is declared as a list type. */ private final List<T> collectedData = new ArrayList<>(); public ServerTripleMutinySubscriber() {} public ServerTripleMutinySubscriber(CallStreamObserver<T> streamObserver) { this.downstream = streamObserver; } @Override public void subscribe(CallStreamObserver<T> downstream) { super.subscribe(downstream); if (downstream instanceof CancelableStreamObserver<?>) { final CancelableStreamObserver<?> observer = (CancelableStreamObserver<?>) downstream; final CancellationContext context; if (observer.getCancellationContext() == null) { context = new CancellationContext(); observer.setCancellationContext(context); } else { context = observer.getCancellationContext(); } context.addListener(ctx -> super.cancel()); } } @Override public void onNext(T t) { super.onNext(t); collectedData.add(t); } @Override public void onError(Throwable throwable) { super.onError(throwable); executionFuture.completeExceptionally(throwable); } @Override public void onComplete() { super.onComplete(); executionFuture.complete(this.collectedData); } public CompletableFuture<List<T>> getExecutionFuture() { return executionFuture; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/ClientTripleMutinyPublisher.java
dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/ClientTripleMutinyPublisher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.mutiny; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import org.apache.dubbo.rpc.protocol.tri.observer.ClientCallToObserverAdapter; import java.util.function.Consumer; /** * Used in OneToMany & ManyToOne & ManyToMany in client. <br> * It is a Publisher for user subscriber to subscribe. <br> * It is a StreamObserver for responseStream. <br> * It is a Subscription for user subscriber to request and pass request to requestStream. */ public class ClientTripleMutinyPublisher<T> extends AbstractTripleMutinyPublisher<T> { public ClientTripleMutinyPublisher() {} public ClientTripleMutinyPublisher(Consumer<CallStreamObserver<?>> onSubscribe, Runnable shutdownHook) { super(onSubscribe, shutdownHook); } @Override public void beforeStart(ClientCallToObserverAdapter<T> clientCallToObserverAdapter) { super.onSubscribe(clientCallToObserverAdapter); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/AbstractTripleMutinySubscriber.java
dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/AbstractTripleMutinySubscriber.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.mutiny; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import java.util.concurrent.Flow; import java.util.concurrent.atomic.AtomicBoolean; /** * The middle layer between {@link CallStreamObserver} and Reactive API. <br> * Passing the data from Reactive producer to CallStreamObserver. */ public abstract class AbstractTripleMutinySubscriber<T> implements Flow.Subscriber<T> { private volatile boolean cancelled; protected volatile CallStreamObserver<T> downstream; private final AtomicBoolean subscribed = new AtomicBoolean(); private final AtomicBoolean hasSubscribed = new AtomicBoolean(); private volatile Flow.Subscription subscription; // complete status private volatile boolean done; /** * Binding the downstream, and call subscription#request(1). * * @param downstream downstream */ public void subscribe(CallStreamObserver<T> downstream) { if (downstream == null) { throw new NullPointerException(); } if (subscribed.compareAndSet(false, true)) { this.downstream = downstream; if (subscription != null) subscription.request(1); } } @Override public void onSubscribe(Flow.Subscription sub) { if (this.subscription == null && hasSubscribed.compareAndSet(false, true)) { this.subscription = sub; return; } sub.cancel(); } @Override public void onNext(T item) { if (!done && !cancelled) { downstream.onNext(item); subscription.request(1); } } @Override public void onError(Throwable t) { if (!cancelled) { done = true; downstream.onError(t); } } @Override public void onComplete() { if (!cancelled) { done = true; downstream.onCompleted(); } } public void cancel() { if (!cancelled && subscription != null) { cancelled = true; subscription.cancel(); } } public boolean isCancelled() { return cancelled; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/AbstractTripleMutinyPublisher.java
dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/AbstractTripleMutinyPublisher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.mutiny; import org.apache.dubbo.rpc.protocol.tri.CancelableStreamObserver; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import java.util.concurrent.Flow; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; /** * The middle layer between {@link org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver} and Mutiny API. <p> * 1. passing the data received by CallStreamObserver to Mutiny consumer <br> * 2. passing the request of Mutiny API to CallStreamObserver */ public abstract class AbstractTripleMutinyPublisher<T> extends CancelableStreamObserver<T> implements Flow.Publisher<T>, Flow.Subscription { private boolean canRequest; private long requested; // whether publisher has been subscribed private final AtomicBoolean subscribed = new AtomicBoolean(); private volatile Flow.Subscriber<? super T> downstream; protected volatile CallStreamObserver<?> subscription; private final AtomicBoolean hasSub = new AtomicBoolean(); // cancel status private volatile boolean cancelled; // complete status private volatile boolean done; // to help bind TripleSubscriber private volatile Consumer<CallStreamObserver<?>> onSubscribe; private volatile Runnable shutdownHook; private final AtomicBoolean calledShutdown = new AtomicBoolean(); public AbstractTripleMutinyPublisher() {} public AbstractTripleMutinyPublisher(Consumer<CallStreamObserver<?>> onSubscribe, Runnable shutdownHook) { this.onSubscribe = onSubscribe; this.shutdownHook = shutdownHook; } protected void onSubscribe(CallStreamObserver<?> subscription) { if (subscription != null && this.subscription == null && hasSub.compareAndSet(false, true)) { this.subscription = subscription; subscription.disableAutoFlowControl(); if (onSubscribe != null) { onSubscribe.accept(subscription); } return; } throw new IllegalStateException(getClass().getSimpleName() + " supports only a single subscription"); } @Override public void subscribe(Flow.Subscriber<? super T> s) { if (s == null) { throw new NullPointerException(); } if (subscribed.compareAndSet(false, true)) { this.downstream = s; s.onSubscribe(this); if (cancelled) this.downstream = null; } } @Override public void request(long n) { synchronized (this) { if (subscribed.get() && canRequest) { subscription.request(n >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) n); } else { requested += n; } } } @Override public void startRequest() { synchronized (this) { if (!canRequest) { canRequest = true; long n = requested; subscription.request(n >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) n); } } } @Override public void cancel() { if (!cancelled) { cancelled = true; doShutdown(); } } @Override public void onNext(T item) { if (done || cancelled) { return; } downstream.onNext(item); } @Override public void onError(Throwable t) { if (done || cancelled) { return; } done = true; downstream.onError(t); doShutdown(); } @Override public void onCompleted() { if (done || cancelled) { return; } done = true; downstream.onComplete(); doShutdown(); } private void doShutdown() { Runnable r = shutdownHook; // CAS to confirm shutdownHook will be run only once. if (r != null && calledShutdown.compareAndSet(false, true)) { shutdownHook = null; r.run(); } } public boolean isCancelled() { return cancelled; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/calls/MutinyServerCalls.java
dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/calls/MutinyServerCalls.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.mutiny.calls; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.mutiny.ServerTripleMutinyPublisher; import org.apache.dubbo.mutiny.ServerTripleMutinySubscriber; import org.apache.dubbo.rpc.StatusRpcException; import org.apache.dubbo.rpc.TriRpcStatus; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; /** * A collection of methods to convert server-side stream calls to Mutiny calls. */ public class MutinyServerCalls { private MutinyServerCalls() {} /** * Implements a unary -> unary call as Uni -> Uni * * @param request request * @param responseObserver response StreamObserver * @param func service implementation */ public static <T, R> void oneToOne(T request, StreamObserver<R> responseObserver, Function<Uni<T>, Uni<R>> func) { try { func.apply(Uni.createFrom().item(request)) .onItem() .ifNull() .failWith(TriRpcStatus.NOT_FOUND.asException()) .subscribe() .with( item -> { responseObserver.onNext(item); responseObserver.onCompleted(); }, throwable -> doOnResponseHasException(throwable, responseObserver)); } catch (Throwable throwable) { doOnResponseHasException(throwable, responseObserver); } } /** * Implements a unary -> stream call as Uni -> Multi * * @param request request * @param responseObserver response StreamObserver * @param func service implementation */ public static <T, R> CompletableFuture<List<R>> oneToMany( T request, StreamObserver<R> responseObserver, Function<Uni<T>, Multi<R>> func) { try { CallStreamObserver<R> callStreamObserver = (CallStreamObserver<R>) responseObserver; Multi<R> response = func.apply(Uni.createFrom().item(request)); ServerTripleMutinySubscriber<R> mutinySubscriber = new ServerTripleMutinySubscriber<>(callStreamObserver); response.subscribe().withSubscriber(mutinySubscriber).subscribe(callStreamObserver); return mutinySubscriber.getExecutionFuture(); } catch (Throwable throwable) { doOnResponseHasException(throwable, responseObserver); CompletableFuture<List<R>> failed = new CompletableFuture<>(); failed.completeExceptionally(throwable); return failed; } } /** * Implements a stream -> unary call as Multi -> Uni * * @param responseObserver response StreamObserver * @param func service implementation * @return request StreamObserver */ public static <T, R> StreamObserver<T> manyToOne( StreamObserver<R> responseObserver, Function<Multi<T>, Uni<R>> func) { CallStreamObserver<R> callStreamObserver = (CallStreamObserver<R>) responseObserver; ServerTripleMutinyPublisher<T> serverPublisher = new ServerTripleMutinyPublisher<>(callStreamObserver); try { Uni<R> responseUni = func.apply(Multi.createFrom().publisher(serverPublisher)) .onItem() .ifNull() .failWith(TriRpcStatus.NOT_FOUND.asException()); responseUni .subscribe() .with( value -> { if (!serverPublisher.isCancelled()) { callStreamObserver.onNext(value); callStreamObserver.onCompleted(); } }, throwable -> { if (!serverPublisher.isCancelled()) { callStreamObserver.onError(throwable); } }); serverPublisher.startRequest(); } catch (Throwable throwable) { responseObserver.onError(throwable); } return serverPublisher; } /** * Implements a stream -> stream call as Multi -> Multi * * @param responseObserver response StreamObserver * @param func service implementation * @return request StreamObserver */ public static <T, R> StreamObserver<T> manyToMany( StreamObserver<R> responseObserver, Function<Multi<T>, Multi<R>> func) { CallStreamObserver<R> callStreamObserver = (CallStreamObserver<R>) responseObserver; ServerTripleMutinyPublisher<T> serverPublisher = new ServerTripleMutinyPublisher<>(callStreamObserver); try { Multi<R> responseMulti = func.apply(Multi.createFrom().publisher(serverPublisher)); ServerTripleMutinySubscriber<R> serverSubscriber = responseMulti.subscribe().withSubscriber(new ServerTripleMutinySubscriber<>()); serverSubscriber.subscribe(callStreamObserver); serverPublisher.startRequest(); } catch (Throwable throwable) { responseObserver.onError(throwable); } return serverPublisher; } private static void doOnResponseHasException(Throwable throwable, StreamObserver<?> responseObserver) { StatusRpcException statusRpcException = TriRpcStatus.getStatus(throwable).asException(); responseObserver.onError(statusRpcException); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/calls/MutinyClientCalls.java
dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/calls/MutinyClientCalls.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.mutiny.calls; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.mutiny.ClientTripleMutinyPublisher; import org.apache.dubbo.mutiny.ClientTripleMutinySubscriber; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.StubMethodDescriptor; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import org.apache.dubbo.rpc.stub.StubInvocationUtil; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; import io.smallrye.mutiny.subscription.UniEmitter; /** * A collection of methods to convert client-side Mutiny calls to stream calls. */ public class MutinyClientCalls { private MutinyClientCalls() {} /** * Implements a unary -> unary call as Uni -> Uni * * @param invoker invoker * @param uniRequest the uni with request * @param methodDescriptor the method descriptor * @return the uni with response */ public static <TRequest, TResponse, TInvoker> Uni<TResponse> oneToOne( Invoker<TInvoker> invoker, Uni<TRequest> uniRequest, StubMethodDescriptor methodDescriptor) { try { return uniRequest.onItem().transformToUni(request -> Uni.createFrom() .emitter((UniEmitter<? super TResponse> emitter) -> { StubInvocationUtil.unaryCall( invoker, methodDescriptor, request, new StreamObserver<TResponse>() { @Override public void onNext(TResponse value) { emitter.complete(value); } @Override public void onError(Throwable t) { emitter.fail(t); } @Override public void onCompleted() { // No-op } }); })); } catch (Throwable throwable) { return Uni.createFrom().failure(throwable); } } /** * Implements a unary -> stream call as Uni -> Multi * * @param invoker invoker * @param uniRequest the uni with request * @param methodDescriptor the method descriptor * @return the multi with response */ public static <TRequest, TResponse, TInvoker> Multi<TResponse> oneToMany( Invoker<TInvoker> invoker, Uni<TRequest> uniRequest, StubMethodDescriptor methodDescriptor) { try { return uniRequest.onItem().transformToMulti(request -> { ClientTripleMutinyPublisher<TResponse> clientPublisher = new ClientTripleMutinyPublisher<>(); StubInvocationUtil.serverStreamCall(invoker, methodDescriptor, request, clientPublisher); return clientPublisher; }); } catch (Throwable throwable) { return Multi.createFrom().failure(throwable); } } /** * Implements a stream -> unary call as Multi -> Uni * * @param invoker invoker * @param multiRequest the multi with request * @param methodDescriptor the method descriptor * @return the uni with response */ public static <TRequest, TResponse, TInvoker> Uni<TResponse> manyToOne( Invoker<TInvoker> invoker, Multi<TRequest> multiRequest, StubMethodDescriptor methodDescriptor) { try { ClientTripleMutinySubscriber<TRequest> clientSubscriber = multiRequest.subscribe().withSubscriber(new ClientTripleMutinySubscriber<>()); ClientTripleMutinyPublisher<TResponse> clientPublisher = new ClientTripleMutinyPublisher<>( s -> clientSubscriber.subscribe((CallStreamObserver<TRequest>) s), clientSubscriber::cancel); return Uni.createFrom() .publisher(clientPublisher) .onSubscription() .invoke(() -> StubInvocationUtil.biOrClientStreamCall(invoker, methodDescriptor, clientPublisher)); } catch (Throwable err) { return Uni.createFrom().failure(err); } } /** * Implements a stream -> stream call as Multi -> Multi * * @param invoker invoker * @param multiRequest the multi with request * @param methodDescriptor the method descriptor * @return the multi with response */ public static <TRequest, TResponse, TInvoker> Multi<TResponse> manyToMany( Invoker<TInvoker> invoker, Multi<TRequest> multiRequest, StubMethodDescriptor methodDescriptor) { try { ClientTripleMutinySubscriber<TRequest> clientSubscriber = multiRequest.subscribe().withSubscriber(new ClientTripleMutinySubscriber<>()); ClientTripleMutinyPublisher<TResponse> clientPublisher = new ClientTripleMutinyPublisher<>( s -> clientSubscriber.subscribe((CallStreamObserver<TRequest>) s), clientSubscriber::cancel); return Multi.createFrom() .publisher(clientPublisher) .onSubscription() .invoke(() -> StubInvocationUtil.biOrClientStreamCall(invoker, methodDescriptor, clientPublisher)); } catch (Throwable err) { return Multi.createFrom().failure(err); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/handler/ManyToManyMethodHandler.java
dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/handler/ManyToManyMethodHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.mutiny.handler; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.mutiny.calls.MutinyServerCalls; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import org.apache.dubbo.rpc.stub.StubMethodHandler; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import io.smallrye.mutiny.Multi; /** * The handler of ManyToMany() method for stub invocation. */ public class ManyToManyMethodHandler<T, R> implements StubMethodHandler<T, R> { private final Function<Multi<T>, Multi<R>> func; public ManyToManyMethodHandler(Function<Multi<T>, Multi<R>> func) { this.func = func; } @SuppressWarnings("unchecked") @Override public CompletableFuture<StreamObserver<T>> invoke(Object[] arguments) { CallStreamObserver<R> responseObserver = (CallStreamObserver<R>) arguments[0]; StreamObserver<T> requestObserver = MutinyServerCalls.manyToMany(responseObserver, func); return CompletableFuture.completedFuture(requestObserver); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/handler/OneToOneMethodHandler.java
dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/handler/OneToOneMethodHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.mutiny.handler; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.mutiny.calls.MutinyServerCalls; import org.apache.dubbo.rpc.stub.FutureToObserverAdaptor; import org.apache.dubbo.rpc.stub.StubMethodHandler; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import io.smallrye.mutiny.Uni; /** * The handler of OneToOne() method for stub invocation. */ public class OneToOneMethodHandler<T, R> implements StubMethodHandler<T, R> { private final Function<Uni<T>, Uni<R>> func; public OneToOneMethodHandler(Function<Uni<T>, Uni<R>> func) { this.func = func; } @SuppressWarnings("unchecked") @Override public CompletableFuture<R> invoke(Object[] arguments) { T request = (T) arguments[0]; CompletableFuture<R> future = new CompletableFuture<>(); StreamObserver<R> responseObserver = new FutureToObserverAdaptor<>(future); MutinyServerCalls.oneToOne(request, responseObserver, func); return future; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/handler/ManyToOneMethodHandler.java
dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/handler/ManyToOneMethodHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.mutiny.handler; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.mutiny.calls.MutinyServerCalls; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import org.apache.dubbo.rpc.stub.StubMethodHandler; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; /** * The handler of ManyToOne() method for stub invocation. */ public class ManyToOneMethodHandler<T, R> implements StubMethodHandler<T, R> { private final Function<Multi<T>, Uni<R>> func; public ManyToOneMethodHandler(Function<Multi<T>, Uni<R>> func) { this.func = func; } @SuppressWarnings("unchecked") @Override public CompletableFuture<StreamObserver<T>> invoke(Object[] arguments) { CallStreamObserver<R> responseObserver = (CallStreamObserver<R>) arguments[0]; StreamObserver<T> requestObserver = MutinyServerCalls.manyToOne(responseObserver, func); return CompletableFuture.completedFuture(requestObserver); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/handler/OneToManyMethodHandler.java
dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/handler/OneToManyMethodHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.mutiny.handler; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.mutiny.calls.MutinyServerCalls; import org.apache.dubbo.rpc.stub.StubMethodHandler; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; /** * The handler of OneToMany() method for stub invocation. */ public class OneToManyMethodHandler<T, R> implements StubMethodHandler<T, R> { private final Function<Uni<T>, Multi<R>> func; public OneToManyMethodHandler(Function<Uni<T>, Multi<R>> func) { this.func = func; } @SuppressWarnings("unchecked") @Override public CompletableFuture<?> invoke(Object[] arguments) { T request = (T) arguments[0]; StreamObserver<R> responseObserver = (StreamObserver<R>) arguments[1]; return MutinyServerCalls.oneToMany(request, responseObserver, func); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/service/SpringDemoServiceImpl.java
dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/service/SpringDemoServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring.service; import org.apache.dubbo.rpc.protocol.tri.rest.service.DemoServiceImpl; import org.springframework.util.MultiValueMap; public class SpringDemoServiceImpl extends DemoServiceImpl implements SpringDemoService { @Override public MultiValueMap<String, Integer> multiValueMapTest(MultiValueMap<String, Integer> params) { return params; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/service/SpringDemoService.java
dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/service/SpringDemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring.service; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.rpc.protocol.tri.rest.service.Book; import org.apache.dubbo.rpc.protocol.tri.rest.service.User.Group; import org.apache.dubbo.rpc.protocol.tri.rest.service.User.UserEx; import java.util.List; import java.util.Map; import io.grpc.health.v1.HealthCheckRequest; import io.grpc.health.v1.HealthCheckResponse; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping("/spring") public interface SpringDemoService { @RequestMapping String hello(String name); @RequestMapping String argTest(String name, int age); @RequestMapping Book beanArgTest(@RequestBody(required = false) Book book, Integer quote); @RequestMapping Book beanArgTest2(@RequestBody Book book); @RequestMapping("/bean") UserEx advanceBeanArgTest(UserEx user); @RequestMapping List<Integer> listArgBodyTest(@RequestBody List<Integer> list, int age); @RequestMapping List<Integer> listArgBodyTest2(List<Integer> list, int age); @RequestMapping Map<Integer, List<Long>> mapArgBodyTest(@RequestBody Map<Integer, List<Long>> map, int age); @RequestMapping Map<Integer, List<Long>> mapArgBodyTest2(Map<Integer, List<Long>> map, int age); @RequestMapping List<Group> beanBodyTest(@RequestBody List<Group> groups, int age); @RequestMapping List<Group> beanBodyTest2(List<Group> groups, int age); @RequestMapping MultiValueMap<String, Integer> multiValueMapTest(MultiValueMap<String, Integer> params); @RequestMapping Book buy(Book book); @RequestMapping("/buy2") Book buy(Book book, int count); @RequestMapping String say(String name, Long count); @RequestMapping String say(String name); @RequestMapping String argNameTest(String name); @RequestMapping void pbServerStream(@RequestBody HealthCheckRequest request, StreamObserver<HealthCheckResponse> 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-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/compatible/SpringDemoServiceImpl.java
dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/compatible/SpringDemoServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring.compatible; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.rpc.RpcContext; import java.util.List; import java.util.Map; import org.springframework.util.LinkedMultiValueMap; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.ExceptionHandler; @CrossOrigin public class SpringDemoServiceImpl implements SpringRestDemoService { private static Map<String, Object> context; private boolean called; @Override public String sayHello(String name) { called = true; return "Hello, " + name; } @Override public boolean isCalled() { return called; } @Override public String testFormBody(User user) { return user.getName(); } @Override public List<String> testFormMapBody(LinkedMultiValueMap map) { return map.get("form"); } @Override public String testHeader(String header) { return header; } @Override public String testHeaderInt(int header) { return String.valueOf(header); } @Override public Integer hello(Integer a, Integer b) { context = RpcContext.getServerAttachment().getObjectAttachments(); return a + b; } @Override public String error() { throw new RuntimeException(); } @ExceptionHandler(RuntimeException.class) public String onError(HttpRequest request, Throwable t) { return "ok"; } @ExceptionHandler(Exception.class) public String onError1() { return "ok1"; } public static Map<String, Object> getAttachments() { return context; } @Override public int primitiveInt(int a, int b) { return a + b; } @Override public long primitiveLong(long a, Long b) { return a + b; } @Override public long primitiveByte(byte a, Long b) { return a + b; } @Override public long primitiveShort(short a, Long b, int c) { return a + b; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/compatible/SpringRestDemoService.java
dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/compatible/SpringRestDemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring.compatible; import java.util.List; import org.springframework.http.MediaType; import org.springframework.util.LinkedMultiValueMap; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @RequestMapping("/demoService") public interface SpringRestDemoService { @RequestMapping(value = "/hello", method = RequestMethod.GET) Integer hello(@RequestParam Integer a, @RequestParam Integer b); @RequestMapping(value = "/error", method = RequestMethod.GET, consumes = MediaType.TEXT_PLAIN_VALUE) String error(); @RequestMapping(value = "/sayHello", method = RequestMethod.POST, consumes = MediaType.TEXT_PLAIN_VALUE) String sayHello(String name); boolean isCalled(); @RequestMapping( value = "/testFormBody", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.TEXT_PLAIN_VALUE) String testFormBody(@RequestBody User user); @RequestMapping( value = "/testFormMapBody", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) List<String> testFormMapBody(@RequestBody LinkedMultiValueMap map); @RequestMapping(value = "/testHeader", method = RequestMethod.POST, consumes = MediaType.TEXT_PLAIN_VALUE) String testHeader(@RequestHeader String header); @RequestMapping(value = "/testHeaderInt", method = RequestMethod.GET, consumes = MediaType.TEXT_PLAIN_VALUE) String testHeaderInt(@RequestHeader int header); @RequestMapping(method = RequestMethod.GET, value = "/primitive") int primitiveInt(@RequestParam("a") int a, @RequestParam("b") int b); @RequestMapping(method = RequestMethod.GET, value = "/primitiveLong") long primitiveLong(@RequestParam("a") long a, @RequestParam("b") Long b); @RequestMapping(method = RequestMethod.GET, value = "/primitiveByte") long primitiveByte(@RequestParam("a") byte a, @RequestParam("b") Long b); @RequestMapping(method = RequestMethod.POST, value = "/primitiveShort") long primitiveShort(@RequestParam("a") short a, @RequestParam("b") Long b, @RequestBody int c); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/compatible/SpringMvcRestProtocolTest.java
dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/compatible/SpringMvcRestProtocolTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring.compatible; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import java.util.Arrays; import org.hamcrest.CoreMatchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.aop.framework.AdvisedSupport; import org.springframework.aop.framework.AopProxy; import org.springframework.aop.framework.ProxyCreatorSupport; import org.springframework.util.LinkedMultiValueMap; import static org.apache.dubbo.remoting.Constants.SERVER_KEY; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @Disabled public class SpringMvcRestProtocolTest { private final Protocol tProtocol = ApplicationModel.defaultModel().getExtensionLoader(Protocol.class).getExtension("tri"); private final Protocol protocol = ApplicationModel.defaultModel().getExtensionLoader(Protocol.class).getExtension("rest"); private final ProxyFactory proxy = ApplicationModel.defaultModel() .getExtensionLoader(ProxyFactory.class) .getAdaptiveExtension(); private static URL getUrl() { return URL.valueOf("tri://127.0.0.1:" + NetUtils.getAvailablePort() + "/rest?interface=" + SpringRestDemoService.class.getName()); } private static final String SERVER = "netty4"; private final ModuleServiceRepository repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); @AfterEach public void tearDown() { tProtocol.destroy(); protocol.destroy(); FrameworkModel.destroyAll(); } public SpringRestDemoService getServerImpl() { return new SpringDemoServiceImpl(); } public Class<SpringRestDemoService> getServerClass() { return SpringRestDemoService.class; } public Exporter<SpringRestDemoService> getExport(URL url, SpringRestDemoService server) { url = url.addParameter(SERVER_KEY, SERVER); return tProtocol.export(proxy.getInvoker(server, getServerClass(), url)); } @Test void testRestProtocol() { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf( "tri://127.0.0.1:" + port + "/?version=1.0.0&interface=" + SpringRestDemoService.class.getName()); SpringRestDemoService server = getServerImpl(); url = this.registerProvider(url, server, getServerClass()); Exporter<SpringRestDemoService> exporter = getExport(url, server); Invoker<SpringRestDemoService> invoker = protocol.refer(SpringRestDemoService.class, url); Assertions.assertFalse(server.isCalled()); SpringRestDemoService client = proxy.getProxy(invoker); String result = client.sayHello("haha"); Assertions.assertTrue(server.isCalled()); Assertions.assertEquals("Hello, haha", result); String header = client.testHeader("header"); Assertions.assertEquals("header", header); String headerInt = client.testHeaderInt(1); Assertions.assertEquals("1", headerInt); invoker.destroy(); exporter.unexport(); } @Test void testRestProtocolWithContextPath() { SpringRestDemoService server = getServerImpl(); Assertions.assertFalse(server.isCalled()); int port = NetUtils.getAvailablePort(); URL url = URL.valueOf( "tri://127.0.0.1:" + port + "/a/b/c?version=1.0.0&interface=" + SpringRestDemoService.class.getName()); url = this.registerProvider(url, server, SpringRestDemoService.class); Exporter<SpringRestDemoService> exporter = getExport(url, server); url = URL.valueOf("rest://127.0.0.1:" + port + "/a/b/c/?version=1.0.0&interface=" + SpringRestDemoService.class.getName()); Invoker<SpringRestDemoService> invoker = protocol.refer(SpringRestDemoService.class, url); SpringRestDemoService client = proxy.getProxy(invoker); String result = client.sayHello("haha"); Assertions.assertTrue(server.isCalled()); Assertions.assertEquals("Hello, haha", result); invoker.destroy(); exporter.unexport(); } @Test void testExport() { SpringRestDemoService server = getServerImpl(); URL url = this.registerProvider(getUrl(), server, SpringRestDemoService.class); RpcContext.getClientAttachment().setAttachment("timeout", "200"); Exporter<SpringRestDemoService> exporter = getExport(url, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, url)); Integer echoString = demoService.hello(1, 2); assertThat(echoString, is(3)); exporter.unexport(); } @Test void testNettyServer() { SpringRestDemoService server = getServerImpl(); URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); Exporter<SpringRestDemoService> exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); Integer echoString = demoService.hello(10, 10); assertThat(echoString, is(20)); exporter.unexport(); } @Test void testInvoke() { SpringRestDemoService server = getServerImpl(); URL url = this.registerProvider(getUrl(), server, SpringRestDemoService.class); Exporter<SpringRestDemoService> exporter = getExport(url, server); RpcInvocation rpcInvocation = new RpcInvocation( "hello", SpringRestDemoService.class.getName(), "", new Class[] {Integer.class, Integer.class}, new Integer[] {2, 3}); Result result = exporter.getInvoker().invoke(rpcInvocation); assertThat(result.getValue(), CoreMatchers.<Object>is(5)); } @Test void testFilter() { SpringRestDemoService server = getServerImpl(); URL url = this.registerProvider(getUrl(), server, SpringRestDemoService.class); Exporter<SpringRestDemoService> exporter = getExport(url, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, url)); Integer result = demoService.hello(1, 2); assertThat(result, is(3)); exporter.unexport(); } @Test void testDefaultPort() { assertThat(protocol.getDefaultPort(), is(80)); } @Test void testFormConsumerParser() { SpringRestDemoService server = getServerImpl(); URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); Exporter<SpringRestDemoService> exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); User user = new User(); user.setAge(18); user.setName("dubbo"); user.setId(404l); String name = demoService.testFormBody(user); Assertions.assertEquals("dubbo", name); LinkedMultiValueMap<String, String> forms = new LinkedMultiValueMap<>(); forms.put("form", Arrays.asList("F1")); Assertions.assertEquals(Arrays.asList("F1"), demoService.testFormMapBody(forms)); exporter.unexport(); } @Test void testPrimitive() { SpringRestDemoService server = getServerImpl(); URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); Exporter<SpringRestDemoService> exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); Integer result = demoService.primitiveInt(1, 2); Long resultLong = demoService.primitiveLong(1, 2l); long resultByte = demoService.primitiveByte((byte) 1, 2l); long resultShort = demoService.primitiveShort((short) 1, 2l, 1); assertThat(result, is(3)); assertThat(resultShort, is(3l)); assertThat(resultLong, is(3l)); assertThat(resultByte, is(3l)); exporter.unexport(); } @Test void testExceptionHandler() { SpringRestDemoService server = getServerImpl(); URL nettyUrl = registerProvider(getUrl(), server, SpringRestDemoService.class); Exporter<SpringRestDemoService> exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); String result = demoService.error(); assertThat(result, is("ok")); exporter.unexport(); } @Test void testProxyDoubleCheck() { ProxyCreatorSupport proxyCreatorSupport = new ProxyCreatorSupport(); AdvisedSupport advisedSupport = new AdvisedSupport(); advisedSupport.setTarget(getServerImpl()); AopProxy aopProxy = proxyCreatorSupport.getAopProxyFactory().createAopProxy(advisedSupport); Object proxy = aopProxy.getProxy(); SpringRestDemoService server = (SpringRestDemoService) proxy; URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); Exporter<SpringRestDemoService> exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); Integer result = demoService.primitiveInt(1, 2); Long resultLong = demoService.primitiveLong(1, 2l); long resultByte = demoService.primitiveByte((byte) 1, 2l); long resultShort = demoService.primitiveShort((short) 1, 2l, 1); assertThat(result, is(3)); assertThat(resultShort, is(3l)); assertThat(resultLong, is(3l)); assertThat(resultByte, is(3l)); exporter.unexport(); } private URL registerProvider(URL url, Object impl, Class<?> interfaceClass) { ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); repository.registerProvider(providerModel); return url.setServiceModel(providerModel); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/compatible/User.java
dubbo-plugin/dubbo-rest-spring/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/compatible/User.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.spring.compatible; import java.io.Serializable; import java.util.Objects; /** * User Entity * * @since 2.7.6 */ public class User implements Serializable { private Long id; private String name; private Integer age; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public static User getInstance() { User user = new User(); user.setAge(18); user.setName("dubbo"); user.setId(404l); return user; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } User user = (User) o; return Objects.equals(id, user.id) && Objects.equals(name, user.name) && Objects.equals(age, user.age); } @Override public int hashCode() { return Objects.hash(id, name, age); } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/PathVariableArgumentResolver.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/PathVariableArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.Messages; import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants; import org.apache.dubbo.rpc.protocol.tri.rest.RestParameterException; import org.apache.dubbo.rpc.protocol.tri.rest.argument.AnnotationBaseArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import java.lang.annotation.Annotation; import java.util.Map; @Activate(onClass = "org.springframework.web.bind.annotation.PathVariable") public class PathVariableArgumentResolver implements AnnotationBaseArgumentResolver<Annotation> { @Override public Class<Annotation> accept() { return Annotations.PathVariable.type(); } @Override public NamedValueMeta getNamedValueMeta(ParameterMeta parameter, AnnotationMeta<Annotation> annotation) { return new NamedValueMeta(annotation.getValue(), true).setParamType(ParamType.PathVariable); } @Override public Object resolve( ParameterMeta parameter, AnnotationMeta<Annotation> annotation, HttpRequest request, HttpResponse response) { Map<String, String> variableMap = request.attribute(RestConstants.URI_TEMPLATE_VARIABLES_ATTRIBUTE); String name = annotation.getValue(); if (StringUtils.isEmpty(name)) { name = parameter.getRequiredName(); } if (variableMap == null) { if (Helper.isRequired(annotation)) { throw new RestParameterException(Messages.ARGUMENT_VALUE_MISSING, name, parameter.getType()); } return null; } String value = variableMap.get(name); if (value == null) { return null; } int index = value.indexOf(';'); return RequestUtils.decodeURL(index == -1 ? value : value.substring(0, index)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/BeanArgumentBinder.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/BeanArgumentBinder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.rpc.protocol.tri.rest.Messages; 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.argument.CompositeArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta.ConstructorMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import java.lang.reflect.Modifier; import java.util.Map; import org.springframework.beans.MutablePropertyValues; import org.springframework.core.convert.ConversionService; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.DataBinder; import org.springframework.web.bind.WebDataBinder; import static org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta.resolveConstructor; final class BeanArgumentBinder { private static final Map<Class<?>, ConstructorMeta> CACHE = CollectionUtils.newConcurrentHashMap(); private final ArgumentResolver argumentResolver; private final ConversionService conversionService; BeanArgumentBinder(CompositeArgumentResolver argumentResolver, ConversionService conversionService) { this.argumentResolver = argumentResolver; this.conversionService = conversionService; } public Object bind(ParameterMeta paramMeta, HttpRequest request, HttpResponse response) { String name = StringUtils.defaultIf(paramMeta.getName(), DataBinder.DEFAULT_OBJECT_NAME); try { Object bean = createBean(paramMeta, request, response); WebDataBinder binder = new WebDataBinder(bean, name); binder.setConversionService(conversionService); binder.bind(new MutablePropertyValues(RequestUtils.getParametersMap(request))); BindingResult result = binder.getBindingResult(); if (result.hasErrors()) { throw new BindException(result); } return binder.getTarget(); } catch (Exception e) { throw new RestException(e, Messages.ARGUMENT_BIND_ERROR, name, paramMeta.getType()); } } private Object createBean(ParameterMeta paramMeta, HttpRequest request, HttpResponse response) { Class<?> type = paramMeta.getActualType(); if (Modifier.isAbstract(type.getModifiers())) { throw new IllegalStateException(Messages.ARGUMENT_COULD_NOT_RESOLVED.format(paramMeta.getDescription())); } ConstructorMeta ct = CACHE.computeIfAbsent(type, k -> { try { return resolveConstructor(paramMeta.getToolKit(), null, type); } catch (IllegalArgumentException e) { throw new IllegalStateException(Messages.ARGUMENT_COULD_NOT_RESOLVED.format(paramMeta.getDescription()) + ", " + e.getMessage()); } }); ParameterMeta[] parameters = ct.getParameters(); int len = parameters.length; if (len == 0) { return ct.newInstance(); } Object[] args = new Object[len]; for (int i = 0; i < len; i++) { ParameterMeta parameter = parameters[i]; args[i] = parameter.isSimple() ? argumentResolver.resolve(parameter, request, response) : null; } return ct.newInstance(args); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/CookieValueArgumentResolver.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/CookieValueArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.remoting.http12.HttpCookie; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; @Activate(onClass = "org.springframework.web.bind.annotation.CookieValue") public class CookieValueArgumentResolver extends AbstractSpringArgumentResolver { @Override public Class<Annotation> accept() { return Annotations.CookieValue.type(); } @Override protected ParamType getParamType(NamedValueMeta meta) { return ParamType.Cookie; } @Override protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.cookie(meta.name()); } @Override protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { Collection<HttpCookie> cookies = request.cookies(); if (cookies.isEmpty()) { return Collections.emptyList(); } String name = meta.name(); List<HttpCookie> result = new ArrayList<>(cookies.size()); for (HttpCookie cookie : cookies) { if (name.equals(cookie.name())) { result.add(cookie); } } return result; } @Override protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { Collection<HttpCookie> cookies = request.cookies(); if (cookies.isEmpty()) { return Collections.emptyMap(); } Map<String, List<HttpCookie>> mapValue = CollectionUtils.newLinkedHashMap(cookies.size()); for (HttpCookie cookie : cookies) { mapValue.computeIfAbsent(cookie.name(), k -> new ArrayList<>()).add(cookie); } return mapValue; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/BindParamArgumentResolver.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/BindParamArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; 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.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.argument.AbstractAnnotationBaseArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import java.lang.annotation.Annotation; @Activate(onClass = "org.springframework.web.bind.annotation.BindParam") public final class BindParamArgumentResolver extends AbstractAnnotationBaseArgumentResolver { @Override public Class<Annotation> accept() { return Annotations.BindParam.type(); } @Override protected ParamType getParamType(NamedValueMeta meta) { return ParamType.Param; } @Override protected NamedValueMeta createNamedValueMeta(ParameterMeta param, AnnotationMeta<Annotation> anno) { return new NamedValueMeta(anno.getValue(), param.isAnnotated(Annotations.Nonnull)); } @Override protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.parameter(meta.name()); } @Override protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.parameterValues(meta.name()); } @Override protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return RequestUtils.getParametersMap(request); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/RequestParamArgumentResolver.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/RequestParamArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; 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.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import java.lang.annotation.Annotation; @Activate(onClass = "org.springframework.web.bind.annotation.RequestParam") public final class RequestParamArgumentResolver extends AbstractSpringArgumentResolver { @Override public Class<Annotation> accept() { return Annotations.RequestParam.type(); } @Override protected ParamType getParamType(NamedValueMeta meta) { return ParamType.Param; } @Override protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.parameter(meta.name()); } @Override protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.parameterValues(meta.name()); } @Override protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return RequestUtils.getParametersMap(request); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/FallbackArgumentResolver.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/FallbackArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; 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.RestConstants; import org.apache.dubbo.rpc.protocol.tri.rest.argument.AbstractArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils; @Activate(order = Integer.MAX_VALUE - 10000, onClass = "org.springframework.web.bind.annotation.RequestMapping") public class FallbackArgumentResolver extends AbstractArgumentResolver { @Override public boolean accept(ParameterMeta param) { return param.getToolKit().getDialect() == RestConstants.DIALECT_SPRING_MVC; } @Override protected NamedValueMeta createNamedValueMeta(ParameterMeta param) { return new NamedValueMeta(null, param.isAnnotated(Annotations.Nonnull)); } @Override protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { ParameterMeta parameter = meta.parameter(); if (parameter.isStream()) { return null; } if (parameter.isSimple()) { return request.parameter(meta.name()); } return parameter.bind(request, response); } @Override protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { if (TypeUtils.isSimpleProperty(meta.nestedType(0))) { return request.parameterValues(meta.name()); } return null; } @Override protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { if (TypeUtils.isSimpleProperty(meta.nestedType(1))) { return RequestUtils.getParametersMap(request); } 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-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/MultiValueMapCreator.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/MultiValueMapCreator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.protocol.tri.rest.argument.ArgumentConverter; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; @Activate(onClass = "org.springframework.util.MultiValueMap") public class MultiValueMapCreator implements ArgumentConverter<Integer, MultiValueMap<?, ?>> { @Override public MultiValueMap<?, ?> convert(Integer value, ParameterMeta parameter) { return new LinkedMultiValueMap<>(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-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/RequestPartArgumentResolver.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/RequestPartArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpRequest.FileUpload; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; @Activate(onClass = "org.springframework.web.bind.annotation.RequestPart") public class RequestPartArgumentResolver extends AbstractSpringArgumentResolver { @Override public Class<Annotation> accept() { return Annotations.RequestPart.type(); } @Override protected ParamType getParamType(NamedValueMeta meta) { return ParamType.Part; } @Override protected NamedValueMeta createNamedValueMeta(ParameterMeta param, AnnotationMeta<Annotation> anno) { return new NamedValueMeta(anno.getValue(), Helper.isRequired(anno)); } @Override protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.part(meta.name()); } @Override protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return meta.type() == byte[].class ? request.part(meta.name()) : request.parts(); } @Override protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { Collection<FileUpload> parts = request.parts(); if (parts.isEmpty()) { return Collections.emptyMap(); } Map<String, FileUpload> result = new LinkedHashMap<>(parts.size()); for (FileUpload part : parts) { result.put(part.name(), 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-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/ModelAttributeArgumentResolver.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/ModelAttributeArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; 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.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils; import java.lang.annotation.Annotation; @Activate(onClass = "org.springframework.web.bind.annotation.ModelAttribute") public final class ModelAttributeArgumentResolver extends AbstractSpringArgumentResolver { @Override public Class<Annotation> accept() { return Annotations.ModelAttribute.type(); } @Override protected ParamType getParamType(NamedValueMeta meta) { return ParamType.Param; } @Override protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { if (meta.parameter().isSimple()) { return request.parameter(meta.name()); } return meta.parameter().bind(request, response); } @Override protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { if (meta.parameter().isSimple()) { return request.parameterValues(meta.name()); } return meta.parameter().bind(request, response); } @Override protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { if (TypeUtils.isSimpleProperty(meta.nestedType(1))) { return RequestUtils.getParametersMap(request); } return meta.parameter().bind(request, response); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/RequestHeaderArgumentResolver.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/RequestHeaderArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; 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.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import java.lang.annotation.Annotation; @Activate(onClass = "org.springframework.web.bind.annotation.RequestHeader") public final class RequestHeaderArgumentResolver extends AbstractSpringArgumentResolver { @Override public Class<Annotation> accept() { return Annotations.RequestHeader.type(); } @Override protected ParamType getParamType(NamedValueMeta meta) { return ParamType.Header; } @Override protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.header(meta.name()); } @Override protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.headerValues(meta.name()); } @Override protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.headers().asMap(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/HandlerInterceptorAdapter.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/HandlerInterceptorAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; 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.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants; 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.filter.RestFilter.Listener; import org.apache.dubbo.rpc.protocol.tri.rest.util.RestUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Arrays; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; @Activate(onClass = "org.springframework.web.servlet.HandlerInterceptor") public final class HandlerInterceptorAdapter implements RestExtensionAdapter<HandlerInterceptor> { @Override public boolean accept(Object extension) { return extension instanceof HandlerInterceptor; } @Override public RestFilter adapt(HandlerInterceptor extension) { return new HandlerInterceptorRestFilter(extension); } private static final class HandlerInterceptorRestFilter implements RestFilter, Listener { private final HandlerInterceptor interceptor; @Override public int getPriority() { return RestUtils.getPriority(interceptor); } @Override public String[] getPatterns() { return RestUtils.getPattens(interceptor); } public HandlerInterceptorRestFilter(HandlerInterceptor interceptor) { this.interceptor = interceptor; } @Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws Exception { Object handler = request.attribute(RestConstants.HANDLER_ATTRIBUTE); if (interceptor.preHandle((HttpServletRequest) request, (HttpServletResponse) response, handler)) { chain.doFilter(request, response); } } @Override public void onResponse(Result result, HttpRequest request, HttpResponse response) throws Exception { if (result.hasException()) { onError(result.getException(), request, response); return; } Object handler = request.attribute(RestConstants.HANDLER_ATTRIBUTE); ModelAndView mv = new ModelAndView(); mv.addObject("result", result); interceptor.postHandle((HttpServletRequest) request, (HttpServletResponse) response, handler, mv); } @Override public void onError(Throwable t, HttpRequest request, HttpResponse response) throws Exception { Object handler = request.attribute(RestConstants.HANDLER_ATTRIBUTE); Exception ex = t instanceof Exception ? (Exception) t : new RpcException(t); interceptor.afterCompletion((HttpServletRequest) request, (HttpServletResponse) response, handler, ex); } @Override public String toString() { StringBuilder sb = new StringBuilder("RestFilter{interceptor="); sb.append(interceptor); 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-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/SpringMvcRequestMappingResolver.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/SpringMvcRequestMappingResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.nested.RestConfig; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.tri.rest.cors.CorsUtils; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMapping; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMapping.Builder; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMappingResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.CorsMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ServiceMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RestToolKit; import org.springframework.http.HttpStatus; @Activate(onClass = "org.springframework.web.bind.annotation.RequestMapping") public class SpringMvcRequestMappingResolver implements RequestMappingResolver { private final RestToolKit toolKit; private RestConfig restConfig; private CorsMeta globalCorsMeta; public SpringMvcRequestMappingResolver(FrameworkModel frameworkModel) { toolKit = new SpringRestToolKit(frameworkModel); } @Override public void setRestConfig(RestConfig restConfig) { this.restConfig = restConfig; } @Override public RestToolKit getRestToolKit() { return toolKit; } @Override public RequestMapping resolve(ServiceMeta serviceMeta) { AnnotationMeta<?> requestMapping = serviceMeta.findMergedAnnotation(Annotations.RequestMapping); AnnotationMeta<?> httpExchange = serviceMeta.findMergedAnnotation(Annotations.HttpExchange); if (requestMapping == null && httpExchange == null) { return null; } String[] methods = requestMapping == null ? httpExchange.getStringArray("method") : requestMapping.getStringArray("method"); String[] paths = requestMapping == null ? httpExchange.getValueArray() : requestMapping.getValueArray(); return builder(requestMapping, httpExchange, serviceMeta.findMergedAnnotation(Annotations.ResponseStatus)) .method(methods) .name(serviceMeta.getType().getSimpleName()) .path(paths) .contextPath(serviceMeta.getContextPath()) .cors(buildCorsMeta(serviceMeta.findMergedAnnotation(Annotations.CrossOrigin), methods)) .build(); } @Override public RequestMapping resolve(MethodMeta methodMeta) { AnnotationMeta<?> requestMapping = methodMeta.findMergedAnnotation(Annotations.RequestMapping); AnnotationMeta<?> httpExchange = methodMeta.findMergedAnnotation(Annotations.HttpExchange); if (requestMapping == null && httpExchange == null) { AnnotationMeta<?> exceptionHandler = methodMeta.getAnnotation(Annotations.ExceptionHandler); if (exceptionHandler != null) { methodMeta.initParameters(); methodMeta.getServiceMeta().addExceptionHandler(methodMeta); } return null; } ServiceMeta serviceMeta = methodMeta.getServiceMeta(); String name = methodMeta.getMethodName(); String[] methods = requestMapping == null ? httpExchange.getStringArray("method") : requestMapping.getStringArray("method"); String[] paths = requestMapping == null ? httpExchange.getValueArray() : requestMapping.getValueArray(); if (paths.length == 0) { paths = new String[] {'/' + name}; } return builder(requestMapping, httpExchange, methodMeta.findMergedAnnotation(Annotations.ResponseStatus)) .method(methods) .name(name) .path(paths) .contextPath(serviceMeta.getContextPath()) .service(serviceMeta.getServiceGroup(), serviceMeta.getServiceVersion()) .cors(buildCorsMeta(methodMeta.findMergedAnnotation(Annotations.CrossOrigin), methods)) .build(); } private Builder builder( AnnotationMeta<?> requestMapping, AnnotationMeta<?> httpExchange, AnnotationMeta<?> responseStatus) { Builder builder = RequestMapping.builder(); if (responseStatus != null) { HttpStatus value = responseStatus.getEnum("value"); builder.responseStatus(value.value()); String reason = responseStatus.getString("reason"); if (StringUtils.isNotEmpty(reason)) { builder.responseReason(reason); } } if (requestMapping == null) { return builder.consume(httpExchange.getStringArray("contentType")) .produce(httpExchange.getStringArray("accept")); } return builder.param(requestMapping.getStringArray("params")) .header(requestMapping.getStringArray("headers")) .consume(requestMapping.getStringArray("consumes")) .produce(requestMapping.getStringArray("produces")); } private CorsMeta buildCorsMeta(AnnotationMeta<?> crossOrigin, String[] methods) { if (globalCorsMeta == null) { globalCorsMeta = CorsUtils.getGlobalCorsMeta(restConfig); } if (crossOrigin == null) { return globalCorsMeta; } String[] allowedMethods = crossOrigin.getStringArray("methods"); if (allowedMethods.length == 0) { allowedMethods = methods; if (allowedMethods.length == 0) { allowedMethods = new String[] {CommonConstants.ANY_VALUE}; } } CorsMeta corsMeta = CorsMeta.builder() .allowedOrigins(crossOrigin.getStringArray("origins")) .allowedMethods(allowedMethods) .allowedHeaders(crossOrigin.getStringArray("allowedHeaders")) .exposedHeaders(crossOrigin.getStringArray("exposedHeaders")) .allowCredentials(crossOrigin.getString("allowCredentials")) .maxAge(crossOrigin.getNumber("maxAge")) .build(); return globalCorsMeta.combine(corsMeta); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/AbstractSpringArgumentResolver.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/AbstractSpringArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.protocol.tri.rest.argument.AbstractAnnotationBaseArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import java.lang.annotation.Annotation; import java.util.Optional; public abstract class AbstractSpringArgumentResolver extends AbstractAnnotationBaseArgumentResolver { @Override protected NamedValueMeta createNamedValueMeta(ParameterMeta param, AnnotationMeta<Annotation> anno) { return new NamedValueMeta( anno.getValue(), param.getType() != Optional.class && Helper.isRequired(anno), Helper.defaultValue(anno)); } @Override protected Object filterValue(Object value, NamedValueMeta meta) { return StringUtils.EMPTY_STRING.equals(value) ? meta.defaultValue() : 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-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/RequestBodyArgumentResolver.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/RequestBodyArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.io.StreamUtils; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.RestException; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import java.io.IOException; import java.lang.annotation.Annotation; @Activate(onClass = "org.springframework.web.bind.annotation.RequestBody") public class RequestBodyArgumentResolver extends AbstractSpringArgumentResolver { @Override public Class<Annotation> accept() { return Annotations.RequestBody.type(); } @Override protected ParamType getParamType(NamedValueMeta meta) { return ParamType.Body; } @Override protected NamedValueMeta createNamedValueMeta(ParameterMeta param, AnnotationMeta<Annotation> anno) { return new NamedValueMeta(null, Helper.isRequired(anno)); } @Override protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { if (RequestUtils.isFormOrMultiPart(request)) { if (meta.parameter().isSimple()) { return request.formParameter(meta.name()); } return meta.parameter().bind(request, response); } return RequestUtils.decodeBody(request, meta.genericType()); } @Override protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { Class<?> type = meta.type(); if (type == byte[].class) { try { return StreamUtils.readBytes(request.inputStream()); } catch (IOException e) { throw new RestException(e); } } if (RequestUtils.isFormOrMultiPart(request)) { return request.formParameterValues(meta.name()); } return RequestUtils.decodeBody(request, meta.genericType()); } @Override protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { if (RequestUtils.isFormOrMultiPart(request)) { return RequestUtils.getFormParametersMap(request); } return RequestUtils.decodeBody(request, meta.genericType()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/ConfigurationWrapper.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/ConfigurationWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Properties; @SuppressWarnings("serial") public final class ConfigurationWrapper extends Properties { private final Configuration configuration; ConfigurationWrapper(ApplicationModel applicationModel) { configuration = applicationModel.modelEnvironment().getConfiguration(); } @Override public String getProperty(String key) { Object value = configuration.getProperty(key); return value == null ? null : value.toString(); } @Override public Object get(Object key) { return configuration.getProperty(key == null ? null : key.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-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/RestSpringScopeModelInitializer.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/RestSpringScopeModelInitializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.utils.DefaultParameterNameReader; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeModelInitializer; import org.apache.dubbo.rpc.protocol.tri.rest.argument.CompositeArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.argument.GeneralTypeConverter; public class RestSpringScopeModelInitializer implements ScopeModelInitializer { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) { ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory(); beanFactory.registerBean(GeneralTypeConverter.class); beanFactory.registerBean(DefaultParameterNameReader.class); beanFactory.registerBean(CompositeArgumentResolver.class); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/SpringMiscArgumentResolver.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/SpringMiscArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; 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.argument.ArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import javax.servlet.http.HttpServletRequest; import java.util.HashSet; import java.util.Set; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.util.CollectionUtils; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.request.WebRequest; @Activate(onClass = "org.springframework.web.context.request.WebRequest") public class SpringMiscArgumentResolver implements ArgumentResolver { private static final Set<Class<?>> SUPPORTED_TYPES = new HashSet<>(); static { SUPPORTED_TYPES.add(WebRequest.class); SUPPORTED_TYPES.add(NativeWebRequest.class); SUPPORTED_TYPES.add(HttpEntity.class); SUPPORTED_TYPES.add(HttpHeaders.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 == WebRequest.class || type == NativeWebRequest.class) { return new ServletWebRequest((HttpServletRequest) request); } if (type == HttpEntity.class) { return new HttpEntity<>( CollectionUtils.toMultiValueMap(request.headers().asMap())); } if (type == HttpHeaders.class) { return new HttpHeaders( CollectionUtils.toMultiValueMap(request.headers().asMap())); } 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-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/SpringRestToolKit.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/SpringRestToolKit.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.DefaultParameterNameReader; import org.apache.dubbo.common.utils.ParameterNameReader; import org.apache.dubbo.config.spring.extension.SpringExtensionInjector; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.tri.rest.Messages; import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants; import org.apache.dubbo.rpc.protocol.tri.rest.RestException; import org.apache.dubbo.rpc.protocol.tri.rest.argument.CompositeArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.argument.GeneralTypeConverter; import org.apache.dubbo.rpc.protocol.tri.rest.argument.TypeConverter; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RestToolKit; import org.apache.dubbo.rpc.protocol.tri.rest.util.RestUtils; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Collection; import java.util.Map; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.MethodParameter; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.util.PropertyPlaceholderHelper; final class SpringRestToolKit implements RestToolKit { private static final Logger LOGGER = LoggerFactory.getLogger(SpringRestToolKit.class); private final Map<MethodParameterMeta, TypeDescriptor> cache = CollectionUtils.newConcurrentHashMap(); private final ConfigurableBeanFactory beanFactory; private final PropertyPlaceholderHelper placeholderHelper; private final ConfigurationWrapper configuration; private final ConversionService conversionService; private final TypeConverter typeConverter; private final BeanArgumentBinder argumentBinder; private final ParameterNameReader parameterNameReader; private final CompositeArgumentResolver argumentResolver; public SpringRestToolKit(FrameworkModel frameworkModel) { ApplicationModel applicationModel = frameworkModel.defaultApplication(); SpringExtensionInjector injector = SpringExtensionInjector.get(applicationModel); ApplicationContext context = injector.getContext(); if (context instanceof ConfigurableApplicationContext) { beanFactory = ((ConfigurableApplicationContext) context).getBeanFactory(); placeholderHelper = null; configuration = null; } else { beanFactory = null; placeholderHelper = new PropertyPlaceholderHelper("${", "}", ":", true); configuration = new ConfigurationWrapper(applicationModel); } if (context != null && context.containsBean("mvcConversionService")) { conversionService = context.getBean("mvcConversionService", ConversionService.class); } else { conversionService = DefaultConversionService.getSharedInstance(); } typeConverter = frameworkModel.getOrRegisterBean(GeneralTypeConverter.class); parameterNameReader = frameworkModel.getOrRegisterBean(DefaultParameterNameReader.class); argumentResolver = frameworkModel.getOrRegisterBean(CompositeArgumentResolver.class); argumentBinder = new BeanArgumentBinder(argumentResolver, conversionService); } @Override public int getDialect() { return RestConstants.DIALECT_SPRING_MVC; } @Override public String resolvePlaceholders(String text) { if (!RestUtils.hasPlaceholder(text)) { return text; } if (beanFactory != null) { return beanFactory.resolveEmbeddedValue(text); } return placeholderHelper.replacePlaceholders(text, configuration); } @Override public Object convert(Object value, ParameterMeta parameter) { boolean tried = false; if (value instanceof Collection || value instanceof Map) { tried = true; Object target = typeConverter.convert(value, parameter.getGenericType()); if (target != null) { return target; } } if (parameter instanceof MethodParameterMeta) { TypeDescriptor targetType = cache.computeIfAbsent( (MethodParameterMeta) parameter, k -> new TypeDescriptor(new MethodParameter(k.getMethod(), k.getIndex()))); TypeDescriptor sourceType = TypeDescriptor.forObject(value); if (conversionService.canConvert(sourceType, targetType)) { try { return conversionService.convert(value, sourceType, targetType); } catch (Throwable t) { LOGGER.debug( "Spring convert value '{}' from type [{}] to type [{}] failed", value, value.getClass(), parameter.getGenericType(), t); } } } Object target = tried ? null : typeConverter.convert(value, parameter.getGenericType()); if (target == null && value != null) { throw new RestException( Messages.ARGUMENT_CONVERT_ERROR, parameter.getName(), value, value.getClass(), parameter.getGenericType()); } return target; } @Override public Object bind(ParameterMeta parameter, HttpRequest request, HttpResponse response) { return argumentBinder.bind(parameter, request, response); } @Override public NamedValueMeta getNamedValueMeta(ParameterMeta parameter) { return argumentResolver.getNamedValueMeta(parameter); } @Override public String[] getParameterNames(Method method) { return parameterNameReader.readParameterNames(method); } @Override public String[] getParameterNames(Constructor<?> ctor) { return parameterNameReader.readParameterNames(ctor); } @Override public Map<String, Object> getAttributes(AnnotatedElement element, Annotation annotation) { return AnnotatedElementUtils.getMergedAnnotationAttributes(element, annotation.annotationType()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/MatrixVariableArgumentResolver.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/MatrixVariableArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @Activate(onClass = "org.springframework.web.bind.annotation.MatrixVariable") public class MatrixVariableArgumentResolver extends AbstractSpringArgumentResolver { @Override public Class<Annotation> accept() { return Annotations.MatrixVariable.type(); } @Override protected ParamType getParamType(NamedValueMeta meta) { return ParamType.MatrixVariable; } @Override protected NamedValueMeta createNamedValueMeta(ParameterMeta param, AnnotationMeta<Annotation> anno) { return new MatrixNamedValueMeta( anno.getValue(), Helper.isRequired(anno), Helper.defaultValue(anno), Helper.defaultValue(anno, "pathVar")); } @Override protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return CollectionUtils.first(doResolveCollectionValue(meta, request)); } @Override protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return doResolveCollectionValue(meta, request); } private static List<String> doResolveCollectionValue(NamedValueMeta meta, HttpRequest request) { String name = meta.name(); Map<String, String> variableMap = request.attribute(RestConstants.URI_TEMPLATE_VARIABLES_ATTRIBUTE); if (variableMap == null) { return Collections.emptyList(); } List<String> result = null; String pathVar = ((MatrixNamedValueMeta) meta).pathVar; if (pathVar == null) { result = RequestUtils.parseMatrixVariableValues(variableMap, name); } else { String value = variableMap.get(pathVar); if (value != null) { Map<String, List<String>> matrixVariables = RequestUtils.parseMatrixVariables(value); if (matrixVariables != null) { List<String> values = matrixVariables.get(name); if (values != null) { return values; } } } } return result == null ? Collections.emptyList() : result; } @Override protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { Map<String, String> variableMap = request.attribute(RestConstants.URI_TEMPLATE_VARIABLES_ATTRIBUTE); if (variableMap == null) { return Collections.emptyMap(); } Map<String, List<String>> result = null; String pathVar = ((MatrixNamedValueMeta) meta).pathVar; if (pathVar == null) { for (Map.Entry<String, String> entry : variableMap.entrySet()) { Map<String, List<String>> matrixVariables = RequestUtils.parseMatrixVariables(entry.getValue()); if (matrixVariables == null) { continue; } if (result == null) { result = new HashMap<>(); } for (Map.Entry<String, List<String>> matrixEntry : matrixVariables.entrySet()) { result.computeIfAbsent(matrixEntry.getKey(), k -> new ArrayList<>()) .addAll(matrixEntry.getValue()); } } } else { String value = variableMap.get(pathVar); if (value != null) { result = RequestUtils.parseMatrixVariables(value); } } return result == null ? Collections.emptyMap() : result; } private static class MatrixNamedValueMeta extends NamedValueMeta { private final String pathVar; MatrixNamedValueMeta(String name, boolean required, String defaultValue, String pathVar) { super(name, required, defaultValue); this.pathVar = pathVar; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/RequestAttributeArgumentResolver.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/RequestAttributeArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; 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.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import java.lang.annotation.Annotation; @Activate(onClass = "org.springframework.web.bind.annotation.RequestAttribute") public class RequestAttributeArgumentResolver extends AbstractSpringArgumentResolver { @Override public Class<Annotation> accept() { return Annotations.RequestAttribute.type(); } @Override protected ParamType getParamType(NamedValueMeta meta) { return ParamType.Attribute; } @Override protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.attribute(meta.name()); } @Override protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.attributes(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/Annotations.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/Annotations.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.spring; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationEnum; import java.lang.annotation.Annotation; public enum Annotations implements AnnotationEnum { RequestMapping, PathVariable, MatrixVariable, RequestParam, RequestHeader, CookieValue, RequestAttribute, RequestPart, RequestBody, ModelAttribute, BindParam, ResponseStatus, CrossOrigin, ExceptionHandler, HttpExchange("org.springframework.web.service.annotation.HttpExchange"), Nonnull("javax.annotation.Nonnull"); private final String className; private Class<Annotation> type; Annotations() { className = "org.springframework.web.bind.annotation." + name(); } Annotations(String className) { this.className = className; } @Override public String className() { return className; } @Override public Class<Annotation> type() { if (type == null) { type = loadType(); } return 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-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/Helper.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/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.spring; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import org.springframework.core.SpringVersion; import org.springframework.http.ResponseEntity; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.ValueConstants; final class Helper { public static boolean IS_SPRING_6; private static Method getStatusCode; private static Method value; private Helper() {} static { try { String version = SpringVersion.getVersion(); IS_SPRING_6 = StringUtils.hasLength(version) && version.charAt(0) >= '6'; } catch (Throwable ignored) { } } public static boolean isRequired(AnnotationMeta<Annotation> annotation) { return annotation.getBoolean("required"); } public static String defaultValue(AnnotationMeta<Annotation> annotation) { return defaultValue(annotation, "defaultValue"); } public static String defaultValue(AnnotationMeta<Annotation> annotation, String name) { return defaultValue(annotation.getString(name)); } public static String defaultValue(String value) { return ValueConstants.DEFAULT_NONE.equals(value) ? null : value; } public static int getStatusCode(ResponseEntity<?> entity) { if (IS_SPRING_6) { try { if (getStatusCode == null) { getStatusCode = ResponseEntity.class.getMethod("getStatusCode"); value = getStatusCode.getReturnType().getMethod("value"); } return (Integer) value.invoke(getStatusCode.invoke(entity)); } catch (Exception e) { throw new RuntimeException(e); } } return entity.getStatusCode().value(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false