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-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/Http1SseServerChannelObserver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/Http1SseServerChannelObserver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.http1;
import org.apache.dubbo.remoting.http12.HttpChannel;
import org.apache.dubbo.remoting.http12.HttpConstants;
import org.apache.dubbo.remoting.http12.HttpHeaderNames;
import org.apache.dubbo.remoting.http12.HttpMetadata;
import org.apache.dubbo.remoting.http12.HttpOutputMessage;
import org.apache.dubbo.remoting.http12.HttpResult;
import org.apache.dubbo.remoting.http12.h1.Http1ServerChannelObserver;
import org.apache.dubbo.remoting.http12.message.HttpMessageEncoder;
import org.apache.dubbo.remoting.http12.message.ServerSentEventEncoder;
public class Http1SseServerChannelObserver extends Http1ServerChannelObserver {
private HttpMessageEncoder originalResponseEncoder;
public Http1SseServerChannelObserver(HttpChannel httpChannel) {
super(httpChannel);
}
@Override
public void setResponseEncoder(HttpMessageEncoder responseEncoder) {
super.setResponseEncoder(new ServerSentEventEncoder(responseEncoder));
this.originalResponseEncoder = responseEncoder;
}
@Override
protected void doOnCompleted(Throwable throwable) {
if (!isHeaderSent()) {
sendMetadata(encodeHttpMetadata(true));
}
super.doOnCompleted(throwable);
}
@Override
protected HttpMetadata encodeHttpMetadata(boolean endStream) {
return super.encodeHttpMetadata(endStream)
.header(HttpHeaderNames.TRANSFER_ENCODING.getKey(), HttpConstants.CHUNKED)
.header(HttpHeaderNames.CACHE_CONTROL.getKey(), HttpConstants.NO_CACHE);
}
@Override
protected HttpOutputMessage buildMessage(int statusCode, Object data) throws Throwable {
if (data instanceof HttpResult) {
data = ((HttpResult<?>) data).getBody();
if (data == null && statusCode != 200) {
return null;
}
HttpOutputMessage message = encodeHttpOutputMessage(data);
try {
originalResponseEncoder.encode(message.getBody(), data);
} catch (Throwable t) {
message.close();
throw t;
}
return message;
}
return super.buildMessage(statusCode, data);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListenerFactory.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListenerFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.http1;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.http12.HttpChannel;
import org.apache.dubbo.remoting.http12.h1.Http1ServerTransportListener;
import org.apache.dubbo.remoting.http12.h1.Http1ServerTransportListenerFactory;
import org.apache.dubbo.rpc.model.FrameworkModel;
public class DefaultHttp11ServerTransportListenerFactory implements Http1ServerTransportListenerFactory {
public static final Http1ServerTransportListenerFactory INSTANCE =
new DefaultHttp11ServerTransportListenerFactory();
@Override
public Http1ServerTransportListener newInstance(HttpChannel httpChannel, URL url, FrameworkModel frameworkModel) {
return new DefaultHttp11ServerTransportListener(httpChannel, url, frameworkModel);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/Http1UnaryServerChannelObserver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/Http1UnaryServerChannelObserver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.http1;
import org.apache.dubbo.remoting.http12.HttpChannel;
import org.apache.dubbo.remoting.http12.HttpHeaderNames;
import org.apache.dubbo.remoting.http12.HttpHeaders;
import org.apache.dubbo.remoting.http12.HttpOutputMessage;
import org.apache.dubbo.remoting.http12.h1.Http1ServerChannelObserver;
import org.apache.dubbo.rpc.protocol.tri.ExceptionUtils;
import org.apache.dubbo.rpc.protocol.tri.TripleProtocol;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import io.netty.buffer.ByteBufOutputStream;
public final class Http1UnaryServerChannelObserver extends Http1ServerChannelObserver {
public Http1UnaryServerChannelObserver(HttpChannel httpChannel) {
super(httpChannel);
}
@Override
protected void doOnNext(Object data) throws Throwable {
int statusCode = resolveStatusCode(data);
HttpOutputMessage message = buildMessage(statusCode, data);
sendMetadata(buildMetadata(statusCode, data, null, message));
sendMessage(message);
}
@Override
protected void doOnError(Throwable throwable) throws Throwable {
int statusCode = resolveErrorStatusCode(throwable);
Object data = buildErrorResponse(statusCode, throwable);
HttpOutputMessage message = buildMessage(statusCode, data);
sendMetadata(buildMetadata(statusCode, data, throwable, message));
sendMessage(message);
}
@Override
protected void customizeHeaders(HttpHeaders headers, Throwable throwable, HttpOutputMessage message) {
super.customizeHeaders(headers, throwable, message);
int contentLength = 0;
if (message != null) {
OutputStream body = message.getBody();
if (body instanceof ByteBufOutputStream) {
contentLength = ((ByteBufOutputStream) body).writtenBytes();
} else if (body instanceof ByteArrayOutputStream) {
contentLength = ((ByteArrayOutputStream) body).size();
} else {
throw new IllegalArgumentException("Unsupported body type: " + body.getClass());
}
}
headers.set(HttpHeaderNames.CONTENT_LENGTH.getKey(), String.valueOf(contentLength));
}
@Override
protected Throwable customizeError(Throwable throwable) {
throwable = super.customizeError(throwable);
if (throwable == null) {
doOnCompleted(null);
}
return throwable;
}
@Override
protected String getDisplayMessage(Throwable throwable) {
return TripleProtocol.VERBOSE_ENABLED
? ExceptionUtils.buildVerboseMessage(throwable)
: super.getDisplayMessage(throwable);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.http1;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.http12.HttpChannel;
import org.apache.dubbo.remoting.http12.HttpHeaderNames;
import org.apache.dubbo.remoting.http12.HttpInputMessage;
import org.apache.dubbo.remoting.http12.RequestMetadata;
import org.apache.dubbo.remoting.http12.h1.Http1ServerChannelObserver;
import org.apache.dubbo.remoting.http12.h1.Http1ServerTransportListener;
import org.apache.dubbo.remoting.http12.message.DefaultListeningDecoder;
import org.apache.dubbo.remoting.http12.message.MediaType;
import org.apache.dubbo.remoting.http12.message.codec.JsonCodec;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.protocol.tri.Http3Exchanger;
import org.apache.dubbo.rpc.protocol.tri.RpcInvocationBuildContext;
import org.apache.dubbo.rpc.protocol.tri.h12.AbstractServerTransportListener;
import org.apache.dubbo.rpc.protocol.tri.h12.DefaultHttpMessageListener;
import org.apache.dubbo.rpc.protocol.tri.h12.HttpMessageListener;
import org.apache.dubbo.rpc.protocol.tri.h12.ServerCallListener;
import org.apache.dubbo.rpc.protocol.tri.h12.ServerStreamServerCallListener;
import org.apache.dubbo.rpc.protocol.tri.h12.UnaryServerCallListener;
public class DefaultHttp11ServerTransportListener
extends AbstractServerTransportListener<RequestMetadata, HttpInputMessage>
implements Http1ServerTransportListener {
private final HttpChannel httpChannel;
private Http1ServerChannelObserver responseObserver;
public DefaultHttp11ServerTransportListener(HttpChannel httpChannel, URL url, FrameworkModel frameworkModel) {
super(frameworkModel, url, httpChannel);
this.httpChannel = httpChannel;
responseObserver = prepareResponseObserver(new Http1UnaryServerChannelObserver(httpChannel));
}
private Http1ServerChannelObserver prepareResponseObserver(Http1ServerChannelObserver responseObserver) {
responseObserver.setExceptionCustomizer(getExceptionCustomizer());
RpcInvocationBuildContext context = getContext();
responseObserver.setResponseEncoder(context == null ? JsonCodec.INSTANCE : context.getHttpMessageEncoder());
return responseObserver;
}
@Override
protected HttpMessageListener buildHttpMessageListener() {
RpcInvocationBuildContext context = getContext();
RpcInvocation rpcInvocation = buildRpcInvocation(context);
ServerCallListener serverCallListener =
startListener(rpcInvocation, context.getMethodDescriptor(), context.getInvoker());
DefaultListeningDecoder listeningDecoder = new DefaultListeningDecoder(
context.getHttpMessageDecoder(), context.getMethodMetadata().getActualRequestTypes());
listeningDecoder.setListener(serverCallListener::onMessage);
return new DefaultHttpMessageListener(listeningDecoder);
}
private ServerCallListener startListener(
RpcInvocation invocation, MethodDescriptor methodDescriptor, Invoker<?> invoker) {
switch (methodDescriptor.getRpcType()) {
case UNARY:
return new AutoCompleteUnaryServerCallListener(invocation, invoker, responseObserver);
case SERVER_STREAM:
responseObserver = prepareResponseObserver(new Http1SseServerChannelObserver(httpChannel));
responseObserver.addHeadersCustomizer((hs, t) ->
hs.set(HttpHeaderNames.CONTENT_TYPE.getKey(), MediaType.TEXT_EVENT_STREAM.getName()));
return new AutoCompleteServerStreamServerCallListener(invocation, invoker, responseObserver);
default:
throw new UnsupportedOperationException("HTTP1.x only support unary and server-stream");
}
}
@Override
protected void onMetadataCompletion(RequestMetadata metadata) {
responseObserver.setResponseEncoder(getContext().getHttpMessageEncoder());
}
@Override
protected void onError(Throwable throwable) {
responseObserver.onError(throwable);
}
@Override
protected void initializeAltSvc(URL url) {
String protocolId = Http3Exchanger.isEnabled(url) ? "h3" : "h2";
String value = protocolId + "=\":" + url.getParameter(Constants.BIND_PORT_KEY, url.getPort()) + '"';
responseObserver.addHeadersCustomizer((hs, t) -> hs.set(HttpHeaderNames.ALT_SVC.getKey(), value));
}
private static final class AutoCompleteUnaryServerCallListener extends UnaryServerCallListener {
AutoCompleteUnaryServerCallListener(
RpcInvocation invocation, Invoker<?> invoker, StreamObserver<Object> responseObserver) {
super(invocation, invoker, responseObserver);
}
@Override
public void onMessage(Object message) {
super.onMessage(message);
onComplete();
}
}
private static final class AutoCompleteServerStreamServerCallListener extends ServerStreamServerCallListener {
AutoCompleteServerStreamServerCallListener(
RpcInvocation invocation, Invoker<?> invoker, StreamObserver<Object> responseObserver) {
super(invocation, invoker, responseObserver);
}
@Override
public void onMessage(Object message) {
super.onMessage(message);
onComplete();
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2ClientStreamFactory.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2ClientStreamFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.http2;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.call.TripleClientCall;
import org.apache.dubbo.rpc.protocol.tri.stream.ClientStream;
import org.apache.dubbo.rpc.protocol.tri.stream.ClientStreamFactory;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue;
import java.util.concurrent.Executor;
@Activate
public class Http2ClientStreamFactory implements ClientStreamFactory {
@Override
public ClientStream createClientStream(
AbstractConnectionClient client,
FrameworkModel frameworkModel,
Executor executor,
TripleClientCall clientCall,
TripleWriteQueue writeQueue) {
return new Http2TripleClientStream(frameworkModel, executor, client.getChannel(true), clientCall, writeQueue);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2ServerStreamObserver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2ServerStreamObserver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.http2;
import org.apache.dubbo.remoting.http12.HttpHeaders;
import org.apache.dubbo.remoting.http12.HttpMetadata;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http12.h2.Http2ServerChannelObserver;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.ServerStreamObserver;
import org.apache.dubbo.rpc.protocol.tri.TripleProtocol;
import org.apache.dubbo.rpc.protocol.tri.compressor.Compressor;
import org.apache.dubbo.rpc.protocol.tri.h12.AttachmentHolder;
import org.apache.dubbo.rpc.protocol.tri.h12.CompressibleEncoder;
import org.apache.dubbo.rpc.protocol.tri.stream.StreamUtils;
import java.util.Map;
public class Http2ServerStreamObserver extends Http2ServerChannelObserver
implements ServerStreamObserver<Object>, AttachmentHolder {
private final FrameworkModel frameworkModel;
private Map<String, Object> attachments;
public Http2ServerStreamObserver(FrameworkModel frameworkModel, H2StreamChannel h2StreamChannel) {
super(h2StreamChannel);
this.frameworkModel = frameworkModel;
}
@Override
public void setCompression(String compression) {
CompressibleEncoder compressibleEncoder = new CompressibleEncoder(getResponseEncoder());
compressibleEncoder.setCompressor(Compressor.getCompressor(frameworkModel, compression));
setResponseEncoder(compressibleEncoder);
}
@Override
public void setResponseAttachments(Map<String, Object> attachments) {
this.attachments = attachments;
}
@Override
public Map<String, Object> getResponseAttachments() {
return attachments;
}
@Override
protected HttpMetadata encodeTrailers(Throwable throwable) {
HttpMetadata metadata = super.encodeTrailers(throwable);
HttpHeaders headers = metadata.headers();
StreamUtils.putHeaders(headers, attachments, TripleProtocol.CONVERT_NO_LOWER_HEADER);
return metadata;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2SseServerChannelObserver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2SseServerChannelObserver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.http2;
import org.apache.dubbo.remoting.http12.HttpConstants;
import org.apache.dubbo.remoting.http12.HttpHeaderNames;
import org.apache.dubbo.remoting.http12.HttpMetadata;
import org.apache.dubbo.remoting.http12.HttpOutputMessage;
import org.apache.dubbo.remoting.http12.HttpResult;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http12.message.HttpMessageEncoder;
import org.apache.dubbo.remoting.http12.message.ServerSentEventEncoder;
import org.apache.dubbo.rpc.model.FrameworkModel;
public final class Http2SseServerChannelObserver extends Http2StreamServerChannelObserver {
private HttpMessageEncoder originalResponseEncoder;
public Http2SseServerChannelObserver(FrameworkModel frameworkModel, H2StreamChannel h2StreamChannel) {
super(frameworkModel, h2StreamChannel);
}
@Override
public void setResponseEncoder(HttpMessageEncoder responseEncoder) {
super.setResponseEncoder(new ServerSentEventEncoder(responseEncoder));
this.originalResponseEncoder = responseEncoder;
}
@Override
protected HttpMetadata encodeHttpMetadata(boolean endStream) {
return super.encodeHttpMetadata(endStream)
.header(HttpHeaderNames.CACHE_CONTROL.getKey(), HttpConstants.NO_CACHE);
}
@Override
protected HttpOutputMessage buildMessage(int statusCode, Object data) throws Throwable {
if (data instanceof HttpResult) {
data = ((HttpResult<?>) data).getBody();
if (data == null && statusCode != 200) {
return null;
}
HttpOutputMessage message = encodeHttpOutputMessage(data);
try {
originalResponseEncoder.encode(message.getBody(), data);
} catch (Throwable t) {
message.close();
throw t;
}
return message;
}
return super.buildMessage(statusCode, data);
}
@Override
protected void doOnCompleted(Throwable throwable) {
// if throwable is not null, the header will be flushed by super.doOnCompleted(throwable)
if (!isHeaderSent() && throwable == null) {
sendMetadata(encodeHttpMetadata(true));
}
super.doOnCompleted(throwable);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2StreamServerChannelObserver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2StreamServerChannelObserver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.http2;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.ExceptionUtils;
import org.apache.dubbo.rpc.protocol.tri.TripleProtocol;
public class Http2StreamServerChannelObserver extends Http2ServerStreamObserver {
public Http2StreamServerChannelObserver(FrameworkModel frameworkModel, H2StreamChannel h2StreamChannel) {
super(frameworkModel, h2StreamChannel);
}
@Override
protected String getDisplayMessage(Throwable throwable) {
return TripleProtocol.VERBOSE_ENABLED
? ExceptionUtils.buildVerboseMessage(throwable)
: super.getDisplayMessage(throwable);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2TripleClientStream.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2TripleClientStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.http2;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.command.CreateStreamQueueCommand;
import org.apache.dubbo.rpc.protocol.tri.stream.AbstractTripleClientStream;
import org.apache.dubbo.rpc.protocol.tri.stream.ClientStream;
import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleCommandOutBoundHandler;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleHttp2ClientResponseHandler;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue;
import java.util.concurrent.Executor;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http2.Http2StreamChannel;
import io.netty.handler.codec.http2.Http2StreamChannelBootstrap;
public final class Http2TripleClientStream extends AbstractTripleClientStream {
public Http2TripleClientStream(
FrameworkModel frameworkModel,
Executor executor,
Channel parent,
ClientStream.Listener listener,
TripleWriteQueue writeQueue) {
super(frameworkModel, executor, writeQueue, listener, parent);
}
/**
* For test only
*/
public Http2TripleClientStream(
FrameworkModel frameworkModel,
Executor executor,
TripleWriteQueue writeQueue,
ClientStream.Listener listener,
Http2StreamChannel http2StreamChannel) {
super(frameworkModel, executor, writeQueue, listener, http2StreamChannel);
}
@Override
protected TripleStreamChannelFuture initStreamChannel(Channel parent) {
Http2StreamChannelBootstrap bootstrap = new Http2StreamChannelBootstrap(parent);
bootstrap.handler(new ChannelInboundHandlerAdapter() {
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
ctx.channel()
.pipeline()
.addLast(new TripleCommandOutBoundHandler())
.addLast(new TripleHttp2ClientResponseHandler(createTransportListener()));
}
});
TripleStreamChannelFuture streamChannelFuture = new TripleStreamChannelFuture(parent);
writeQueue.enqueue(CreateStreamQueueCommand.create(bootstrap, streamChannelFuture));
return streamChannelFuture;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/GenericHttp2ServerTransportListenerFactory.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/GenericHttp2ServerTransportListenerFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.http2;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http12.h2.Http2ServerTransportListenerFactory;
import org.apache.dubbo.remoting.http12.h2.Http2TransportListener;
import org.apache.dubbo.rpc.model.FrameworkModel;
public class GenericHttp2ServerTransportListenerFactory implements Http2ServerTransportListenerFactory {
public static final Http2ServerTransportListenerFactory INSTANCE = new GenericHttp2ServerTransportListenerFactory();
@Override
public Http2TransportListener newInstance(H2StreamChannel streamChannel, URL url, FrameworkModel frameworkModel) {
return new GenericHttp2ServerTransportListener(streamChannel, url, frameworkModel);
}
@Override
public boolean supportContentType(String contentType) {
return true;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/GenericHttp2ServerTransportListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/GenericHttp2ServerTransportListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.http2;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.http12.HttpHeaderNames;
import org.apache.dubbo.remoting.http12.h2.CancelStreamException;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http12.h2.Http2Header;
import org.apache.dubbo.remoting.http12.h2.Http2InputMessage;
import org.apache.dubbo.remoting.http12.h2.Http2ServerChannelObserver;
import org.apache.dubbo.remoting.http12.h2.Http2TransportListener;
import org.apache.dubbo.remoting.http12.message.DefaultListeningDecoder;
import org.apache.dubbo.remoting.http12.message.DefaultStreamingDecoder;
import org.apache.dubbo.remoting.http12.message.ListeningDecoder;
import org.apache.dubbo.remoting.http12.message.MediaType;
import org.apache.dubbo.remoting.http12.message.StreamingDecoder;
import org.apache.dubbo.remoting.http12.message.codec.JsonCodec;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.protocol.tri.Http3Exchanger;
import org.apache.dubbo.rpc.protocol.tri.RpcInvocationBuildContext;
import org.apache.dubbo.rpc.protocol.tri.h12.AbstractServerTransportListener;
import org.apache.dubbo.rpc.protocol.tri.h12.BiStreamServerCallListener;
import org.apache.dubbo.rpc.protocol.tri.h12.HttpMessageListener;
import org.apache.dubbo.rpc.protocol.tri.h12.ServerCallListener;
import org.apache.dubbo.rpc.protocol.tri.h12.ServerStreamServerCallListener;
import org.apache.dubbo.rpc.protocol.tri.h12.UnaryServerCallListener;
import java.io.InputStream;
public class GenericHttp2ServerTransportListener extends AbstractServerTransportListener<Http2Header, Http2InputMessage>
implements Http2TransportListener {
private final H2StreamChannel h2StreamChannel;
private final StreamingDecoder streamingDecoder;
private Http2ServerChannelObserver responseObserver;
private ServerCallListener serverCallListener;
public GenericHttp2ServerTransportListener(
H2StreamChannel h2StreamChannel, URL url, FrameworkModel frameworkModel) {
super(frameworkModel, url, h2StreamChannel);
this.h2StreamChannel = h2StreamChannel;
streamingDecoder = newStreamingDecoder();
responseObserver = prepareResponseObserver(newResponseObserver(h2StreamChannel));
}
protected StreamingDecoder newStreamingDecoder() {
return new DefaultStreamingDecoder();
}
protected Http2ServerChannelObserver newResponseObserver(H2StreamChannel h2StreamChannel) {
return new Http2UnaryServerChannelObserver(getFrameworkModel(), h2StreamChannel);
}
protected Http2ServerChannelObserver newStreamResponseObserver(H2StreamChannel h2StreamChannel) {
Http2ServerChannelObserver responseObserver =
new Http2SseServerChannelObserver(getFrameworkModel(), h2StreamChannel);
responseObserver.addHeadersCustomizer(
(hs, t) -> hs.set(HttpHeaderNames.CONTENT_TYPE.getKey(), MediaType.TEXT_EVENT_STREAM.getName()));
return responseObserver;
}
protected Http2ServerChannelObserver prepareResponseObserver(Http2ServerChannelObserver responseObserver) {
responseObserver.setExceptionCustomizer(getExceptionCustomizer());
RpcInvocationBuildContext context = getContext();
responseObserver.setResponseEncoder(context == null ? JsonCodec.INSTANCE : context.getHttpMessageEncoder());
responseObserver.setCancellationContext(RpcContext.getCancellationContext());
responseObserver.setStreamingDecoder(streamingDecoder);
return responseObserver;
}
@Override
protected HttpMessageListener buildHttpMessageListener() {
RpcInvocationBuildContext context = getContext();
RpcInvocation rpcInvocation = buildRpcInvocation(context);
serverCallListener = startListener(rpcInvocation, context.getMethodDescriptor(), context.getInvoker());
DefaultListeningDecoder listeningDecoder = new DefaultListeningDecoder(
context.getHttpMessageDecoder(), context.getMethodMetadata().getActualRequestTypes());
listeningDecoder.setListener(new Http2StreamingDecodeListener(serverCallListener));
streamingDecoder.setFragmentListener(new StreamingDecoder.DefaultFragmentListener(listeningDecoder));
return new StreamingHttpMessageListener(streamingDecoder);
}
private ServerCallListener startListener(
RpcInvocation invocation, MethodDescriptor methodDescriptor, Invoker<?> invoker) {
switch (methodDescriptor.getRpcType()) {
case UNARY:
prepareUnaryServerCall();
return new UnaryServerCallListener(invocation, invoker, responseObserver);
case SERVER_STREAM:
prepareStreamServerCall();
return new ServerStreamServerCallListener(invocation, invoker, responseObserver);
case BI_STREAM:
case CLIENT_STREAM:
prepareStreamServerCall();
return new BiStreamServerCallListener(invocation, invoker, responseObserver);
default:
throw new IllegalStateException("Can not reach here");
}
}
protected void prepareUnaryServerCall() {}
protected void prepareStreamServerCall() {
responseObserver = prepareResponseObserver(newStreamResponseObserver(h2StreamChannel));
}
@Override
protected void initializeAltSvc(URL url) {
if (Http3Exchanger.isEnabled(url)) {
String value = "h3=\":" + url.getParameter(Constants.BIND_PORT_KEY, url.getPort()) + '"';
responseObserver.addHeadersCustomizer((hs, t) -> hs.set(HttpHeaderNames.ALT_SVC.getKey(), value));
}
}
@Override
protected void onMetadataCompletion(Http2Header metadata) {
responseObserver.setResponseEncoder(getContext().getHttpMessageEncoder());
responseObserver.request(1);
if (metadata.isEndStream()) {
getStreamingDecoder().close();
}
}
@Override
protected void onDataCompletion(Http2InputMessage message) {
if (message.isEndStream()) {
getStreamingDecoder().close();
}
}
@Override
protected void onError(Throwable throwable) {
responseObserver.onError(throwable);
}
@Override
protected void onError(Http2InputMessage message, Throwable throwable) {
try {
message.close();
} catch (Exception e) {
throwable.addSuppressed(e);
}
onError(throwable);
}
@Override
protected void onDataFinally(Http2InputMessage message) {}
@Override
public void cancelByRemote(long errorCode) {
responseObserver.cancel(CancelStreamException.fromRemote(errorCode));
if (serverCallListener != null) {
serverCallListener.onCancel(errorCode);
}
}
protected final StreamingDecoder getStreamingDecoder() {
return streamingDecoder;
}
protected final Http2ServerChannelObserver getResponseObserver() {
return responseObserver;
}
@Override
public void close() {
responseObserver.close();
}
private static final class Http2StreamingDecodeListener implements ListeningDecoder.Listener {
private final ServerCallListener serverCallListener;
Http2StreamingDecodeListener(ServerCallListener serverCallListener) {
this.serverCallListener = serverCallListener;
}
@Override
public void onMessage(Object message) {
serverCallListener.onMessage(message);
}
@Override
public void onClose() {
serverCallListener.onComplete();
}
}
private static final class StreamingHttpMessageListener implements HttpMessageListener {
private final StreamingDecoder streamingDecoder;
StreamingHttpMessageListener(StreamingDecoder streamingDecoder) {
this.streamingDecoder = streamingDecoder;
}
@Override
public void onMessage(InputStream inputStream) {
streamingDecoder.decode(inputStream);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2UnaryServerChannelObserver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2UnaryServerChannelObserver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.http2;
import org.apache.dubbo.common.logger.FluentLogger;
import org.apache.dubbo.remoting.http12.HttpHeaders;
import org.apache.dubbo.remoting.http12.HttpMetadata;
import org.apache.dubbo.remoting.http12.HttpOutputMessage;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http12.h2.Http2MetadataFrame;
import org.apache.dubbo.remoting.http12.netty4.NettyHttpHeaders;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.TripleProtocol;
import org.apache.dubbo.rpc.protocol.tri.stream.StreamUtils;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
public class Http2UnaryServerChannelObserver extends Http2StreamServerChannelObserver {
private static final FluentLogger LOGGER = FluentLogger.of(Http2UnaryServerChannelObserver.class);
public Http2UnaryServerChannelObserver(FrameworkModel frameworkModel, H2StreamChannel h2StreamChannel) {
super(frameworkModel, h2StreamChannel);
}
@Override
protected void doOnNext(Object data) throws Throwable {
int statusCode = resolveStatusCode(data);
HttpOutputMessage message = buildMessage(statusCode, data);
HttpMetadata metadata = buildMetadata(statusCode, data, null, message);
customizeTrailers(metadata.headers(), null);
sendMetadata(metadata);
sendMessage(message);
}
@Override
protected void doOnError(Throwable throwable) throws Throwable {
int statusCode = resolveErrorStatusCode(throwable);
Object data = buildErrorResponse(statusCode, throwable);
HttpOutputMessage message;
try {
message = buildMessage(statusCode, data);
} catch (Throwable t) {
LOGGER.internalError("Failed to build message", t);
message = encodeHttpOutputMessage(data);
}
HttpMetadata metadata = buildMetadata(statusCode, data, throwable, message);
customizeTrailers(metadata.headers(), throwable);
sendMetadata(metadata);
sendMessage(message);
}
@Override
protected void customizeTrailers(HttpHeaders headers, Throwable throwable) {
StreamUtils.putHeaders(headers, getResponseAttachments(), TripleProtocol.CONVERT_NO_LOWER_HEADER);
super.customizeTrailers(headers, throwable);
}
@Override
protected void doOnCompleted(Throwable throwable) {}
@Override
protected HttpOutputMessage encodeHttpOutputMessage(Object data) {
return getHttpChannel().newOutputMessage(true);
}
@Override
protected HttpMetadata encodeHttpMetadata(boolean endStream) {
return new Http2MetadataFrame(new NettyHttpHeaders<>(new DefaultHttp2Headers(false, 8)), endStream);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcStreamingDecoder.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcStreamingDecoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.grpc;
import org.apache.dubbo.remoting.http12.message.LengthFieldStreamingDecoder;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor;
import java.io.IOException;
import java.io.InputStream;
public class GrpcStreamingDecoder extends LengthFieldStreamingDecoder {
private static final int COMPRESSED_FLAG_MASK = 1;
private static final int RESERVED_MASK = 0xFE;
private boolean compressedFlag;
private DeCompressor deCompressor = DeCompressor.NONE;
public GrpcStreamingDecoder() {
super(1, 4);
}
public void setDeCompressor(DeCompressor deCompressor) {
this.deCompressor = deCompressor;
}
@Override
protected void processOffset(InputStream inputStream, int lengthFieldOffset) throws IOException {
int type = inputStream.read();
if ((type & RESERVED_MASK) != 0) {
throw new RpcException("gRPC frame header malformed: reserved bits not zero");
}
compressedFlag = (type & COMPRESSED_FLAG_MASK) != 0;
}
@Override
protected byte[] readRawMessage(InputStream inputStream, int length) throws IOException {
byte[] rawMessage = super.readRawMessage(inputStream, length);
return compressedFlag ? deCompressedMessage(rawMessage) : rawMessage;
}
private byte[] deCompressedMessage(byte[] rawMessage) {
return deCompressor.decompress(rawMessage);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcCompositeCodecFactory.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcCompositeCodecFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.grpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.remoting.http12.message.HttpMessageCodec;
import org.apache.dubbo.remoting.http12.message.HttpMessageDecoderFactory;
import org.apache.dubbo.remoting.http12.message.HttpMessageEncoderFactory;
import org.apache.dubbo.remoting.http12.message.MediaType;
import org.apache.dubbo.rpc.model.FrameworkModel;
@Activate
public class GrpcCompositeCodecFactory implements HttpMessageEncoderFactory, HttpMessageDecoderFactory {
@Override
public HttpMessageCodec createCodec(URL url, FrameworkModel frameworkModel, String mediaType) {
return new GrpcCompositeCodec(url, frameworkModel, mediaType);
}
@Override
public MediaType mediaType() {
return MediaType.APPLICATION_GRPC;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHttp2ServerTransportListenerFactory.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHttp2ServerTransportListenerFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.grpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http12.h2.Http2ServerTransportListenerFactory;
import org.apache.dubbo.remoting.http12.h2.Http2TransportListener;
import org.apache.dubbo.rpc.model.FrameworkModel;
public class GrpcHttp2ServerTransportListenerFactory implements Http2ServerTransportListenerFactory {
@Override
public Http2TransportListener newInstance(H2StreamChannel streamChannel, URL url, FrameworkModel frameworkModel) {
return new GrpcHttp2ServerTransportListener(streamChannel, url, frameworkModel);
}
@Override
public boolean supportContentType(String contentType) {
return GrpcUtils.isGrpcRequest(contentType);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcCompositeCodec.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcCompositeCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.grpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.io.StreamUtils;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.remoting.http12.exception.DecodeException;
import org.apache.dubbo.remoting.http12.exception.EncodeException;
import org.apache.dubbo.remoting.http12.exception.HttpStatusException;
import org.apache.dubbo.remoting.http12.message.HttpMessageCodec;
import org.apache.dubbo.remoting.http12.message.MediaType;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.PackableMethod;
import org.apache.dubbo.rpc.model.PackableMethodFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.concurrent.ConcurrentHashMap;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PACKABLE_METHOD_FACTORY;
public class GrpcCompositeCodec implements HttpMessageCodec {
private static final String PACKABLE_METHOD_CACHE = "PACKABLE_METHOD_CACHE";
private final URL url;
private final FrameworkModel frameworkModel;
private final String mediaType;
private PackableMethod packableMethod;
public GrpcCompositeCodec(URL url, FrameworkModel frameworkModel, String mediaType) {
this.url = url;
this.frameworkModel = frameworkModel;
this.mediaType = mediaType;
}
public void loadPackableMethod(MethodDescriptor methodDescriptor) {
if (methodDescriptor instanceof PackableMethod) {
packableMethod = (PackableMethod) methodDescriptor;
return;
}
packableMethod = ConcurrentHashMapUtils.computeIfAbsent(
UrlUtils.computeServiceAttribute(
url, PACKABLE_METHOD_CACHE, k -> new ConcurrentHashMap<MethodDescriptor, PackableMethod>()),
methodDescriptor,
md -> frameworkModel
.getExtensionLoader(PackableMethodFactory.class)
.getExtension(ConfigurationUtils.getGlobalConfiguration(url.getApplicationModel())
.getString(DUBBO_PACKABLE_METHOD_FACTORY, DEFAULT_KEY))
.create(methodDescriptor, url, mediaType));
}
@Override
public void encode(OutputStream outputStream, Object data, Charset charset) throws EncodeException {
// protobuf
// TODO int compressed = Identity.MESSAGE_ENCODING.equals(requestMetadata.compressor.getMessageEncoding()) ? 0 :
// 1;
try {
int compressed = 0;
outputStream.write(compressed);
byte[] bytes = packableMethod.packResponse(data);
writeLength(outputStream, bytes.length);
outputStream.write(bytes);
} catch (HttpStatusException e) {
throw e;
} catch (Exception e) {
throw new EncodeException(e);
}
}
@Override
public Object decode(InputStream inputStream, Class<?> targetType, Charset charset) throws DecodeException {
try {
byte[] data = StreamUtils.readBytes(inputStream);
return packableMethod.parseRequest(data);
} catch (HttpStatusException e) {
throw e;
} catch (Exception e) {
throw new DecodeException(e);
}
}
@Override
public Object[] decode(InputStream inputStream, Class<?>[] targetTypes, Charset charset) throws DecodeException {
Object message = decode(inputStream, ArrayUtils.isEmpty(targetTypes) ? null : targetTypes[0], charset);
if (message instanceof Object[]) {
return (Object[]) message;
}
return new Object[] {message};
}
private void writeLength(OutputStream outputStream, int length) {
try {
outputStream.write(((length >> 24) & 0xFF));
outputStream.write(((length >> 16) & 0xFF));
outputStream.write(((length >> 8) & 0xFF));
outputStream.write((length & 0xFF));
} catch (IOException e) {
throw new EncodeException(e);
}
}
@Override
public MediaType mediaType() {
return MediaType.APPLICATION_GRPC;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcRequestHandlerMapping.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcRequestHandlerMapping.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.grpc;
import org.apache.dubbo.common.URL;
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.HttpStatus;
import org.apache.dubbo.remoting.http12.exception.HttpStatusException;
import org.apache.dubbo.remoting.http12.message.HttpMessageCodec;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.PathResolver;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.DescriptorUtils;
import org.apache.dubbo.rpc.protocol.tri.RequestPath;
import org.apache.dubbo.rpc.protocol.tri.TripleConstants;
import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
import org.apache.dubbo.rpc.protocol.tri.route.RequestHandler;
import org.apache.dubbo.rpc.protocol.tri.route.RequestHandlerMapping;
@Activate(order = -3000)
public final class GrpcRequestHandlerMapping implements RequestHandlerMapping {
public static final GrpcCompositeCodecFactory CODEC_FACTORY = new GrpcCompositeCodecFactory();
private final FrameworkModel frameworkModel;
private final PathResolver pathResolver;
public GrpcRequestHandlerMapping(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
pathResolver = frameworkModel.getDefaultExtension(PathResolver.class);
}
@Override
public RequestHandler getRequestHandler(URL url, HttpRequest request, HttpResponse response) {
if (!GrpcUtils.isGrpcRequest(request.contentType())) {
return null;
}
RequestPath path = RequestPath.parse(request.uri());
if (path == null) {
throw notFound();
}
String group = request.header(TripleHeaderEnum.SERVICE_GROUP.getKey());
String version = request.header(TripleHeaderEnum.SERVICE_VERSION.getKey());
Invoker<?> invoker = pathResolver.resolve(path.getPath(), group, version);
if (invoker == null) {
throw notFound();
}
RequestHandler handler = new RequestHandler(invoker);
handler.setHasStub(pathResolver.hasNativeStub(path.getStubPath()));
handler.setMethodName(path.getMethodName());
String serviceName = path.getServiceInterface();
handler.setServiceDescriptor(DescriptorUtils.findServiceDescriptor(invoker, serviceName, handler.isHasStub()));
HttpMessageCodec codec = CODEC_FACTORY.createCodec(url, frameworkModel, request.contentType());
handler.setHttpMessageDecoder(codec);
handler.setHttpMessageEncoder(codec);
return handler;
}
private static HttpStatusException notFound() {
return new HttpStatusException(HttpStatus.NOT_FOUND.getCode(), "Invoker for gRPC not found");
}
@Override
public String getType() {
return TripleConstants.TRIPLE_HANDLER_TYPE_GRPC;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcStreamServerChannelObserver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcStreamServerChannelObserver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.grpc;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http12.message.MediaType;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.h12.http2.Http2StreamServerChannelObserver;
public class GrpcStreamServerChannelObserver extends Http2StreamServerChannelObserver {
public GrpcStreamServerChannelObserver(FrameworkModel frameworkModel, H2StreamChannel h2StreamChannel) {
super(frameworkModel, h2StreamChannel);
}
@Override
protected void doOnError(Throwable throwable) {}
@Override
protected String getContentType() {
return MediaType.APPLICATION_GRPC.getName();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHeaderNames.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHeaderNames.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.grpc;
public enum GrpcHeaderNames {
GRPC_STATUS("grpc-status"),
GRPC_MESSAGE("grpc-message"),
GRPC_ENCODING("grpc-encoding"), // client request compress type
GRPC_ACCEPT_ENCODING("grpc-accept-encoding"), // client required response compress type
GRPC_TIMEOUT("grpc-timeout"),
;
private final String name;
GrpcHeaderNames(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHttp2ServerTransportListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHttp2ServerTransportListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.grpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.remoting.http12.exception.DecodeException;
import org.apache.dubbo.remoting.http12.exception.UnimplementedException;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http12.h2.Http2Header;
import org.apache.dubbo.remoting.http12.h2.Http2ServerChannelObserver;
import org.apache.dubbo.remoting.http12.h2.Http2TransportListener;
import org.apache.dubbo.remoting.http12.message.MethodMetadata;
import org.apache.dubbo.remoting.http12.message.StreamingDecoder;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.protocol.tri.DescriptorUtils;
import org.apache.dubbo.rpc.protocol.tri.ReflectionPackableMethod;
import org.apache.dubbo.rpc.protocol.tri.RpcInvocationBuildContext;
import org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor;
import org.apache.dubbo.rpc.protocol.tri.compressor.Identity;
import org.apache.dubbo.rpc.protocol.tri.h12.HttpMessageListener;
import org.apache.dubbo.rpc.protocol.tri.h12.http2.GenericHttp2ServerTransportListener;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executor;
import java.util.function.Function;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_PARSE;
public class GrpcHttp2ServerTransportListener extends GenericHttp2ServerTransportListener
implements Http2TransportListener {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(GrpcHttp2ServerTransportListener.class);
public GrpcHttp2ServerTransportListener(H2StreamChannel h2StreamChannel, URL url, FrameworkModel frameworkModel) {
super(h2StreamChannel, url, frameworkModel);
}
@Override
protected void onBeforeMetadata(Http2Header metadata) {}
@Override
protected Executor initializeExecutor(URL url, Http2Header metadata) {
return getExecutor(url, metadata);
}
@Override
protected void onPrepareMetadata(Http2Header metadata) {
doRoute(metadata);
}
@Override
protected void onMetadataCompletion(Http2Header metadata) {
processGrpcHeaders(metadata);
super.onMetadataCompletion(metadata);
}
private void processGrpcHeaders(Http2Header metadata) {
String messageEncoding = metadata.header(GrpcHeaderNames.GRPC_ENCODING.getName());
if (messageEncoding != null && !Identity.MESSAGE_ENCODING.equals(messageEncoding)) {
DeCompressor compressor = DeCompressor.getCompressor(getFrameworkModel(), messageEncoding);
if (compressor == null) {
throw new UnimplementedException(
GrpcHeaderNames.GRPC_ENCODING.getName() + " '" + messageEncoding + "'");
}
((GrpcStreamingDecoder) getStreamingDecoder()).setDeCompressor(compressor);
}
}
@Override
protected StreamingDecoder newStreamingDecoder() {
return new GrpcStreamingDecoder();
}
@Override
protected Http2ServerChannelObserver newResponseObserver(H2StreamChannel h2StreamChannel) {
return new GrpcUnaryServerChannelObserver(getFrameworkModel(), h2StreamChannel);
}
@Override
protected Http2ServerChannelObserver newStreamResponseObserver(H2StreamChannel h2StreamChannel) {
return new GrpcStreamServerChannelObserver(getFrameworkModel(), h2StreamChannel);
}
@Override
protected Http2ServerChannelObserver prepareResponseObserver(Http2ServerChannelObserver responseObserver) {
responseObserver.addTrailersCustomizer(getExceptionCustomizerWrapper()::customizeGrpcStatus);
return super.prepareResponseObserver(responseObserver);
}
@Override
protected HttpMessageListener buildHttpMessageListener() {
return getContext().isHasStub() ? super.buildHttpMessageListener() : new LazyFindMethodListener();
}
@Override
protected void prepareUnaryServerCall() {
if (needWrap()) {
getExceptionCustomizerWrapper().setNeedWrap(true);
}
}
private boolean needWrap() {
RpcInvocationBuildContext context = getContext();
if (context.isHasStub()) {
return false;
}
MethodMetadata methodMetadata = context.getMethodMetadata();
return ReflectionPackableMethod.needWrap(
context.getMethodDescriptor(),
methodMetadata.getActualRequestTypes(),
methodMetadata.getActualResponseType());
}
@Override
protected RpcInvocation onBuildRpcInvocationCompletion(RpcInvocation invocation) {
String timeoutString = getHttpMetadata().header(GrpcHeaderNames.GRPC_TIMEOUT.getName());
try {
if (timeoutString != null) {
Long timeout = GrpcUtils.parseTimeoutToMills(timeoutString);
invocation.put(CommonConstants.TIMEOUT_KEY, timeout);
}
} catch (Throwable t) {
LOGGER.warn(
PROTOCOL_FAILED_PARSE,
"",
"",
String.format(
"Failed to parse request timeout set from:%s, service=%s " + "method=%s",
timeoutString,
getContext().getServiceDescriptor().getInterfaceName(),
getContext().getMethodName()));
}
return invocation;
}
@Override
protected Function<Throwable, Object> getExceptionCustomizer() {
return getExceptionCustomizerWrapper()::customizeGrpc;
}
@Override
protected void setMethodDescriptor(MethodDescriptor methodDescriptor) {
((GrpcCompositeCodec) getContext().getHttpMessageDecoder()).loadPackableMethod(methodDescriptor);
super.setMethodDescriptor(methodDescriptor);
}
private class LazyFindMethodListener implements HttpMessageListener {
private final StreamingDecoder streamingDecoder;
private LazyFindMethodListener() {
streamingDecoder = new GrpcStreamingDecoder();
streamingDecoder.setFragmentListener(new DetermineMethodDescriptorListener());
streamingDecoder.request(Integer.MAX_VALUE);
}
@Override
public void onMessage(InputStream inputStream) {
streamingDecoder.decode(inputStream);
}
}
private class DetermineMethodDescriptorListener implements StreamingDecoder.FragmentListener {
@Override
public void onClose() {
getStreamingDecoder().close();
}
@Override
public void onFragmentMessage(InputStream rawMessage) {
try {
RpcInvocationBuildContext context = getContext();
if (context.getMethodDescriptor() == null) {
MethodDescriptor methodDescriptor = DescriptorUtils.findTripleMethodDescriptor(
context.getServiceDescriptor(), context.getMethodName(), rawMessage);
setMethodDescriptor(methodDescriptor);
setHttpMessageListener(GrpcHttp2ServerTransportListener.super.buildHttpMessageListener());
}
((GrpcStreamingDecoder) getStreamingDecoder()).invokeListener(rawMessage);
} catch (IOException e) {
throw new DecodeException(e);
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcUnaryServerChannelObserver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcUnaryServerChannelObserver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.grpc;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.rpc.model.FrameworkModel;
public class GrpcUnaryServerChannelObserver extends GrpcStreamServerChannelObserver {
public GrpcUnaryServerChannelObserver(FrameworkModel frameworkModel, H2StreamChannel h2StreamChannel) {
super(frameworkModel, h2StreamChannel);
}
@Override
protected Throwable customizeError(Throwable throwable) {
throwable = super.customizeError(throwable);
if (throwable == null) {
doOnCompleted(null);
}
return throwable;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcUtils.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h12.grpc;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.message.MediaType;
import java.util.concurrent.TimeUnit;
public class GrpcUtils {
private GrpcUtils() {}
public static Long parseTimeoutToMills(String timeoutVal) {
if (StringUtils.isEmpty(timeoutVal) || StringUtils.isContains(timeoutVal, "null")) {
return null;
}
long value = Long.parseLong(timeoutVal.substring(0, timeoutVal.length() - 1));
char unit = timeoutVal.charAt(timeoutVal.length() - 1);
switch (unit) {
case 'n':
return TimeUnit.NANOSECONDS.toMillis(value);
case 'u':
return TimeUnit.MICROSECONDS.toMillis(value);
case 'm':
return value;
case 'S':
return TimeUnit.SECONDS.toMillis(value);
case 'M':
return TimeUnit.MINUTES.toMillis(value);
case 'H':
return TimeUnit.HOURS.toMillis(value);
default:
// invalid timeout config
return null;
}
}
/**
* Converts a timeout value to the gRPC `grpc-timeout` ASCII string format.
* <p>
* This method applies a greedy strategy: it chooses the largest possible unit
* (nanos, micros, millis, seconds, minutes, hours) such that the numeric part is
* less than 100_000_000, as required by the gRPC specification.
* For example, a 1-second timeout will be encoded as "1000000u" (in microseconds).
* </p>
*
* @param timeout the timeout value
* @param unit the time unit of the timeout
* @return a string suitable for use as the value of the gRPC `grpc-timeout` header
* @throws IllegalArgumentException if the timeout too small
*/
public static String getTimeoutHeaderValue(Long timeout, TimeUnit unit) {
long timeoutNanos = timeout;
if (unit != TimeUnit.NANOSECONDS) {
timeoutNanos = unit.toNanos(timeout);
}
final long cutoff = 100_000_000L;
if (timeoutNanos < 0) {
throw new IllegalArgumentException("Timeout too small");
} else if (timeoutNanos < cutoff) {
return timeoutNanos + "n";
} else if (timeoutNanos < cutoff * 1_000L) {
return TimeUnit.NANOSECONDS.toMicros(timeoutNanos) + "u";
} else if (timeoutNanos < cutoff * 1_000_000L) {
return TimeUnit.NANOSECONDS.toMillis(timeoutNanos) + "m";
} else if (timeoutNanos < cutoff * 1_000_000_000L) {
return TimeUnit.NANOSECONDS.toSeconds(timeoutNanos) + "S";
} else if (timeoutNanos < cutoff * 1_000_000_000L * 60L) {
return TimeUnit.NANOSECONDS.toMinutes(timeoutNanos) + "M";
} else {
return TimeUnit.NANOSECONDS.toHours(timeoutNanos) + "H";
}
}
public static boolean isGrpcRequest(String contentType) {
return contentType != null && contentType.startsWith(MediaType.APPLICATION_GRPC.getName());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Gzip.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Gzip.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.compressor;
import org.apache.dubbo.common.config.Configuration;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* gzip compressor
*/
public class Gzip implements Compressor, DeCompressor {
public static final String GZIP = "gzip";
private final int maxMessageSize;
public Gzip() {
Configuration conf = ConfigurationUtils.getEnvConfiguration(ApplicationModel.defaultModel());
this.maxMessageSize = conf.getInteger(Constants.H2_SETTINGS_MAX_MESSAGE_SIZE, 50 * 1024 * 1024);
}
@Override
public String getMessageEncoding() {
return GZIP;
}
@Override
public byte[] compress(byte[] payloadByteArr) throws RpcException {
if (null == payloadByteArr || 0 == payloadByteArr.length) {
return new byte[0];
}
ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteOutStream)) {
gzipOutputStream.write(payloadByteArr);
} catch (Exception exception) {
throw new IllegalStateException(exception);
}
return byteOutStream.toByteArray();
}
@Override
public OutputStream decorate(OutputStream outputStream) {
try {
return new GZIPOutputStream(outputStream);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public byte[] decompress(byte[] payloadByteArr) throws RpcException {
if (null == payloadByteArr || 0 == payloadByteArr.length) {
return new byte[0];
}
ByteArrayInputStream byteInStream = new ByteArrayInputStream(payloadByteArr);
ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
try (GZIPInputStream gzipInputStream = new GZIPInputStream(byteInStream)) {
int readByteNum;
int totalBytesRead = 0;
byte[] bufferArr = new byte[256];
while ((readByteNum = gzipInputStream.read(bufferArr)) >= 0) {
totalBytesRead += readByteNum;
if (totalBytesRead > maxMessageSize) {
throw new RpcException("Decompressed message size " + totalBytesRead
+ " exceeds the maximum configured message size " + maxMessageSize);
}
byteOutStream.write(bufferArr, 0, readByteNum);
}
} catch (Exception exception) {
throw new IllegalStateException(exception);
}
return byteOutStream.toByteArray();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Identity.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Identity.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.compressor;
import java.io.OutputStream;
/**
* Default compressor
* <p>
* Do not use the spi
*/
public class Identity implements Compressor, DeCompressor {
public static final String MESSAGE_ENCODING = "identity";
public static final Identity IDENTITY = new Identity();
@Override
public String getMessageEncoding() {
return MESSAGE_ENCODING;
}
@Override
public byte[] compress(byte[] payloadByteArr) {
return payloadByteArr;
}
@Override
public OutputStream decorate(OutputStream outputStream) {
return outputStream;
}
@Override
public byte[] decompress(byte[] payloadByteArr) {
return payloadByteArr;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/MessageEncoding.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/MessageEncoding.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.compressor;
public interface MessageEncoding {
/**
* message encoding of current compressor
*
* @return return message encoding
*/
String getMessageEncoding();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Compressor.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Compressor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.compressor;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.io.OutputStream;
/**
* compress payload for grpc request, and decompress response payload Configure it in files,
* pictures or other configurations that exist in the system properties Configure {@link
* Constants#COMPRESSOR_KEY} in dubbo.properties、dubbo.yml or other configuration that exist in the
* system property
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface Compressor extends MessageEncoding {
Compressor NONE = Identity.IDENTITY;
static Compressor getCompressor(FrameworkModel frameworkModel, String compressorStr) {
if (null == compressorStr) {
return null;
}
if (compressorStr.equals(Identity.MESSAGE_ENCODING)) {
return NONE;
}
return frameworkModel.getExtensionLoader(Compressor.class).getExtension(compressorStr);
}
/**
* compress payload
*
* @param payloadByteArr payload byte array
* @return compressed payload byte array
*/
byte[] compress(byte[] payloadByteArr);
OutputStream decorate(OutputStream outputStream);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Snappy.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Snappy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.compressor;
import org.apache.dubbo.rpc.RpcException;
import java.io.IOException;
import java.io.OutputStream;
/**
* snappy compressor, Provide high-speed compression speed and reasonable compression ratio
*
* @link https://github.com/google/snappy
*/
public class Snappy implements Compressor, DeCompressor {
public static final String SNAPPY = "snappy";
@Override
public String getMessageEncoding() {
return SNAPPY;
}
@Override
public byte[] compress(byte[] payloadByteArr) throws RpcException {
if (null == payloadByteArr || 0 == payloadByteArr.length) {
return new byte[0];
}
try {
return org.xerial.snappy.Snappy.compress(payloadByteArr);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public OutputStream decorate(OutputStream outputStream) {
return outputStream;
}
@Override
public byte[] decompress(byte[] payloadByteArr) {
if (null == payloadByteArr || 0 == payloadByteArr.length) {
return new byte[0];
}
try {
return org.xerial.snappy.Snappy.uncompress(payloadByteArr);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Bzip2.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Bzip2.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.compressor;
import org.apache.dubbo.common.config.Configuration;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
import org.apache.commons.io.output.ByteArrayOutputStream;
/**
* bzip2 compressor, faster compression efficiency
*
* @link https://commons.apache.org/proper/commons-compress/
*/
public class Bzip2 implements Compressor, DeCompressor {
public static final String BZIP2 = "bzip2";
private final int maxMessageSize;
@Override
public String getMessageEncoding() {
return BZIP2;
}
public Bzip2() {
Configuration conf = ConfigurationUtils.getEnvConfiguration(ApplicationModel.defaultModel());
this.maxMessageSize = conf.getInteger(Constants.H2_SETTINGS_MAX_MESSAGE_SIZE, 50 * 1024 * 1024);
}
@Override
public byte[] compress(byte[] payloadByteArr) throws RpcException {
if (null == payloadByteArr || 0 == payloadByteArr.length) {
return new byte[0];
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
BZip2CompressorOutputStream cos;
try {
cos = new BZip2CompressorOutputStream(out);
cos.write(payloadByteArr);
cos.close();
} catch (Exception e) {
throw new IllegalStateException(e);
}
return out.toByteArray();
}
@Override
public OutputStream decorate(OutputStream outputStream) {
try {
return new BZip2CompressorOutputStream(outputStream);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public byte[] decompress(byte[] payloadByteArr) {
if (null == payloadByteArr || 0 == payloadByteArr.length) {
return new byte[0];
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(payloadByteArr);
try {
int totalBytesRead = 0;
BZip2CompressorInputStream unZip = new BZip2CompressorInputStream(in);
byte[] buffer = new byte[2048];
int n;
while ((n = unZip.read(buffer)) >= 0) {
totalBytesRead += n;
if (totalBytesRead > maxMessageSize) {
throw new RpcException("Decompressed message size " + totalBytesRead
+ " exceeds the maximum configured message size " + maxMessageSize);
}
out.write(buffer, 0, n);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
return out.toByteArray();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/DeCompressor.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/DeCompressor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.compressor;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.model.FrameworkModel;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface DeCompressor extends MessageEncoding {
DeCompressor NONE = Identity.IDENTITY;
static DeCompressor getCompressor(FrameworkModel frameworkModel, String compressorStr) {
if (null == compressorStr) {
return null;
}
if (compressorStr.equals(Identity.MESSAGE_ENCODING)) {
return NONE;
}
return frameworkModel.getExtensionLoader(DeCompressor.class).getExtension(compressorStr);
}
/**
* decompress payload
*
* @param payloadByteArr payload byte array
* @return decompressed payload byte array
*/
byte[] decompress(byte[] payloadByteArr);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/aot/TripleReflectionTypeDescriberRegistrar.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/aot/TripleReflectionTypeDescriberRegistrar.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.aot;
import org.apache.dubbo.aot.api.MemberCategory;
import org.apache.dubbo.aot.api.ReflectionTypeDescriberRegistrar;
import org.apache.dubbo.aot.api.TypeDescriber;
import org.apache.dubbo.remoting.http12.ErrorResponse;
import org.apache.dubbo.remoting.http12.message.codec.CodecUtils;
import org.apache.dubbo.rpc.protocol.tri.h12.CompositeExceptionHandler;
import org.apache.dubbo.rpc.protocol.tri.rest.argument.CompositeArgumentConverter;
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.mapping.ContentNegotiator;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.DefaultRequestMappingRegistry;
import org.apache.dubbo.rpc.protocol.tri.route.DefaultRequestRouter;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleCommandOutBoundHandler;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleGoAwayHandler;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleHttp2ClientResponseHandler;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleServerConnectionHandler;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleTailHandler;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TripleReflectionTypeDescriberRegistrar implements ReflectionTypeDescriberRegistrar {
@Override
public List<TypeDescriber> getTypeDescribers() {
List<TypeDescriber> typeDescribers = new ArrayList<>();
typeDescribers.add(buildTypeDescriberWithPublicMethod(TripleCommandOutBoundHandler.class));
typeDescribers.add(buildTypeDescriberWithPublicMethod(TripleTailHandler.class));
typeDescribers.add(buildTypeDescriberWithPublicMethod(TripleServerConnectionHandler.class));
typeDescribers.add(buildTypeDescriberWithPublicMethod(TripleGoAwayHandler.class));
typeDescribers.add(buildTypeDescriberWithPublicMethod(TripleHttp2ClientResponseHandler.class));
typeDescribers.add(buildTypeDescriberWithPublicMethod(ErrorResponse.class));
typeDescribers.add(buildTypeDescriberWithDeclaredConstructors(DefaultRequestMappingRegistry.class));
typeDescribers.add(buildTypeDescriberWithDeclaredConstructors(DefaultRequestRouter.class));
typeDescribers.add(buildTypeDescriberWithDeclaredConstructors(ContentNegotiator.class));
typeDescribers.add(buildTypeDescriberWithDeclaredConstructors(CompositeArgumentResolver.class));
typeDescribers.add(buildTypeDescriberWithDeclaredConstructors(CompositeArgumentConverter.class));
typeDescribers.add(buildTypeDescriberWithDeclaredConstructors(CompositeExceptionHandler.class));
typeDescribers.add(buildTypeDescriberWithDeclaredConstructors(GeneralTypeConverter.class));
typeDescribers.add(buildTypeDescriberWithDeclaredConstructors(CodecUtils.class));
return typeDescribers;
}
private TypeDescriber buildTypeDescriberWithPublicMethod(Class<?> c) {
Set<MemberCategory> memberCategories = new HashSet<>();
memberCategories.add(MemberCategory.INVOKE_PUBLIC_METHODS);
return new TypeDescriber(
c.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories);
}
private TypeDescriber buildTypeDescriberWithDeclaredConstructors(Class<?> cl) {
Set<MemberCategory> memberCategories = new HashSet<>();
memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
return new TypeDescriber(
cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/route/RequestRouter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/route/RequestRouter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.route;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.http12.HttpChannel;
import org.apache.dubbo.remoting.http12.RequestMetadata;
import org.apache.dubbo.rpc.protocol.tri.RpcInvocationBuildContext;
public interface RequestRouter {
RpcInvocationBuildContext route(URL url, RequestMetadata metadata, HttpChannel httpChannel);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/route/RequestHandler.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/route/RequestHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.route;
import org.apache.dubbo.remoting.http12.message.HttpMessageDecoder;
import org.apache.dubbo.remoting.http12.message.HttpMessageEncoder;
import org.apache.dubbo.remoting.http12.message.MethodMetadata;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.protocol.tri.RpcInvocationBuildContext;
import java.util.HashMap;
import java.util.Map;
public final class RequestHandler implements RpcInvocationBuildContext {
private final Invoker<?> invoker;
private boolean hasStub;
private String methodName;
private MethodDescriptor methodDescriptor;
private MethodMetadata methodMetadata;
private ServiceDescriptor serviceDescriptor;
private HttpMessageDecoder httpMessageDecoder;
private HttpMessageEncoder httpMessageEncoder;
private Map<String, Object> attributes = new HashMap<>();
public RequestHandler(Invoker<?> invoker) {
this.invoker = invoker;
}
@Override
public Invoker<?> getInvoker() {
return invoker;
}
@Override
public boolean isHasStub() {
return hasStub;
}
public void setHasStub(boolean hasStub) {
this.hasStub = hasStub;
}
@Override
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
@Override
public MethodDescriptor getMethodDescriptor() {
return methodDescriptor;
}
@Override
public MethodMetadata getMethodMetadata() {
return methodMetadata;
}
@Override
public void setMethodMetadata(MethodMetadata methodMetadata) {
this.methodMetadata = methodMetadata;
}
@Override
public void setMethodDescriptor(MethodDescriptor methodDescriptor) {
this.methodDescriptor = methodDescriptor;
}
@Override
public ServiceDescriptor getServiceDescriptor() {
return serviceDescriptor;
}
public void setServiceDescriptor(ServiceDescriptor serviceDescriptor) {
this.serviceDescriptor = serviceDescriptor;
}
@Override
public HttpMessageDecoder getHttpMessageDecoder() {
return httpMessageDecoder;
}
public void setHttpMessageDecoder(HttpMessageDecoder httpMessageDecoder) {
this.httpMessageDecoder = httpMessageDecoder;
}
@Override
public HttpMessageEncoder getHttpMessageEncoder() {
return httpMessageEncoder;
}
public void setHttpMessageEncoder(HttpMessageEncoder httpMessageEncoder) {
this.httpMessageEncoder = httpMessageEncoder;
}
@Override
public Map<String, Object> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, Object> attributes) {
this.attributes = attributes;
}
public void setAttribute(String key, Object value) {
attributes.put(key, value);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/route/RequestHandlerMapping.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/route/RequestHandlerMapping.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.route;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface RequestHandlerMapping {
RequestHandler getRequestHandler(URL url, HttpRequest request, HttpResponse response);
String getType();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/route/DefaultRequestRouter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/route/DefaultRequestRouter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.route;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.http12.HttpChannel;
import org.apache.dubbo.remoting.http12.HttpMetadata;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.remoting.http12.RequestMetadata;
import org.apache.dubbo.remoting.http12.message.HttpMessageAdapterFactory;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.RpcInvocationBuildContext;
import org.apache.dubbo.rpc.protocol.tri.TripleConstants;
import java.util.List;
public final class DefaultRequestRouter implements RequestRouter {
private final HttpMessageAdapterFactory<HttpRequest, HttpMetadata, Void> httpMessageAdapterFactory;
private final List<RequestHandlerMapping> requestHandlerMappings;
@SuppressWarnings("unchecked")
public DefaultRequestRouter(FrameworkModel frameworkModel) {
httpMessageAdapterFactory = frameworkModel.getFirstActivateExtension(HttpMessageAdapterFactory.class);
requestHandlerMappings = frameworkModel.getActivateExtensions(RequestHandlerMapping.class);
}
@Override
public RpcInvocationBuildContext route(URL url, RequestMetadata metadata, HttpChannel httpChannel) {
HttpRequest request = httpMessageAdapterFactory.adaptRequest(metadata, httpChannel);
HttpResponse response = httpMessageAdapterFactory.adaptResponse(request, metadata);
for (int i = 0, size = requestHandlerMappings.size(); i < size; i++) {
RequestHandlerMapping mapping = requestHandlerMappings.get(i);
RequestHandler handler = mapping.getRequestHandler(url, request, response);
if (handler == null) {
continue;
}
handler.setAttribute(TripleConstants.HANDLER_TYPE_KEY, mapping.getType());
handler.setAttribute(TripleConstants.HTTP_REQUEST_KEY, request);
handler.setAttribute(TripleConstants.HTTP_RESPONSE_KEY, response);
return handler;
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/Http3ServerUnaryChannelObserver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/Http3ServerUnaryChannelObserver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h3;
import org.apache.dubbo.remoting.http12.HttpMetadata;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.h12.http2.Http2UnaryServerChannelObserver;
public final class Http3ServerUnaryChannelObserver extends Http2UnaryServerChannelObserver {
public Http3ServerUnaryChannelObserver(FrameworkModel frameworkModel, H2StreamChannel h2StreamChannel) {
super(frameworkModel, h2StreamChannel);
}
@Override
protected HttpMetadata encodeHttpMetadata(boolean endStream) {
return Helper.encodeHttpMetadata(endStream);
}
@Override
protected HttpMetadata encodeTrailers(Throwable throwable) {
return Helper.encodeTrailers();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/GenericHttp3ServerTransportListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/GenericHttp3ServerTransportListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h3;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http12.h2.Http2InputMessage;
import org.apache.dubbo.remoting.http12.h2.Http2ServerChannelObserver;
import org.apache.dubbo.remoting.http3.Http3TransportListener;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.h12.http2.GenericHttp2ServerTransportListener;
public final class GenericHttp3ServerTransportListener extends GenericHttp2ServerTransportListener
implements Http3TransportListener {
public GenericHttp3ServerTransportListener(
H2StreamChannel h2StreamChannel, URL url, FrameworkModel frameworkModel) {
super(h2StreamChannel, url, frameworkModel);
}
@Override
protected Http2ServerChannelObserver newResponseObserver(H2StreamChannel h2StreamChannel) {
return new Http3ServerUnaryChannelObserver(getFrameworkModel(), h2StreamChannel);
}
@Override
protected Http2ServerChannelObserver newStreamResponseObserver(H2StreamChannel h2StreamChannel) {
return new Http3ServerUnaryChannelObserver(getFrameworkModel(), h2StreamChannel);
}
@Override
protected void doOnData(Http2InputMessage message) {
if (message.isEndStream()) {
onDataCompletion(message);
return;
}
super.doOnData(message);
}
@Override
protected void initializeAltSvc(URL url) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/Http3ClientStreamFactory.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/Http3ClientStreamFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h3;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.remoting.transport.netty4.NettyHttp3ConnectionClient;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.call.TripleClientCall;
import org.apache.dubbo.rpc.protocol.tri.stream.ClientStream;
import org.apache.dubbo.rpc.protocol.tri.stream.ClientStreamFactory;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue;
import java.util.concurrent.Executor;
@Activate(order = -100, onClass = "io.netty.handler.codec.quic.QuicChannel")
public class Http3ClientStreamFactory implements ClientStreamFactory {
@Override
public ClientStream createClientStream(
AbstractConnectionClient client,
FrameworkModel frameworkModel,
Executor executor,
TripleClientCall clientCall,
TripleWriteQueue writeQueue) {
if (client instanceof NettyHttp3ConnectionClient) {
return new Http3TripleClientStream(
frameworkModel, executor, client.getChannel(true), clientCall, writeQueue);
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/Http3TripleClientStream.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/Http3TripleClientStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h3;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.command.Http3CreateStreamQueueCommand;
import org.apache.dubbo.rpc.protocol.tri.stream.AbstractTripleClientStream;
import org.apache.dubbo.rpc.protocol.tri.stream.ClientStream;
import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleCommandOutBoundHandler;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleGoAwayHandler;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleHttp2ClientResponseHandler;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleTailHandler;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue;
import java.util.concurrent.Executor;
import io.netty.channel.Channel;
import io.netty.handler.codec.http2.Http2StreamChannel;
import io.netty.handler.codec.http3.Http3RequestStreamInitializer;
import io.netty.handler.codec.quic.QuicStreamChannel;
public final class Http3TripleClientStream extends AbstractTripleClientStream {
public Http3TripleClientStream(
FrameworkModel frameworkModel,
Executor executor,
Channel parent,
ClientStream.Listener listener,
TripleWriteQueue writeQueue) {
super(frameworkModel, executor, writeQueue, listener, parent);
}
/**
* For test only
*/
public Http3TripleClientStream(
FrameworkModel frameworkModel,
Executor executor,
TripleWriteQueue writeQueue,
ClientStream.Listener listener,
Http2StreamChannel http2StreamChannel) {
super(frameworkModel, executor, writeQueue, listener, http2StreamChannel);
}
@Override
protected TripleStreamChannelFuture initStreamChannel(Channel parent) {
Http3RequestStreamInitializer initializer = new Http3RequestStreamInitializer() {
@Override
protected void initRequestStream(QuicStreamChannel ch) {
ch.pipeline()
.addLast(Http3ClientFrameCodec.INSTANCE)
.addLast(new TripleCommandOutBoundHandler())
.addLast(new TripleHttp2ClientResponseHandler(createTransportListener()))
.addLast(new TripleGoAwayHandler())
.addLast(new TripleTailHandler());
}
};
TripleStreamChannelFuture future = new TripleStreamChannelFuture(parent);
writeQueue.enqueue(Http3CreateStreamQueueCommand.create(initializer, future));
return future;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/GenericHttp3ServerTransportListenerFactory.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/GenericHttp3ServerTransportListenerFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h3;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http3.Http3ServerTransportListenerFactory;
import org.apache.dubbo.remoting.http3.Http3TransportListener;
import org.apache.dubbo.rpc.model.FrameworkModel;
@Activate
public class GenericHttp3ServerTransportListenerFactory implements Http3ServerTransportListenerFactory {
@Override
public Http3TransportListener newInstance(H2StreamChannel streamChannel, URL url, FrameworkModel frameworkModel) {
return new GenericHttp3ServerTransportListener(streamChannel, url, frameworkModel);
}
@Override
public boolean supportContentType(String contentType) {
return true;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/Http3TripleServerConnectionHandler.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/Http3TripleServerConnectionHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h3;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http3.Http3GoAwayFrame;
import io.netty.util.ReferenceCountUtil;
public class Http3TripleServerConnectionHandler extends ChannelDuplexHandler {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof Http3GoAwayFrame) {
ReferenceCountUtil.release(msg);
return;
}
super.channelRead(ctx, msg);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
super.close(ctx, promise);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/Http3ClientFrameCodec.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/Http3ClientFrameCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h3;
import org.apache.dubbo.common.logger.FluentLogger;
import org.apache.dubbo.remoting.http12.HttpConstants;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.remoting.http3.netty4.Constants;
import org.apache.dubbo.remoting.http3.netty4.Http2HeadersAdapter;
import org.apache.dubbo.remoting.http3.netty4.Http3HeadersAdapter;
import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.DefaultHttp2PingFrame;
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Headers.PseudoHeaderName;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2PingFrame;
import io.netty.handler.codec.http3.DefaultHttp3DataFrame;
import io.netty.handler.codec.http3.DefaultHttp3Headers;
import io.netty.handler.codec.http3.DefaultHttp3HeadersFrame;
import io.netty.handler.codec.http3.Http3;
import io.netty.handler.codec.http3.Http3DataFrame;
import io.netty.handler.codec.http3.Http3ErrorCode;
import io.netty.handler.codec.http3.Http3Exception;
import io.netty.handler.codec.http3.Http3GoAwayFrame;
import io.netty.handler.codec.http3.Http3Headers;
import io.netty.handler.codec.http3.Http3HeadersFrame;
import io.netty.handler.codec.http3.Http3RequestStreamInitializer;
import io.netty.handler.codec.quic.QuicChannel;
import io.netty.handler.codec.quic.QuicStreamChannel;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RECONNECT;
@Sharable
public class Http3ClientFrameCodec extends ChannelDuplexHandler {
private static final FluentLogger LOGGER = FluentLogger.of(Http3ClientFrameCodec.class);
public static final Http3ClientFrameCodec INSTANCE = new Http3ClientFrameCodec();
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof Http3HeadersFrame) {
Http3Headers headers = ((Http3HeadersFrame) msg).headers();
if (headers.contains(Constants.TRI_PING)) {
pingAck(ctx);
} else {
boolean endStream = headers.contains(TripleHeaderEnum.STATUS_KEY.getKey());
ctx.fireChannelRead(new DefaultHttp2HeadersFrame(new Http2HeadersAdapter(headers), endStream));
}
} else if (msg instanceof Http3DataFrame) {
ctx.fireChannelRead(new DefaultHttp2DataFrame(((Http3DataFrame) msg).content()));
} else if (msg instanceof Http3GoAwayFrame) {
ctx.fireUserEventTriggered(new DefaultHttp2GoAwayFrame(((Http3GoAwayFrame) msg).id()));
} else {
ctx.fireChannelRead(msg);
}
}
private void pingAck(ChannelHandlerContext ctx) {
ChannelPipeline pipeline = ctx.channel().parent().pipeline();
pipeline.fireChannelRead(new DefaultHttp2PingFrame(0, true));
pipeline.fireChannelReadComplete();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
if (ctx instanceof QuicStreamChannel) {
ctx.fireChannelRead(new DefaultHttp2DataFrame(Unpooled.EMPTY_BUFFER, true));
} else {
ctx.fireChannelReadComplete();
}
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof Http2HeadersFrame) {
Http2HeadersFrame frame = (Http2HeadersFrame) msg;
if (frame.isEndStream()) {
ChannelFuture future = ctx.write(
new DefaultHttp3HeadersFrame(new Http3HeadersAdapter(frame.headers())), ctx.newPromise());
if (future.isDone()) {
((QuicStreamChannel) ctx.channel()).shutdownOutput(promise);
} else {
future.addListener(
(ChannelFutureListener) f -> ((QuicStreamChannel) ctx.channel()).shutdownOutput(promise));
}
return;
}
ctx.write(new DefaultHttp3HeadersFrame(new Http3HeadersAdapter(frame.headers())), promise);
} else if (msg instanceof Http2DataFrame) {
Http2DataFrame frame = (Http2DataFrame) msg;
if (frame.isEndStream()) {
if (Unpooled.EMPTY_BUFFER.equals(frame.content())) {
((QuicStreamChannel) ctx.channel()).shutdownOutput(promise);
return;
}
ChannelFuture future = ctx.write(new DefaultHttp3DataFrame(frame.content()), ctx.newPromise());
if (future.isDone()) {
((QuicStreamChannel) ctx.channel()).shutdownOutput(promise);
} else {
future.addListener(
(ChannelFutureListener) f -> ((QuicStreamChannel) ctx.channel()).shutdownOutput(promise));
}
return;
}
if (Unpooled.EMPTY_BUFFER.equals(frame.content())) {
promise.trySuccess();
return;
}
ctx.write(new DefaultHttp3DataFrame(frame.content()), promise);
} else if (msg instanceof Http2PingFrame) {
sendPing((QuicChannel) ctx.channel());
} else {
ctx.write(msg, promise);
}
}
private void sendPing(QuicChannel channel) {
Http3.newRequestStream(channel, new Http3RequestStreamInitializer() {
@Override
protected void initRequestStream(QuicStreamChannel ch) {
ch.pipeline().addLast(INSTANCE);
}
})
.addListener(future -> {
if (future.isSuccess()) {
QuicStreamChannel streamChannel = (QuicStreamChannel) future.getNow();
Http3Headers header = new DefaultHttp3Headers(false);
header.set(PseudoHeaderName.METHOD.value(), HttpMethods.OPTIONS.name());
header.set(PseudoHeaderName.PATH.value(), "*");
header.set(PseudoHeaderName.SCHEME.value(), HttpConstants.HTTPS);
header.set(Constants.TRI_PING, "0");
ChannelFuture pingSentFuture =
streamChannel.write(new DefaultHttp3HeadersFrame(header), streamChannel.newPromise());
if (pingSentFuture.isDone()) {
streamChannel.shutdownOutput();
} else {
pingSentFuture.addListener((ChannelFutureListener) f -> streamChannel.shutdownOutput());
}
} else {
LOGGER.warn(TRANSPORT_FAILED_RECONNECT, "Failed to send ping frame", future.cause());
}
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (cause instanceof Http3Exception) {
Http3Exception e = (Http3Exception) cause;
Http3ErrorCode errorCode = e.errorCode();
if (errorCode == Http3ErrorCode.H3_CLOSED_CRITICAL_STREAM) {
ctx.fireUserEventTriggered(new DefaultHttp2ResetFrame(256 + errorCode.ordinal()));
return;
}
}
super.exceptionCaught(ctx, cause);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/Helper.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/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.h3;
import org.apache.dubbo.remoting.http12.HttpConstants;
import org.apache.dubbo.remoting.http12.HttpHeaderNames;
import org.apache.dubbo.remoting.http12.HttpHeaders;
import org.apache.dubbo.remoting.http12.HttpMetadata;
import org.apache.dubbo.remoting.http12.h2.Http2MetadataFrame;
import org.apache.dubbo.remoting.http12.netty4.NettyHttpHeaders;
import io.netty.handler.codec.http3.DefaultHttp3Headers;
public final class Helper {
private Helper() {}
public static HttpMetadata encodeHttpMetadata(boolean endStream) {
HttpHeaders headers = new NettyHttpHeaders<>(new DefaultHttp3Headers(false, 8));
headers.set(HttpHeaderNames.TE.getKey(), HttpConstants.TRAILERS);
return new Http2MetadataFrame(headers, endStream);
}
public static HttpMetadata encodeTrailers() {
return new Http2MetadataFrame(new NettyHttpHeaders<>(new DefaultHttp3Headers(false, 4)), true);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/negotiation/AutoSwitchConnectionClient.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/negotiation/AutoSwitchConnectionClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h3.negotiation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.rpc.protocol.tri.TripleConstants;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT;
public class AutoSwitchConnectionClient extends AbstractConnectionClient {
private static final int MAX_RETRIES = 8;
private final URL url;
private final AbstractConnectionClient connectionClient;
private AbstractConnectionClient http3ConnectionClient;
private ScheduledExecutorService executor;
private NegotiateClientCall clientCall;
private boolean negotiated = false;
private boolean http3Connected = false;
private final AtomicBoolean scheduling = new AtomicBoolean();
private int attempt = 0;
public AutoSwitchConnectionClient(URL url, AbstractConnectionClient connectionClient) {
this.url = url;
this.connectionClient = connectionClient;
executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-http3-negotiation"));
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
connectionClient.addConnectedListener(() -> ClassUtils.runWith(tccl, () -> executor.execute(this::negotiate)));
increase();
if (logger.isInfoEnabled()) {
logger.info(
"Start HTTP/3 AutoSwitchConnectionClient {} connect to the server {}",
NetUtils.getLocalAddress(),
url.toInetSocketAddress());
}
}
private String getBaseUrl() {
boolean ssl = url.getParameter(CommonConstants.SSL_ENABLED_KEY, false);
CharSequence scheme = ssl ? TripleConstants.HTTPS_SCHEME : TripleConstants.HTTP_SCHEME;
return scheme + "://" + url.getHost() + ':' + url.getPort() + '/';
}
private void negotiate() {
if (negotiated) {
return;
}
scheduling.set(false);
if (clientCall == null) {
clientCall = new NegotiateClientCall(connectionClient, executor);
}
logger.info("Start HTTP/3 negotiation for [{}]", getBaseUrl());
clientCall.start(url).whenComplete((altSvc, t) -> {
if (t == null) {
if (altSvc.contains("h3=")) {
negotiateSuccess();
return;
}
logger.info(
"HTTP/3 negotiation succeed, but provider reply alt-svc='{}' not support HTTP/3 for [{}]",
altSvc,
getBaseUrl());
return;
}
if (scheduling.compareAndSet(false, true)) {
reScheduleNegotiate(t);
}
});
}
private void negotiateSuccess() {
negotiated = true;
logger.info("HTTP/3 negotiation succeed for [{}], create http3 client", getBaseUrl());
http3ConnectionClient = Helper.createHttp3Client(url, connectionClient.getDelegateHandler());
http3ConnectionClient.addConnectedListener(() -> setHttp3Connected(true));
http3ConnectionClient.addDisconnectedListener(() -> setHttp3Connected(false));
negotiateEnd();
}
private void reScheduleNegotiate(Throwable t) {
if (attempt++ < MAX_RETRIES) {
int delay = 1 << attempt + 2;
logger.info("HTTP/3 negotiation failed, retry after {} seconds for [{}]", delay, getBaseUrl(), t);
executor.schedule(this::negotiate, delay, TimeUnit.SECONDS);
return;
}
logger.warn(
PROTOCOL_ERROR_CLOSE_CLIENT,
"",
"",
"Max retries " + MAX_RETRIES + " reached, HTTP/3 negotiation failed for " + getBaseUrl(),
t);
negotiateEnd();
}
private void negotiateEnd() {
scheduling.set(false);
executor.shutdown();
executor = null;
clientCall = null;
}
private void setHttp3Connected(boolean http3Connected) {
this.http3Connected = http3Connected;
logger.info("Switch protocol to {} for [{}]", http3Connected ? "HTTP/3" : "HTTP/2", url.toString(""));
}
public boolean isHttp3Connected() {
return http3Connected;
}
@Override
public boolean isConnected() {
return http3Connected ? http3ConnectionClient.isConnected() : connectionClient.isConnected();
}
@Override
public InetSocketAddress getLocalAddress() {
return http3Connected ? http3ConnectionClient.getLocalAddress() : connectionClient.getLocalAddress();
}
@Override
public boolean release() {
try {
connectionClient.release();
} catch (Throwable t) {
logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", t.getMessage(), t);
}
if (http3ConnectionClient != null) {
try {
http3ConnectionClient.release();
} catch (Throwable t) {
logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", t.getMessage(), t);
}
}
return true;
}
@Override
protected void initConnectionClient() {
throw new UnsupportedOperationException();
}
@Override
public boolean isAvailable() {
return http3Connected ? http3ConnectionClient.isAvailable() : connectionClient.isAvailable();
}
@Override
public void addCloseListener(Runnable func) {
connectionClient.addCloseListener(func);
}
@Override
public void addConnectedListener(Runnable func) {
throw new UnsupportedOperationException();
}
@Override
public void addDisconnectedListener(Runnable func) {
throw new UnsupportedOperationException();
}
@Override
public void onConnected(Object channel) {
throw new UnsupportedOperationException();
}
@Override
public void onGoaway(Object channel) {
throw new UnsupportedOperationException();
}
@Override
public void destroy() {
connectionClient.destroy();
if (http3ConnectionClient != null) {
http3ConnectionClient.destroy();
}
}
@Override
public <T> T getChannel(Boolean generalizable) {
return http3Connected
? http3ConnectionClient.getChannel(generalizable)
: connectionClient.getChannel(generalizable);
}
@Override
protected void doOpen() {
throw new UnsupportedOperationException();
}
@Override
protected void doClose() {
throw new UnsupportedOperationException();
}
@Override
protected void doConnect() {
throw new UnsupportedOperationException();
}
@Override
protected void doDisConnect() {
throw new UnsupportedOperationException();
}
@Override
protected Channel getChannel() {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
return "AutoSwitchConnectionClient{" + "http3Enabled=" + http3Connected + ", http3=" + http3ConnectionClient
+ ", http2=" + connectionClient + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/negotiation/NegotiateClientCall.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/negotiation/NegotiateClientCall.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h3.negotiation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.remoting.http12.HttpHeaderNames;
import org.apache.dubbo.rpc.TriRpcStatus;
import org.apache.dubbo.rpc.protocol.tri.TripleConstants;
import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
import org.apache.dubbo.rpc.protocol.tri.transport.H2TransportListener;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleHttp2ClientResponseHandler;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2StreamChannel;
import io.netty.handler.codec.http2.Http2StreamChannelBootstrap;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.util.concurrent.Future;
public class NegotiateClientCall {
private final AbstractConnectionClient connectionClient;
private final Executor executor;
public NegotiateClientCall(AbstractConnectionClient connectionClient, Executor executor) {
this.connectionClient = connectionClient;
this.executor = executor;
}
public CompletableFuture<String> start(URL url) {
CompletableFuture<String> future = new CompletableFuture<>();
try {
Channel channel = connectionClient.getChannel(true);
if (channel == null) {
future.completeExceptionally(new IllegalStateException("Channel is null"));
return future;
}
Http2StreamChannelBootstrap bootstrap = new Http2StreamChannelBootstrap(channel);
bootstrap.handler(new ChannelInboundHandlerAdapter() {
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
ctx.channel()
.pipeline()
.addLast(new ReadTimeoutHandler(12, TimeUnit.SECONDS))
.addLast(new TripleHttp2ClientResponseHandler(new Listener(executor, future)));
}
});
Future<Http2StreamChannel> streamFuture = bootstrap.open();
streamFuture.addListener(f -> {
if (f.isSuccess()) {
streamFuture.getNow().writeAndFlush(buildHeaders(url)).addListener(cf -> {
if (cf.isSuccess()) {
return;
}
future.completeExceptionally(cf.cause());
});
return;
}
future.completeExceptionally(f.cause());
});
} catch (Throwable t) {
future.completeExceptionally(t);
}
return future;
}
private Http2HeadersFrame buildHeaders(URL url) {
Http2Headers headers = new DefaultHttp2Headers(false);
boolean ssl = url.getParameter(CommonConstants.SSL_ENABLED_KEY, false);
CharSequence scheme = ssl ? TripleConstants.HTTPS_SCHEME : TripleConstants.HTTP_SCHEME;
headers.scheme(scheme)
.authority(url.getAddress())
.method(HttpMethod.OPTIONS.asciiName())
.path("/")
.set(TripleHeaderEnum.SERVICE_TIMEOUT.name(), "10000");
return new DefaultHttp2HeadersFrame(headers, true);
}
private static final class Listener implements H2TransportListener {
private final Executor executor;
private final CompletableFuture<String> future;
Listener(Executor executor, CompletableFuture<String> future) {
this.executor = executor;
this.future = future;
}
@Override
public void onHeader(Http2Headers headers, boolean endStream) {
CharSequence line = headers.status();
if (line != null) {
HttpResponseStatus status = HttpResponseStatus.parseLine(line);
if (status.code() < 500) {
CharSequence altSvc = headers.get(HttpHeaderNames.ALT_SVC.getKey());
executor.execute(() -> future.complete(String.valueOf(altSvc)));
return;
}
}
if (endStream) {
return;
}
executor.execute(() -> future.completeExceptionally(new RuntimeException("Status: " + line)));
}
@Override
public void onData(ByteBuf data, boolean endStream) {}
@Override
public void cancelByRemote(long errorCode) {
executor.execute(() -> future.completeExceptionally(new RuntimeException("Canceled by remote")));
}
@Override
public void onClose() {
if (future.isDone()) {
return;
}
cancelByRemote(TriRpcStatus.CANCELLED.code.code);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/negotiation/AdaptiveClientStreamFactory.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/negotiation/AdaptiveClientStreamFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h3.negotiation;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.call.TripleClientCall;
import org.apache.dubbo.rpc.protocol.tri.h12.http2.Http2TripleClientStream;
import org.apache.dubbo.rpc.protocol.tri.h3.Http3TripleClientStream;
import org.apache.dubbo.rpc.protocol.tri.stream.ClientStream;
import org.apache.dubbo.rpc.protocol.tri.stream.ClientStreamFactory;
import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue;
import java.util.concurrent.Executor;
import io.netty.channel.Channel;
@Activate(order = -90, onClass = "io.netty.handler.codec.quic.QuicChannel")
public class AdaptiveClientStreamFactory implements ClientStreamFactory {
@Override
public ClientStream createClientStream(
AbstractConnectionClient client,
FrameworkModel frameworkModel,
Executor executor,
TripleClientCall clientCall,
TripleWriteQueue writeQueue) {
if (client instanceof AutoSwitchConnectionClient) {
Channel channel = client.getChannel(true);
if (((AutoSwitchConnectionClient) client).isHttp3Connected()) {
return new Http3TripleClientStream(frameworkModel, executor, channel, clientCall, writeQueue);
}
return new Http2TripleClientStream(frameworkModel, executor, channel, clientCall, writeQueue);
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/negotiation/Helper.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/negotiation/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.h3.negotiation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.remoting.exchange.PortUnificationExchanger;
import org.apache.dubbo.remoting.transport.netty4.NettyHttp3ConnectionClient;
import org.apache.dubbo.rpc.protocol.tri.ExceptionUtils;
public class Helper {
private Helper() {}
public static AbstractConnectionClient createAutoSwitchClient(URL url, ChannelHandler handler) {
return new AutoSwitchConnectionClient(url, PortUnificationExchanger.connect(url, handler));
}
public static AbstractConnectionClient createHttp3Client(URL url, ChannelHandler handler) {
try {
return new NettyHttp3ConnectionClient(url, handler);
} catch (RemotingException e) {
throw ExceptionUtils.wrap(e);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/grpc/GrpcHttp3UnaryServerChannelObserver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/grpc/GrpcHttp3UnaryServerChannelObserver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h3.grpc;
import org.apache.dubbo.remoting.http12.HttpMetadata;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.h12.grpc.GrpcUnaryServerChannelObserver;
import org.apache.dubbo.rpc.protocol.tri.h3.Helper;
public class GrpcHttp3UnaryServerChannelObserver extends GrpcUnaryServerChannelObserver {
public GrpcHttp3UnaryServerChannelObserver(FrameworkModel frameworkModel, H2StreamChannel h2StreamChannel) {
super(frameworkModel, h2StreamChannel);
}
@Override
protected HttpMetadata encodeHttpMetadata(boolean endStream) {
return Helper.encodeHttpMetadata(endStream);
}
@Override
protected HttpMetadata encodeTrailers(Throwable throwable) {
return Helper.encodeTrailers();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/grpc/GrpcHttp3ServerTransportListenerFactory.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/grpc/GrpcHttp3ServerTransportListenerFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h3.grpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http3.Http3ServerTransportListenerFactory;
import org.apache.dubbo.remoting.http3.Http3TransportListener;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.h12.grpc.GrpcUtils;
@Activate(order = -100, onClass = CommonConstants.PROTOBUF_MESSAGE_CLASS_NAME)
public class GrpcHttp3ServerTransportListenerFactory implements Http3ServerTransportListenerFactory {
@Override
public Http3TransportListener newInstance(H2StreamChannel streamChannel, URL url, FrameworkModel frameworkModel) {
return new GrpcHttp3ServerTransportListener(streamChannel, url, frameworkModel);
}
@Override
public boolean supportContentType(String contentType) {
return GrpcUtils.isGrpcRequest(contentType);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/grpc/GrpcHttp3ServerChannelObserver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/grpc/GrpcHttp3ServerChannelObserver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h3.grpc;
import org.apache.dubbo.remoting.http12.HttpMetadata;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.h12.grpc.GrpcStreamServerChannelObserver;
import org.apache.dubbo.rpc.protocol.tri.h3.Helper;
public final class GrpcHttp3ServerChannelObserver extends GrpcStreamServerChannelObserver {
public GrpcHttp3ServerChannelObserver(FrameworkModel frameworkModel, H2StreamChannel h2StreamChannel) {
super(frameworkModel, h2StreamChannel);
}
@Override
protected HttpMetadata encodeHttpMetadata(boolean endStream) {
return Helper.encodeHttpMetadata(endStream);
}
@Override
protected HttpMetadata encodeTrailers(Throwable throwable) {
return Helper.encodeTrailers();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/grpc/GrpcHttp3ServerTransportListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h3/grpc/GrpcHttp3ServerTransportListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.h3.grpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http12.h2.Http2InputMessage;
import org.apache.dubbo.remoting.http12.h2.Http2ServerChannelObserver;
import org.apache.dubbo.remoting.http3.Http3TransportListener;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.h12.grpc.GrpcHttp2ServerTransportListener;
public final class GrpcHttp3ServerTransportListener extends GrpcHttp2ServerTransportListener
implements Http3TransportListener {
public GrpcHttp3ServerTransportListener(H2StreamChannel h2StreamChannel, URL url, FrameworkModel frameworkModel) {
super(h2StreamChannel, url, frameworkModel);
}
@Override
protected Http2ServerChannelObserver newResponseObserver(H2StreamChannel h2StreamChannel) {
return new GrpcHttp3UnaryServerChannelObserver(getFrameworkModel(), h2StreamChannel);
}
@Override
protected Http2ServerChannelObserver newStreamResponseObserver(H2StreamChannel h2StreamChannel) {
return new GrpcHttp3ServerChannelObserver(getFrameworkModel(), h2StreamChannel);
}
@Override
protected void doOnData(Http2InputMessage message) {
if (message.isEndStream()) {
onDataCompletion(message);
return;
}
super.doOnData(message);
}
@Override
protected void initializeAltSvc(URL url) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/TriDecoder.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/TriDecoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.frame;
import org.apache.dubbo.common.config.Configuration;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
public class TriDecoder implements Deframer {
private static final int HEADER_LENGTH = 5;
private static final int COMPRESSED_FLAG_MASK = 1;
private static final int RESERVED_MASK = 0xFE;
private final CompositeByteBuf accumulate = Unpooled.compositeBuffer();
private final Listener listener;
private final DeCompressor decompressor;
private final Integer maxMessageSize;
private boolean compressedFlag;
private long pendingDeliveries;
private boolean inDelivery = false;
private boolean closing;
private boolean closed;
private int requiredLength = HEADER_LENGTH;
private GrpcDecodeState state = GrpcDecodeState.HEADER;
public TriDecoder(DeCompressor decompressor, Listener listener) {
Configuration conf = ConfigurationUtils.getEnvConfiguration(ApplicationModel.defaultModel());
maxMessageSize = conf.getInteger(Constants.H2_SETTINGS_MAX_MESSAGE_SIZE, 50 * 1024 * 1024);
this.decompressor = decompressor;
this.listener = listener;
}
@Override
public void deframe(ByteBuf data) {
if (closing || closed) {
// ignored
return;
}
accumulate.addComponent(true, data);
deliver();
}
public void request(int numMessages) {
pendingDeliveries += numMessages;
deliver();
}
@Override
public void close() {
closing = true;
deliver();
}
private void deliver() {
// We can have reentrancy here when using a direct executor, triggered by calls to
// request more messages. This is safe as we simply loop until pendingDelivers = 0
if (inDelivery) {
return;
}
inDelivery = true;
try {
// Process the uncompressed bytes.
while (pendingDeliveries > 0 && hasEnoughBytes()) {
switch (state) {
case HEADER:
processHeader();
break;
case PAYLOAD:
// Read the body and deliver the message.
processBody();
// Since we've delivered a message, decrement the number of pending
// deliveries remaining.
pendingDeliveries--;
break;
default:
throw new AssertionError("Invalid state: " + state);
}
}
if (closing) {
if (!closed) {
closed = true;
accumulate.clear();
accumulate.release();
listener.close();
}
}
} finally {
inDelivery = false;
}
}
private boolean hasEnoughBytes() {
return requiredLength - accumulate.readableBytes() <= 0;
}
/**
* Processes the GRPC compression header which is composed of the compression flag and the outer
* frame length.
*/
private void processHeader() {
int type = accumulate.readUnsignedByte();
if ((type & RESERVED_MASK) != 0) {
throw new RpcException("gRPC frame header malformed: reserved bits not zero");
}
compressedFlag = (type & COMPRESSED_FLAG_MASK) != 0;
requiredLength = accumulate.readInt();
if (requiredLength < 0) {
throw new RpcException("Invalid message length: " + requiredLength);
}
if (requiredLength > maxMessageSize) {
throw new RpcException(String.format("Message size %d exceeds limit %d", requiredLength, maxMessageSize));
}
// Continue reading the frame body.
state = GrpcDecodeState.PAYLOAD;
}
/**
* Processes the GRPC message body, which depending on frame header flags may be compressed.
*/
private void processBody() {
// There is no reliable way to get the uncompressed size per message when it's compressed,
// because the uncompressed bytes are provided through an InputStream whose total size is
// unknown until all bytes are read, and we don't know when it happens.
byte[] stream = compressedFlag ? getCompressedBody() : getUncompressedBody();
listener.onRawMessage(stream);
// Done with this frame, begin processing the next header.
state = GrpcDecodeState.HEADER;
requiredLength = HEADER_LENGTH;
}
private byte[] getCompressedBody() {
final byte[] compressedBody = getUncompressedBody();
return decompressor.decompress(compressedBody);
}
private byte[] getUncompressedBody() {
byte[] data = new byte[requiredLength];
accumulate.readBytes(data);
accumulate.discardReadComponents();
return data;
}
private enum GrpcDecodeState {
HEADER,
PAYLOAD
}
public interface Listener {
void onRawMessage(byte[] data);
void close();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/Deframer.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/Deframer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.frame;
import io.netty.buffer.ByteBuf;
public interface Deframer {
/**
* Adds the given data to this deframer and attempts delivery to the listener.
*
* @param data the raw data read from the remote endpoint. Must be non-null.
*/
void deframe(ByteBuf data);
/**
* Requests up to the given number of messages from the call. No additional messages will be
* delivered.
*
* <p>If {@link #close()} has been called, this method will have no effect.
*
* @param numMessages the requested number of messages to be delivered to the listener.
*/
void request(int numMessages);
/**
* Closes this deframer and frees any resources. After this method is called, additional calls
* will have no effect.
*/
void close();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/RestConstants.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/RestConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.message.HttpMessageDecoder;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMapping;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.HandlerMeta;
public final class RestConstants {
public static final String REST_FILTER_KEY = "rest.filter";
public static final String EXTENSION_KEY = "extension";
public static final int DIALECT_BASIC = 0;
public static final int DIALECT_SPRING_MVC = 1;
public static final int DIALECT_JAXRS = 2;
public static final String HEADER_SERVICE_VERSION = "rest-service-version";
public static final String HEADER_SERVICE_GROUP = "rest-service-group";
public static final String SLASH = "/";
/* Request Attribute */
public static final String BODY_ATTRIBUTE = HttpRequest.class.getName() + ".body";
public static final String BODY_DECODER_ATTRIBUTE = HttpMessageDecoder.class.getName() + ".body";
public static final String SIG_ATTRIBUTE = RequestMapping.class.getName() + ".sig";
public static final String MAPPING_ATTRIBUTE = RequestMapping.class.getName();
public static final String HANDLER_ATTRIBUTE = HandlerMeta.class.getName();
public static final String PATH_ATTRIBUTE = "org.springframework.web.util.UrlPathHelper.PATH";
public static final String URI_TEMPLATE_VARIABLES_ATTRIBUTE =
"org.springframework.web.servlet.HandlerMapping.uriTemplateVariables";
public static final String PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE =
"org.springframework.web.servlet.HandlerMapping.producibleMediaTypes";
/* Configuration Key */
public static final String CONFIG_PREFIX = "dubbo.protocol.triple.rest.";
private RestConstants() {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/PathParserException.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/PathParserException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
public final class PathParserException extends RestException {
private static final long serialVersionUID = 1L;
public PathParserException(Messages message, Object... arguments) {
super(message, arguments);
}
public PathParserException(Messages message, Throwable cause, Object... arguments) {
super(cause, message, arguments);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/RestException.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/RestException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.remoting.http12.exception.HttpStatusException;
import org.apache.dubbo.rpc.protocol.tri.ExceptionUtils;
public class RestException extends HttpStatusException {
private static final long serialVersionUID = 1L;
private final Messages message;
private final String displayMessage;
public RestException(String message) {
super(500, message);
this.message = Messages.INTERNAL_ERROR;
displayMessage = null;
}
public RestException(Throwable cause) {
super(500, ExceptionUtils.unwrap(cause));
message = Messages.INTERNAL_ERROR;
displayMessage = null;
}
public RestException(String message, Throwable cause) {
super(500, message, ExceptionUtils.unwrap(cause));
this.message = Messages.INTERNAL_ERROR;
displayMessage = null;
}
public RestException(Messages message, Object... arguments) {
super(message.statusCode(), message.format(arguments));
this.message = message;
displayMessage = message.formatDisplay(arguments);
}
public RestException(Throwable cause, Messages message, Object... arguments) {
super(message.statusCode(), message.format(arguments), ExceptionUtils.unwrap(cause));
this.message = message;
displayMessage = message.formatDisplay(arguments);
}
public String getErrorCode() {
return message.name();
}
@Override
public String getDisplayMessage() {
return displayMessage == null ? getMessage() : displayMessage;
}
@Override
public String toString() {
return getClass().getName() + ": status=" + getStatusCode() + ", " + getErrorCode() + ", " + getMessage();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/Messages.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/Messages.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.common.utils.ArrayUtils;
import java.text.MessageFormat;
public enum Messages {
MISSING_CLOSE_CAPTURE("Expected close capture character after variable name '}' for path ''{0}'' at index {1}"),
MISSING_OPEN_CAPTURE("Missing preceding open capture character before variable name '{' for path ''{0}''"),
ILLEGAL_NESTED_CAPTURE("Not allowed to nest variable captures for path ''{0}'' at index {1}"),
ILLEGAL_DOUBLE_CAPTURE("Not allowed to capture ''{0}'' twice in the same pattern"),
DUPLICATE_CAPTURE_VARIABLE("Duplicate capture variable ''{0}''"),
MISSING_REGEX_CONSTRAINT("Missing regex constraint on capture for path ''{0}'' at index {1}"),
REGEX_PATTERN_INVALID("Invalid regex pattern ''{0}'' for path ''{0}''"),
NO_MORE_DATA_ALLOWED("No more data allowed after '{*...}' or '**' pattern segment for path ''{0}'' at index {1}"),
CANNOT_COMBINE_PATHS("Cannot combine paths: ''{0}'' vs ''{1}''"),
DUPLICATE_MAPPING(
"Duplicate mapping for ''{0}'': mapping={1}, method={2}, exists={3}", "Duplicate mapping for ''{0}''"),
AMBIGUOUS_MAPPING("Ambiguous mapping for ''{0}'': [{1}, {2}]", "Ambiguous mapping for ''{0}''"),
EXTENSION_INIT_FAILED(
"Rest extension: ''{0}'' initialization failed for invoker: ''{1}''",
"Rest extension initialization failed"),
ARGUMENT_NAME_MISSING("Name for argument of type [{0}] not specified, and parameter name information not "
+ "available via reflection. Ensure that the compiler uses the '-parameters' flag"),
ARGUMENT_VALUE_MISSING("Missing argument ''{0}'' for method parameter of type [{1}]", 400),
ARGUMENT_CONVERT_ERROR("Could not convert argument ''{0}'' value ''{1}'' from type [{2}] to type [{3}]", 400),
ARGUMENT_COULD_NOT_RESOLVED("Could not resolve ''{0}'', no suitable resolver", 400),
ARGUMENT_BIND_ERROR("Bind argument ''{0}'' of type [{1}] error", 400),
BAD_REQUEST("Rest Bad Request", 400),
INTERNAL_ERROR("Rest Internal Error");
private final String message;
private final String displayMessage;
private final int statusCode;
Messages(String message) {
this.message = message;
displayMessage = null;
statusCode = 500;
}
Messages(String message, String displayMessage) {
this.message = message;
this.displayMessage = displayMessage;
statusCode = 500;
}
Messages(String message, int statusCode) {
this.message = message;
displayMessage = null;
this.statusCode = statusCode;
}
Messages(String message, String displayMessage, int statusCode) {
this.message = message;
this.displayMessage = displayMessage;
this.statusCode = statusCode;
}
public int statusCode() {
return statusCode;
}
public String format(Object... args) {
return ArrayUtils.isEmpty(args) ? message : MessageFormat.format(message, args);
}
public String formatDisplay(Object... args) {
return displayMessage == null || ArrayUtils.isEmpty(args)
? displayMessage
: MessageFormat.format(displayMessage, args);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/RestParameterException.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/RestParameterException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
public class RestParameterException extends RestException {
private static final long serialVersionUID = 1L;
public RestParameterException(String message) {
super(message);
}
public RestParameterException(Throwable cause) {
super(cause);
}
public RestParameterException(String message, Throwable cause) {
super(message, cause);
}
public RestParameterException(Messages message, Object... arguments) {
super(message, arguments);
}
public RestParameterException(Throwable cause, Messages message, Object... arguments) {
super(cause, message, arguments);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/RestHttpMessageCodec.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/RestHttpMessageCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
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.exception.DecodeException;
import org.apache.dubbo.remoting.http12.exception.EncodeException;
import org.apache.dubbo.remoting.http12.exception.HttpStatusException;
import org.apache.dubbo.remoting.http12.message.HttpMessageDecoder;
import org.apache.dubbo.remoting.http12.message.HttpMessageEncoder;
import org.apache.dubbo.remoting.http12.message.MediaType;
import org.apache.dubbo.rpc.protocol.tri.rest.argument.ArgumentResolver;
import org.apache.dubbo.rpc.protocol.tri.rest.argument.TypeConverter;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Optional;
public final class RestHttpMessageCodec implements HttpMessageDecoder, HttpMessageEncoder {
private static final Object[] EMPTY_ARGS = new Object[0];
private final HttpRequest request;
private final HttpResponse response;
private final ParameterMeta[] parameters;
private final ArgumentResolver argumentResolver;
private final TypeConverter typeConverter;
private final HttpMessageEncoder messageEncoder;
private final Charset charset;
public RestHttpMessageCodec(
HttpRequest request,
HttpResponse response,
ParameterMeta[] parameters,
ArgumentResolver argumentResolver,
TypeConverter typeConverter,
HttpMessageEncoder messageEncoder) {
this.request = request;
this.response = response;
this.parameters = parameters;
this.argumentResolver = argumentResolver;
this.typeConverter = typeConverter;
this.messageEncoder = messageEncoder;
charset = request.charsetOrDefault();
}
public HttpMessageEncoder getMessageEncoder() {
return messageEncoder;
}
@Override
public Object decode(InputStream inputStream, Class<?> targetType, Charset charset) throws DecodeException {
return decode(inputStream, new Class<?>[] {targetType}, charset);
}
@Override
public Object[] decode(InputStream inputStream, Class<?>[] targetTypes, Charset charset) throws DecodeException {
request.setInputStream(decodeInputStream(inputStream));
ParameterMeta[] parameters = this.parameters;
int len = parameters.length;
if (len == 0) {
return EMPTY_ARGS;
}
Object[] args = new Object[len];
for (int i = 0; i < len; i++) {
args[i] = argumentResolver.resolve(parameters[i], request, response);
}
return args;
}
@Override
public void encode(OutputStream os, Object data, Charset charset) throws EncodeException {
encode(os, data);
}
private InputStream decodeInputStream(InputStream is) {
if (is.getClass() == ByteArrayInputStream.class) {
return is;
}
try {
byte[] bytes = new byte[is.available()];
is.read(bytes);
return new ByteArrayInputStream(bytes);
} catch (IOException e) {
throw new DecodeException(e);
}
}
@Override
public void encode(OutputStream os, Object data) throws EncodeException {
if (data != null) {
Class<?> type = data.getClass();
if (type == Optional.class) {
encode(os, ((Optional<?>) data).orElse(null));
return;
}
try {
if (type == byte[].class) {
os.write((byte[]) data);
return;
}
if (type == ByteArrayOutputStream.class) {
((ByteArrayOutputStream) data).writeTo(os);
return;
}
if (data instanceof InputStream) {
try (InputStream is = (InputStream) data) {
StreamUtils.copy(is, os);
}
return;
}
if (messageEncoder.mediaType().isPureText() && type != String.class) {
data = typeConverter.convert(data, String.class);
}
} catch (HttpStatusException e) {
throw e;
} catch (Exception e) {
throw new EncodeException(e);
}
}
messageEncoder.encode(os, data, charset);
}
@Override
public MediaType mediaType() {
return messageEncoder.mediaType();
}
@Override
public String contentType() {
String contentType = response.contentType();
return contentType == null ? messageEncoder.contentType() : contentType;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/RestBadRequestException.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/RestBadRequestException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
public class RestBadRequestException extends RestException {
private static final long serialVersionUID = 1L;
public RestBadRequestException(String message) {
super(Messages.BAD_REQUEST, message);
}
public RestBadRequestException(Throwable cause) {
super(cause, Messages.BAD_REQUEST);
}
public RestBadRequestException(String message, Throwable cause) {
super(cause, Messages.BAD_REQUEST, message);
}
public RestBadRequestException(Messages message, Object... arguments) {
super(message, arguments);
}
public RestBadRequestException(Throwable cause, Messages message, Object... arguments) {
super(cause, message, arguments);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/RestMappingException.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/RestMappingException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
public final class RestMappingException extends RestException {
private static final long serialVersionUID = 1L;
public RestMappingException(Messages message, Object... arguments) {
super(message, arguments);
}
public RestMappingException(Throwable cause, Messages message, Object... arguments) {
super(cause, message, arguments);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/RestInitializeException.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/RestInitializeException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
public final class RestInitializeException extends RestException {
private static final long serialVersionUID = 1L;
public RestInitializeException(Messages message, Object... arguments) {
super(message, arguments);
}
public RestInitializeException(Throwable cause, Messages message, Object... arguments) {
super(cause, message, arguments);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/RequestMappingRegistry.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/RequestMappingRegistry.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.HandlerMeta;
import java.util.Collection;
/**
* RequestMappingRegistry used for registering and unregistering rest request mappings.
*/
public interface RequestMappingRegistry {
void register(Invoker<?> invoker);
void unregister(Invoker<?> invoker);
HandlerMeta lookup(HttpRequest request);
boolean exists(String path, String method);
Collection<Registration> getRegistrations();
void destroy();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/ContentNegotiator.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/ContentNegotiator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpUtils;
import org.apache.dubbo.remoting.http12.message.HttpMessageEncoderFactory;
import org.apache.dubbo.remoting.http12.message.MediaType;
import org.apache.dubbo.remoting.http12.message.codec.CodecUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.HandlerMeta;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ContentNegotiator {
private final CodecUtils codecUtils;
private Map<String, MediaType> extensionMapping;
private String parameterName;
public ContentNegotiator(FrameworkModel frameworkModel) {
codecUtils = frameworkModel.getOrRegisterBean(CodecUtils.class);
}
public String negotiate(HttpRequest request, HandlerMeta meta) {
String mediaType;
// 1. find mediaType by producible
List<MediaType> produces = request.attribute(RestConstants.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
if (produces != null) {
for (int i = 0, size = produces.size(); i < size; i++) {
mediaType = getSuitableMediaType(produces.get(i).getName());
if (mediaType != null) {
return mediaType;
}
}
}
// 2. find mediaType by accept header
List<String> accepts = HttpUtils.parseAccept(request.accept());
String preferMediaType = null;
boolean hasAll = false;
if (accepts != null) {
for (int i = 0, size = accepts.size(); i < size; i++) {
String accept = accepts.get(i);
if (!hasAll && MediaType.ALL.getName().equals(accept)) {
hasAll = true;
}
if (preferMediaType == null) {
mediaType = getSuitableMediaType(accept);
if (mediaType != null) {
preferMediaType = mediaType;
}
}
}
}
// 3. find mediaType by format parameter
String format = request.queryParameter(getParameterName());
if (format != null) {
mediaType = getMediaTypeByExtension(format);
if (mediaType != null) {
return mediaType;
}
}
// 4. find mediaType by extension
String path = request.rawPath();
int index = path.lastIndexOf('.');
if (index != -1) {
mediaType = getMediaTypeByExtension(path.substring(index + 1));
if (mediaType != null) {
return mediaType;
}
}
if (preferMediaType == null) {
return null;
}
// Keep consistent with Spring MVC behavior
if (hasAll && preferMediaType.startsWith("text/")) {
Class<?> responseType = meta.getMethodMetadata().getActualResponseType();
if (responseType != null && !CharSequence.class.isAssignableFrom(responseType)) {
return MediaType.APPLICATION_JSON.getName();
}
}
return preferMediaType;
}
public boolean supportExtension(String extension) {
return getMediaTypeByExtension(extension) != null;
}
private String getSuitableMediaType(String name) {
int index = name.indexOf('/');
if (index == -1 || index == name.length() - 1) {
return null;
}
String type = name.substring(0, index);
if (MediaType.WILDCARD.equals(type)) {
return null;
}
String subType = name.substring(index + 1);
if (MediaType.WILDCARD.equals(subType)) {
return MediaType.TEXT_PLAIN.getType().equals(type) ? MediaType.TEXT_PLAIN.getName() : null;
}
int suffixIndex = subType.lastIndexOf('+');
if (suffixIndex != -1) {
return getMediaTypeByExtension(subType.substring(suffixIndex + 1));
}
return name;
}
public String getParameterName() {
if (parameterName == null) {
parameterName = ConfigManager.getProtocolOrDefault(CommonConstants.TRIPLE)
.getTripleOrDefault()
.getRestOrDefault()
.getFormatParameterNameOrDefault();
}
return parameterName;
}
private String getMediaTypeByExtension(String extension) {
Map<String, MediaType> extensionMapping = this.extensionMapping;
if (extensionMapping == null) {
extensionMapping = new HashMap<>();
for (HttpMessageEncoderFactory factory : codecUtils.getEncoderFactories()) {
MediaType mediaType = factory.mediaType();
String subType = mediaType.getSubType();
int index = subType.lastIndexOf('+');
if (index != -1) {
subType = subType.substring(index + 1);
}
extensionMapping.putIfAbsent(subType, mediaType);
}
extensionMapping.put("css", MediaType.TEXT_CSS);
extensionMapping.put("js", MediaType.TEXT_JAVASCRIPT);
extensionMapping.put("yml", MediaType.APPLICATION_YAML);
extensionMapping.put("xhtml", MediaType.TEXT_HTML);
extensionMapping.put("html", MediaType.TEXT_HTML);
extensionMapping.put("htm", MediaType.TEXT_HTML);
extensionMapping.put("proto", new MediaType(MediaType.TEXT, "proto"));
for (String ext : new String[] {"txt", "md", "csv", "log", "properties"}) {
extensionMapping.put(ext, MediaType.TEXT_PLAIN);
}
for (String ext : new String[] {"jpg", "jpeg", "png", "gif", "bmp", "svg", "webp", "tiff", "ico"}) {
extensionMapping.put(ext, new MediaType("image", ext));
}
for (String ext : new String[] {"zip", "gz", "7z", "tar", "rar"}) {
extensionMapping.put(ext, MediaType.APPLICATION_OCTET_STREAM);
}
for (String ext : new String[] {"xls", "xlsx", "doc", "docx", "ppt", "pptx", "pdf"}) {
extensionMapping.put(ext, MediaType.APPLICATION_OCTET_STREAM);
}
for (String ext : new String[] {"mp3", "m4a", "mp4", "avi", "flv"}) {
extensionMapping.put(ext, MediaType.APPLICATION_OCTET_STREAM);
}
this.extensionMapping = extensionMapping;
}
MediaType mediaType = extensionMapping.get(extension);
return mediaType == null ? null : mediaType.getName();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/RestRequestHandlerMapping.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/RestRequestHandlerMapping.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping;
import org.apache.dubbo.common.URL;
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.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.remoting.http12.HttpResult;
import org.apache.dubbo.remoting.http12.HttpStatus;
import org.apache.dubbo.remoting.http12.exception.HttpResultPayloadException;
import org.apache.dubbo.remoting.http12.message.MediaType;
import org.apache.dubbo.remoting.http12.message.codec.CodecUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.TripleConstants;
import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants;
import org.apache.dubbo.rpc.protocol.tri.rest.RestHttpMessageCodec;
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.argument.GeneralTypeConverter;
import org.apache.dubbo.rpc.protocol.tri.rest.argument.TypeConverter;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.MethodsCondition;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.HandlerMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils;
import org.apache.dubbo.rpc.protocol.tri.route.RequestHandler;
import org.apache.dubbo.rpc.protocol.tri.route.RequestHandlerMapping;
import java.util.Set;
@Activate(order = -2000)
public final class RestRequestHandlerMapping implements RequestHandlerMapping {
private static final Logger LOGGER = LoggerFactory.getLogger(RestRequestHandlerMapping.class);
private final RequestMappingRegistry requestMappingRegistry;
private final ArgumentResolver argumentResolver;
private final TypeConverter typeConverter;
private final ContentNegotiator contentNegotiator;
private final CodecUtils codecUtils;
public RestRequestHandlerMapping(FrameworkModel frameworkModel) {
ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory();
requestMappingRegistry = beanFactory.getOrRegisterBean(DefaultRequestMappingRegistry.class);
argumentResolver = beanFactory.getOrRegisterBean(CompositeArgumentResolver.class);
typeConverter = beanFactory.getOrRegisterBean(GeneralTypeConverter.class);
contentNegotiator = beanFactory.getOrRegisterBean(ContentNegotiator.class);
codecUtils = beanFactory.getOrRegisterBean(CodecUtils.class);
}
@Override
public RequestHandler getRequestHandler(URL url, HttpRequest request, HttpResponse response) {
LOGGER.debug("Received http request: {}", request);
HandlerMeta meta = requestMappingRegistry.lookup(request);
if (meta == null) {
String path = request.attribute(RestConstants.PATH_ATTRIBUTE);
if (RestConstants.SLASH.equals(path) && HttpMethods.OPTIONS.name().equals(request.method())) {
handleOptionsRequest(request);
}
LOGGER.debug("No handler found for http request: {}", request);
return null;
}
String method = request.method();
if (HttpMethods.OPTIONS.name().equals(method)) {
handleOptionsRequest(request);
}
String requestMediaType = request.mediaType();
String responseMediaType = contentNegotiator.negotiate(request, meta);
if (responseMediaType != null) {
response.setContentType(responseMediaType);
} else {
if (requestMediaType != null && !RequestUtils.isFormOrMultiPart(request)) {
responseMediaType = requestMediaType;
} else {
responseMediaType = MediaType.APPLICATION_JSON.getName();
}
}
RestHttpMessageCodec codec = new RestHttpMessageCodec(
request,
response,
meta.getParameters(),
argumentResolver,
typeConverter,
codecUtils.determineHttpMessageEncoder(url, responseMediaType));
if (HttpMethods.supportBody(method) && !RequestUtils.isFormOrMultiPart(request)) {
if (StringUtils.isEmpty(requestMediaType)) {
requestMediaType = responseMediaType;
}
request.setAttribute(
RestConstants.BODY_DECODER_ATTRIBUTE,
codecUtils.determineHttpMessageDecoder(url, requestMediaType));
}
LOGGER.debug("Content-type negotiate result: request='{}', response='{}'", requestMediaType, responseMediaType);
RequestHandler handler = new RequestHandler(meta.getInvoker());
handler.setHasStub(false);
handler.setMethodDescriptor(meta.getMethodDescriptor());
handler.setMethodMetadata(meta.getMethodMetadata());
handler.setServiceDescriptor(meta.getServiceDescriptor());
handler.setHttpMessageDecoder(codec);
handler.setHttpMessageEncoder(codec);
return handler;
}
private static void handleOptionsRequest(HttpRequest request) {
RequestMapping mapping = request.attribute(RestConstants.MAPPING_ATTRIBUTE);
MethodsCondition condition = mapping == null ? null : mapping.getMethodsCondition();
if (condition == null) {
throw new HttpResultPayloadException(HttpResult.builder()
.status(HttpStatus.NO_CONTENT)
.header("allow", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS")
.build());
}
Set<String> methods = condition.getMethods();
if (methods.size() == 1 && methods.contains(HttpMethods.OPTIONS.name())) {
return;
}
throw new HttpResultPayloadException(HttpResult.builder()
.status(HttpStatus.NO_CONTENT)
.header("allow", StringUtils.join(methods, ","))
.build());
}
@Override
public String getType() {
return TripleConstants.TRIPLE_HANDLER_TYPE_REST;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/Registration.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/Registration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.HandlerMeta;
import java.util.Collections;
import java.util.Objects;
public final class Registration {
private final RequestMapping mapping;
private final HandlerMeta meta;
public Registration(RequestMapping mapping, HandlerMeta meta) {
this.mapping = mapping;
this.meta = meta;
}
public RequestMapping getMapping() {
return mapping;
}
public HandlerMeta getMeta() {
return meta;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != Registration.class) {
return false;
}
return mapping.equals(((Registration) obj).mapping);
}
public boolean isMappingOverlap(Registration other) {
RequestMapping otherMapping = other.getMapping();
if (mapping == otherMapping) {
return true;
}
return (mapping.getMethodsCondition() == null
|| otherMapping.getMethodsCondition() == null
|| !Collections.disjoint(
mapping.getMethodsCondition().getMethods(),
otherMapping.getMethodsCondition().getMethods()))
&& Objects.equals(mapping.getParamsCondition(), otherMapping.getParamsCondition())
&& Objects.equals(mapping.getHeadersCondition(), otherMapping.getHeadersCondition())
&& Objects.equals(mapping.getConsumesCondition(), otherMapping.getConsumesCondition())
&& Objects.equals(mapping.getProducesCondition(), otherMapping.getProducesCondition())
&& Objects.equals(mapping.getCustomCondition(), otherMapping.getCustomCondition())
&& Objects.equals(mapping.getSig(), otherMapping.getSig());
}
@Override
public int hashCode() {
return mapping.hashCode();
}
@Override
public String toString() {
return "Registration{mapping=" + mapping + ", method=" + meta.getMethod() + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/RequestMappingResolver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/RequestMappingResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.config.nested.RestConfig;
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;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface RequestMappingResolver {
RestToolKit getRestToolKit();
default void setRestConfig(RestConfig restConfig) {}
default boolean accept(ServiceMeta serviceMeta) {
return true;
}
RequestMapping resolve(ServiceMeta serviceMeta);
default boolean accept(MethodMeta methodMeta) {
return true;
}
RequestMapping resolve(MethodMeta methodMeta);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/RadixTree.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/RadixTree.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping;
import org.apache.dubbo.common.utils.Pair;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.PathExpression;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.PathSegment;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.PathSegment.Type;
import org.apache.dubbo.rpc.protocol.tri.rest.util.KeyString;
import org.apache.dubbo.rpc.protocol.tri.rest.util.PathUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Predicate;
/**
* A high-performance Radix Tree for efficient path matching.
*
* @param <T> Type of values associated with the paths.
*/
public final class RadixTree<T> {
private final Map<KeyString, List<Match<T>>> directPathMap = new HashMap<>();
private final Node<T> root = new Node<>();
private final char separator;
private final boolean caseSensitive;
public RadixTree(boolean caseSensitive, char separator) {
this.caseSensitive = caseSensitive;
this.separator = separator;
}
public RadixTree(boolean caseSensitive) {
this(caseSensitive, '/');
}
public RadixTree(char separator) {
this(true, separator);
}
public RadixTree() {
this(true, '/');
}
/**
* This is a default implementation that does not check for equality.
*/
public T addPath(PathExpression path, T value) {
return addPath(path, value, (t, t2) -> Boolean.TRUE);
}
/**
* When the path is the same, the predicate is used to determine whether the values are considered equal.
* If the predicate returns true, the existing value is returned directly.
*/
public T addPath(PathExpression path, T value, BiFunction<T, T, Boolean> predicate) {
Objects.requireNonNull(predicate);
if (path.isDirect()) {
KeyString key = new KeyString(path.getPath(), caseSensitive);
List<Match<T>> matches = directPathMap.computeIfAbsent(key, k -> new ArrayList<>());
for (int i = 0, size = matches.size(); i < size; i++) {
Match<T> match = matches.get(i);
if (predicate.apply(match.getValue(), value)) {
return match.getValue();
}
}
matches.add(new Match<>(path, value));
return null;
}
Node<T> current = root;
PathSegment[] segments = path.getSegments();
for (int i = 0, len = segments.length; i < len; i++) {
Node<T> child = getChild(current, segments[i]);
if (i == len - 1) {
List<Pair<PathExpression, T>> values = child.values;
for (int j = 0, size = values.size(); j < size; j++) {
if (values.get(j).getLeft().equals(path)) {
if (predicate.apply(values.get(j).getRight(), value)) {
return values.get(j).getRight();
}
}
}
values.add(Pair.of(path, value));
}
current = child;
}
return null;
}
public T addPath(String path, T value) {
if (path == null) {
return value;
}
if (separator == '/') {
path = PathUtils.normalize(path);
} else {
path = path.replace(separator, '/');
if (path.isEmpty() || path.charAt(0) != '/') {
path = '/' + path;
}
}
return addPath(PathExpression.parse(path), value);
}
public void addPath(T value, String... paths) {
for (String path : paths) {
addPath(path, value);
}
}
private Node<T> getChild(Node<T> current, PathSegment segment) {
Node<T> child;
if (segment.getType() == Type.LITERAL) {
Map<KeyString, Node<T>> children = current.children;
KeyString key = new KeyString(segment.getValue(), caseSensitive);
child = children.get(key);
if (child == null) {
child = new Node<>();
children.put(key, child);
}
} else {
Map<PathSegment, Node<T>> children = current.fuzzyChildren;
child = children.get(segment);
if (child == null) {
child = new Node<>();
children.put(segment, child);
}
}
return child;
}
public void remove(Predicate<T> tester) {
directPathMap.entrySet().removeIf(entry -> {
List<Match<T>> values = entry.getValue();
values.removeIf(match -> tester.test(match.getValue()));
return values.isEmpty();
});
removeRecursive(root, tester);
}
private void removeRecursive(Node<T> current, Predicate<T> tester) {
current.values.removeIf(pair -> tester.test(pair.getValue()));
List<Map<?, Node<T>>> list = new ArrayList<>();
list.add(current.children);
list.add(current.fuzzyChildren);
for (Map<?, Node<T>> children : list) {
Iterator<? extends Entry<?, Node<T>>> cit = children.entrySet().iterator();
while (cit.hasNext()) {
Node<T> node = cit.next().getValue();
removeRecursive(node, tester);
if (node.isEmpty()) {
cit.remove();
}
}
}
}
public void walk(BiConsumer<PathExpression, T> consumer) {
for (List<Match<T>> matches : directPathMap.values()) {
for (Match<T> match : matches) {
consumer.accept(match.getExpression(), match.getValue());
}
}
walkRecursive(root, consumer);
}
private void walkRecursive(Node<T> root, BiConsumer<PathExpression, T> consumer) {
for (Pair<PathExpression, T> pair : root.values) {
consumer.accept(pair.getLeft(), pair.getRight());
}
for (Node<T> node : root.children.values()) {
walkRecursive(node, consumer);
}
for (Node<T> node : root.fuzzyChildren.values()) {
walkRecursive(node, consumer);
}
}
/**
* Ensure that the path is normalized using {@link PathUtils#normalize(String)} before matching.
*/
public void match(KeyString path, List<Match<T>> matches) {
List<Match<T>> directMatches = directPathMap.get(path);
if (directMatches != null) {
for (int i = 0, size = directMatches.size(); i < size; i++) {
matches.add(directMatches.get(i));
}
}
if (root.isLeaf()) {
return;
}
matchRecursive(root, path, 1, new HashMap<>(), matches);
}
public void match(String path, List<Match<T>> matches) {
match(new KeyString(path, caseSensitive), matches);
}
public List<Match<T>> match(KeyString path) {
List<Match<T>> matches = directPathMap.get(path);
if (matches == null) {
if (root.isLeaf()) {
return Collections.emptyList();
}
matches = new ArrayList<>();
} else {
if (root.isLeaf()) {
return Collections.unmodifiableList(matches);
}
matches = new ArrayList<>(matches);
}
matchRecursive(root, path, 1, new HashMap<>(), matches);
return matches;
}
public List<Match<T>> match(String path) {
return match(new KeyString(path, caseSensitive));
}
public List<Match<T>> matchRelaxed(String path) {
KeyString keyPath = new KeyString(path, caseSensitive);
List<Match<T>> matches = new ArrayList<>();
match(keyPath, matches);
if (!matches.isEmpty()) {
return matches;
}
int end = path.length();
if (end > 1 && path.charAt(end - 1) == '/') {
match(keyPath.subSequence(0, --end), matches);
if (!matches.isEmpty()) {
return matches;
}
}
for (int i = end - 1; i >= 0; i--) {
char ch = path.charAt(i);
if (ch == '/') {
break;
}
if (ch == '.') {
match(keyPath.subSequence(0, i), matches);
if (!matches.isEmpty()) {
return matches;
}
}
}
return matches;
}
private void matchRecursive(
Node<T> current, KeyString path, int start, Map<String, String> variableMap, List<Match<T>> matches) {
int end = -2;
if (!current.children.isEmpty()) {
end = path.indexOf(separator, start);
Node<T> child = current.children.get(path.subSequence(start, end));
if (child != null) {
if (end == -1) {
addMatch(child, variableMap, matches);
} else {
matchRecursive(child, path, end + 1, variableMap, matches);
}
}
}
if (current.fuzzyChildren.isEmpty()) {
return;
}
if (end == -2) {
end = path.indexOf(separator, start);
}
Map<String, String> workVariableMap = new LinkedHashMap<>();
for (Map.Entry<PathSegment, Node<T>> entry : current.fuzzyChildren.entrySet()) {
PathSegment segment = entry.getKey();
if (segment.match(path, start, end, workVariableMap)) {
workVariableMap.putAll(variableMap);
Node<T> child = entry.getValue();
if (segment.isTailMatching()) {
addMatch(child, workVariableMap, matches);
} else {
if (end == -1) {
addMatch(child, workVariableMap, matches);
} else {
matchRecursive(child, path, end + 1, workVariableMap, matches);
}
}
if (!workVariableMap.isEmpty()) {
workVariableMap = new LinkedHashMap<>();
}
}
}
}
private static <T> void addMatch(Node<T> node, Map<String, String> variableMap, List<Match<T>> matches) {
List<Pair<PathExpression, T>> values = node.values;
if (values.isEmpty()) {
if (node.fuzzyChildren.isEmpty()) {
return;
}
for (Entry<PathSegment, Node<T>> entry : node.fuzzyChildren.entrySet()) {
if (entry.getKey().getType() == Type.WILDCARD_TAIL) {
addMatch(entry.getValue(), variableMap, matches);
}
}
return;
}
variableMap = variableMap.isEmpty() ? Collections.emptyMap() : Collections.unmodifiableMap(variableMap);
for (int i = 0, size = values.size(); i < size; i++) {
Pair<PathExpression, T> pair = values.get(i);
matches.add(new Match<>(pair.getLeft(), pair.getRight(), variableMap));
}
}
public void clear() {
directPathMap.clear();
root.clear();
}
public boolean isEmpty() {
return directPathMap.isEmpty() && root.isEmpty();
}
public static final class Match<T> implements Comparable<Match<T>> {
private final PathExpression expression;
private final T value;
private final Map<String, String> variableMap;
Match(PathExpression expression, T value, Map<String, String> variableMap) {
this.expression = expression;
this.value = value;
this.variableMap = variableMap;
}
private Match(PathExpression expression, T value) {
this.expression = expression;
this.value = value;
variableMap = Collections.emptyMap();
}
public PathExpression getExpression() {
return expression;
}
public T getValue() {
return value;
}
public Map<String, String> getVariableMap() {
return variableMap;
}
@Override
public int compareTo(Match<T> other) {
int comparison = expression.compareTo(other.getExpression());
return comparison == 0 ? variableMap.size() - other.variableMap.size() : comparison;
}
}
private static final class Node<T> {
private final Map<KeyString, Node<T>> children = new HashMap<>();
private final Map<PathSegment, Node<T>> fuzzyChildren = new HashMap<>();
private final List<Pair<PathExpression, T>> values = new ArrayList<>();
private boolean isLeaf() {
return children.isEmpty() && fuzzyChildren.isEmpty();
}
private boolean isEmpty() {
return isLeaf() && values.isEmpty();
}
private void clear() {
children.clear();
fuzzyChildren.clear();
values.clear();
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/RequestMapping.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/RequestMapping.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.Condition;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.ConditionWrapper;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.ConsumesCondition;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.HeadersCondition;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.MethodsCondition;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.ParamsCondition;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.PathCondition;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.PathExpression;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.ProducesCondition;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.ServiceGroupVersionCondition;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.CorsMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ResponseMeta;
import java.util.Objects;
import static org.apache.dubbo.common.utils.ArrayUtils.isEmpty;
public final class RequestMapping implements Condition<RequestMapping, HttpRequest> {
private final String name;
private final String sig;
private final PathCondition pathCondition;
private final MethodsCondition methodsCondition;
private final ParamsCondition paramsCondition;
private final HeadersCondition headersCondition;
private final ConsumesCondition consumesCondition;
private final ProducesCondition producesCondition;
private final ConditionWrapper customCondition;
private final CorsMeta cors;
private final ResponseMeta response;
private int hashCode;
private RequestMapping(
String name,
String sig,
PathCondition pathCondition,
MethodsCondition methodsCondition,
ParamsCondition paramsCondition,
HeadersCondition headersCondition,
ConsumesCondition consumesCondition,
ProducesCondition producesCondition,
ConditionWrapper customCondition,
CorsMeta cors,
ResponseMeta response) {
this.name = name;
this.sig = sig;
this.pathCondition = pathCondition;
this.methodsCondition = methodsCondition;
this.paramsCondition = paramsCondition;
this.headersCondition = headersCondition;
this.consumesCondition = consumesCondition;
this.producesCondition = producesCondition;
this.customCondition = customCondition;
this.cors = cors;
this.response = response;
}
public static Builder builder() {
return new Builder();
}
@Override
public RequestMapping combine(RequestMapping other) {
return new RequestMapping(
combineName(name, other.name, other.sig),
other.sig,
combine(pathCondition, other.pathCondition),
combine(methodsCondition, other.methodsCondition),
combine(paramsCondition, other.paramsCondition),
combine(headersCondition, other.headersCondition),
combine(consumesCondition, other.consumesCondition),
combine(producesCondition, other.producesCondition),
combine(customCondition, other.customCondition),
CorsMeta.combine(cors, other.cors),
ResponseMeta.combine(response, other.response));
}
private String combineName(String name, String otherName, String otherSig) {
if (name == null) {
name = otherName;
} else if (otherName != null) {
name += '#' + otherName;
}
return otherSig == null ? name : name + '~' + otherSig;
}
private <T extends Condition<T, HttpRequest>> T combine(T source, T other) {
return source == null ? other : other == null ? source : source.combine(other);
}
public RequestMapping match(HttpRequest request, PathExpression path) {
return doMatch(request, new PathCondition(path));
}
public boolean matchMethod(String method) {
return methodsCondition == null || methodsCondition.getMethods().contains(method);
}
public boolean matchParams(HttpRequest request) {
return paramsCondition == null || paramsCondition.match(request) != null;
}
public boolean matchConsumes(HttpRequest request) {
return consumesCondition == null || consumesCondition.match(request) != null;
}
public boolean matchProduces(HttpRequest request) {
return producesCondition == null || producesCondition.match(request) != null;
}
@Override
public RequestMapping match(HttpRequest request) {
return doMatch(request, null);
}
private RequestMapping doMatch(HttpRequest request, PathCondition pathCondition) {
MethodsCondition methods = null;
if (methodsCondition != null) {
methods = methodsCondition.match(request);
if (methods == null) {
return null;
}
}
PathCondition paths = pathCondition;
if (paths == null && this.pathCondition != null) {
paths = this.pathCondition.match(request);
if (paths == null) {
return null;
}
}
ParamsCondition params = null;
if (paramsCondition != null) {
params = paramsCondition.match(request);
if (params == null) {
return null;
}
}
HeadersCondition headers = null;
if (headersCondition != null) {
headers = headersCondition.match(request);
if (headers == null) {
return null;
}
}
ConsumesCondition consumes = null;
if (consumesCondition != null) {
consumes = consumesCondition.match(request);
if (consumes == null) {
return null;
}
}
ProducesCondition produces = null;
if (producesCondition != null) {
produces = producesCondition.match(request);
if (produces == null) {
return null;
}
}
ConditionWrapper custom = null;
if (customCondition != null) {
custom = customCondition.match(request);
if (custom == null) {
return null;
}
}
if (StringUtils.isNotEmpty(sig)) {
String rSig = request.attribute(RestConstants.SIG_ATTRIBUTE);
if (rSig != null && !rSig.equals(sig)) {
return null;
}
}
return new RequestMapping(
name, sig, paths, methods, params, headers, consumes, produces, custom, cors, response);
}
public String getName() {
return name;
}
public String getSig() {
return sig;
}
public PathCondition getPathCondition() {
return pathCondition;
}
public MethodsCondition getMethodsCondition() {
return methodsCondition;
}
public ParamsCondition getParamsCondition() {
return paramsCondition;
}
public HeadersCondition getHeadersCondition() {
return headersCondition;
}
public ConsumesCondition getConsumesCondition() {
return consumesCondition;
}
public ProducesCondition getProducesCondition() {
return producesCondition;
}
public ConditionWrapper getCustomCondition() {
return customCondition;
}
public CorsMeta getCors() {
return cors;
}
public ResponseMeta getResponse() {
return response;
}
@Override
public int compareTo(RequestMapping other, HttpRequest request) {
int result;
if (methodsCondition != null && HttpMethods.HEAD.name().equals(request.method())) {
result = methodsCondition.compareTo(other.methodsCondition, request);
if (result != 0) {
return result;
}
}
if (pathCondition != null) {
result = pathCondition.compareTo(other.pathCondition, request);
if (result != 0) {
return result;
}
}
if (paramsCondition != null) {
result = paramsCondition.compareTo(other.paramsCondition, request);
if (result != 0) {
return result;
}
}
if (headersCondition != null) {
result = headersCondition.compareTo(other.headersCondition, request);
if (result != 0) {
return result;
}
}
if (consumesCondition != null) {
result = consumesCondition.compareTo(other.consumesCondition, request);
if (result != 0) {
return result;
}
}
if (producesCondition != null) {
result = producesCondition.compareTo(other.producesCondition, request);
if (result != 0) {
return result;
}
}
if (methodsCondition != null) {
result = methodsCondition.compareTo(other.methodsCondition, request);
if (result != 0) {
return result;
}
}
if (customCondition != null) {
result = customCondition.compareTo(other.customCondition, request);
if (result != 0) {
return result;
}
}
if (sig != null && other.sig != null) {
int size = request.queryParameters().size();
int size1 = sig.length();
int size2 = other.sig.length();
if (size1 == size) {
if (size2 != size) {
return -1;
}
} else if (size2 == size) {
return 1;
}
}
return 0;
}
@Override
public int hashCode() {
int hashCode = this.hashCode;
if (hashCode == 0) {
hashCode = Objects.hash(
pathCondition,
methodsCondition,
paramsCondition,
headersCondition,
consumesCondition,
producesCondition,
customCondition,
sig);
this.hashCode = hashCode;
}
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != RequestMapping.class) {
return false;
}
RequestMapping other = (RequestMapping) obj;
return Objects.equals(pathCondition, other.pathCondition)
&& Objects.equals(methodsCondition, other.methodsCondition)
&& Objects.equals(paramsCondition, other.paramsCondition)
&& Objects.equals(headersCondition, other.headersCondition)
&& Objects.equals(consumesCondition, other.consumesCondition)
&& Objects.equals(producesCondition, other.producesCondition)
&& Objects.equals(customCondition, other.customCondition)
&& Objects.equals(sig, other.sig);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("RequestMapping{name='");
sb.append(name).append('\'');
if (pathCondition != null) {
sb.append(", path=").append(pathCondition);
}
if (methodsCondition != null) {
sb.append(", methods=").append(methodsCondition);
}
if (paramsCondition != null) {
sb.append(", params=").append(paramsCondition);
}
if (headersCondition != null) {
sb.append(", headers=").append(headersCondition);
}
if (consumesCondition != null) {
sb.append(", consumes=").append(consumesCondition);
}
if (producesCondition != null) {
sb.append(", produces=").append(producesCondition);
}
if (customCondition != null) {
sb.append(", custom=").append(customCondition);
}
if (response != null) {
sb.append(", response=").append(response);
}
if (cors != null) {
sb.append(", cors=").append(cors);
}
sb.append('}');
return sb.toString();
}
public static final class Builder {
private String name;
private String sig;
private String contextPath;
private String[] paths;
private String[] methods;
private String[] params;
private String[] headers;
private String[] consumes;
private String[] produces;
private Condition<?, HttpRequest> customCondition;
private CorsMeta cors;
private Integer responseStatus;
private String responseReason;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder sig(String sig) {
this.sig = sig;
return this;
}
public Builder contextPath(String contextPath) {
this.contextPath = contextPath;
return this;
}
public Builder path(String... paths) {
this.paths = paths;
return this;
}
public Builder method(String... methods) {
this.methods = methods;
return this;
}
public Builder param(String... params) {
this.params = params;
return this;
}
public Builder header(String... headers) {
this.headers = headers;
return this;
}
public Builder consume(String... consumes) {
this.consumes = consumes;
return this;
}
public Builder produce(String... produces) {
this.produces = produces;
return this;
}
public Builder custom(Condition<?, HttpRequest> customCondition) {
this.customCondition = customCondition;
return this;
}
public Builder service(String ServiceGroup, String ServiceVersion) {
if (ServiceGroup != null || ServiceVersion != null) {
customCondition = new ServiceGroupVersionCondition(ServiceGroup, ServiceVersion);
}
return this;
}
public Builder cors(CorsMeta cors) {
this.cors = cors;
return this;
}
public Builder responseStatus(int status) {
responseStatus = status;
return this;
}
public Builder responseReason(String reason) {
responseReason = reason;
return this;
}
public RequestMapping build() {
return new RequestMapping(
name,
sig,
isEmpty(paths) ? null : new PathCondition(contextPath, paths),
isEmpty(methods) ? null : new MethodsCondition(methods),
isEmpty(params) ? null : new ParamsCondition(params),
isEmpty(headers) ? null : new HeadersCondition(headers),
isEmpty(consumes) ? null : new ConsumesCondition(consumes),
isEmpty(produces) ? null : new ProducesCondition(produces),
customCondition == null ? null : ConditionWrapper.wrap(customCondition),
cors == null || cors.isEmpty() ? null : cors,
responseStatus == null ? null : new ResponseMeta(responseStatus, responseReason));
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/DefaultRequestMappingRegistry.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/DefaultRequestMappingRegistry.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.FluentLogger;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.nested.RestConfig;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.exception.HttpStatusException;
import org.apache.dubbo.remoting.http12.message.MethodMetadata;
import org.apache.dubbo.remoting.http12.rest.OpenAPIService;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.ReflectionMethodDescriptor;
import org.apache.dubbo.rpc.model.ReflectionServiceDescriptor;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.model.StubServiceDescriptor;
import org.apache.dubbo.rpc.protocol.tri.DescriptorUtils;
import org.apache.dubbo.rpc.protocol.tri.TripleProtocol;
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.RestMappingException;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RadixTree.Match;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.PathExpression;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.ProducesCondition;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.HandlerMeta;
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.KeyString;
import org.apache.dubbo.rpc.protocol.tri.rest.util.MethodWalker;
import org.apache.dubbo.rpc.protocol.tri.rest.util.PathUtils;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public final class DefaultRequestMappingRegistry implements RequestMappingRegistry {
private static final FluentLogger LOGGER = FluentLogger.of(DefaultRequestMappingRegistry.class);
private final FrameworkModel frameworkModel;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final AtomicBoolean initialized = new AtomicBoolean();
private ContentNegotiator contentNegotiator;
private OpenAPIService openAPIService;
private List<RequestMappingResolver> resolvers;
private RestConfig restConfig;
private RadixTree<Registration> tree;
public DefaultRequestMappingRegistry(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
private void init(Invoker<?> invoker) {
contentNegotiator = frameworkModel.getOrRegisterBean(ContentNegotiator.class);
if (TripleProtocol.OPENAPI_ENABLED) {
openAPIService = frameworkModel.getBean(OpenAPIService.class);
}
resolvers = frameworkModel.getActivateExtensions(RequestMappingResolver.class);
restConfig = ConfigManager.getProtocolOrDefault(invoker.getUrl())
.getTripleOrDefault()
.getRestOrDefault();
for (RequestMappingResolver resolver : resolvers) {
resolver.setRestConfig(restConfig);
}
tree = new RadixTree<>(restConfig.getCaseSensitiveMatchOrDefault());
}
@Override
public void register(Invoker<?> invoker) {
if (tree == null) {
lock.writeLock().lock();
try {
if (initialized.compareAndSet(false, true)) {
init(invoker);
}
} finally {
lock.writeLock().unlock();
}
}
URL url = invoker.getUrl();
Object service = url.getServiceModel().getProxyObject();
ServiceDescriptor sd = DescriptorUtils.getReflectionServiceDescriptor(url);
if (sd == null) {
return;
}
AtomicInteger counter = new AtomicInteger();
long start = System.currentTimeMillis();
new MethodWalker().walk(service.getClass(), (classes, consumer) -> {
for (int i = 0, size = resolvers.size(); i < size; i++) {
RequestMappingResolver resolver = resolvers.get(i);
ServiceMeta serviceMeta = new ServiceMeta(classes, sd, service, url, resolver.getRestToolKit());
if (LOGGER.isInfoEnabled()) {
LOGGER.info(
"{} resolving rest mappings for {} at url [{}]",
resolver.getClass().getSimpleName(),
serviceMeta,
url.toString(""));
}
if (!resolver.accept(serviceMeta)) {
continue;
}
RequestMapping classMapping = resolver.resolve(serviceMeta);
consumer.accept((methods) -> {
Method method = methods.get(0);
Class<?>[] paramTypes = method.getParameterTypes();
MethodDescriptor md = sd.getMethod(method.getName(), paramTypes);
if (md == null && sd instanceof StubServiceDescriptor) {
int len = paramTypes.length;
if (len > 0 && StreamObserver.class.isAssignableFrom(paramTypes[len - 1])) {
md = sd.getMethod(method.getName(), Arrays.copyOf(paramTypes, len - 1));
}
}
MethodMeta methodMeta = new MethodMeta(methods, md, serviceMeta);
if (!resolver.accept(methodMeta)) {
return;
}
RequestMapping methodMapping = resolver.resolve(methodMeta);
if (methodMapping == null || methodMapping.getPathCondition() == null) {
return;
}
if (md == null) {
if (!(sd instanceof ReflectionServiceDescriptor)) {
return;
}
md = new ReflectionMethodDescriptor(method);
((ReflectionServiceDescriptor) sd).addMethod(md);
methodMeta.setMethodDescriptor(md);
}
if (classMapping != null) {
methodMapping = classMapping.combine(methodMapping);
}
methodMeta.initParameters();
MethodMetadata methodMetadata = MethodMetadata.fromMethodDescriptor(md);
register0(methodMapping, new HandlerMeta(invoker, methodMeta, methodMetadata, md, sd), counter);
});
}
});
onMappingChanged();
LOGGER.info(
"Registered {} rest mappings for service [{}] at url [{}] in {}ms",
counter,
ClassUtils.toShortString(service),
url.toString(""),
System.currentTimeMillis() - start);
}
private void register0(RequestMapping mapping, HandlerMeta handler, AtomicInteger counter) {
lock.writeLock().lock();
try {
Registration registration = new Registration(mapping, handler);
for (PathExpression path : mapping.getPathCondition().getExpressions()) {
Registration exists = tree.addPath(path, registration, Registration::isMappingOverlap);
if (exists == null) {
counter.incrementAndGet();
if (LOGGER.isDebugEnabled()) {
String msg = "Register rest mapping: '{}' -> mapping={}, method={}";
LOGGER.debug(msg, path, mapping, handler.getMethod());
}
} else if (LOGGER.isWarnEnabled()) {
LOGGER.internalWarn(Messages.DUPLICATE_MAPPING.format(path, mapping, handler.getMethod(), exists));
}
}
} finally {
lock.writeLock().unlock();
}
}
@Override
public void unregister(Invoker<?> invoker) {
if (tree == null) {
return;
}
lock.writeLock().lock();
try {
tree.remove(r -> r.getMeta().getInvoker() == invoker);
onMappingChanged();
} finally {
lock.writeLock().unlock();
}
}
@Override
public void destroy() {
if (tree == null) {
return;
}
lock.writeLock().lock();
try {
tree.clear();
} finally {
lock.writeLock().unlock();
}
}
public HandlerMeta lookup(HttpRequest request) {
if (tree == null) {
return null;
}
String stringPath = PathUtils.normalize(request.uri());
request.setAttribute(RestConstants.PATH_ATTRIBUTE, stringPath);
KeyString path = new KeyString(stringPath, restConfig.getCaseSensitiveMatchOrDefault());
List<Candidate> candidates = new ArrayList<>();
List<RequestMapping> partialMatches = new LinkedList<>();
tryMatch(request, path, candidates, partialMatches);
if (candidates.isEmpty()) {
int end = path.length();
if (end > 1 && restConfig.getTrailingSlashMatchOrDefault()) {
if (path.charAt(end - 1) == '/') {
tryMatch(request, path.subSequence(0, --end), candidates, partialMatches);
}
}
if (candidates.isEmpty()) {
for (int i = end - 1; i >= 0; i--) {
char ch = path.charAt(i);
if (ch == '/') {
break;
}
if (ch == '.' && restConfig.getSuffixPatternMatchOrDefault()) {
if (contentNegotiator.supportExtension(path.toString(i + 1, end))) {
tryMatch(request, path.subSequence(0, i), candidates, partialMatches);
if (!candidates.isEmpty()) {
break;
}
end = i;
}
}
if (ch == '~') {
request.setAttribute(RestConstants.SIG_ATTRIBUTE, path.toString(i + 1, end));
tryMatch(request, path.subSequence(0, i), candidates, partialMatches);
if (!candidates.isEmpty()) {
break;
}
}
}
}
}
int size = candidates.size();
if (size == 0) {
handleNoMatch(request, partialMatches);
return null;
}
if (size > 1) {
candidates.sort((c1, c2) -> {
int comparison = c1.expression.compareTo(c2.expression, stringPath);
if (comparison != 0) {
return comparison;
}
comparison = c1.mapping.compareTo(c2.mapping, request);
if (comparison != 0) {
return comparison;
}
return c1.variableMap.size() - c2.variableMap.size();
});
LOGGER.debug("Candidate rest mappings: {}", candidates);
Candidate first = candidates.get(0);
Candidate second = candidates.get(1);
if (first.mapping.compareTo(second.mapping, request) == 0) {
throw new RestMappingException(Messages.AMBIGUOUS_MAPPING, path, first, second);
}
}
Candidate winner = candidates.get(0);
RequestMapping mapping = winner.mapping;
HandlerMeta handler = winner.meta;
request.setAttribute(RestConstants.MAPPING_ATTRIBUTE, mapping);
request.setAttribute(RestConstants.HANDLER_ATTRIBUTE, handler);
LOGGER.debug("Matched rest mapping={}, method={}", mapping, handler.getMethod());
if (!winner.variableMap.isEmpty()) {
request.setAttribute(RestConstants.URI_TEMPLATE_VARIABLES_ATTRIBUTE, winner.variableMap);
}
ProducesCondition producesCondition = mapping.getProducesCondition();
if (producesCondition != null) {
request.setAttribute(RestConstants.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, producesCondition.getMediaTypes());
}
return handler;
}
private void tryMatch(
HttpRequest request, KeyString path, List<Candidate> candidates, List<RequestMapping> partialMatches) {
List<Match<Registration>> matches = new ArrayList<>();
lock.readLock().lock();
try {
tree.match(path, matches);
} finally {
lock.readLock().unlock();
}
int size = matches.size();
if (size == 0) {
return;
}
for (int i = 0; i < size; i++) {
Match<Registration> match = matches.get(i);
RequestMapping mapping = match.getValue().getMapping().match(request, match.getExpression());
if (mapping != null) {
Candidate candidate = new Candidate();
candidate.mapping = mapping;
candidate.meta = match.getValue().getMeta();
candidate.expression = match.getExpression();
candidate.variableMap = match.getVariableMap();
candidates.add(candidate);
}
}
if (candidates.isEmpty()) {
for (int i = 0; i < size; i++) {
partialMatches.add(matches.get(i).getValue().getMapping());
}
}
}
private void handleNoMatch(HttpRequest request, List<RequestMapping> partialMatches) {
if (partialMatches.isEmpty()) {
return;
}
boolean methodsMismatch = true;
boolean consumesMismatch = true;
boolean producesMismatch = true;
boolean paramsMismatch = true;
for (RequestMapping mapping : partialMatches) {
if (methodsMismatch) {
methodsMismatch = !mapping.matchMethod(request.method());
}
if (consumesMismatch) {
consumesMismatch = !mapping.matchConsumes(request);
}
if (producesMismatch) {
producesMismatch = !mapping.matchProduces(request);
}
if (paramsMismatch) {
paramsMismatch = !mapping.matchParams(request);
}
}
if (methodsMismatch) {
throw new HttpStatusException(405, "Request method '" + request.method() + "' not supported");
}
if (consumesMismatch) {
throw new HttpStatusException(415, "Content type '" + request.contentType() + "' not supported");
}
if (producesMismatch) {
throw new HttpStatusException(406, "Could not find acceptable representation");
}
if (paramsMismatch) {
throw new HttpStatusException(400, "Unsatisfied query parameter conditions");
}
}
@Override
public boolean exists(String stringPath, String method) {
if (tree == null) {
return false;
}
KeyString path = new KeyString(stringPath, restConfig.getCaseSensitiveMatchOrDefault());
if (tryExists(path, method)) {
return true;
}
int end = path.length();
if (restConfig.getTrailingSlashMatchOrDefault()) {
if (path.charAt(end - 1) == '/') {
end--;
if (tryExists(path.subSequence(0, end - 1), method)) {
return true;
}
}
}
for (int i = end - 1; i >= 0; i--) {
char ch = path.charAt(i);
if (ch == '/') {
break;
}
if (ch == '.' && restConfig.getSuffixPatternMatchOrDefault()) {
if (contentNegotiator.supportExtension(path.toString(i + 1, end))) {
if (tryExists(path.subSequence(0, i), method)) {
return true;
}
end = i;
}
}
if (ch == '~') {
return tryExists(path.subSequence(0, i), method);
}
}
return false;
}
@Override
public Collection<Registration> getRegistrations() {
lock.readLock().lock();
try {
Map<Registration, Boolean> registrations = new IdentityHashMap<>();
tree.walk((expr, registration) -> registrations.put(registration, Boolean.TRUE));
return registrations.keySet();
} finally {
lock.readLock().unlock();
}
}
private boolean tryExists(KeyString path, String method) {
List<Match<Registration>> matches = new ArrayList<>();
lock.readLock().lock();
try {
tree.match(path, matches);
} finally {
lock.readLock().unlock();
}
for (int i = 0, size = matches.size(); i < size; i++) {
if (matches.get(i).getValue().getMapping().matchMethod(method)) {
return true;
}
}
return false;
}
private void onMappingChanged() {
if (openAPIService != null) {
openAPIService.refresh();
}
}
private static final class Candidate {
RequestMapping mapping;
HandlerMeta meta;
PathExpression expression;
Map<String, String> variableMap;
@Override
public String toString() {
return "Candidate{mapping=" + mapping + ", method=" + meta.getMethod() + '}';
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/NameValueExpression.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/NameValueExpression.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.condition;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
public final class NameValueExpression {
private final String name;
private final String value;
private final boolean negated;
private NameValueExpression(String name, String value, boolean negated) {
this.name = name;
this.value = value;
this.negated = negated;
}
public NameValueExpression(String name, String value) {
this.name = name;
this.value = value;
negated = false;
}
public static Set<NameValueExpression> parse(String... params) {
if (ArrayUtils.isEmpty(params)) {
return Collections.emptySet();
}
int len = params.length;
Set<NameValueExpression> expressions = CollectionUtils.newHashSet(len);
for (String param : params) {
expressions.add(parse(param));
}
return expressions;
}
public static NameValueExpression parse(String expr) {
int index = expr.indexOf('=');
if (index == -1) {
boolean negated = expr.indexOf('!') == 0;
return new NameValueExpression(negated ? expr.substring(1) : expr, null, negated);
} else {
boolean negated = index > 0 && expr.charAt(index - 1) == '!';
return new NameValueExpression(
negated ? expr.substring(0, index - 1) : expr.substring(0, index),
expr.substring(index + 1),
negated);
}
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public boolean match(Predicate<String> nameFn, Function<String, String> valueFn) {
boolean matched;
if (value == null) {
matched = nameFn.test(name);
} else {
matched = Objects.equals(valueFn.apply(name), value);
}
return matched != negated;
}
public boolean match(Function<String, String> valueFn) {
return match(n -> valueFn.apply(n) != null, valueFn);
}
@Override
public int hashCode() {
return Objects.hash(name, value, negated);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != NameValueExpression.class) {
return false;
}
NameValueExpression other = (NameValueExpression) obj;
return negated == other.negated && Objects.equals(name, other.name) && Objects.equals(value, other.value);
}
@Override
public String toString() {
return name + (negated ? "!=" : "=") + value;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/PathCondition.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/PathCondition.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.condition;
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.rpc.protocol.tri.rest.RestConstants;
import org.apache.dubbo.rpc.protocol.tri.rest.util.PathUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public final class PathCondition implements Condition<PathCondition, HttpRequest> {
private final String contextPath;
private final Set<String> paths;
private List<PathExpression> expressions;
public PathCondition(String contextPath, String... paths) {
this.contextPath = contextPath;
this.paths = new LinkedHashSet<>(Arrays.asList(paths));
}
private PathCondition(String contextPath, Set<String> paths) {
this.contextPath = contextPath;
this.paths = paths;
}
public PathCondition(PathExpression path) {
contextPath = null;
paths = Collections.singleton(path.getPath());
expressions = Collections.singletonList(path);
}
public List<PathExpression> getExpressions() {
List<PathExpression> expressions = this.expressions;
if (expressions == null) {
expressions = new ArrayList<>();
for (String path : paths) {
expressions.add(PathExpression.parse(PathUtils.normalize(contextPath, path)));
}
this.expressions = expressions;
}
return expressions;
}
@Override
public PathCondition combine(PathCondition other) {
Set<String> result = new LinkedHashSet<>();
if (paths.isEmpty()) {
if (other.paths.isEmpty()) {
result.add(StringUtils.EMPTY_STRING);
} else {
result.addAll(other.paths);
}
} else {
if (other.paths.isEmpty()) {
result.addAll(paths);
} else {
for (String left : paths) {
for (String right : other.paths) {
result.add(PathUtils.combine(left, right));
}
}
}
}
return new PathCondition(contextPath, result);
}
@Override
public PathCondition match(HttpRequest request) {
List<PathExpression> matches = null;
String path = request.rawPath();
List<PathExpression> expressions = getExpressions();
for (int i = 0, size = expressions.size(); i < size; i++) {
PathExpression expression = expressions.get(i);
Map<String, String> variables = expression.match(path);
if (variables != null) {
if (matches == null) {
matches = new ArrayList<>();
}
matches.add(expression);
}
}
if (matches != null) {
if (matches.size() > 1) {
Collections.sort(matches);
}
Set<String> result = CollectionUtils.newLinkedHashSet(matches.size());
for (int i = 0, size = matches.size(); i < size; i++) {
result.add(matches.get(i).getPath());
}
return new PathCondition(contextPath, result);
}
return null;
}
@Override
public int compareTo(PathCondition other, HttpRequest request) {
String lookupPath = request.attribute(RestConstants.PATH_ATTRIBUTE);
Iterator<PathExpression> it = getExpressions().iterator();
Iterator<PathExpression> oit = other.getExpressions().iterator();
while (it.hasNext() && oit.hasNext()) {
int result = it.next().compareTo(oit.next(), lookupPath);
if (result != 0) {
return result;
}
}
if (it.hasNext()) {
return -1;
}
if (oit.hasNext()) {
return 1;
}
return 0;
}
@Override
public int hashCode() {
return 31 * paths.hashCode() + contextPath.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != PathCondition.class) {
return false;
}
PathCondition other = (PathCondition) obj;
return paths.equals(other.paths) && Objects.equals(contextPath, other.contextPath);
}
@Override
public String toString() {
return "PathCondition{paths=" + paths + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/ProducesCondition.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/ProducesCondition.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.condition;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Pair;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.HttpHeaderNames;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.message.MediaType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiPredicate;
public final class ProducesCondition implements Condition<ProducesCondition, HttpRequest> {
private final List<MediaTypeExpression> expressions;
public ProducesCondition(String... produces) {
this(produces, null);
}
public ProducesCondition(String[] produces, String[] headers) {
Set<MediaTypeExpression> expressions = null;
if (headers != null) {
for (String header : headers) {
NameValueExpression expr = NameValueExpression.parse(header);
if (HttpHeaderNames.ACCEPT.getName().equalsIgnoreCase(expr.getName())) {
MediaTypeExpression expression = MediaTypeExpression.parse(expr.getValue());
if (expression == null) {
continue;
}
if (expressions == null) {
expressions = new LinkedHashSet<>();
}
expressions.add(expression);
}
}
}
if (produces != null) {
for (String produce : produces) {
MediaTypeExpression expression = MediaTypeExpression.parse(produce);
if (expression == null) {
continue;
}
if (expressions == null) {
expressions = new LinkedHashSet<>();
}
expressions.add(expression);
}
}
if (expressions == null) {
this.expressions = Collections.emptyList();
} else {
this.expressions = new ArrayList<>(expressions);
Collections.sort(this.expressions);
}
}
private ProducesCondition(List<MediaTypeExpression> expressions) {
this.expressions = expressions;
}
@Override
public ProducesCondition combine(ProducesCondition other) {
return other.expressions.isEmpty() ? this : other;
}
@Override
public ProducesCondition match(HttpRequest request) {
if (expressions.isEmpty()) {
return null;
}
List<MediaTypeExpression> acceptedMediaTypes = getAcceptedMediaTypes(request);
List<MediaTypeExpression> result = null;
for (int i = 0, size = expressions.size(); i < size; i++) {
MediaTypeExpression expression = expressions.get(i);
for (int j = 0, aSize = acceptedMediaTypes.size(); j < aSize; j++) {
if (expression.compatibleWith(acceptedMediaTypes.get(j))) {
if (result == null) {
result = new ArrayList<>();
}
result.add(expression);
break;
}
}
}
return result == null ? null : new ProducesCondition(result);
}
private List<MediaTypeExpression> getAcceptedMediaTypes(HttpRequest request) {
List<String> values = request.headerValues(HttpHeaderNames.ACCEPT.getKey());
if (CollectionUtils.isEmpty(values)) {
return MediaTypeExpression.ALL_LIST;
}
List<MediaTypeExpression> mediaTypes = null;
for (int i = 0, size = values.size(); i < size; i++) {
String value = values.get(i);
if (StringUtils.isEmpty(value)) {
continue;
}
for (String item : StringUtils.tokenize(value, ',')) {
MediaTypeExpression expression = MediaTypeExpression.parse(item);
if (expression == null) {
continue;
}
if (mediaTypes == null) {
mediaTypes = new ArrayList<>();
}
mediaTypes.add(expression);
}
}
if (mediaTypes == null) {
return Collections.emptyList();
}
mediaTypes.sort(MediaTypeExpression.QUALITY_COMPARATOR.thenComparing(MediaTypeExpression.COMPARATOR));
return mediaTypes;
}
@Override
public int compareTo(ProducesCondition other, HttpRequest request) {
if (expressions.isEmpty() && other.expressions.isEmpty()) {
return 0;
}
List<MediaTypeExpression> mediaTypes = getAcceptedMediaTypes(request);
for (int i = 0, size = mediaTypes.size(); i < size; i++) {
MediaTypeExpression mediaType = mediaTypes.get(i);
Pair<Integer, MediaTypeExpression> thisPair, otherPair;
thisPair = findMediaType(mediaType, MediaTypeExpression::typesEquals);
otherPair = findMediaType(mediaType, MediaTypeExpression::typesEquals);
int result = compareMediaType(thisPair, otherPair);
if (result != 0) {
return result;
}
thisPair = findMediaType(mediaType, MediaTypeExpression::compatibleWith);
otherPair = findMediaType(mediaType, MediaTypeExpression::compatibleWith);
result = compareMediaType(thisPair, otherPair);
if (result != 0) {
return result;
}
}
return 0;
}
public List<MediaType> getMediaTypes() {
return MediaTypeExpression.toMediaTypes(expressions);
}
@Override
public int hashCode() {
return expressions.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != ProducesCondition.class) {
return false;
}
return expressions.equals(((ProducesCondition) obj).expressions);
}
private Pair<Integer, MediaTypeExpression> findMediaType(
MediaTypeExpression mediaType, BiPredicate<MediaTypeExpression, MediaTypeExpression> tester) {
List<MediaTypeExpression> toCompare = expressions.isEmpty() ? MediaTypeExpression.ALL_LIST : expressions;
for (int i = 0; i < toCompare.size(); i++) {
MediaTypeExpression currentMediaType = toCompare.get(i);
if (tester.test(mediaType, currentMediaType)) {
return Pair.of(i, currentMediaType);
}
}
return Pair.of(-1, null);
}
private int compareMediaType(Pair<Integer, MediaTypeExpression> p1, Pair<Integer, MediaTypeExpression> p2) {
int index1 = p1.getLeft();
int index2 = p2.getLeft();
if (index1 != index2) {
return index2 - index1;
}
return index1 != -1 ? p1.getRight().compareTo(p2.getRight()) : 0;
}
@Override
public String toString() {
return "ProducesCondition{mediaTypes=" + expressions + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/HeadersCondition.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/HeadersCondition.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.condition;
import org.apache.dubbo.remoting.http12.HttpHeaderNames;
import org.apache.dubbo.remoting.http12.HttpRequest;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
public final class HeadersCondition implements Condition<HeadersCondition, HttpRequest> {
private final Set<NameValueExpression> expressions;
public HeadersCondition(String... headers) {
Set<NameValueExpression> expressions = null;
if (headers != null) {
for (String header : headers) {
NameValueExpression expr = NameValueExpression.parse(header);
String name = expr.getName();
if (HttpHeaderNames.ACCEPT.getName().equalsIgnoreCase(name)
|| HttpHeaderNames.CONTENT_TYPE.getName().equalsIgnoreCase(name)) {
continue;
}
if (expressions == null) {
expressions = new LinkedHashSet<>();
}
expressions.add(expr);
}
}
this.expressions = expressions == null ? Collections.emptySet() : expressions;
}
private HeadersCondition(Set<NameValueExpression> expressions) {
this.expressions = expressions;
}
@Override
public HeadersCondition combine(HeadersCondition other) {
Set<NameValueExpression> set = new LinkedHashSet<>(expressions);
set.addAll(other.expressions);
return new HeadersCondition(set);
}
@Override
public HeadersCondition match(HttpRequest request) {
for (NameValueExpression expression : expressions) {
if (!expression.match(request::hasHeader, request::header)) {
return null;
}
}
return this;
}
@Override
public int compareTo(HeadersCondition other, HttpRequest request) {
return other.expressions.size() - expressions.size();
}
@Override
public int hashCode() {
return expressions.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != HeadersCondition.class) {
return false;
}
return expressions.equals(((HeadersCondition) obj).expressions);
}
@Override
public String toString() {
return "HeadersCondition{headers=" + expressions + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/ConditionWrapper.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/ConditionWrapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.condition;
import org.apache.dubbo.remoting.http12.HttpRequest;
import java.util.Objects;
@SuppressWarnings("unchecked")
public final class ConditionWrapper implements Condition<ConditionWrapper, HttpRequest> {
private final Condition<Object, HttpRequest> condition;
private ConditionWrapper(Condition<?, HttpRequest> condition) {
this.condition = (Condition<Object, HttpRequest>) Objects.requireNonNull(condition);
}
public static ConditionWrapper wrap(Condition<?, HttpRequest> condition) {
return condition instanceof ConditionWrapper ? (ConditionWrapper) condition : new ConditionWrapper(condition);
}
@Override
public ConditionWrapper combine(ConditionWrapper other) {
return new ConditionWrapper((Condition<?, HttpRequest>) condition.combine(other.condition));
}
@Override
public ConditionWrapper match(HttpRequest request) {
Condition<?, HttpRequest> match = (Condition<?, HttpRequest>) condition.match(request);
return match == null ? null : new ConditionWrapper(match);
}
@Override
public int compareTo(ConditionWrapper other, HttpRequest request) {
if (other == null) {
return -1;
}
return condition.compareTo(other.condition, request);
}
public Condition<Object, HttpRequest> getCondition() {
return condition;
}
@Override
public int hashCode() {
return condition.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != ConditionWrapper.class) {
return false;
}
return condition.equals(((ConditionWrapper) obj).condition);
}
@Override
public String toString() {
return condition.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/Condition.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/Condition.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.condition;
import org.apache.dubbo.remoting.http12.HttpRequest;
public interface Condition<T, R extends HttpRequest> {
T combine(T other);
T match(R request);
int compareTo(T other, R request);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/PathExpression.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/PathExpression.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.condition;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.PathSegment.Type;
import org.apache.dubbo.rpc.protocol.tri.rest.util.KeyString;
import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public final class PathExpression implements Comparable<PathExpression> {
private final String path;
private final PathSegment[] segments;
private PathExpression(String path, PathSegment[] segments) {
this.path = path;
this.segments = segments;
}
public static PathExpression parse(@Nonnull String path) {
return new PathExpression(path, PathParser.parse(path));
}
public static boolean match(@Nonnull String path, String value) {
return value != null && parse(path).match(value) != null;
}
public String getPath() {
return path;
}
public PathSegment[] getSegments() {
return segments;
}
public boolean isDirect() {
return segments.length == 1 && segments[0].getType() == Type.LITERAL;
}
public Map<String, String> match(@Nonnull String path) {
if (isDirect()) {
return this.path.equals(path) ? Collections.emptyMap() : null;
}
Map<String, String> variableMap = new LinkedHashMap<>();
int start, end = 0;
for (int i = 0, len = segments.length; i < len; i++) {
PathSegment segment = segments[i];
if (end != -1) {
start = end + 1;
end = path.indexOf('/', start);
if (segment.match(new KeyString(path), start, end, variableMap)) {
if (i == len - 1 && segment.isTailMatching()) {
return variableMap;
}
continue;
}
}
return null;
}
return end == -1 ? variableMap : null;
}
public int compareTo(PathExpression other, String lookupPath) {
boolean equalsPath = path.equals(lookupPath);
boolean otherEqualsPath = other.path.equals(lookupPath);
if (equalsPath) {
return otherEqualsPath ? 0 : -1;
}
if (otherEqualsPath) {
return 1;
}
return compareTo(other);
}
@Override
public int compareTo(PathExpression other) {
int size = segments.length;
int otherSize = other.segments.length;
if (isDirect() && other.isDirect()) {
return other.path.length() - path.length();
}
for (int i = 0; i < size && i < otherSize; i++) {
int result = segments[i].compareTo(other.segments[i]);
if (result != 0) {
return result;
}
}
return size - otherSize;
}
@Override
public int hashCode() {
return path.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != PathExpression.class) {
return false;
}
return path.equals(((PathExpression) obj).path);
}
@Override
public String toString() {
if (isDirect()) {
return path;
}
StringBuilder sb = new StringBuilder(path.length());
int varIndex = 1;
for (PathSegment segment : segments) {
sb.append('/');
switch (segment.getType()) {
case LITERAL:
sb.append(segment.getValue());
break;
case WILDCARD_TAIL:
List<String> variables = segment.getVariables();
if (variables == null) {
sb.append("{path}");
} else {
sb.append('{').append(variables.get(0)).append('}');
}
break;
case VARIABLE:
sb.append('{');
String value = segment.getValue();
if (value.isEmpty()) {
sb.append("var").append(varIndex++);
} else {
sb.append(value);
}
sb.append('}');
break;
case PATTERN:
case PATTERN_MULTI:
sb.append('{').append("var").append(varIndex++).append('}');
break;
default:
break;
}
}
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-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/ConsumesCondition.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/ConsumesCondition.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.condition;
import org.apache.dubbo.remoting.http12.HttpHeaderNames;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.message.MediaType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public final class ConsumesCondition implements Condition<ConsumesCondition, HttpRequest> {
public static final MediaTypeExpression DEFAULT = MediaTypeExpression.parse("application/octet-stream");
private final List<MediaTypeExpression> expressions;
public ConsumesCondition(String... consumes) {
this(consumes, null);
}
public ConsumesCondition(String[] consumes, String[] headers) {
Set<MediaTypeExpression> expressions = null;
if (headers != null) {
for (String header : headers) {
NameValueExpression expr = NameValueExpression.parse(header);
if (HttpHeaderNames.CONTENT_TYPE.getName().equalsIgnoreCase(expr.getName())) {
MediaTypeExpression expression = MediaTypeExpression.parse(expr.getValue());
if (expression == null) {
continue;
}
if (expressions == null) {
expressions = new LinkedHashSet<>();
}
expressions.add(expression);
}
}
}
if (consumes != null) {
for (String consume : consumes) {
MediaTypeExpression expression = MediaTypeExpression.parse(consume);
if (expression == null) {
continue;
}
if (expressions == null) {
expressions = new LinkedHashSet<>();
}
expressions.add(expression);
}
}
if (expressions == null) {
this.expressions = Collections.emptyList();
} else {
this.expressions = new ArrayList<>(expressions);
Collections.sort(this.expressions);
}
}
private ConsumesCondition(List<MediaTypeExpression> expressions) {
this.expressions = expressions;
}
@Override
public ConsumesCondition combine(ConsumesCondition other) {
return other.expressions.isEmpty() ? this : other;
}
@Override
public ConsumesCondition match(HttpRequest request) {
if (expressions.isEmpty()) {
return null;
}
String contentType = request.contentType();
MediaTypeExpression mediaType = contentType == null ? DEFAULT : MediaTypeExpression.parse(contentType);
List<MediaTypeExpression> result = null;
for (int i = 0, size = expressions.size(); i < size; i++) {
MediaTypeExpression expression = expressions.get(i);
if (expression.match(mediaType)) {
if (result == null) {
result = new ArrayList<>();
}
result.add(expression);
}
}
return result == null ? null : new ConsumesCondition(result);
}
@Override
public int compareTo(ConsumesCondition other, HttpRequest request) {
if (expressions.isEmpty()) {
return other.expressions.isEmpty() ? 0 : 1;
}
if (other.expressions.isEmpty()) {
return -1;
}
return expressions.get(0).compareTo(other.expressions.get(0));
}
public List<MediaType> getMediaTypes() {
return MediaTypeExpression.toMediaTypes(expressions);
}
@Override
public int hashCode() {
return expressions.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != ConsumesCondition.class) {
return false;
}
return expressions.equals(((ConsumesCondition) obj).expressions);
}
@Override
public String toString() {
return "ConsumesCondition{mediaTypes=" + expressions + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/MediaTypeExpression.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/MediaTypeExpression.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.condition;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.HttpUtils;
import org.apache.dubbo.remoting.http12.message.MediaType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
public final class MediaTypeExpression implements Comparable<MediaTypeExpression> {
public static final MediaTypeExpression ALL = new MediaTypeExpression(MediaType.WILDCARD, MediaType.WILDCARD);
public static final List<MediaTypeExpression> ALL_LIST = Collections.singletonList(ALL);
public static final Comparator<MediaTypeExpression> COMPARATOR = (m1, m2) -> {
int comparison = compareQuality(m1, m2);
if (comparison != 0) {
return comparison;
}
comparison = compareType(m1.type, m2.type);
if (comparison != Integer.MIN_VALUE) {
return comparison;
}
comparison = compareType(m1.subType, m2.subType);
return comparison == Integer.MIN_VALUE ? 0 : comparison;
};
public static final Comparator<MediaTypeExpression> QUALITY_COMPARATOR = MediaTypeExpression::compareQuality;
private final String type;
private final String subType;
private final boolean negated;
private final float quality;
private MediaTypeExpression(String type, String subType, float quality, boolean negated) {
this.type = type;
this.subType = subType;
this.quality = quality;
this.negated = negated;
}
public MediaTypeExpression(String type, String subType) {
this.type = type;
this.subType = subType;
quality = 1.0F;
negated = false;
}
public static List<MediaType> toMediaTypes(List<MediaTypeExpression> expressions) {
int size = expressions.size();
List<MediaType> mediaTypes = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
MediaTypeExpression expr = expressions.get(i);
mediaTypes.add(new MediaType(expr.getType(), expr.getSubType()));
}
return mediaTypes;
}
public static MediaTypeExpression parse(String expr) {
boolean negated;
if (expr.indexOf('!') == 0) {
negated = true;
expr = expr.substring(1);
} else {
negated = false;
}
if (StringUtils.isEmpty(expr)) {
return null;
}
int index = expr.indexOf(';');
String mimeType = (index == -1 ? expr : expr.substring(0, index)).trim();
if (MediaType.WILDCARD.equals(mimeType)) {
mimeType = "*/*";
}
int subIndex = mimeType.indexOf('/');
if (subIndex == -1 || subIndex == mimeType.length() - 1) {
return null;
}
String type = mimeType.substring(0, subIndex);
String subType = mimeType.substring(subIndex + 1);
if (MediaType.WILDCARD.equals(type) && !MediaType.WILDCARD.equals(subType)) {
return null;
}
return new MediaTypeExpression(type, subType, HttpUtils.parseQuality(expr, index), negated);
}
private static int compareType(String type1, String type2) {
boolean type1IsWildcard = MediaType.WILDCARD.equals(type1);
boolean type2IsWildcard = MediaType.WILDCARD.equals(type2);
if (type1IsWildcard && !type2IsWildcard) {
return 1;
}
if (type2IsWildcard && !type1IsWildcard) {
return -1;
}
if (!type1.equals(type2)) {
return 0;
}
return Integer.MIN_VALUE;
}
public String getType() {
return type;
}
public String getSubType() {
return subType;
}
public float getQuality() {
return quality;
}
private static int compareQuality(MediaTypeExpression m1, MediaTypeExpression m2) {
return Float.compare(m2.quality, m1.quality);
}
public boolean typesEquals(MediaTypeExpression other) {
return type.equalsIgnoreCase(other.type) && subType.equalsIgnoreCase(other.subType);
}
public boolean match(MediaTypeExpression other) {
return matchMediaType(other) != negated;
}
private boolean matchMediaType(MediaTypeExpression other) {
if (other == null) {
return false;
}
if (isWildcardType()) {
return true;
}
if (type.equals(other.type)) {
if (subType.equals(other.subType)) {
return true;
}
if (isWildcardSubtype()) {
int plusIdx = subType.lastIndexOf('+');
if (plusIdx == -1) {
return true;
}
int otherPlusIdx = other.subType.indexOf('+');
if (otherPlusIdx != -1) {
String subTypeNoSuffix = subType.substring(0, plusIdx);
String subTypeSuffix = subType.substring(plusIdx + 1);
String otherSubtypeSuffix = other.subType.substring(otherPlusIdx + 1);
return subTypeSuffix.equals(otherSubtypeSuffix) && MediaType.WILDCARD.equals(subTypeNoSuffix);
}
}
}
return false;
}
public boolean compatibleWith(MediaTypeExpression other) {
return compatibleWithMediaType(other) != negated;
}
private boolean compatibleWithMediaType(MediaTypeExpression other) {
if (other == null) {
return false;
}
if (isWildcardType() || other.isWildcardType()) {
return true;
}
if (type.equals(other.type)) {
if (subType.equalsIgnoreCase(other.subType)) {
return true;
}
if (isWildcardSubtype() || other.isWildcardSubtype()) {
if (subType.equals(MediaType.WILDCARD) || other.subType.equals(MediaType.WILDCARD)) {
return true;
}
String thisSuffix = getSubtypeSuffix();
String otherSuffix = other.getSubtypeSuffix();
if (isWildcardSubtype() && thisSuffix != null) {
return (thisSuffix.equals(other.subType) || thisSuffix.equals(otherSuffix));
}
if (other.isWildcardSubtype() && otherSuffix != null) {
return (subType.equals(otherSuffix) || otherSuffix.equals(thisSuffix));
}
}
}
return false;
}
private boolean isWildcardType() {
return MediaType.WILDCARD.equals(type);
}
private boolean isWildcardSubtype() {
return MediaType.WILDCARD.equals(subType) || subType.startsWith("*+");
}
private String getSubtypeSuffix() {
int suffixIndex = subType.lastIndexOf('+');
if (suffixIndex != -1) {
return subType.substring(suffixIndex + 1);
}
return null;
}
@Override
public int compareTo(MediaTypeExpression other) {
return COMPARATOR.compare(this, other);
}
@Override
public int hashCode() {
return Objects.hash(type, subType, negated, quality);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != MediaTypeExpression.class) {
return false;
}
MediaTypeExpression other = (MediaTypeExpression) obj;
return negated == other.negated
&& Float.compare(quality, other.quality) == 0
&& Objects.equals(type, other.type)
&& Objects.equals(subType, other.subType);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (negated) {
sb.append('!');
}
sb.append(type).append('/').append(subType);
if (quality != 1.0F) {
sb.append(";q=").append(quality);
}
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-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/ParamsCondition.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/ParamsCondition.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.condition;
import org.apache.dubbo.remoting.http12.HttpRequest;
import java.util.LinkedHashSet;
import java.util.Set;
public final class ParamsCondition implements Condition<ParamsCondition, HttpRequest> {
private final Set<NameValueExpression> expressions;
public ParamsCondition(String... params) {
expressions = NameValueExpression.parse(params);
}
private ParamsCondition(Set<NameValueExpression> expressions) {
this.expressions = expressions;
}
@Override
public ParamsCondition combine(ParamsCondition other) {
Set<NameValueExpression> set = new LinkedHashSet<>(expressions);
set.addAll(other.expressions);
return new ParamsCondition(set);
}
@Override
public ParamsCondition match(HttpRequest request) {
for (NameValueExpression expression : expressions) {
if (!expression.match(request::hasParameter, request::parameter)) {
return null;
}
}
return this;
}
@Override
public int compareTo(ParamsCondition other, HttpRequest request) {
return other.expressions.size() - expressions.size();
}
@Override
public int hashCode() {
return expressions.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != ParamsCondition.class) {
return false;
}
return expressions.equals(((ParamsCondition) obj).expressions);
}
@Override
public String toString() {
return "ParamsCondition{params=" + expressions + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/PathParser.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/PathParser.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.condition;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.Messages;
import org.apache.dubbo.rpc.protocol.tri.rest.PathParserException;
import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.PathSegment.Type;
import org.apache.dubbo.rpc.protocol.tri.rest.util.PathUtils;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
/**
* See
* <p>
* <a href="https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-requestmapping.html#mvc-ann-requestmapping-uri-templates">Spring uri templates</a>
* <br/>
* <a href="https://docs.jboss.org/resteasy/docs/6.2.7.Final/userguide/html/ch04.html">Path and regular expression mappings</a>
* </p>
*/
final class PathParser {
private static final PathSegment SLASH = new PathSegment(Type.SLASH, RestConstants.SLASH);
private final List<PathSegment> segments = new LinkedList<>();
private final StringBuilder buf = new StringBuilder();
/**
* Ensure that the path is normalized using {@link PathUtils#normalize(String)} before parsing.
*/
static PathSegment[] parse(String path) {
if (path == null || path.isEmpty() || RestConstants.SLASH.equals(path)) {
return new PathSegment[] {PathSegment.literal(RestConstants.SLASH)};
}
if (PathUtils.isDirectPath(path)) {
return new PathSegment[] {PathSegment.literal(path)};
}
List<PathSegment> segments = new PathParser().doParse(path);
return segments.toArray(new PathSegment[0]);
}
private List<PathSegment> doParse(String path) {
parseSegments(path);
transformSegments(segments, path);
for (PathSegment segment : segments) {
try {
segment.initPattern();
} catch (Exception e) {
throw new PathParserException(Messages.REGEX_PATTERN_INVALID, segment.getValue(), path, e);
}
}
return segments;
}
private void parseSegments(String path) {
int state = State.INITIAL;
boolean regexBraceStart = false;
boolean regexMulti = false;
String variableName = null;
int len = path.length();
for (int i = 0; i < len; i++) {
char c = path.charAt(i);
switch (c) {
case '/':
switch (state) {
case State.INITIAL:
case State.SEGMENT_END:
continue;
case State.LITERAL_START:
if (buf.length() > 0) {
appendSegment(Type.LITERAL);
}
break;
case State.WILDCARD_START:
appendSegment(Type.WILDCARD);
break;
case State.REGEX_VARIABLE_START:
if (path.charAt(i - 1) != '^' || path.charAt(i - 2) != '[') {
regexMulti = true;
}
buf.append(c);
continue;
case State.VARIABLE_START:
case State.WILDCARD_VARIABLE_START:
throw new PathParserException(Messages.MISSING_CLOSE_CAPTURE, path, i);
default:
}
segments.add(SLASH);
state = State.SEGMENT_END;
continue;
case '?':
switch (state) {
case State.INITIAL:
case State.LITERAL_START:
case State.SEGMENT_END:
state = State.WILDCARD_START;
break;
default:
}
break;
case '*':
switch (state) {
case State.INITIAL:
case State.LITERAL_START:
case State.SEGMENT_END:
state = State.WILDCARD_START;
break;
case State.VARIABLE_START:
if (path.charAt(i - 1) == '{') {
state = State.WILDCARD_VARIABLE_START;
continue;
}
break;
default:
}
break;
case '.':
if (state == State.REGEX_VARIABLE_START) {
if (path.charAt(i - 1) != '\\') {
regexMulti = true;
}
}
break;
case 'S':
case 'W':
if (state == State.REGEX_VARIABLE_START) {
if (path.charAt(i - 1) == '\\') {
regexMulti = true;
}
}
break;
case ':':
if (state == State.VARIABLE_START) {
state = State.REGEX_VARIABLE_START;
variableName = buf.toString();
buf.setLength(0);
continue;
}
break;
case '{':
switch (state) {
case State.INITIAL:
case State.SEGMENT_END:
state = State.VARIABLE_START;
continue;
case State.LITERAL_START:
if (buf.length() > 0) {
appendSegment(Type.LITERAL);
}
state = State.VARIABLE_START;
continue;
case State.VARIABLE_START:
case State.WILDCARD_VARIABLE_START:
throw new PathParserException(Messages.ILLEGAL_NESTED_CAPTURE, path, i);
case State.REGEX_VARIABLE_START:
if (path.charAt(i - 1) != '\\') {
regexBraceStart = true;
}
break;
default:
}
break;
case '}':
switch (state) {
case State.INITIAL:
case State.LITERAL_START:
case State.SEGMENT_END:
throw new PathParserException(Messages.MISSING_OPEN_CAPTURE, path);
case State.VARIABLE_START:
appendSegment(Type.VARIABLE, buf.toString());
state = State.LITERAL_START;
continue;
case State.REGEX_VARIABLE_START:
if (regexBraceStart) {
regexBraceStart = false;
} else {
if (buf.length() == 0) {
throw new PathParserException(Messages.MISSING_REGEX_CONSTRAINT, path, i);
}
appendSegment(regexMulti ? Type.PATTERN_MULTI : Type.PATTERN, variableName);
regexMulti = false;
state = State.LITERAL_START;
continue;
}
break;
case State.WILDCARD_VARIABLE_START:
appendSegment(Type.WILDCARD_TAIL, buf.toString());
state = State.END;
continue;
default:
}
break;
default:
if (state == State.INITIAL || state == State.SEGMENT_END) {
state = State.LITERAL_START;
}
break;
}
if (state == State.END) {
throw new PathParserException(Messages.NO_MORE_DATA_ALLOWED, path, i);
}
buf.append(c);
}
if (buf.length() > 0) {
switch (state) {
case State.LITERAL_START:
appendSegment(Type.LITERAL);
break;
case State.WILDCARD_START:
appendSegment(Type.WILDCARD);
break;
case State.VARIABLE_START:
case State.REGEX_VARIABLE_START:
case State.WILDCARD_VARIABLE_START:
throw new PathParserException(Messages.MISSING_CLOSE_CAPTURE, path, len - 1);
default:
}
}
}
private void appendSegment(Type type) {
segments.add(new PathSegment(type, buf.toString()));
buf.setLength(0);
}
private void appendSegment(Type type, String name) {
segments.add(new PathSegment(type, buf.toString().trim(), name.trim()));
buf.setLength(0);
}
private static void transformSegments(List<PathSegment> segments, String path) {
ListIterator<PathSegment> iterator = segments.listIterator();
PathSegment curr, prev = null;
while (iterator.hasNext()) {
curr = iterator.next();
String value = curr.getValue();
Type type = curr.getType();
switch (type) {
case SLASH:
if (prev != null) {
switch (prev.getType()) {
case LITERAL:
case VARIABLE:
case PATTERN:
prev = curr;
break;
case PATTERN_MULTI:
if (!".*".equals(prev.getValue())) {
prev.setValue(prev.getValue() + '/');
}
break;
default:
}
}
iterator.remove();
continue;
case WILDCARD:
if ("*".equals(value)) {
type = Type.VARIABLE;
value = StringUtils.EMPTY_STRING;
} else if ("**".equals(value)) {
if (!iterator.hasNext()) {
type = Type.WILDCARD_TAIL;
value = StringUtils.EMPTY_STRING;
} else {
type = Type.PATTERN_MULTI;
value = ".*";
}
} else {
type = Type.PATTERN;
value = toRegex(value);
}
curr.setType(type);
curr.setValue(value);
break;
case WILDCARD_TAIL:
break;
case PATTERN:
case PATTERN_MULTI:
curr.setValue("(?<" + curr.getVariable() + '>' + value + ')');
break;
default:
}
if (prev == null) {
prev = curr;
continue;
}
String pValue = prev.getValue();
switch (prev.getType()) {
case LITERAL:
switch (type) {
case VARIABLE:
prev.setType(Type.PATTERN);
prev.setValue(quoteRegex(pValue) + "(?<" + curr.getVariable() + ">[^/]+)");
prev.setVariables(curr.getVariables());
iterator.remove();
continue;
case PATTERN:
case PATTERN_MULTI:
prev.setType(type);
prev.setValue(quoteRegex(pValue) + "(?<" + curr.getVariable() + '>' + value + ')');
prev.setVariables(curr.getVariables());
iterator.remove();
continue;
default:
}
break;
case VARIABLE:
switch (type) {
case LITERAL:
prev.setType(Type.PATTERN);
prev.setValue("(?<" + prev.getVariable() + ">[^/]+)" + quoteRegex(value));
iterator.remove();
continue;
case VARIABLE:
throw new PathParserException(Messages.ILLEGAL_DOUBLE_CAPTURE, path);
case PATTERN:
case PATTERN_MULTI:
String var = curr.getVariable();
prev.addVariable(var);
prev.setType(type);
prev.setValue("(?<" + prev.getVariable() + ">[^/]+)(?<" + var + '>' + value + ')');
iterator.remove();
continue;
default:
}
break;
case PATTERN:
case PATTERN_MULTI:
switch (type) {
case LITERAL:
prev.setValue(pValue + quoteRegex(value));
iterator.remove();
continue;
case WILDCARD_TAIL:
if (curr.getVariables() == null) {
prev.setValue(pValue + ".*");
} else {
prev.addVariable(curr.getVariable());
prev.setValue(pValue + "(?<" + curr.getVariable() + ">.*)");
}
prev.setType(Type.PATTERN_MULTI);
iterator.remove();
continue;
case VARIABLE:
if (value.isEmpty()) {
prev.setValue(pValue + "[^/]+");
iterator.remove();
continue;
}
prev.addVariable(curr.getVariable());
prev.setValue(pValue + "(?<" + curr.getVariable() + ">[^/]+)");
iterator.remove();
continue;
case PATTERN_MULTI:
prev.setType(Type.PATTERN_MULTI);
case PATTERN:
if (curr.getVariables() == null) {
prev.setValue(pValue + value);
} else {
prev.addVariable(curr.getVariable());
prev.setValue(pValue + "(?<" + curr.getVariable() + '>' + value + ')');
}
iterator.remove();
continue;
default:
}
break;
default:
}
prev = curr;
}
}
private static String quoteRegex(String regex) {
for (int i = 0, len = regex.length(); i < len; i++) {
switch (regex.charAt(i)) {
case '(':
case ')':
case '[':
case ']':
case '$':
case '^':
case '.':
case '{':
case '}':
case '|':
case '\\':
return "\\Q" + regex + "\\E";
default:
}
}
return regex;
}
private static String toRegex(String wildcard) {
int len = wildcard.length();
StringBuilder sb = new StringBuilder(len + 8);
for (int i = 0; i < len; i++) {
char c = wildcard.charAt(i);
switch (c) {
case '*':
if (i > 0) {
char prev = wildcard.charAt(i - 1);
if (prev == '*') {
continue;
}
if (prev == '?') {
sb.append("*");
continue;
}
}
sb.append("[^/]*");
break;
case '?':
if (i > 0 && wildcard.charAt(i - 1) == '*') {
continue;
}
sb.append("[^/]");
break;
case '(':
case ')':
case '$':
case '.':
case '{':
case '}':
case '|':
case '\\':
sb.append('\\');
sb.append(c);
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
private interface State {
int INITIAL = 0;
int LITERAL_START = 1;
int WILDCARD_START = 2;
int VARIABLE_START = 3;
int REGEX_VARIABLE_START = 4;
int WILDCARD_VARIABLE_START = 5;
int SEGMENT_END = 6;
int END = 7;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/ServiceGroupVersionCondition.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/ServiceGroupVersionCondition.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.condition;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.rpc.protocol.tri.TripleConstants;
import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
import org.apache.dubbo.rpc.protocol.tri.TripleProtocol;
import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants;
import java.util.Objects;
public final class ServiceGroupVersionCondition implements Condition<ServiceGroupVersionCondition, HttpRequest> {
private final String group;
private final String version;
public ServiceGroupVersionCondition(String group, String version) {
this.group = group;
this.version = version;
}
@Override
public ServiceGroupVersionCondition combine(ServiceGroupVersionCondition other) {
return this;
}
@Override
public ServiceGroupVersionCondition match(HttpRequest request) {
if (TripleProtocol.RESOLVE_FALLBACK_TO_DEFAULT) {
return this;
}
String group = getHeader(request, TripleHeaderEnum.SERVICE_GROUP, RestConstants.HEADER_SERVICE_GROUP);
if (!Objects.equals(group, this.group)) {
return null;
}
String version = getHeader(request, TripleHeaderEnum.SERVICE_VERSION, RestConstants.HEADER_SERVICE_VERSION);
if (!Objects.equals(version, this.version)) {
return null;
}
return this;
}
@Override
public int compareTo(ServiceGroupVersionCondition other, HttpRequest request) {
if (!TripleProtocol.RESOLVE_FALLBACK_TO_DEFAULT) {
return 0;
}
String group = getHeader(request, TripleHeaderEnum.SERVICE_GROUP, RestConstants.HEADER_SERVICE_GROUP);
String version = getHeader(request, TripleHeaderEnum.SERVICE_VERSION, RestConstants.HEADER_SERVICE_VERSION);
return getMatchLevel(other, group, version) - getMatchLevel(this, group, version);
}
private static String getHeader(HttpRequest request, TripleHeaderEnum en, String key) {
String value = request.header(en.getKey());
if (value == null) {
value = request.header(key);
}
return value;
}
private static int getMatchLevel(ServiceGroupVersionCondition condition, String group, String version) {
if (Objects.equals(group, condition.group)) {
if (Objects.equals(version, condition.version)) {
return 9;
}
if (Objects.equals(TripleConstants.DEFAULT_VERSION, condition.version)) {
return 8;
}
return group == null ? 5 : 7;
} else {
if (Objects.equals(version, condition.version)) {
return 6;
}
if (Objects.equals(TripleConstants.DEFAULT_VERSION, condition.version)) {
return 4;
}
return 3;
}
}
@Override
public int hashCode() {
return Objects.hash(group, version);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != ServiceGroupVersionCondition.class) {
return false;
}
ServiceGroupVersionCondition other = (ServiceGroupVersionCondition) obj;
return Objects.equals(group, other.group) && Objects.equals(version, other.version);
}
@Override
public String toString() {
return "ServiceVersionCondition{group='" + group + "', version='" + version + "'}";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/PathSegment.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/PathSegment.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.condition;
import org.apache.dubbo.rpc.protocol.tri.rest.Messages;
import org.apache.dubbo.rpc.protocol.tri.rest.PathParserException;
import org.apache.dubbo.rpc.protocol.tri.rest.util.KeyString;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class PathSegment implements Comparable<PathSegment> {
private Type type;
private String value;
private List<String> variables;
private Pattern pattern;
private KeyString keyValue;
public PathSegment(Type type, String value) {
this.type = type;
this.value = value;
}
public PathSegment(Type type, String value, String variable) {
this.type = type;
this.value = value;
addVariable(variable);
}
public static PathSegment literal(String value) {
return new PathSegment(Type.LITERAL, value);
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public List<String> getVariables() {
return variables;
}
public void setVariables(List<String> variables) {
this.variables = variables;
}
public String getVariable() {
return variables.get(0);
}
public void addVariable(String variable) {
if (variables == null) {
variables = new ArrayList<>();
} else if (variables.contains(variable)) {
throw new PathParserException(Messages.DUPLICATE_CAPTURE_VARIABLE, variable);
}
variables.add(variable);
}
public Pattern getPattern() {
if (pattern == null) {
initPattern();
}
return pattern;
}
public void initPattern() {
if (isPattern()) {
pattern = Pattern.compile(value);
}
}
public boolean isPattern() {
return type == Type.PATTERN || type == Type.PATTERN_MULTI;
}
public boolean isTailMatching() {
return type == Type.WILDCARD_TAIL || type == Type.PATTERN_MULTI;
}
public boolean match(KeyString path, int start, int end, Map<String, String> variableMap) {
switch (type) {
case SLASH:
case LITERAL:
if (keyValue == null) {
keyValue = new KeyString(value);
}
return path.regionMatches(start, keyValue);
case WILDCARD_TAIL:
if (variables != null) {
variableMap.put(getVariable(), path.toString(start));
}
return true;
case VARIABLE:
if (variables != null) {
variableMap.put(getVariable(), path.toString(start, end));
}
return true;
case PATTERN:
return matchPattern(path.toString(start, end), variableMap);
case PATTERN_MULTI:
return matchPattern(path.toString(start), variableMap);
default:
return false;
}
}
public boolean match(String path, int start, int end, Map<String, String> variableMap) {
return match(new KeyString(path), start, end, variableMap);
}
private boolean matchPattern(String path, Map<String, String> variableMap) {
Matcher matcher = getPattern().matcher(path);
if (matcher.matches()) {
if (variables == null) {
return true;
}
for (int i = 0, size = variables.size(); i < size; i++) {
String variable = variables.get(i);
variableMap.put(variable, matcher.group(variable));
}
return true;
}
return false;
}
@Override
public int hashCode() {
return type.ordinal() | (value == null ? 0 : value.hashCode() << 3);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != PathSegment.class) {
return false;
}
PathSegment that = (PathSegment) obj;
return type == that.type && value.equals(that.value);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{type=");
sb.append(type);
if (value != null) {
sb.append(", value=").append(value);
}
if (variables != null) {
sb.append(", variables=").append(variables);
}
sb.append('}');
return sb.toString();
}
@Override
public int compareTo(PathSegment other) {
if (type != other.type) {
int comparison = type.score() - other.type.score;
if (comparison != 0) {
return comparison;
}
}
int size = variables == null ? 99 : variables.size();
int otherSize = other.variables == null ? 99 : other.variables.size();
return size - otherSize;
}
public enum Type {
/**
* A slash segment, transient type used for parsing.
* will not be present in the PathExpression
* E.g.: '/'
*/
SLASH,
/**
* A literal segment.
* E.g.: 'foo'
*/
LITERAL(1),
/**
* A wildcard segment.
* E.g.: 't?st*uv'
*/
WILDCARD,
/**
* A wildcard matching suffix.
* Transient type used for parsing, will not be present in the PathExpression
* E.g.: '/foo/**' or '/**' or '/{*bar}'
*/
WILDCARD_TAIL,
/**
* A template variable segment.
* E.g.: '{foo}' or '/foo/*/bar'
*/
VARIABLE(10),
/**
* A regex variable matching single segment.
* E.g.: '{foo:\d+}'
*/
PATTERN(100),
/**
* A regex variable matching multiple segments.
* E.g.: '{foo:.*}'
*/
PATTERN_MULTI(200);
private final int score;
Type(int score) {
this.score = score;
}
Type() {
score = 10000;
}
public int score() {
return score;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/MethodsCondition.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/MethodsCondition.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.condition;
import org.apache.dubbo.remoting.http12.HttpRequest;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static org.apache.dubbo.remoting.http12.HttpMethods.GET;
import static org.apache.dubbo.remoting.http12.HttpMethods.HEAD;
import static org.apache.dubbo.remoting.http12.HttpMethods.OPTIONS;
public final class MethodsCondition implements Condition<MethodsCondition, HttpRequest> {
private final Set<String> methods;
public MethodsCondition(String... methods) {
this.methods = new HashSet<>(Arrays.asList(methods));
}
private MethodsCondition(Set<String> methods) {
this.methods = methods;
}
public Set<String> getMethods() {
return methods;
}
@Override
public MethodsCondition combine(MethodsCondition other) {
Set<String> set = new HashSet<>(methods);
set.addAll(other.methods);
return new MethodsCondition(set);
}
@Override
public MethodsCondition match(HttpRequest request) {
String method = request.method();
if (OPTIONS.is(method)) {
if (request.hasHeader("origin") && request.hasHeader("access-control-request-method")) {
return new MethodsCondition(OPTIONS.name());
} else {
return this;
}
}
if (methods.contains(method)) {
return new MethodsCondition(method);
}
if (HEAD.is(method) && methods.contains(GET.name())) {
return new MethodsCondition(GET.name());
}
return null;
}
@Override
public int compareTo(MethodsCondition other, HttpRequest request) {
if (other.methods.size() != methods.size()) {
return other.methods.size() - methods.size();
}
if (methods.size() == 1) {
if (methods.contains(HEAD.name()) && other.methods.contains(GET.name())) {
return -1;
}
if (methods.contains(GET.name()) && other.methods.contains(HEAD.name())) {
return 1;
}
}
return 0;
}
@Override
public int hashCode() {
return methods.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != MethodsCondition.class) {
return false;
}
return methods.equals(((MethodsCondition) obj).methods);
}
@Override
public String toString() {
return "MethodsCondition{methods=" + methods + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/AnnotationSupport.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/AnnotationSupport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.meta;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RestToolKit;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@SuppressWarnings({"rawtypes", "unchecked"})
public abstract class AnnotationSupport {
private static final AnnotationMeta[] EMPTY = new AnnotationMeta[0];
private static final int GET_KEY = 1;
private static final int GET_MERGED_KEY = 2;
private static final int FIND_KEY = 3;
private static final int FIND_MERGED_KEY = 4;
private final Map<Key, Optional<AnnotationMeta>> cache = CollectionUtils.newConcurrentHashMap();
private final Map<Integer, AnnotationMeta[]> arrayCache = CollectionUtils.newConcurrentHashMap();
private final RestToolKit toolKit;
protected AnnotationSupport(RestToolKit toolKit) {
this.toolKit = toolKit;
}
public final AnnotationMeta[] getAnnotations() {
return arrayCache.computeIfAbsent(GET_KEY, k -> {
AnnotatedElement element = getAnnotatedElement();
Annotation[] annotations = element.getAnnotations();
int len = annotations.length;
if (len == 0) {
return EMPTY;
}
AnnotationMeta[] metas = new AnnotationMeta[len];
for (int i = 0; i < len; i++) {
metas[i] = new AnnotationMeta(element, annotations[i], toolKit);
}
return metas;
});
}
public final Annotation[] getRawAnnotations() {
AnnotationMeta[] annotations = getAnnotations();
int len = annotations.length;
Annotation[] result = new Annotation[len];
for (int i = 0; i < len; i++) {
result[i] = annotations[i].getAnnotation();
}
return result;
}
public final <A extends Annotation> AnnotationMeta<A> getAnnotation(Class<A> annotationType) {
return cache.computeIfAbsent(new Key(annotationType, GET_KEY), k -> {
AnnotatedElement element = getAnnotatedElement();
Annotation annotation = element.getAnnotation(annotationType);
if (annotation != null) {
return Optional.of(new AnnotationMeta(element, annotation, toolKit));
}
return Optional.empty();
})
.orElse(null);
}
public final AnnotationMeta getAnnotation(AnnotationEnum annotationEnum) {
return annotationEnum.isPresent() ? getAnnotation(annotationEnum.type()) : null;
}
public final boolean isAnnotated(Class<? extends Annotation> annotationType) {
return getAnnotation(annotationType) != null;
}
public final boolean isAnnotated(AnnotationEnum annotationEnum) {
return getAnnotation(annotationEnum) != null;
}
public final <A extends Annotation> AnnotationMeta<A> getMergedAnnotation(Class<A> annotationType) {
return cache.computeIfAbsent(new Key(annotationType, GET_MERGED_KEY), k -> {
AnnotatedElement element = getAnnotatedElement();
Annotation[] annotations = element.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation.annotationType() == annotationType) {
return Optional.of(new AnnotationMeta(element, annotation, toolKit));
}
Annotation metaAnnotation = annotation.annotationType().getAnnotation(annotationType);
if (metaAnnotation != null) {
return Optional.of(new AnnotationMeta(element, metaAnnotation, toolKit));
}
}
return Optional.empty();
})
.orElse(null);
}
public final AnnotationMeta getMergedAnnotation(AnnotationEnum annotationEnum) {
return annotationEnum.isPresent() ? getMergedAnnotation(annotationEnum.type()) : null;
}
public final boolean isMergedAnnotated(Class<? extends Annotation> annotationType) {
return getMergedAnnotation(annotationType) != null;
}
public final boolean isMergedAnnotated(AnnotationEnum annotationEnum) {
return getMergedAnnotation(annotationEnum) != null;
}
public final AnnotationMeta[] findAnnotations() {
return arrayCache.computeIfAbsent(FIND_KEY, k -> {
List<? extends AnnotatedElement> elements = getAnnotatedElements();
List<AnnotationMeta> metas = new ArrayList<>();
for (int i = 0, size = elements.size(); i < size; i++) {
AnnotatedElement element = elements.get(i);
Annotation[] annotations = element.getAnnotations();
for (Annotation annotation : annotations) {
metas.add(new AnnotationMeta(element, annotation, toolKit));
}
}
if (metas.isEmpty()) {
return EMPTY;
}
return metas.toArray(new AnnotationMeta[0]);
});
}
public final <A extends Annotation> AnnotationMeta<A> findAnnotation(Class<A> annotationType) {
return cache.computeIfAbsent(new Key(annotationType, FIND_KEY), k -> {
List<? extends AnnotatedElement> elements = getAnnotatedElements();
for (int i = 0, size = elements.size(); i < size; i++) {
AnnotatedElement element = elements.get(i);
Annotation annotation = element.getDeclaredAnnotation(annotationType);
if (annotation != null) {
return Optional.of(new AnnotationMeta(element, annotation, toolKit));
}
}
return Optional.empty();
})
.orElse(null);
}
public final AnnotationMeta findAnnotation(AnnotationEnum annotationEnum) {
return annotationEnum.isPresent() ? findAnnotation(annotationEnum.type()) : null;
}
public final boolean isHierarchyAnnotated(Class<? extends Annotation> annotationType) {
return findAnnotation(annotationType) != null;
}
public final boolean isHierarchyAnnotated(AnnotationEnum annotationEnum) {
return findAnnotation(annotationEnum) != null;
}
public final <A extends Annotation> AnnotationMeta<A> findMergedAnnotation(Class<A> annotationType) {
return cache.computeIfAbsent(new Key(annotationType, FIND_MERGED_KEY), k -> {
List<? extends AnnotatedElement> elements = getAnnotatedElements();
for (int i = 0, size = elements.size(); i < size; i++) {
AnnotatedElement element = elements.get(i);
Annotation[] annotations = element.getDeclaredAnnotations();
for (Annotation annotation : annotations) {
if (annotation.annotationType() == annotationType) {
return Optional.of(new AnnotationMeta(element, annotation, toolKit));
}
Annotation metaAnnotation =
annotation.annotationType().getAnnotation(annotationType);
if (metaAnnotation != null) {
return Optional.of(new AnnotationMeta(element, metaAnnotation, toolKit));
}
}
}
return Optional.empty();
})
.orElse(null);
}
public final AnnotationMeta findMergedAnnotation(AnnotationEnum annotationEnum) {
return annotationEnum.isPresent() ? findMergedAnnotation(annotationEnum.type()) : null;
}
public final boolean isMergedHierarchyAnnotated(Class<? extends Annotation> annotationType) {
return findMergedAnnotation(annotationType) != null;
}
public final boolean isMergedHierarchyAnnotated(AnnotationEnum annotationEnum) {
return findMergedAnnotation(annotationEnum) != null;
}
public final RestToolKit getToolKit() {
return toolKit;
}
public List<? extends AnnotatedElement> getAnnotatedElements() {
return Collections.singletonList(getAnnotatedElement());
}
private static final class Key {
private final Class<? extends Annotation> annotationType;
private final int type;
Key(Class<? extends Annotation> annotationType, int type) {
this.annotationType = annotationType;
this.type = type;
}
@Override
public int hashCode() {
return (annotationType.hashCode() << 2) + type;
}
@SuppressWarnings({"EqualsWhichDoesntCheckParameterClass", "EqualsDoesntCheckParameterClass"})
@Override
public boolean equals(Object obj) {
Key other = (Key) obj;
return annotationType == other.annotationType && type == other.type;
}
}
protected abstract AnnotatedElement getAnnotatedElement();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/HandlerMeta.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/HandlerMeta.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.meta;
import org.apache.dubbo.remoting.http12.message.MethodMetadata;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
public final class HandlerMeta {
private final Invoker<?> invoker;
private final MethodMeta method;
private final MethodMetadata methodMetadata;
private final MethodDescriptor methodDescriptor;
private final ServiceDescriptor serviceDescriptor;
public HandlerMeta(
Invoker<?> invoker,
MethodMeta method,
MethodMetadata methodMetadata,
MethodDescriptor methodDescriptor,
ServiceDescriptor serviceDescriptor) {
this.invoker = invoker;
this.method = method;
this.methodMetadata = methodMetadata;
this.methodDescriptor = methodDescriptor;
this.serviceDescriptor = serviceDescriptor;
}
public Invoker<?> getInvoker() {
return invoker;
}
public MethodMeta getMethod() {
return method;
}
public ServiceMeta getService() {
return method.getServiceMeta();
}
public ParameterMeta[] getParameters() {
return method.getParameters();
}
public MethodMetadata getMethodMetadata() {
return methodMetadata;
}
public MethodDescriptor getMethodDescriptor() {
return methodDescriptor;
}
public ServiceDescriptor getServiceDescriptor() {
return serviceDescriptor;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/AnnotationMeta.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/AnnotationMeta.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.meta;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RestToolKit;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
@SuppressWarnings("unchecked")
public final class AnnotationMeta<A extends Annotation> {
private final Map<String, Optional<Object>> cache = CollectionUtils.newConcurrentHashMap();
private final AnnotatedElement element;
private final A annotation;
private final RestToolKit toolKit;
private Map<String, Object> attributes;
public AnnotationMeta(AnnotatedElement element, A annotation, RestToolKit toolKit) {
this.element = element;
this.annotation = annotation;
this.toolKit = toolKit;
}
public A getAnnotation() {
return annotation;
}
public Class<? extends Annotation> getAnnotationType() {
return annotation.annotationType();
}
public Map<String, Object> getAttributes() {
Map<String, Object> attributes = this.attributes;
if (attributes == null) {
Map<String, Object> map = toolKit.getAttributes(element, annotation);
if (CollectionUtils.isEmptyMap(map)) {
attributes = Collections.emptyMap();
} else {
attributes = CollectionUtils.newHashMap(map.size());
for (Map.Entry<String, Object> entry : map.entrySet()) {
Object value = entry.getValue();
if (value instanceof String) {
value = toolKit.resolvePlaceholders((String) value);
} else if (value instanceof String[]) {
String[] array = (String[]) value;
for (int i = 0, len = array.length; i < len; i++) {
array[i] = toolKit.resolvePlaceholders(array[i]);
}
}
attributes.put(entry.getKey(), value);
}
}
this.attributes = attributes;
}
return attributes;
}
public boolean hasAttribute(String attributeName) {
return getAttributes().containsKey(attributeName);
}
public String getValue() {
return getString("value");
}
public String[] getValueArray() {
return getStringArray("value");
}
public String getString(String attributeName) {
return getRequiredAttribute(attributeName, String.class);
}
public String[] getStringArray(String attributeName) {
return getRequiredAttribute(attributeName, String[].class);
}
public boolean getBoolean(String attributeName) {
return getRequiredAttribute(attributeName, Boolean.class);
}
public <N extends Number> N getNumber(String attributeName) {
return (N) getRequiredAttribute(attributeName, Number.class);
}
public <E extends Enum<?>> E getEnum(String attributeName) {
return (E) getRequiredAttribute(attributeName, Enum.class);
}
public <E extends Enum<?>> E[] getEnumArray(String attributeName) {
return (E[]) getRequiredAttribute(attributeName, Enum[].class);
}
public <T> Class<? extends T> getClass(String attributeName) {
return getRequiredAttribute(attributeName, Class.class);
}
public Class<?>[] getClassArray(String attributeName) {
return getRequiredAttribute(attributeName, Class[].class);
}
public <A1 extends Annotation> AnnotationMeta<A1> getAnnotation(String attributeName) {
return (AnnotationMeta<A1>) cache.computeIfAbsent(attributeName, k -> {
if (getAttributes().get(attributeName) == null) {
return Optional.empty();
}
Annotation annotation = getRequiredAttribute(attributeName, Annotation.class);
return Optional.of(new AnnotationMeta<>(getAnnotationType(), annotation, toolKit));
})
.orElseThrow(() -> attributeNotFound(attributeName));
}
public <A1 extends Annotation> AnnotationMeta<A1>[] getAnnotationArray(String attributeName) {
return (AnnotationMeta<A1>[]) cache.computeIfAbsent(attributeName, k -> {
if (getAttributes().get(attributeName) == null) {
return Optional.empty();
}
Annotation[] annotation = getRequiredAttribute(attributeName, Annotation[].class);
int len = annotation.length;
AnnotationMeta<A1>[] metas = new AnnotationMeta[len];
for (int i = 0; i < len; i++) {
metas[i] = new AnnotationMeta<>(getAnnotationType(), (A1) annotation[i], toolKit);
}
return Optional.of(metas);
})
.orElseThrow(() -> attributeNotFound(attributeName));
}
public <A1 extends Annotation> A1 getAnnotation(String attributeName, Class<A1> annotationType) {
return getRequiredAttribute(attributeName, annotationType);
}
public <A1 extends Annotation> A1[] getAnnotationArray(String attributeName, Class<A1> annotationType) {
Class<?> arrayType = Array.newInstance(annotationType, 0).getClass();
return (A1[]) getRequiredAttribute(attributeName, arrayType);
}
public <T> T getRequiredAttribute(String attributeName, Class<T> expectedType) {
Object value = getAttributes().get(attributeName);
if (value == null) {
throw attributeNotFound(attributeName);
}
if (value instanceof Throwable) {
throw new IllegalArgumentException(
String.format(
"Attribute '%s' for annotation [%s] was not resolvable due to exception [%s]",
attributeName, getAnnotationType().getName(), value),
(Throwable) value);
}
if (expectedType.isInstance(value)) {
return (T) value;
}
if (expectedType == String.class) {
return (T) value.toString();
}
if (expectedType == Boolean.class) {
Boolean b = StringUtils.toBoolean(value.toString());
return (T) (b == null ? Boolean.FALSE : b);
}
if (expectedType == Number.class) {
String str = value.toString();
return str.indexOf('.') > -1 ? (T) Double.valueOf(str) : (T) Long.valueOf(str);
}
if (expectedType.isArray()) {
Class<?> expectedComponentType = expectedType.getComponentType();
if (expectedComponentType.isInstance(value)) {
Object array = Array.newInstance(expectedComponentType, 1);
Array.set(array, 0, value);
return (T) array;
}
if (expectedComponentType == String.class) {
String[] array;
if (value.getClass().isArray()) {
int len = Array.getLength(value);
array = new String[len];
for (int i = 0; i < len; i++) {
array[i] = Array.get(value, i).toString();
}
} else {
array = new String[] {value.toString()};
}
return (T) array;
}
}
throw new IllegalArgumentException(String.format(
"Attribute '%s' is of type %s, but %s was expected in attributes for annotation [%s]",
attributeName,
value.getClass().getSimpleName(),
expectedType.getSimpleName(),
getAnnotationType().getName()));
}
private IllegalArgumentException attributeNotFound(String attributeName) {
return new IllegalArgumentException(String.format(
"Attribute '%s' not found in attributes for annotation [%s]",
attributeName, getAnnotationType().getName()));
}
@Override
public int hashCode() {
return 31 * element.hashCode() + annotation.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != AnnotationMeta.class) {
return false;
}
AnnotationMeta<?> other = (AnnotationMeta<?>) obj;
return element.equals(other.element) && annotation.equals(other.annotation);
}
@Override
public String toString() {
return "AnnotationMeta{" + "element=" + element + ", annotation=" + annotation + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/ResponseMeta.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/ResponseMeta.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.meta;
import org.apache.dubbo.common.utils.StringUtils;
public class ResponseMeta {
private final Integer status;
private final String reason;
public ResponseMeta(Integer status, String reason) {
this.status = status;
this.reason = reason;
}
public Integer getStatus() {
return status;
}
public String getReason() {
return reason;
}
public static ResponseMeta combine(ResponseMeta self, ResponseMeta other) {
if (self == null) {
return other;
}
if (other == null) {
return self;
}
Integer status = other.getStatus() == null ? self.status : other.getStatus();
String reason = other.getReason() == null ? self.reason : other.getReason();
return new ResponseMeta(status, reason);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("ResponseMeta{");
if (status != null) {
sb.append("status=").append(status);
}
if (StringUtils.isNotEmpty(reason)) {
sb.append(", reason='").append(reason).append('\'');
}
sb.append('}');
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-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/MethodParameterMeta.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/MethodParameterMeta.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.meta;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.List;
public final class MethodParameterMeta extends ParameterMeta {
private final List<Parameter> hierarchy;
private final Parameter parameter;
private final int index;
private final MethodMeta methodMeta;
public MethodParameterMeta(List<Parameter> hierarchy, String name, int index, MethodMeta methodMeta) {
super(methodMeta.getToolKit(), name);
this.hierarchy = hierarchy;
parameter = hierarchy.get(0);
this.index = index;
this.methodMeta = methodMeta;
}
public List<Parameter> getHierarchy() {
return hierarchy;
}
public Parameter getParameter() {
return parameter;
}
@Override
public int getIndex() {
return index;
}
public MethodMeta getMethodMeta() {
return methodMeta;
}
@Override
public Class<?> getType() {
return parameter.getType();
}
@Override
public Type getGenericType() {
return parameter.getParameterizedType();
}
@Override
public String getDescription() {
return "parameter [" + getMethod() + "] in {" + index + "}";
}
public Method getMethod() {
return methodMeta.getMethod();
}
@Override
protected AnnotatedElement getAnnotatedElement() {
return parameter;
}
@Override
public List<? extends AnnotatedElement> getAnnotatedElements() {
return hierarchy;
}
@Override
public int hashCode() {
return 31 * getMethod().hashCode() + index;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != MethodParameterMeta.class) {
return false;
}
MethodParameterMeta other = (MethodParameterMeta) obj;
return getMethod().equals(other.getMethod()) && index == other.index;
}
@Override
public String toString() {
return "MethodParameterMeta{parameter=" + parameter + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/CorsMeta.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/CorsMeta.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.meta;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.rpc.protocol.tri.rest.cors.CorsUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
import static org.apache.dubbo.common.utils.StringUtils.EMPTY_STRING_ARRAY;
public class CorsMeta {
private final String[] allowedOrigins;
private final Pattern[] allowedOriginsPatterns;
private final String[] allowedMethods;
private final String[] allowedHeaders;
private final String[] exposedHeaders;
private final Boolean allowCredentials;
private final Long maxAge;
private CorsMeta(
String[] allowedOrigins,
Pattern[] allowedOriginsPatterns,
String[] allowedMethods,
String[] allowedHeaders,
String[] exposedHeaders,
Boolean allowCredentials,
Long maxAge) {
this.allowedOrigins = allowedOrigins;
this.allowedOriginsPatterns = allowedOriginsPatterns;
this.allowedMethods = allowedMethods;
this.allowedHeaders = allowedHeaders;
this.exposedHeaders = exposedHeaders;
this.allowCredentials = allowCredentials;
this.maxAge = maxAge;
}
public static Builder builder() {
return new Builder();
}
public static CorsMeta combine(CorsMeta source, CorsMeta other) {
return source == null || source.isEmpty()
? other == null || other.isEmpty() ? null : other.applyDefault()
: source.combine(other).applyDefault();
}
public String[] getAllowedOrigins() {
return allowedOrigins;
}
public Pattern[] getAllowedOriginsPatterns() {
return allowedOriginsPatterns;
}
public String[] getAllowedMethods() {
return allowedMethods;
}
public String[] getAllowedHeaders() {
return allowedHeaders;
}
public String[] getExposedHeaders() {
return exposedHeaders;
}
public Boolean getAllowCredentials() {
return allowCredentials;
}
public Long getMaxAge() {
return maxAge;
}
public boolean isEmpty() {
return allowedOrigins.length == 0
&& allowedMethods.length == 0
&& allowedHeaders.length == 0
&& exposedHeaders.length == 0
&& allowCredentials == null
&& maxAge == null;
}
public CorsMeta applyDefault() {
String[] allowedOriginArray = null;
Pattern[] allowedOriginPatternArray = null;
if (allowedOrigins.length == 0) {
allowedOriginArray = new String[] {ANY_VALUE};
allowedOriginPatternArray = new Pattern[] {null};
}
String[] allowedMethodArray = null;
if (allowedMethods.length == 0) {
allowedMethodArray =
new String[] {HttpMethods.GET.name(), HttpMethods.HEAD.name(), HttpMethods.POST.name()};
}
String[] allowedHeaderArray = null;
if (allowedHeaders.length == 0) {
allowedHeaderArray = new String[] {ANY_VALUE};
}
Long maxAgeValue = null;
if (maxAge == null) {
maxAgeValue = 1800L;
}
if (allowedOriginArray == null
&& allowedMethodArray == null
&& allowedHeaderArray == null
&& maxAgeValue == null) {
return this;
}
return new CorsMeta(
allowedOriginArray == null ? allowedOrigins : allowedOriginArray,
allowedOriginPatternArray == null ? allowedOriginsPatterns : allowedOriginPatternArray,
allowedMethodArray == null ? allowedMethods : allowedMethodArray,
allowedHeaderArray == null ? allowedHeaders : allowedHeaderArray,
exposedHeaders,
allowCredentials,
maxAgeValue);
}
public CorsMeta combine(CorsMeta other) {
if (other == null || other.isEmpty()) {
return this;
}
return new CorsMeta(
combine(allowedOrigins, other.allowedOrigins),
merge(allowedOriginsPatterns, other.allowedOriginsPatterns).toArray(new Pattern[0]),
combine(allowedMethods, other.allowedMethods),
combine(allowedHeaders, other.allowedHeaders),
combine(exposedHeaders, other.exposedHeaders),
other.allowCredentials == null ? allowCredentials : other.allowCredentials,
other.maxAge == null ? maxAge : other.maxAge);
}
/**
* Merge two arrays of CORS config values, the other array having higher priority.
*/
private static String[] combine(String[] source, String[] other) {
if (other.length == 0) {
return source;
}
if (source.length == 0 || source[0].equals(ANY_VALUE) || other[0].equals(ANY_VALUE)) {
return other;
}
return merge(source, other).toArray(EMPTY_STRING_ARRAY);
}
private static <T> Set<T> merge(T[] source, T[] other) {
int size = source.length + other.length;
if (size == 0) {
return Collections.emptySet();
}
Set<T> merged = CollectionUtils.newLinkedHashSet(size);
Collections.addAll(merged, source);
Collections.addAll(merged, other);
return merged;
}
@Override
public String toString() {
return "CorsMeta{"
+ "allowedOrigins=" + Arrays.toString(allowedOrigins)
+ ", allowedOriginsPatterns=" + Arrays.toString(allowedOriginsPatterns)
+ ", allowedMethods=" + Arrays.toString(allowedMethods)
+ ", allowedHeaders=" + Arrays.toString(allowedHeaders)
+ ", exposedHeaders=" + Arrays.toString(exposedHeaders)
+ ", allowCredentials=" + allowCredentials
+ ", maxAge=" + maxAge
+ '}';
}
public static final class Builder {
private static final Pattern PORTS_PATTERN = Pattern.compile("(.*):\\[(\\*|\\d+(,\\d+)*)]");
private final Set<String> allowedOrigins = new LinkedHashSet<>();
private final Set<String> allowedMethods = new LinkedHashSet<>();
private final Set<String> allowedHeaders = new LinkedHashSet<>();
private final Set<String> exposedHeaders = new LinkedHashSet<>();
private Boolean allowCredentials;
private Long maxAge;
public Builder allowedOrigins(String... origins) {
addValues(allowedOrigins, CorsUtils::formatOrigin, origins);
return this;
}
public Builder allowedMethods(String... methods) {
addValues(allowedMethods, v -> v.trim().toUpperCase(), methods);
return this;
}
public Builder allowedHeaders(String... headers) {
addValues(allowedHeaders, String::trim, headers);
return this;
}
public Builder exposedHeaders(String... headers) {
addValues(exposedHeaders, String::trim, headers);
return this;
}
private static void addValues(Set<String> set, Function<String, String> fn, String... values) {
if (values == null || set.contains(ANY_VALUE)) {
return;
}
for (String value : values) {
if (StringUtils.isNotEmpty(value)) {
value = fn.apply(value);
if (value.isEmpty()) {
continue;
}
if (ANY_VALUE.equals(value)) {
set.clear();
set.add(ANY_VALUE);
return;
}
set.add(value);
}
}
}
private static Pattern initPattern(String patternValue) {
String ports = null;
Matcher matcher = PORTS_PATTERN.matcher(patternValue);
if (matcher.matches()) {
patternValue = matcher.group(1);
ports = matcher.group(2);
}
patternValue = "\\Q" + patternValue + "\\E";
patternValue = patternValue.replace("*", "\\E.*\\Q");
if (ports != null) {
patternValue += (ANY_VALUE.equals(ports) ? "(:\\d+)?" : ":(" + ports.replace(',', '|') + ")");
}
return Pattern.compile(patternValue);
}
public Builder allowCredentials(Boolean allowCredentials) {
this.allowCredentials = allowCredentials;
return this;
}
public Builder allowCredentials(String allowCredentials) {
if ("true".equals(allowCredentials)) {
this.allowCredentials = true;
} else if ("false".equals(allowCredentials)) {
this.allowCredentials = false;
}
return this;
}
public Builder maxAge(Long maxAge) {
if (maxAge != null && maxAge > -1) {
this.maxAge = maxAge;
}
return this;
}
public CorsMeta build() {
int len = allowedOrigins.size();
String[] origins = new String[len];
List<Pattern> originsPatterns = new ArrayList<>(len);
int i = 0;
for (String origin : allowedOrigins) {
origins[i++] = origin;
if (ANY_VALUE.equals(origin)) {
continue;
}
originsPatterns.add(initPattern(origin));
}
return new CorsMeta(
origins,
originsPatterns.toArray(new Pattern[0]),
allowedMethods.toArray(EMPTY_STRING_ARRAY),
allowedHeaders.toArray(EMPTY_STRING_ARRAY),
exposedHeaders.toArray(EMPTY_STRING_ARRAY),
allowCredentials,
maxAge);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/ProtoBean.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/ProtoBean.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.meta;
import org.apache.dubbo.common.utils.ClassUtils;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Message;
final class ProtoBean {
public static final boolean HAS_PB = ClassUtils.hasProtobuf();
public static Set<String> getFields(Class<?> clazz) {
if (HAS_PB && Message.class.isAssignableFrom(clazz)) {
try {
Descriptor descriptor =
(Descriptor) clazz.getMethod("getDescriptor").invoke(null);
return descriptor.getFields().stream()
.map(FieldDescriptor::getName)
.collect(Collectors.toSet());
} catch (Exception ignored) {
}
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/NamedValueMeta.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/NamedValueMeta.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.meta;
import org.apache.dubbo.common.utils.StringUtils;
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.RestException;
import java.lang.reflect.Type;
import java.util.Arrays;
public class NamedValueMeta {
public static final NamedValueMeta EMPTY = new NamedValueMeta();
private String name;
private final boolean required;
private final String defaultValue;
private ParamType paramType;
private Class<?> type;
private Type genericType;
private Class<?>[] nestedTypes;
private ParameterMeta parameter;
public NamedValueMeta(String name, boolean required, String defaultValue) {
this.name = name;
this.required = required;
this.defaultValue = defaultValue;
}
public NamedValueMeta(String name, boolean required) {
this.name = name;
this.required = required;
defaultValue = null;
}
public NamedValueMeta() {
required = false;
defaultValue = null;
}
public String name() {
if (name == null) {
throw new RestException(Messages.ARGUMENT_NAME_MISSING, type);
}
return name;
}
public NamedValueMeta setName(String name) {
this.name = name;
return this;
}
public boolean isNameEmpty() {
return StringUtils.isEmpty(name);
}
public boolean required() {
return required;
}
public String defaultValue() {
return defaultValue;
}
public ParamType paramType() {
return paramType;
}
public NamedValueMeta setParamType(ParamType paramType) {
this.paramType = paramType;
return this;
}
public Class<?> type() {
return type;
}
public NamedValueMeta setType(Class<?> type) {
this.type = type;
return this;
}
public Type genericType() {
return genericType;
}
public NamedValueMeta setGenericType(Type genericType) {
this.genericType = genericType;
return this;
}
public Class<?>[] nestedTypes() {
return nestedTypes;
}
public NamedValueMeta setNestedTypes(Class<?>[] nestedTypes) {
this.nestedTypes = nestedTypes;
return this;
}
public Class<?> nestedType() {
return nestedTypes == null ? null : nestedTypes[0];
}
public Class<?> nestedType(int index) {
return nestedTypes == null || nestedTypes.length <= index ? null : nestedTypes[index];
}
public ParameterMeta parameter() {
return parameter;
}
public NamedValueMeta setParameter(ParameterMeta parameter) {
this.parameter = parameter;
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("NamedValueMeta{name='");
sb.append(name).append('\'');
if (required) {
sb.append(", required=true");
}
if (defaultValue != null) {
sb.append(", defaultValue='").append(defaultValue).append('\'');
}
if (paramType != null) {
sb.append(", paramType=").append(paramType);
}
if (type != null) {
sb.append(", type=").append(type);
if (genericType != type) {
sb.append(", genericType=").append(genericType);
}
}
if (nestedTypes != null) {
sb.append(", nestedTypes=").append(Arrays.toString(nestedTypes));
}
sb.append('}');
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-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/MethodMeta.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/MethodMeta.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.meta;
import org.apache.dubbo.common.utils.MethodUtils;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.MethodDescriptor.RpcType;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RestToolKit;
import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public final class MethodMeta extends AnnotationSupport {
private final List<Method> hierarchy;
private final Method method;
private MethodDescriptor methodDescriptor;
private ParameterMeta[] parameters;
private ParameterMeta returnParameter;
private final ServiceMeta serviceMeta;
public MethodMeta(List<Method> hierarchy, MethodDescriptor methodDescriptor, ServiceMeta serviceMeta) {
super(serviceMeta.getToolKit());
this.hierarchy = hierarchy;
method = initMethod(hierarchy, methodDescriptor);
this.methodDescriptor = methodDescriptor;
this.serviceMeta = serviceMeta;
}
private Method initMethod(List<Method> hierarchy, MethodDescriptor methodDescriptor) {
Method method = null;
if (methodDescriptor != null) {
method = methodDescriptor.getMethod();
}
return method == null ? hierarchy.get(hierarchy.size() - 1) : method;
}
public void initParameters() {
RpcType rpcType = methodDescriptor.getRpcType();
if (rpcType == RpcType.CLIENT_STREAM || rpcType == RpcType.BI_STREAM) {
Type genericType = TypeUtils.getNestedGenericType(method.getGenericReturnType(), 0);
parameters = new ParameterMeta[] {new StreamParameterMeta(getToolKit(), genericType, method, hierarchy)};
return;
}
int count = rpcType == RpcType.SERVER_STREAM ? 1 : method.getParameterCount();
List<List<Parameter>> parameterHierarchies = new ArrayList<>(count);
for (int i = 0, size = hierarchy.size(); i < size; i++) {
Method m = hierarchy.get(i);
Parameter[] mps = m.getParameters();
for (int j = 0; j < count; j++) {
List<Parameter> parameterHierarchy;
if (parameterHierarchies.size() <= j) {
parameterHierarchy = new ArrayList<>(size);
parameterHierarchies.add(parameterHierarchy);
} else {
parameterHierarchy = parameterHierarchies.get(j);
}
parameterHierarchy.add(mps[j]);
}
}
String[] parameterNames = getToolKit().getParameterNames(method);
ParameterMeta[] parameters = new ParameterMeta[count];
for (int i = 0; i < count; i++) {
String parameterName = parameterNames == null ? null : parameterNames[i];
parameters[i] = new MethodParameterMeta(parameterHierarchies.get(i), parameterName, i, this);
}
this.parameters = parameters;
}
public List<Method> getHierarchy() {
return hierarchy;
}
public Method getMethod() {
return method;
}
public String getMethodName() {
if (methodDescriptor == null) {
return method.getName();
}
return methodDescriptor.getMethodName();
}
public MethodDescriptor getMethodDescriptor() {
return methodDescriptor;
}
public void setMethodDescriptor(MethodDescriptor methodDescriptor) {
this.methodDescriptor = methodDescriptor;
}
public ParameterMeta[] getParameters() {
return parameters;
}
public ParameterMeta getReturnParameter() {
ParameterMeta returnParameter = this.returnParameter;
if (returnParameter == null) {
this.returnParameter = returnParameter = new ReturnParameterMeta(getToolKit(), hierarchy, method);
}
return returnParameter;
}
public ServiceMeta getServiceMeta() {
return serviceMeta;
}
public Class<?> getReturnType() {
return method.getReturnType();
}
public Class<?> getActualReturnType() {
return getReturnParameter().getActualType();
}
public Type getGenericReturnType() {
return method.getGenericReturnType();
}
public Type getActualGenericReturnType() {
return getReturnParameter().getActualGenericType();
}
@Override
public List<? extends AnnotatedElement> getAnnotatedElements() {
return hierarchy;
}
@Override
protected AnnotatedElement getAnnotatedElement() {
return method;
}
@Override
public int hashCode() {
return method.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != MethodMeta.class) {
return false;
}
return method.equals(((MethodMeta) obj).method);
}
@Override
public String toString() {
return "MethodMeta{method=" + toShortString() + ", service=" + serviceMeta.toShortString() + '}';
}
public String toShortString() {
return MethodUtils.toShortString(method);
}
public static final class StreamParameterMeta extends ParameterMeta {
private final Class<?> type;
private final Type genericType;
private final AnnotatedElement element;
private final List<? extends AnnotatedElement> elements;
StreamParameterMeta(
RestToolKit toolKit,
Type genericType,
AnnotatedElement element,
List<? extends AnnotatedElement> elements) {
super(toolKit, "value");
type = TypeUtils.getActualType(genericType);
this.genericType = genericType;
this.element = element;
this.elements = elements;
}
@Override
public String getDescription() {
return "Stream parameter [" + element + "]";
}
@Override
public Class<?> getType() {
return type;
}
@Override
public Type getGenericType() {
return genericType;
}
@Override
protected AnnotatedElement getAnnotatedElement() {
return element;
}
@Override
public List<? extends AnnotatedElement> getAnnotatedElements() {
return elements;
}
}
public static final class ReturnParameterMeta extends ParameterMeta {
private final List<Method> hierarchy;
private final Method method;
ReturnParameterMeta(RestToolKit toolKit, List<Method> hierarchy, Method method) {
super(toolKit, null);
this.hierarchy = hierarchy;
this.method = method;
}
public Method getMethod() {
return method;
}
@Override
public Class<?> getType() {
return method.getReturnType();
}
@Override
public Type getGenericType() {
return method.getGenericReturnType();
}
@Override
public List<? extends AnnotatedElement> getAnnotatedElements() {
return hierarchy;
}
@Override
protected AnnotatedElement getAnnotatedElement() {
return method;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/TypeParameterMeta.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/TypeParameterMeta.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.meta;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RestToolKit;
import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Type;
public final class TypeParameterMeta extends ParameterMeta {
private final Type type;
public TypeParameterMeta(RestToolKit toolKit, Type type) {
super(toolKit, null);
this.type = type;
}
public TypeParameterMeta(Type type) {
super(null, null);
this.type = type;
}
@Override
public Class<?> getType() {
return TypeUtils.getActualType(type);
}
@Override
public Type getGenericType() {
return type;
}
@Override
protected AnnotatedElement getAnnotatedElement() {
return getActualType();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/BeanMeta.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/BeanMeta.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.meta;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.remoting.http12.rest.Param;
import org.apache.dubbo.rpc.protocol.tri.ExceptionUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RestToolKit;
import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils;
import javax.annotation.Nullable;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Message;
public final class BeanMeta extends ParameterMeta {
private static final boolean HAS_PB = ClassUtils.hasProtobuf();
private final Class<?> type;
private final boolean flatten;
private ConstructorMeta constructor;
private Map<String, PropertyMeta> propertyMap;
public BeanMeta(RestToolKit toolKit, String prefix, Class<?> type, boolean flatten) {
super(toolKit, prefix, null);
this.type = type;
this.flatten = flatten;
}
public BeanMeta(RestToolKit toolKit, Class<?> type, boolean flatten) {
this(toolKit, null, type, flatten);
}
public BeanMeta(RestToolKit toolKit, String prefix, Class<?> type) {
this(toolKit, prefix, type, true);
}
public BeanMeta(RestToolKit toolKit, Class<?> type) {
this(toolKit, null, type, true);
}
@Override
public Class<?> getType() {
return type;
}
@Override
public Type getGenericType() {
return type;
}
@Override
protected AnnotatedElement getAnnotatedElement() {
return type;
}
public ConstructorMeta getConstructor() {
if (constructor == null) {
constructor = resolveConstructor(getToolKit(), getPrefix(), type);
}
return constructor;
}
public Collection<PropertyMeta> getProperties() {
return getPropertiesMap().values();
}
public PropertyMeta getProperty(String name) {
return getPropertiesMap().get(name);
}
private Map<String, PropertyMeta> getPropertiesMap() {
Map<String, PropertyMeta> propertyMap = this.propertyMap;
if (propertyMap == null) {
propertyMap = new LinkedHashMap<>();
resolvePropertyMap(getToolKit(), getPrefix(), type, flatten, propertyMap);
this.propertyMap = propertyMap;
}
return propertyMap;
}
public Object newInstance() {
return getConstructor().newInstance();
}
public static ConstructorMeta resolveConstructor(RestToolKit toolKit, String prefix, Class<?> type) {
Constructor<?>[] constructors = type.getConstructors();
Constructor<?> ct = null;
if (constructors.length == 1) {
ct = constructors[0];
} else {
try {
ct = type.getDeclaredConstructor();
} catch (NoSuchMethodException ignored) {
}
}
if (ct == null) {
throw new IllegalArgumentException("No available default constructor found in " + type);
}
return new ConstructorMeta(toolKit, prefix, ct);
}
public static void resolvePropertyMap(
RestToolKit toolKit, String prefix, Class<?> type, boolean flatten, Map<String, PropertyMeta> propertyMap) {
if (type == null || type == Object.class || TypeUtils.isSystemType(type)) {
return;
}
Set<String> pbFields = null;
if (HAS_PB && Message.class.isAssignableFrom(type)) {
try {
Descriptor descriptor =
(Descriptor) type.getMethod("getDescriptor").invoke(null);
pbFields = descriptor.getFields().stream()
.map(FieldDescriptor::getName)
.collect(Collectors.toSet());
} catch (Exception ignored) {
}
}
Set<String> allNames = new LinkedHashSet<>();
Map<String, Field> fieldMap = new LinkedHashMap<>();
if (pbFields == null) {
for (Field field : type.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers())
|| Modifier.isTransient(field.getModifiers())
|| field.isSynthetic()) {
continue;
}
if (!field.isAccessible()) {
field.setAccessible(true);
}
fieldMap.put(field.getName(), field);
allNames.add(field.getName());
}
}
Map<String, Method> getMethodMap = new LinkedHashMap<>();
Map<String, Method> setMethodMap = new LinkedHashMap<>();
for (Method method : type.getDeclaredMethods()) {
int modifiers = method.getModifiers();
if ((modifiers & (Modifier.PUBLIC | Modifier.ABSTRACT | Modifier.STATIC)) == Modifier.PUBLIC) {
String name = method.getName();
int count = method.getParameterCount();
if (count == 0) {
Class<?> returnType = method.getReturnType();
if (returnType == Void.TYPE) {
continue;
}
if (name.length() > 3 && name.startsWith("get")) {
name = toName(name, 3);
if (pbFields == null || pbFields.contains(name)) {
getMethodMap.put(name, method);
allNames.add(name);
}
} else if (name.length() > 2 && name.startsWith("is") && returnType == Boolean.TYPE) {
if (pbFields == null || pbFields.contains(name)) {
name = toName(name, 2);
getMethodMap.put(name, method);
allNames.add(name);
}
} else if (fieldMap.containsKey(name)) {
// For record class
getMethodMap.put(name, method);
allNames.add(name);
}
} else if (count == 1) {
if (name.length() > 3 && name.startsWith("set")) {
name = toName(name, 3);
setMethodMap.put(name, method);
allNames.add(name);
}
}
}
}
for (String name : allNames) {
Field field = fieldMap.get(name);
Method getMethod = getMethodMap.get(name);
Method setMethod = setMethodMap.get(name);
int visibility = pbFields == null
? (setMethod == null ? 0 : 1) << 2 | (getMethod == null ? 0 : 1) << 1 | (field == null ? 0 : 1)
: 0b011;
PropertyMeta meta = new PropertyMeta(toolKit, field, getMethod, setMethod, prefix, name, visibility);
propertyMap.put(meta.getName(), meta);
}
if (flatten) {
resolvePropertyMap(toolKit, prefix, type.getSuperclass(), true, propertyMap);
}
}
private static String toName(String name, int index) {
return Character.toLowerCase(name.charAt(index)) + name.substring(index + 1);
}
public static final class ConstructorMeta {
private final Constructor<?> constructor;
private final ConstructorParameterMeta[] parameters;
ConstructorMeta(RestToolKit toolKit, String prefix, Constructor<?> constructor) {
this.constructor = constructor;
parameters = initParameters(toolKit, prefix, constructor);
}
public ConstructorParameterMeta[] getParameters() {
return parameters;
}
private ConstructorParameterMeta[] initParameters(RestToolKit toolKit, String prefix, Constructor<?> ct) {
Parameter[] cps = ct.getParameters();
int len = cps.length;
if (len == 0) {
return new ConstructorParameterMeta[0];
}
String[] parameterNames = toolKit == null ? null : toolKit.getParameterNames(ct);
ConstructorParameterMeta[] parameters = new ConstructorParameterMeta[len];
for (int i = 0; i < len; i++) {
String parameterName = parameterNames == null ? null : parameterNames[i];
parameters[i] = new ConstructorParameterMeta(toolKit, cps[i], prefix, parameterName);
}
return parameters;
}
public Object newInstance(Object... args) {
try {
return constructor.newInstance(args);
} catch (Throwable t) {
throw ExceptionUtils.wrap(t);
}
}
}
public static final class ConstructorParameterMeta extends ParameterMeta {
private final Parameter parameter;
ConstructorParameterMeta(RestToolKit toolKit, Parameter parameter, String prefix, String name) {
super(toolKit, prefix, name == null && parameter.isNamePresent() ? parameter.getName() : name);
this.parameter = parameter;
}
@Override
protected AnnotatedElement getAnnotatedElement() {
return parameter;
}
@Override
public Class<?> getType() {
return parameter.getType();
}
@Override
public Type getGenericType() {
return parameter.getParameterizedType();
}
@Override
public String getDescription() {
return "ConstructorParameter{" + parameter + '}';
}
}
public abstract static class NestableParameterMeta extends ParameterMeta {
private NestableParameterMeta nestedMeta;
private String finalName;
public NestableParameterMeta(RestToolKit toolKit, String prefix, String name) {
super(toolKit, prefix, name);
}
@Nullable
@Override
public final String getName() {
String name = finalName;
if (name == null) {
AnnotationMeta<Param> param = findAnnotation(Param.class);
if (param != null) {
name = param.getValue();
}
if (name == null || name.isEmpty()) {
name = super.getName();
}
finalName = name;
}
return name;
}
public Object getValue(Object bean) {
return null;
}
public void setValue(Object bean, Object value) {}
public final NestableParameterMeta getNestedMeta() {
return nestedMeta;
}
protected final void initNestedMeta() {
Type nestedType = null;
Class<?> type = getType();
if (Map.class.isAssignableFrom(type)) {
nestedType = TypeUtils.getNestedGenericType(getGenericType(), 1);
} else if (Collection.class.isAssignableFrom(type)) {
nestedType = TypeUtils.getNestedGenericType(getGenericType(), 0);
} else if (type.isArray()) {
Type genericType = getGenericType();
if (genericType instanceof GenericArrayType) {
nestedType = ((GenericArrayType) genericType).getGenericComponentType();
} else {
nestedType = type.getComponentType();
}
}
nestedMeta = nestedType == null ? null : new NestedMeta(getToolKit(), nestedType);
}
}
public static final class PropertyMeta extends NestableParameterMeta {
private final Field field;
private final Method getMethod;
private final Method setMethod;
private final Parameter parameter;
private final int visibility;
PropertyMeta(RestToolKit toolKit, Field f, Method gm, Method sm, String prefix, String name, int visibility) {
super(toolKit, prefix, name);
this.visibility = visibility;
field = f;
getMethod = gm;
setMethod = sm;
parameter = setMethod == null ? null : setMethod.getParameters()[0];
initNestedMeta();
}
public int getVisibility() {
return visibility;
}
public Field getField() {
return field;
}
public Method getGetMethod() {
return getMethod;
}
public Method getSetMethod() {
return setMethod;
}
public Parameter getParameter() {
return parameter;
}
@Override
public Class<?> getType() {
if (field != null) {
return field.getType();
}
if (parameter != null) {
return parameter.getType();
}
return getMethod.getReturnType();
}
@Override
public Type getGenericType() {
if (field != null) {
return field.getGenericType();
}
if (parameter != null) {
return parameter.getParameterizedType();
}
return getMethod.getGenericReturnType();
}
@Override
protected AnnotatedElement getAnnotatedElement() {
if (field != null) {
return field;
}
if (parameter != null) {
return parameter;
}
return getMethod;
}
@Override
public List<? extends AnnotatedElement> getAnnotatedElements() {
List<AnnotatedElement> elements = new ArrayList<>(3);
if (field != null) {
elements.add(field);
}
if (parameter != null) {
elements.add(parameter);
}
if (getMethod != null) {
elements.add(getMethod);
}
return elements;
}
public Object getValue(Object bean) {
if (getMethod != null) {
try {
return getMethod.invoke(bean);
} catch (Throwable t) {
throw ExceptionUtils.wrap(t);
}
} else if (field != null) {
try {
return field.get(bean);
} catch (Throwable t) {
throw ExceptionUtils.wrap(t);
}
}
return null;
}
public void setValue(Object bean, Object value) {
if (setMethod != null) {
try {
setMethod.invoke(bean, value);
} catch (Throwable t) {
throw ExceptionUtils.wrap(t);
}
} else if (field != null) {
try {
field.set(bean, value);
} catch (Throwable t) {
throw ExceptionUtils.wrap(t);
}
}
}
@Override
public String getDescription() {
return "PropertyMeta{" + (field == null ? (parameter == null ? getMethod : parameter) : field) + '}';
}
public boolean canSetValue() {
return setMethod != null || field != null;
}
}
private static final class NestedMeta extends NestableParameterMeta {
private final Class<?> type;
private final Type genericType;
NestedMeta(RestToolKit toolKit, Type genericType) {
super(toolKit, null, null);
type = TypeUtils.getActualType(genericType);
this.genericType = genericType;
initNestedMeta();
}
@Override
public Class<?> getType() {
return type;
}
@Override
public Type getGenericType() {
return genericType;
}
@Override
protected AnnotatedElement getAnnotatedElement() {
return type;
}
@Override
public String getDescription() {
return "NestedParameter{" + (genericType == null ? type : genericType) + '}';
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/AnnotationEnum.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/AnnotationEnum.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.meta;
import org.apache.dubbo.common.utils.ClassUtils;
import java.lang.annotation.Annotation;
@SuppressWarnings({"unchecked", "rawtypes"})
public interface AnnotationEnum {
String className();
Class<Annotation> type();
default Class<Annotation> loadType() {
try {
return (Class) ClassUtils.loadClass(className());
} catch (Throwable t) {
return (Class) NotFound.class;
}
}
default boolean isPresent() {
return type() != (Class) NotFound.class;
}
@interface NotFound {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/ParameterMeta.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/ParameterMeta.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.meta;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.rpc.protocol.tri.ReflectionPackableMethod;
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.util.RestToolKit;
import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils;
import javax.annotation.Nullable;
import java.lang.reflect.Type;
import java.util.Collection;
public abstract class ParameterMeta extends AnnotationSupport {
private final String prefix;
private final String name;
private Boolean simple;
private Class<?> actualType;
private Type actualGenericType;
private BeanMeta beanMeta;
private NamedValueMeta namedValueMeta;
protected ParameterMeta(RestToolKit toolKit, String prefix, String name) {
super(toolKit);
this.prefix = prefix;
this.name = name;
}
protected ParameterMeta(RestToolKit toolKit, String name) {
super(toolKit);
prefix = null;
this.name = name;
}
public String getPrefix() {
return prefix;
}
@Nullable
public String getName() {
return name;
}
public String getRequiredName() {
String name = getName();
if (name == null) {
throw new RestException(Messages.ARGUMENT_NAME_MISSING, getType());
}
return name;
}
public final boolean isSimple() {
Boolean simple = this.simple;
if (simple == null) {
Class<?> type = Collection.class.isAssignableFrom(getType())
? TypeUtils.getNestedActualType(getGenericType(), 0)
: getActualType();
simple = TypeUtils.isSimpleProperty(type);
this.simple = simple;
}
return simple;
}
public final boolean isStream() {
return ReflectionPackableMethod.isStreamType(getType());
}
public final Class<?> getActualType() {
Class<?> type = actualType;
if (type == null) {
type = getType();
if (TypeUtils.isWrapperType(type)) {
type = TypeUtils.getNestedActualType(getGenericType(), 0);
if (type == null) {
type = Object.class;
}
}
actualType = type;
}
return type;
}
public final Type getActualGenericType() {
Type type = actualGenericType;
if (type == null) {
type = getGenericType();
if (TypeUtils.isWrapperType(TypeUtils.getActualType(type))) {
type = TypeUtils.getNestedGenericType(type, 0);
if (type == null) {
type = Object.class;
}
}
actualGenericType = type;
}
return type;
}
public final BeanMeta getBeanMeta() {
BeanMeta beanMeta = this.beanMeta;
if (beanMeta == null) {
this.beanMeta = beanMeta = new BeanMeta(getToolKit(), getActualType());
}
return beanMeta;
}
public final Object bind(HttpRequest request, HttpResponse response) {
return getToolKit().bind(this, request, response);
}
public final NamedValueMeta getNamedValueMeta() {
NamedValueMeta namedValueMeta = this.namedValueMeta;
if (namedValueMeta == null) {
namedValueMeta = getToolKit().getNamedValueMeta(this);
if (namedValueMeta == null) {
namedValueMeta = NamedValueMeta.EMPTY;
}
this.namedValueMeta = namedValueMeta;
}
return namedValueMeta;
}
public int getIndex() {
return -1;
}
public String getDescription() {
return name;
}
public abstract Class<?> getType();
public abstract Type getGenericType();
@Override
public String toString() {
return "ParameterMeta{name='" + name + "', type=" + getType() + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/ServiceMeta.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/meta/ServiceMeta.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mapping.meta;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.protocol.tri.rest.util.PathUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RestToolKit;
import java.lang.reflect.AnnotatedElement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public final class ServiceMeta extends AnnotationSupport {
private final List<Class<?>> hierarchy;
private final Class<?> type;
private final Object service;
private final ServiceDescriptor serviceDescriptor;
private final URL url;
private final String contextPath;
private List<MethodMeta> exceptionHandlers;
public ServiceMeta(
Collection<Class<?>> hierarchy,
ServiceDescriptor serviceDescriptor,
Object service,
URL url,
RestToolKit toolKit) {
super(toolKit);
this.hierarchy = new ArrayList<>(hierarchy);
this.serviceDescriptor = serviceDescriptor;
type = this.hierarchy.get(0);
this.service = service;
this.url = url;
contextPath = PathUtils.getContextPath(url);
}
public List<Class<?>> getHierarchy() {
return hierarchy;
}
public Class<?> getType() {
return type;
}
public ServiceDescriptor getServiceDescriptor() {
return serviceDescriptor;
}
public Object getService() {
return service;
}
public URL getUrl() {
return url;
}
public String getServiceInterface() {
return url.getServiceInterface();
}
public String getServiceGroup() {
return url.getGroup();
}
public String getServiceVersion() {
return url.getVersion();
}
public String getContextPath() {
return contextPath;
}
public List<MethodMeta> getExceptionHandlers() {
return exceptionHandlers;
}
@Override
public List<? extends AnnotatedElement> getAnnotatedElements() {
return hierarchy;
}
@Override
protected AnnotatedElement getAnnotatedElement() {
return hierarchy.get(0);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(64);
sb.append("ServiceMeta{interface=")
.append(getServiceInterface())
.append(", service=")
.append(toShortString());
if (StringUtils.isNotEmpty(contextPath)) {
sb.append(", contextPath='").append(contextPath).append('\'');
}
String group = getServiceGroup();
if (StringUtils.isNotEmpty(group)) {
sb.append(", group='").append(group).append('\'');
}
String version = getServiceVersion();
if (StringUtils.isNotEmpty(version)) {
sb.append(", version='").append(version).append('\'');
}
sb.append('}');
return sb.toString();
}
public String toShortString() {
return type.getSimpleName() + '@' + Integer.toHexString(System.identityHashCode(service));
}
public void addExceptionHandler(MethodMeta methodMeta) {
if (exceptionHandlers == null) {
exceptionHandlers = new ArrayList<>();
}
exceptionHandlers.add(methodMeta);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/basic/GRequestArgumentResolver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/basic/GRequestArgumentResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.basic;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.remoting.http12.exception.DecodeException;
import org.apache.dubbo.remoting.http12.message.HttpMessageDecoder;
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.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.stub.annotations.GRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@Activate
public class GRequestArgumentResolver implements AnnotationBaseArgumentResolver<GRequest> {
@Override
public Class<GRequest> accept() {
return GRequest.class;
}
@Override
public NamedValueMeta getNamedValueMeta(ParameterMeta parameter, AnnotationMeta<Annotation> annotation) {
return new NamedValueMeta().setParamType(ParamType.Body);
}
@Override
public Object resolve(
ParameterMeta parameter, AnnotationMeta<GRequest> annotation, HttpRequest request, HttpResponse response) {
HttpMessageDecoder decoder = request.attribute(RestConstants.BODY_DECODER_ATTRIBUTE);
if (decoder == null) {
return null;
}
Map<String, Object> value = new HashMap<>();
Map<String, String> variableMap = request.attribute(RestConstants.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
if (variableMap != null) {
value.putAll(variableMap);
}
InputStream is = request.inputStream();
try {
int available = is.available();
if (available > 0) {
Object body = decoder.decode(is, Object.class, request.charsetOrDefault());
if (body instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> bodyMap = (Map<String, Object>) body;
String key = annotation.getValue();
if ("*".equals(key) || key.isEmpty()) {
value.putAll(bodyMap);
} else {
value.put(key, bodyMap.get(key));
}
}
}
} catch (IOException e) {
throw new DecodeException("Error reading input", e);
}
return decoder.decode(
new ByteArrayInputStream(JsonUtils.toJson(value).getBytes(StandardCharsets.UTF_8)),
parameter.getType(),
StandardCharsets.UTF_8);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/basic/BeanArgumentBinder.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/basic/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.basic;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Pair;
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.Param;
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.RestException;
import org.apache.dubbo.rpc.protocol.tri.rest.argument.CompositeArgumentResolver;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta.ConstructorMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta.NestableParameterMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta.PropertyMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils;
import java.lang.reflect.Array;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
final class BeanArgumentBinder {
private static final Map<Class<?>, BeanMeta> CACHE = CollectionUtils.newConcurrentHashMap();
private final CompositeArgumentResolver argumentResolver;
public BeanArgumentBinder(CompositeArgumentResolver argumentResolver) {
this.argumentResolver = argumentResolver;
}
public Object bind(ParameterMeta paramMeta, HttpRequest request, HttpResponse response) {
try {
BeanMeta beanMeta = getBeanMeta(paramMeta);
if (beanMeta == null) {
return null;
}
ConstructorMeta constructor = beanMeta.getConstructor();
ParameterMeta[] parameters = constructor.getParameters();
Object bean;
int len = parameters.length;
if (len == 0) {
bean = constructor.newInstance();
} else {
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;
}
bean = constructor.newInstance(args);
}
Node root = new Node(paramMeta.getName(), bean, beanMeta);
for (String paramName : request.parameterNames()) {
Node current = root;
List<String> parts = StringUtils.tokenizeToList(paramName, '.');
for (int i = 0, size = parts.size(); i < size; i++) {
if (current == null) {
break;
}
String name = parts.get(i);
Pair<String, String> pair = parseKeyParam(name);
if (pair == null) {
current = current.getChild(name);
if (i == 0 && current == null && name.equals(root.name)) {
current = root;
}
} else {
name = pair.getLeft();
current = current.getChild(name);
if (current == null) {
break;
}
String key = pair.getValue();
if (!key.isEmpty()) {
if (Character.isDigit(key.charAt(0))) {
try {
current = current.getChild(Long.parseLong(key));
continue;
} catch (NumberFormatException ignored) {
}
}
current = current.getChild(key);
}
}
}
if (current == null) {
continue;
}
Class<?> type = current.paramMeta.getActualType();
Object value;
if (type.isArray() || Collection.class.isAssignableFrom(type)) {
value = request.parameterValues(paramName);
} else {
value = request.parameter(paramName);
}
//noinspection unchecked
current.setValue(argumentResolver.getArgumentConverter().convert(value, current.paramMeta));
}
for (PropertyMeta propertyMeta : beanMeta.getProperties()) {
resolveParam(propertyMeta, bean, request, response);
}
return bean;
} catch (Exception e) {
throw new RestException(e, Messages.ARGUMENT_BIND_ERROR, paramMeta.getName(), paramMeta.getType());
}
}
private void resolveParam(NestableParameterMeta meta, Object bean, HttpRequest request, HttpResponse response) {
AnnotationMeta<Param> param = meta.getAnnotation(Param.class);
if (param == null || param.getAnnotation().type() == ParamType.Param) {
return;
}
meta.setValue(bean, argumentResolver.resolve(meta, request, response));
}
private static BeanMeta getBeanMeta(ParameterMeta paramMeta) {
Class<?> type = paramMeta.getActualType();
if (paramMeta.isSimple() || Modifier.isAbstract(type.getModifiers())) {
return null;
}
return CACHE.computeIfAbsent(type, k -> paramMeta.getBeanMeta());
}
/**
* See
* <p>
* <a href="https://docs.spring.io/spring-framework/reference/core/validation/beans-beans.html#beans-binding">Spring beans-binding</a>
*/
private static Pair<String, String> parseKeyParam(String name) {
int len = name.length();
if (name.charAt(len - 1) == ']') {
int start = name.lastIndexOf('[');
if (start > -1) {
return Pair.of(name.substring(0, start), name.substring(start + 1, len - 1));
}
}
return null;
}
private static final class Node {
public final String name;
public NestableParameterMeta paramMeta;
public Consumer<Object> setter;
public Object value;
public Map<Object, Node> children;
public BeanMeta beanMeta;
public Node(String name, NestableParameterMeta paramMeta, Consumer<Object> setter) {
this.name = name;
this.paramMeta = paramMeta;
this.setter = setter;
}
public Node(String name, Object value, BeanMeta beanMeta) {
this.name = name;
this.value = value;
this.beanMeta = beanMeta;
}
@SuppressWarnings({"rawtypes", "unchecked"})
public Node getChild(String name) {
if (children != null) {
Node node = children.get(name);
if (node != null) {
return node;
}
}
if (beanMeta == null) {
Class<?> type = paramMeta.getType();
if (Map.class.isAssignableFrom(type)) {
return createChild(name, paramMeta.getNestedMeta(), v -> ((Map) value).put(name, v));
}
return null;
}
PropertyMeta propertyMeta = beanMeta.getProperty(name);
if (propertyMeta != null) {
return createChild(name, propertyMeta, v -> propertyMeta.setValue(value, v));
}
return null;
}
@SuppressWarnings({"rawtypes", "unchecked", "SuspiciousSystemArraycopy"})
public Node getChild(long num) {
if (children != null) {
Node node = children.get(num);
if (node != null) {
return node;
}
}
NestableParameterMeta nestedMeta = paramMeta.getNestedMeta();
Class<?> type = paramMeta.getType();
Object childValue = null;
Node child;
if (List.class.isAssignableFrom(type)) {
int index = (int) num;
List list = (List) value;
child = new Node(name, nestedMeta, v -> {
if (index < 0) {
return;
}
while (list.size() <= index) {
list.add(null);
}
list.set(index, v);
});
if (index < list.size()) {
childValue = list.get(index);
}
} else if (type.isArray()) {
int index = (int) num;
int len = Array.getLength(value);
child = new Node(name, nestedMeta, v -> {
if (num >= 0 && num < len) {
Array.set(value, index, v);
return;
}
int tail = index < 0 ? len : index;
Object newArr = Array.newInstance(value.getClass().getComponentType(), tail + 1);
System.arraycopy(value, 0, newArr, 0, len);
Array.set(newArr, tail, v);
setter.accept(newArr);
});
if (index < len) {
childValue = Array.get(value, index);
}
} else if (Map.class.isAssignableFrom(type)) {
Class<?> keyType = TypeUtils.getNestedActualType(paramMeta.getGenericType(), 0);
Object key = TypeUtils.longToObject(num, keyType);
child = new Node(name, nestedMeta, v -> {
((Map) value).put(key, v);
});
childValue = ((Map) value).get(key);
} else {
return null;
}
if (childValue == null) {
childValue = createValue(nestedMeta.getType());
if (childValue == null) {
if (nestedMeta.isSimple()) {
return child;
}
BeanMeta beanMeta = getBeanMeta(nestedMeta);
if (beanMeta == null) {
return null;
}
child.beanMeta = beanMeta;
childValue = beanMeta.newInstance();
}
child.setter.accept(childValue);
} else {
child.beanMeta = getBeanMeta(nestedMeta);
}
putChild(child, num, childValue);
return child;
}
public void setValue(Object value) {
setter.accept(value);
}
private Node createChild(String name, NestableParameterMeta paramMeta, Consumer<Object> setter) {
Class<?> type = paramMeta.getType();
if (type.isArray()) {
Consumer<Object> arraySetter = setter;
setter = v -> {
arraySetter.accept(v);
if (children != null) {
children.get(name).value = v;
}
};
}
Node child = new Node(name, paramMeta, setter);
Object childValue = paramMeta.getValue(value);
boolean created = false;
if (childValue == null) {
if (value instanceof Map) {
childValue = ((Map<?, ?>) value).get(name);
if (childValue != null) {
child.beanMeta = getBeanMeta(paramMeta);
}
}
if (childValue == null) {
childValue = createValue(type);
if (childValue == null) {
if (paramMeta.isSimple()) {
return child;
}
} else {
created = true;
}
}
}
if (childValue == null) {
BeanMeta beanMeta = getBeanMeta(paramMeta);
if (beanMeta == null) {
return null;
}
child.beanMeta = beanMeta;
childValue = beanMeta.newInstance();
created = true;
}
if (created) {
setter.accept(childValue);
}
putChild(child, name, childValue);
return child;
}
private Object createValue(Class<?> type) {
if (Map.class.isAssignableFrom(type)) {
return TypeUtils.createMap(type);
}
if (Collection.class.isAssignableFrom(type)) {
return TypeUtils.createCollection(type);
}
if (type.isArray()) {
return Array.newInstance(type.getComponentType(), 1);
}
return null;
}
private void putChild(Node child, Object name, Object value) {
child.value = value;
if (children == null) {
children = new HashMap<>();
}
children.put(name, child);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/basic/FallbackArgumentResolver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/basic/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.basic;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.remoting.http12.exception.DecodeException;
import org.apache.dubbo.remoting.http12.rest.Param;
import org.apache.dubbo.remoting.http12.rest.ParamType;
import org.apache.dubbo.rpc.model.MethodDescriptor.RpcType;
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.AnnotationMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta.StreamParameterMeta;
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.RequestUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RestUtils;
import java.util.List;
import java.util.Map;
@Activate(order = Integer.MAX_VALUE - 10000)
public class FallbackArgumentResolver extends AbstractArgumentResolver {
@Override
public boolean accept(ParameterMeta param) {
return param.getToolKit().getDialect() == RestConstants.DIALECT_BASIC;
}
@Override
protected NamedValueMeta createNamedValueMeta(ParameterMeta param) {
boolean noBodyParam = true;
int paramCount = -1;
if (param instanceof MethodParameterMeta) {
MethodMeta methodMeta = ((MethodParameterMeta) param).getMethodMeta();
ParameterMeta[] paramMetas = methodMeta.getParameters();
for (ParameterMeta paramMeta : paramMetas) {
AnnotationMeta<Param> anno = paramMeta.findAnnotation(Param.class);
if (anno != null && anno.getAnnotation().type() == ParamType.Body) {
noBodyParam = false;
break;
}
}
paramCount = methodMeta.getMethodDescriptor().getRpcType() != RpcType.UNARY ? 1 : paramMetas.length;
} else if (param instanceof StreamParameterMeta) {
paramCount = 1;
noBodyParam = false;
}
return new FallbackNamedValueMeta(param.isAnnotated(Annotations.Nonnull), noBodyParam, paramCount);
}
@Override
protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) {
return doResolveValue(meta, true, request, response);
}
@Override
protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) {
return doResolveValue(meta, false, request, response);
}
protected Object doResolveValue(NamedValueMeta meta, boolean single, HttpRequest request, HttpResponse response) {
FallbackNamedValueMeta fm = (FallbackNamedValueMeta) meta;
if (HttpMethods.supportBody(request.method())) {
if (fm.paramCount == 1) {
try {
Object body = RequestUtils.decodeBody(request, meta.genericType());
if (body != null) {
if (body != RequestUtils.EMPTY_BODY) {
return body;
}
Object value = single ? request.parameter(meta.name()) : request.parameterValues(meta.name());
return value == null ? body : value;
}
} catch (DecodeException ignored) {
}
}
if (fm.noBodyParam) {
Object body = RequestUtils.decodeBodyAsObject(request);
if (body instanceof List) {
List<?> list = (List<?>) body;
if (list.size() == fm.paramCount) {
return list.get(meta.parameter().getIndex());
}
} else if (body instanceof Map) {
Object value = ((Map<?, ?>) body).get(meta.name());
if (value != null) {
return value;
}
}
}
}
if (meta.parameter().isStream()) {
return null;
}
if (single) {
if (Map.class.isAssignableFrom(meta.type())) {
return RequestUtils.getParametersMap(request);
}
String value = request.parameter(meta.name());
if (meta.parameter().isSimple() || RestUtils.isMaybeJSONObject(value)) {
return value;
}
return meta.parameter().bind(request, response);
}
return request.parameterValues(meta.name());
}
@Override
protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) {
return resolveValue(meta, request, response);
}
private static final class FallbackNamedValueMeta extends NamedValueMeta {
private final boolean noBodyParam;
private final int paramCount;
FallbackNamedValueMeta(boolean required, boolean noBodyParam, int paramCount) {
super(null, required);
this.noBodyParam = noBodyParam;
this.paramCount = paramCount;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.