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-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/ListeningDecoder.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/ListeningDecoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
import org.apache.dubbo.remoting.http12.exception.DecodeException;
import java.io.InputStream;
public interface ListeningDecoder {
void decode(InputStream inputStream) throws DecodeException;
void close();
void setListener(Listener listener);
interface Listener {
/**
* call on decode finish
* @param message decoded object
*/
void onMessage(Object message);
default void onClose() {}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/DefaultHttpHeaders.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/DefaultHttpHeaders.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
import org.apache.dubbo.remoting.http12.HttpHeaders;
import org.apache.dubbo.remoting.http12.netty4.NettyHttpHeaders;
import java.util.Map.Entry;
import io.netty.handler.codec.CharSequenceValueConverter;
import io.netty.handler.codec.DefaultHeaders;
import io.netty.handler.codec.Headers;
import io.netty.util.AsciiString;
public final class DefaultHttpHeaders extends NettyHttpHeaders<Headers<CharSequence, CharSequence, ?>> {
public DefaultHttpHeaders() {
super(new HeadersMap());
}
public DefaultHttpHeaders(Headers<CharSequence, CharSequence, ?> headers) {
super(new HeadersMap(headers));
}
public DefaultHttpHeaders(HttpHeaders headers) {
super(new HeadersMap(headers));
}
@SuppressWarnings({"unchecked", "rawtypes"})
private static final class HeadersMap extends DefaultHeaders<CharSequence, CharSequence, HeadersMap> {
HeadersMap() {
this(16);
}
HeadersMap(Headers<?, ?, ?> headers) {
this(headers.size());
addImpl((Headers) headers);
}
HeadersMap(HttpHeaders headers) {
this(headers.size());
for (Entry<CharSequence, String> entry : headers) {
add(entry.getKey(), entry.getValue());
}
}
HeadersMap(int size) {
super(
AsciiString.CASE_INSENSITIVE_HASHER,
CharSequenceValueConverter.INSTANCE,
NameValidator.NOT_NULL,
size,
(ValueValidator) ValueValidator.NO_VALIDATION);
}
@Override
protected void validateName(NameValidator<CharSequence> validator, boolean forAdd, CharSequence name) {}
@Override
protected void validateValue(ValueValidator<CharSequence> validator, CharSequence name, CharSequence value) {}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/ServerSentEventEncoder.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/ServerSentEventEncoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.exception.EncodeException;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.List;
/**
* Encode the data according to the Server-Sent Events specification.
* <p>
* The formatted string follows the text/event-stream format as defined in the HTML specification.
* Each field is formatted as a line with the field name, followed by a colon, followed by the field value,
* and ending with a newline character.
*
* @see <a href="https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation">Event stream interpretation</a>
*/
public final class ServerSentEventEncoder implements HttpMessageEncoder {
private final HttpMessageEncoder httpMessageEncoder;
public ServerSentEventEncoder(HttpMessageEncoder httpMessageEncoder) {
this.httpMessageEncoder = httpMessageEncoder;
}
@Override
public void encode(OutputStream outputStream, Object data, Charset charset) throws EncodeException {
StringBuilder sb = new StringBuilder(256);
if (data instanceof ServerSentEvent) {
ServerSentEvent<?> event = (ServerSentEvent<?>) data;
if (event.getId() != null) {
appendField(sb, "id", event.getId());
}
if (event.getEvent() != null) {
appendField(sb, "event", event.getEvent());
}
if (event.getRetry() != null) {
appendField(sb, "retry", event.getRetry().toMillis());
}
if (event.getComment() != null) {
sb.append(':')
.append(StringUtils.replace(event.getComment(), "\n", "\n:"))
.append('\n');
}
if (event.getData() != null) {
encodeData(sb, event.getData(), charset);
}
} else {
encodeData(sb, data, charset);
}
sb.append('\n');
try {
outputStream.write(sb.toString().getBytes(charset));
} catch (Exception e) {
throw new EncodeException("Error encoding ServerSentEvent", e);
}
}
private void encodeData(StringBuilder sb, Object data, Charset charset) {
ByteArrayOutputStream bos = new ByteArrayOutputStream(256);
httpMessageEncoder.encode(bos, data, charset);
String dataStr = new String(bos.toByteArray(), charset);
List<String> lines = StringUtils.splitToList(dataStr, '\n');
for (int i = 0, size = lines.size(); i < size; i++) {
appendField(sb, "data", lines.get(i));
}
}
private static void appendField(StringBuilder sb, String name, Object value) {
sb.append(name).append(':').append(value).append('\n');
}
@Override
public String contentType() {
// An idea:sse use text/event-stream regardless of the underlying data encoder...
return MediaType.TEXT_EVENT_STREAM.getName();
}
@Override
public MediaType mediaType() {
return MediaType.TEXT_EVENT_STREAM;
}
@Override
public boolean supports(String mediaType) {
return httpMessageEncoder.supports(mediaType);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageEncoderFactory.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageEncoderFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.model.FrameworkModel;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface HttpMessageEncoderFactory extends CodecMediaType {
HttpMessageEncoder createCodec(URL url, FrameworkModel frameworkModel, String mediaType);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/DefaultHttpResponse.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/DefaultHttpResponse.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.HttpCookie;
import org.apache.dubbo.remoting.http12.HttpHeaderNames;
import org.apache.dubbo.remoting.http12.HttpHeaders;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.remoting.http12.HttpResult;
import org.apache.dubbo.remoting.http12.HttpStatus;
import org.apache.dubbo.remoting.http12.HttpUtils;
import org.apache.dubbo.remoting.http12.message.DefaultHttpResult.Builder;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import io.netty.handler.codec.DateFormatter;
public class DefaultHttpResponse implements HttpResponse {
private HttpHeaders headers;
private int status;
private String contentType;
private String charset;
private Object body;
private OutputStream outputStream;
private volatile boolean committed;
@Override
public int status() {
return status;
}
@Override
public void setStatus(int status) {
if (committed) {
return;
}
this.status = status;
}
@Override
public String header(CharSequence name) {
return headers == null ? null : headers.getFirst(name);
}
@Override
public Date dateHeader(CharSequence name) {
String value = header(name);
return StringUtils.isEmpty(value) ? null : DateFormatter.parseHttpDate(value);
}
@Override
public List<String> headerValues(CharSequence name) {
return headers == null ? Collections.emptyList() : headers.get(name);
}
@Override
public boolean hasHeader(CharSequence name) {
return headers != null && headers.containsKey(name);
}
@Override
public Collection<String> headerNames() {
return headers == null ? Collections.emptyList() : headers.names();
}
@Override
public HttpHeaders headers() {
if (headers == null) {
headers = HttpHeaders.create();
}
return headers;
}
@Override
public void addHeader(CharSequence name, String value) {
if (committed) {
return;
}
headers().add(name, value);
}
@Override
public void addHeader(CharSequence name, Date value) {
addHeader(name, DateFormatter.format(value));
}
@Override
public void setHeader(CharSequence name, String value) {
if (committed) {
return;
}
headers().set(name, value);
}
@Override
public void setHeader(CharSequence name, Date value) {
setHeader(name, DateFormatter.format(value));
}
@Override
public void setHeader(CharSequence name, List<String> values) {
if (committed) {
return;
}
headers().set(name, values);
}
@Override
public void addCookie(HttpCookie cookie) {
addHeader(HttpHeaderNames.SET_COOKIE.getKey(), HttpUtils.encodeCookie(cookie));
}
@Override
public String contentType() {
String contentType = this.contentType;
if (contentType == null) {
contentType = header(HttpHeaderNames.CONTENT_TYPE.getKey());
contentType = contentType == null ? StringUtils.EMPTY_STRING : contentType.trim();
this.contentType = contentType;
}
return contentType.isEmpty() ? null : contentType;
}
@Override
public void setContentType(String contentType) {
if (committed) {
return;
}
this.contentType = contentType;
charset = null;
}
@Override
public String mediaType() {
String contentType = contentType();
if (contentType == null) {
return null;
}
int index = contentType.indexOf(';');
return index == -1 ? contentType : contentType.substring(0, index);
}
@Override
public String charset() {
String charset = this.charset;
if (charset == null) {
String contentType = contentType();
charset = HttpUtils.parseCharset(contentType);
this.charset = charset;
}
return charset.isEmpty() ? null : charset;
}
@Override
public void setCharset(String charset) {
if (committed) {
return;
}
String contentType = contentType();
if (contentType != null) {
this.contentType = contentType + "; " + HttpUtils.CHARSET_PREFIX + charset;
}
this.charset = charset;
}
@Override
public String locale() {
return header(HttpHeaderNames.CONTENT_LANGUAGE.getKey());
}
@Override
public void setLocale(String locale) {
if (committed) {
return;
}
setHeader(HttpHeaderNames.CONTENT_LANGUAGE.getKey(), locale);
}
@Override
public Object body() {
return body;
}
@Override
public void setBody(Object body) {
if (committed) {
return;
}
this.body = body;
}
@Override
public OutputStream outputStream() {
if (outputStream == null) {
outputStream = new ByteArrayOutputStream(1024);
}
return outputStream;
}
@Override
public void setOutputStream(OutputStream os) {
if (committed) {
return;
}
outputStream = os;
}
@Override
public void sendRedirect(String location) {
check();
setStatus(HttpStatus.FOUND.getCode());
setHeader(HttpHeaderNames.LOCATION.getKey(), location);
commit();
}
@Override
public void sendError(int status) {
check();
setStatus(status);
commit();
}
@Override
public void sendError(int status, String message) {
check();
setStatus(status);
setBody(message);
commit();
}
@Override
public boolean isEmpty() {
return status == 0 && (headers == null || headers.isEmpty()) && isContentEmpty();
}
@Override
public boolean isContentEmpty() {
if (body != null) {
return false;
}
if (outputStream != null) {
return outputStream instanceof ByteArrayOutputStream && ((ByteArrayOutputStream) outputStream).size() == 0;
}
return true;
}
@Override
public boolean isCommitted() {
return committed;
}
@Override
public void commit() {
committed = true;
}
@Override
public void setCommitted(boolean committed) {
this.committed = committed;
}
@Override
public void reset() {
check();
headers = null;
status = 0;
contentType = null;
body = null;
resetBuffer();
}
@Override
public void resetBuffer() {
check();
if (outputStream == null) {
return;
}
if (outputStream instanceof ByteArrayOutputStream) {
((ByteArrayOutputStream) outputStream).reset();
return;
}
String name = outputStream.getClass().getName();
throw new UnsupportedOperationException("The outputStream type [" + name + "] is not supported to reset");
}
private void check() {
if (committed) {
throw new IllegalStateException("Response already committed");
}
}
@Override
@SuppressWarnings("unchecked")
public HttpResult<Object> toHttpResult() {
Builder<Object> builder = HttpResult.builder();
int status = this.status;
Object body = this.body;
builder.headers(headers);
if (body instanceof HttpResult) {
HttpResult<Object> result = (HttpResult<Object>) body;
if (result.getStatus() != 0) {
status = result.getStatus();
}
if (result.getBody() != null) {
body = result.getBody();
}
builder.headers(result.getHeaders());
}
return builder.status(status == 0 ? HttpStatus.OK.getCode() : status)
.body(body == null ? outputStream : body)
.build();
}
@Override
public String toString() {
return "DefaultHttpResponse{" + fieldToString() + '}';
}
protected final String fieldToString() {
return "status=" + status + ", contentType='" + contentType() + '\'' + ", body=" + body;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageEncoder.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageEncoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.remoting.http12.exception.EncodeException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import static java.nio.charset.StandardCharsets.UTF_8;
public interface HttpMessageEncoder extends CodecMediaType {
void encode(OutputStream outputStream, Object data, Charset charset) throws EncodeException;
default void encode(OutputStream outputStream, Object[] data, Charset charset) throws EncodeException {
encode(outputStream, ArrayUtils.first(data), charset);
}
default void encode(OutputStream outputStream, Object data) throws EncodeException {
encode(outputStream, data, UTF_8);
}
default void encode(OutputStream outputStream, Object[] data) throws EncodeException {
encode(outputStream, ArrayUtils.first(data), UTF_8);
}
default String contentType() {
return mediaType().getName();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageDecoderFactory.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageDecoderFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.model.FrameworkModel;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface HttpMessageDecoderFactory extends CodecMediaType {
HttpMessageDecoder createCodec(URL url, FrameworkModel frameworkModel, String mediaType);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/MediaType.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/MediaType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
import java.util.Objects;
public final class MediaType {
public static final String WILDCARD = "*";
public static final String APPLICATION = "application";
public static final String TEXT = "text";
public static final String JSON = "json";
public static final String XML = "xml";
public static final String YAML = "yaml";
public static final MediaType ALL = new MediaType(WILDCARD, WILDCARD);
public static final MediaType APPLICATION_JSON = new MediaType(APPLICATION, JSON);
public static final MediaType APPLICATION_XML = new MediaType(APPLICATION, XML);
public static final MediaType APPLICATION_YAML = new MediaType(APPLICATION, YAML);
public static final MediaType APPLICATION_JAVASCRIPT = new MediaType(APPLICATION, "javascript");
public static final MediaType APPLICATION_OCTET_STREAM = new MediaType(APPLICATION, "octet-stream");
public static final MediaType APPLICATION_GRPC = new MediaType(APPLICATION, "grpc");
public static final MediaType APPLICATION_GRPC_PROTO = new MediaType(APPLICATION, "grpc+proto");
public static final MediaType APPLICATION_FROM_URLENCODED = new MediaType(APPLICATION, "x-www-form-urlencoded");
public static final MediaType MULTIPART_FORM_DATA = new MediaType("multipart", "form-data");
public static final MediaType TEXT_JSON = new MediaType(TEXT, JSON);
public static final MediaType TEXT_XML = new MediaType(TEXT, XML);
public static final MediaType TEXT_YAML = new MediaType(TEXT, YAML);
public static final MediaType TEXT_CSS = new MediaType(TEXT, "css");
public static final MediaType TEXT_JAVASCRIPT = new MediaType(TEXT, "javascript");
public static final MediaType TEXT_HTML = new MediaType(TEXT, "html");
public static final MediaType TEXT_PLAIN = new MediaType(TEXT, "plain");
public static final MediaType TEXT_EVENT_STREAM = new MediaType(TEXT, "event-stream");
private final String name;
private final String type;
private final String subType;
public MediaType(String type, String subType) {
this.type = type;
this.subType = subType;
this.name = type + '/' + subType;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public String getSubType() {
return subType;
}
public boolean isPureText() {
return TEXT.equals(type);
}
public static MediaType of(String name) {
Objects.requireNonNull(name);
if (APPLICATION_JSON.name.equals(name)) {
return APPLICATION_JSON;
}
if (APPLICATION_YAML.name.equals(name)) {
return APPLICATION_YAML;
}
if (APPLICATION_FROM_URLENCODED.name.equals(name)) {
return APPLICATION_FROM_URLENCODED;
}
int index = name.indexOf('/');
if (index > 0) {
return new MediaType(name.substring(0, index), name.substring(index + 1));
}
throw new IllegalArgumentException("Invalid media type: '" + name + "'");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/LengthFieldStreamingDecoder.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/LengthFieldStreamingDecoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
import org.apache.dubbo.common.config.Configuration;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.remoting.http12.CompositeInputStream;
import org.apache.dubbo.remoting.http12.exception.DecodeException;
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.InputStream;
public class LengthFieldStreamingDecoder implements StreamingDecoder {
private long pendingDeliveries;
private boolean inDelivery = false;
private boolean closing;
private boolean closed;
private DecodeState state = DecodeState.HEADER;
private final CompositeInputStream accumulate = new CompositeInputStream();
private FragmentListener listener;
private final int lengthFieldOffset;
private final int lengthFieldLength;
private final int maxMessageSize;
private int requiredLength;
public LengthFieldStreamingDecoder() {
this(4);
}
public LengthFieldStreamingDecoder(int lengthFieldLength) {
this(0, lengthFieldLength);
}
public LengthFieldStreamingDecoder(int lengthFieldOffset, int lengthFieldLength) {
this.lengthFieldOffset = lengthFieldOffset;
this.lengthFieldLength = lengthFieldLength;
this.requiredLength = lengthFieldOffset + lengthFieldLength;
Configuration conf = ConfigurationUtils.getEnvConfiguration(ApplicationModel.defaultModel());
this.maxMessageSize = conf.getInt(Constants.H2_SETTINGS_MAX_MESSAGE_SIZE, 50 * 1024 * 1024);
}
@Override
public final void decode(InputStream inputStream) throws DecodeException {
if (closing || closed) {
// ignored
return;
}
accumulate.addInputStream(inputStream);
deliver();
}
@Override
public final void request(int numMessages) {
pendingDeliveries += numMessages;
deliver();
}
@Override
public final void close() {
closing = true;
deliver();
}
@Override
public final void onStreamClosed() {
if (closed) {
return;
}
closed = true;
try {
accumulate.close();
} catch (IOException e) {
throw new DecodeException(e);
}
}
@Override
public final void setFragmentListener(FragmentListener listener) {
this.listener = listener;
}
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;
}
if (closed) {
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.close();
listener.onClose();
}
}
} catch (IOException e) {
throw new DecodeException(e);
} finally {
inDelivery = false;
}
}
private void processHeader() throws IOException {
byte[] offsetData = new byte[lengthFieldOffset];
int ignore = accumulate.read(offsetData);
processOffset(new ByteArrayInputStream(offsetData), lengthFieldOffset);
byte[] lengthBytes = new byte[lengthFieldLength];
ignore = accumulate.read(lengthBytes);
requiredLength = bytesToInt(lengthBytes);
// Validate bounds
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 = DecodeState.PAYLOAD;
}
protected void processOffset(InputStream inputStream, int lengthFieldOffset) throws IOException {
// default skip offset
skipOffset(inputStream, lengthFieldOffset);
}
private void skipOffset(InputStream inputStream, int lengthFieldOffset) throws IOException {
if (lengthFieldOffset != 0) {
return;
}
int ignore = inputStream.read(new byte[lengthFieldOffset]);
}
private void processBody() throws IOException {
byte[] rawMessage = readRawMessage(accumulate, requiredLength);
InputStream inputStream = new ByteArrayInputStream(rawMessage);
invokeListener(inputStream);
// Done with this frame, begin processing the next header.
state = DecodeState.HEADER;
requiredLength = lengthFieldOffset + lengthFieldLength;
}
public void invokeListener(InputStream inputStream) {
this.listener.onFragmentMessage(inputStream);
}
protected byte[] readRawMessage(InputStream inputStream, int length) throws IOException {
byte[] data = new byte[length];
inputStream.read(data, 0, length);
return data;
}
private boolean hasEnoughBytes() {
return requiredLength - accumulate.available() <= 0;
}
protected static int bytesToInt(byte[] bytes) {
return ((bytes[0] & 0xFF) << 24) | ((bytes[1] & 0xFF) << 16) | ((bytes[2] & 0xFF) << 8) | (bytes[3]) & 0xFF;
}
private enum DecodeState {
HEADER,
PAYLOAD
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/DefaultHttpRequest.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/DefaultHttpRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.HttpChannel;
import org.apache.dubbo.remoting.http12.HttpConstants;
import org.apache.dubbo.remoting.http12.HttpCookie;
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.HttpMethods;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpUtils;
import org.apache.dubbo.remoting.http12.RequestMetadata;
import org.apache.dubbo.remoting.http12.h2.Http2Header;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import io.netty.handler.codec.DateFormatter;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType;
import io.netty.handler.codec.http2.Http2Headers.PseudoHeaderName;
public class DefaultHttpRequest implements HttpRequest {
private final HttpMetadata metadata;
private final HttpChannel channel;
private final HttpHeaders headers;
private String method;
private String uri;
private String contentType;
private String charset;
private List<HttpCookie> cookies;
private List<Locale> locales;
private QueryStringDecoder decoder;
private HttpPostRequestDecoder postDecoder;
private boolean postParsed;
private Map<String, Object> attributes;
private InputStream inputStream;
public DefaultHttpRequest(HttpMetadata metadata, HttpChannel channel) {
this.metadata = metadata;
this.channel = channel;
headers = metadata.headers();
if (metadata instanceof RequestMetadata) {
RequestMetadata requestMetadata = (RequestMetadata) metadata;
method = requestMetadata.method();
uri = requestMetadata.path();
} else {
throw new UnsupportedOperationException();
}
}
public HttpMetadata getMetadata() {
return metadata;
}
@Override
public boolean isHttp2() {
return metadata instanceof Http2Header;
}
@Override
public String method() {
return method;
}
@Override
public void setMethod(String method) {
this.method = method;
}
@Override
public String uri() {
return uri;
}
@Override
public void setUri(String uri) {
this.uri = uri;
decoder = null;
}
@Override
public String path() {
return getDecoder().path();
}
@Override
public String rawPath() {
return getDecoder().rawPath();
}
@Override
public String query() {
return getDecoder().rawQuery();
}
@Override
public String header(CharSequence name) {
return headers.getFirst(name);
}
@Override
public List<String> headerValues(CharSequence name) {
return headers.get(name);
}
@Override
public Date dateHeader(CharSequence name) {
String value = headers.getFirst(name);
return StringUtils.isEmpty(value) ? null : DateFormatter.parseHttpDate(value);
}
@Override
public boolean hasHeader(CharSequence name) {
return headers.containsKey(name);
}
@Override
public Collection<String> headerNames() {
return headers.names();
}
@Override
public HttpHeaders headers() {
return headers;
}
@Override
public void setHeader(CharSequence name, String value) {
headers.set(name, value);
}
@Override
public void setHeader(CharSequence name, Date value) {
headers.set(name, DateFormatter.format(value));
}
@Override
public void setHeader(CharSequence name, List<String> values) {
headers.set(name, values);
}
@Override
public Collection<HttpCookie> cookies() {
List<HttpCookie> cookies = this.cookies;
if (cookies == null) {
cookies = HttpUtils.decodeCookies(header(HttpHeaderNames.COOKIE.getKey()));
this.cookies = cookies;
}
return cookies;
}
@Override
public HttpCookie cookie(String name) {
List<HttpCookie> cookies = this.cookies;
if (cookies == null) {
cookies = HttpUtils.decodeCookies(header(HttpHeaderNames.COOKIE.getKey()));
this.cookies = cookies;
}
for (int i = 0, size = cookies.size(); i < size; i++) {
HttpCookie cookie = cookies.get(i);
if (cookie.name().equals(name)) {
return cookie;
}
}
return null;
}
@Override
public int contentLength() {
String value = headers.getFirst(HttpHeaderNames.CONTENT_LENGTH.getKey());
return value == null ? 0 : Integer.parseInt(value);
}
@Override
public String contentType() {
String contentType = this.contentType;
if (contentType == null) {
contentType = headers.getFirst(HttpHeaderNames.CONTENT_TYPE.getKey());
contentType = contentType == null ? StringUtils.EMPTY_STRING : contentType.trim();
this.contentType = contentType;
}
return contentType.isEmpty() ? null : contentType;
}
@Override
public void setContentType(String contentType) {
setContentType0(contentType == null ? StringUtils.EMPTY_STRING : contentType.trim());
charset = null;
}
private void setContentType0(String contentType) {
this.contentType = contentType;
headers.set(HttpHeaderNames.CONTENT_TYPE.getKey(), contentType());
}
@Override
public String mediaType() {
String contentType = contentType();
if (contentType == null) {
return null;
}
int index = contentType.indexOf(';');
return index == -1 ? contentType : contentType.substring(0, index);
}
@Override
public String charset() {
String charset = this.charset;
if (charset == null) {
String contentType = contentType();
charset = HttpUtils.parseCharset(contentType);
this.charset = charset;
}
return charset.isEmpty() ? null : charset;
}
@Override
public Charset charsetOrDefault() {
String charset = charset();
return charset == null ? StandardCharsets.UTF_8 : Charset.forName(charset);
}
@Override
public void setCharset(String charset) {
String contentType = contentType();
if (contentType != null) {
setContentType0(contentType + "; " + HttpUtils.CHARSET_PREFIX + charset);
}
this.charset = charset;
}
@Override
public String accept() {
return headers.getFirst(HttpHeaderNames.ACCEPT.getKey());
}
@Override
public Locale locale() {
return locales().get(0);
}
@Override
public List<Locale> locales() {
List<Locale> locales = this.locales;
if (locales == null) {
locales = HttpUtils.parseAcceptLanguage(headers.getFirst(HttpHeaderNames.CONTENT_LANGUAGE.getKey()));
if (locales.isEmpty()) {
locales = Collections.singletonList(Locale.getDefault());
}
this.locales = locales;
}
return locales;
}
@Override
public String scheme() {
String scheme = headers.getFirst(HttpConstants.X_FORWARDED_PROTO);
if (isHttp2()) {
scheme = headers.getFirst(PseudoHeaderName.SCHEME.value());
}
return scheme == null ? HttpConstants.HTTP : scheme;
}
@Override
public String serverHost() {
String host = getHost0();
return host == null ? localHost() + ':' + localPort() : host;
}
@Override
public String serverName() {
String host = headers.getFirst(HttpConstants.X_FORWARDED_HOST);
if (host != null) {
return host;
}
host = getHost0();
if (host != null) {
int index = host.lastIndexOf(':');
return index == -1 ? host : host.substring(0, index);
}
return localHost();
}
@Override
public int serverPort() {
String port = headers.getFirst(HttpConstants.X_FORWARDED_PORT);
if (port != null) {
return Integer.parseInt(port);
}
String host = getHost0();
if (host != null) {
int index = host.lastIndexOf(':');
return index == -1 ? -1 : Integer.parseInt(host.substring(0, index));
}
return localPort();
}
private String getHost0() {
return headers.getFirst(isHttp2() ? PseudoHeaderName.AUTHORITY.value() : HttpHeaderNames.HOST.getKey());
}
@Override
public String remoteHost() {
return getRemoteAddress().getHostString();
}
@Override
public String remoteAddr() {
return getRemoteAddress().getAddress().getHostAddress();
}
@Override
public int remotePort() {
return getRemoteAddress().getPort();
}
private InetSocketAddress getRemoteAddress() {
return (InetSocketAddress) channel.remoteAddress();
}
@Override
public String localHost() {
return getLocalAddress().getHostString();
}
@Override
public String localAddr() {
return getLocalAddress().getAddress().getHostAddress();
}
@Override
public int localPort() {
return getLocalAddress().getPort();
}
private InetSocketAddress getLocalAddress() {
return (InetSocketAddress) channel.localAddress();
}
@Override
public String parameter(String name) {
List<String> values = getDecoder().parameters().get(name);
if (CollectionUtils.isNotEmpty(values)) {
return values.get(0);
}
HttpPostRequestDecoder postDecoder = getPostDecoder();
if (postDecoder == null) {
return null;
}
List<InterfaceHttpData> items = postDecoder.getBodyHttpDatas(name);
if (items == null) {
return null;
}
for (int i = 0, size = items.size(); i < size; i++) {
InterfaceHttpData item = items.get(i);
if (item.getHttpDataType() == HttpDataType.Attribute) {
return HttpUtils.readPostValue(item);
}
}
return formParameter(name);
}
@Override
public String parameter(String name, String defaultValue) {
String value = parameter(name);
return value == null ? defaultValue : value;
}
@Override
public List<String> parameterValues(String name) {
List<String> values = getDecoder().parameters().get(name);
HttpPostRequestDecoder postDecoder = getPostDecoder();
if (postDecoder == null) {
return values;
}
List<InterfaceHttpData> items = postDecoder.getBodyHttpDatas(name);
if (items == null) {
return values;
}
for (int i = 0, size = items.size(); i < size; i++) {
InterfaceHttpData item = items.get(i);
if (item.getHttpDataType() == HttpDataType.Attribute) {
if (values == null) {
values = new ArrayList<>();
}
values.add(HttpUtils.readPostValue(item));
}
}
return values;
}
@Override
public String queryParameter(String name) {
return CollectionUtils.first(queryParameterValues(name));
}
@Override
public List<String> queryParameterValues(String name) {
return getDecoder().parameters().get(name);
}
@Override
public Collection<String> queryParameterNames() {
return getDecoder().parameters().keySet();
}
@Override
public Map<String, List<String>> queryParameters() {
return getDecoder().parameters();
}
@Override
public String formParameter(String name) {
HttpPostRequestDecoder postDecoder = getPostDecoder();
if (postDecoder == null) {
return null;
}
List<InterfaceHttpData> items = postDecoder.getBodyHttpDatas(name);
if (items == null) {
return null;
}
for (int i = 0, size = items.size(); i < size; i++) {
InterfaceHttpData item = items.get(i);
if (item.getHttpDataType() == HttpDataType.Attribute) {
return HttpUtils.readPostValue(item);
}
}
return null;
}
@Override
public List<String> formParameterValues(String name) {
HttpPostRequestDecoder postDecoder = getPostDecoder();
if (postDecoder == null) {
return null;
}
List<InterfaceHttpData> items = postDecoder.getBodyHttpDatas(name);
if (items == null) {
return null;
}
List<String> values = null;
for (int i = 0, size = items.size(); i < size; i++) {
InterfaceHttpData item = items.get(i);
if (item.getHttpDataType() == HttpDataType.Attribute) {
if (values == null) {
values = new ArrayList<>();
}
values.add(HttpUtils.readPostValue(item));
}
}
return values == null ? Collections.emptyList() : values;
}
@Override
public Collection<String> formParameterNames() {
HttpPostRequestDecoder postDecoder = getPostDecoder();
if (postDecoder == null) {
return Collections.emptyList();
}
List<InterfaceHttpData> items = postDecoder.getBodyHttpDatas();
if (items == null) {
return Collections.emptyList();
}
Set<String> names = null;
for (int i = 0, size = items.size(); i < size; i++) {
InterfaceHttpData item = items.get(i);
if (item.getHttpDataType() == HttpDataType.Attribute) {
if (names == null) {
names = new LinkedHashSet<>();
}
names.add(item.getName());
}
}
return names == null ? Collections.emptyList() : names;
}
@Override
public boolean hasParameter(String name) {
if (getDecoder().parameters().containsKey(name)) {
return true;
}
HttpPostRequestDecoder postDecoder = getPostDecoder();
if (postDecoder == null) {
return false;
}
List<InterfaceHttpData> items = postDecoder.getBodyHttpDatas(name);
if (items == null) {
return false;
}
for (int i = 0, size = items.size(); i < size; i++) {
InterfaceHttpData item = items.get(i);
if (item.getHttpDataType() == HttpDataType.Attribute) {
return true;
}
}
return false;
}
@Override
public Collection<String> parameterNames() {
Set<String> names = getDecoder().parameters().keySet();
HttpPostRequestDecoder postDecoder = getPostDecoder();
if (postDecoder == null) {
return names;
}
List<InterfaceHttpData> items = postDecoder.getBodyHttpDatas();
if (items == null) {
return names;
}
Set<String> allNames = null;
for (int i = 0, size = items.size(); i < size; i++) {
InterfaceHttpData item = items.get(i);
if (item.getHttpDataType() == HttpDataType.Attribute) {
if (allNames == null) {
allNames = new LinkedHashSet<>(names);
}
allNames.add(item.getName());
}
}
return allNames == null ? Collections.emptyList() : allNames;
}
@Override
public Collection<FileUpload> parts() {
HttpPostRequestDecoder postDecoder = getPostDecoder();
if (postDecoder == null) {
return Collections.emptyList();
}
List<InterfaceHttpData> items = postDecoder.getBodyHttpDatas();
if (items == null) {
return Collections.emptyList();
}
List<FileUpload> fileUploads = new ArrayList<>();
for (int i = 0, size = items.size(); i < size; i++) {
InterfaceHttpData item = items.get(i);
if (item.getHttpDataType() == HttpDataType.FileUpload) {
fileUploads.add(HttpUtils.readUpload(item));
}
}
return fileUploads;
}
@Override
public FileUpload part(String name) {
HttpPostRequestDecoder postDecoder = getPostDecoder();
if (postDecoder == null) {
return null;
}
List<InterfaceHttpData> items = postDecoder.getBodyHttpDatas(name);
if (items == null) {
return null;
}
for (int i = 0, size = items.size(); i < size; i++) {
InterfaceHttpData item = items.get(i);
if (item.getHttpDataType() == HttpDataType.FileUpload) {
return HttpUtils.readUpload(item);
}
}
return null;
}
private QueryStringDecoder getDecoder() {
if (decoder == null) {
String charset = charset();
if (charset == null) {
decoder = new QueryStringDecoder(uri);
} else {
decoder = new QueryStringDecoder(uri, Charset.forName(charset));
}
}
return decoder;
}
private HttpPostRequestDecoder getPostDecoder() {
HttpPostRequestDecoder postDecoder = this.postDecoder;
if (postDecoder == null) {
if (postParsed) {
return null;
}
if (inputStream != null && HttpMethods.supportBody(method)) {
postDecoder = HttpUtils.createPostRequestDecoder(this, inputStream, charset());
this.postDecoder = postDecoder;
}
postParsed = true;
}
return postDecoder;
}
@Override
@SuppressWarnings("unchecked")
public <T> T attribute(String name) {
return (T) getAttributes().get(name);
}
@Override
public void removeAttribute(String name) {
getAttributes().remove(name);
}
@Override
public void setAttribute(String name, Object value) {
getAttributes().put(name, value);
}
@Override
public boolean hasAttribute(String name) {
return attributes != null && attributes.containsKey(name);
}
@Override
public Collection<String> attributeNames() {
return getAttributes().keySet();
}
@Override
public Map<String, Object> attributes() {
return getAttributes();
}
private Map<String, Object> getAttributes() {
Map<String, Object> attributes = this.attributes;
if (attributes == null) {
attributes = new HashMap<>();
this.attributes = attributes;
}
return attributes;
}
@Override
public InputStream inputStream() {
return inputStream;
}
@Override
public void setInputStream(InputStream is) {
inputStream = is;
if (HttpMethods.isPost(method)) {
postDecoder = null;
postParsed = false;
}
}
@Override
public String toString() {
return "DefaultHttpRequest{" + fieldToString() + '}';
}
protected final String fieldToString() {
return "method='" + method + '\'' + ", uri='" + uri + '\'' + ", contentType='" + contentType() + '\'';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageDecoder.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageDecoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.remoting.http12.exception.DecodeException;
import java.io.InputStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import static java.nio.charset.StandardCharsets.UTF_8;
public interface HttpMessageDecoder extends CodecMediaType {
Object decode(InputStream inputStream, Class<?> targetType, Charset charset) throws DecodeException;
default Object decode(InputStream inputStream, Type targetType, Charset charset) throws DecodeException {
if (targetType instanceof Class) {
return decode(inputStream, (Class<?>) targetType, charset);
}
if (targetType instanceof ParameterizedType) {
return decode(inputStream, (Class<?>) ((ParameterizedType) targetType).getRawType(), charset);
}
throw new DecodeException("targetType " + targetType + " is not a class");
}
default Object[] decode(InputStream inputStream, Class<?>[] targetTypes, Charset charset) throws DecodeException {
return new Object[] {decode(inputStream, ArrayUtils.isEmpty(targetTypes) ? null : targetTypes[0], charset)};
}
default Object decode(InputStream inputStream, Class<?> targetType) throws DecodeException {
return decode(inputStream, targetType, UTF_8);
}
default Object decode(InputStream inputStream, Type targetType) throws DecodeException {
return decode(inputStream, targetType, UTF_8);
}
default Object[] decode(InputStream inputStream, Class<?>[] targetTypes) throws DecodeException {
return decode(inputStream, targetTypes, UTF_8);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/ServerSentEvent.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/ServerSentEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
import java.time.Duration;
/**
* Represents a Server-Sent Event according to the HTML specification.
* <p>
* Server-Sent Events (SSE) is a server push technology enabling a client to receive automatic updates from a server via HTTP connection.
* The server can send new data to the client at any time by pushing messages, without the need to reestablish the connection.
* <p>
* This class encapsulates the structure of a Server-Sent Event, which may include:
* <ul>
* <li>An event ID</li>
* <li>An event type</li>
* <li>A retry interval</li>
* <li>A comment</li>
* <li>Data payload</li>
* </ul>
* <p>
* Use the {@link #builder()} method to create instances of this class.
*
* @param <T> the type of data that this event contains
* @see <a href="https://html.spec.whatwg.org/multipage/server-sent-events.html">Server-Sent Events</a>
*/
public final class ServerSentEvent<T> {
/**
* The event ID that can be used for tracking or resuming event streams.
*/
private final String id;
/**
* The event type or name that identifies the type of event.
*/
private final String event;
/**
* The reconnection time in milliseconds that the client should wait before reconnecting
* after a connection is closed.
*/
private final Duration retry;
/**
* A comment that will be ignored by event-processing clients but can be useful for debugging.
*/
private final String comment;
/**
* The data payload of this event.
*/
private final T data;
/**
* Constructs a new ServerSentEvent with the specified properties.
* <p>
* It's recommended to use the {@link #builder()} method instead of this constructor directly.
*
* @param id the event ID, can be null
* @param event the event type, can be null
* @param retry the reconnection time, can be null
* @param comment the comment, can be null
* @param data the data payload, can be null
*/
public ServerSentEvent(String id, String event, Duration retry, String comment, T data) {
this.id = id;
this.event = event;
this.retry = retry;
this.comment = comment;
this.data = data;
}
/**
* Returns the event ID.
*
* @return the event ID, may be null
*/
public String getId() {
return id;
}
/**
* Returns the event type.
*
* @return the event type, may be null
*/
public String getEvent() {
return event;
}
/**
* Returns the reconnection time that clients should wait before reconnecting.
*
* @return the reconnection time as a Duration, may be null
*/
public Duration getRetry() {
return retry;
}
/**
* Returns the comment associated with this event.
*
* @return the comment, may be null
*/
public String getComment() {
return comment;
}
/**
* Returns the data payload of this event.
*
* @return the data payload, may be null
*/
public T getData() {
return data;
}
@Override
public String toString() {
return "ServerSentEvent{id='" + id + '\'' + ", event='" + event + '\'' + ", retry=" + retry + ", comment='"
+ comment + '\'' + ", data=" + data + '}';
}
/**
* Creates a new {@link Builder} instance.
*
* @param <T> the type of data that the event will contain
* @return a new builder
*/
public static <T> Builder<T> builder() {
return new Builder<>();
}
/**
* Builder for {@link ServerSentEvent}.
*
* @param <T> the type of data that the event will contain
*/
public static final class Builder<T> {
private String id;
private String event;
private Duration retry;
private String comment;
private T data;
private Builder() {}
/**
* Sets the id of the event.
*
* @param id the id
* @return this builder
*/
public Builder<T> id(String id) {
this.id = id;
return this;
}
/**
* Sets the event type.
*
* @param event the event type
* @return this builder
*/
public Builder<T> event(String event) {
this.event = event;
return this;
}
/**
* Sets the retry duration.
*
* @param retry the retry duration
* @return this builder
*/
public Builder<T> retry(Duration retry) {
this.retry = retry;
return this;
}
/**
* Sets the comment.
*
* @param comment the comment
* @return this builder
*/
public Builder<T> comment(String comment) {
this.comment = comment;
return this;
}
/**
* Sets the data.
*
* @param data the data
* @return this builder
*/
public Builder<T> data(T data) {
this.data = data;
return this;
}
/**
* Builds a new {@link ServerSentEvent} with the configured properties.
*
* @return the built event
*/
public ServerSentEvent<T> build() {
return new ServerSentEvent<>(id, event, retry, comment, data);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageCodec.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
/**
* for http body codec
*/
public interface HttpMessageCodec extends HttpMessageEncoder, HttpMessageDecoder {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/StreamingDecoder.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/StreamingDecoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
import org.apache.dubbo.remoting.http12.exception.DecodeException;
import java.io.InputStream;
public interface StreamingDecoder {
void request(int numMessages);
void decode(InputStream inputStream) throws DecodeException;
void close();
void onStreamClosed();
void setFragmentListener(FragmentListener listener);
interface FragmentListener {
/**
* @param rawMessage raw message
*/
void onFragmentMessage(InputStream rawMessage);
default void onClose() {}
}
final class DefaultFragmentListener implements FragmentListener {
private final ListeningDecoder listeningDecoder;
public DefaultFragmentListener(ListeningDecoder listeningDecoder) {
this.listeningDecoder = listeningDecoder;
}
@Override
public void onFragmentMessage(InputStream rawMessage) {
listeningDecoder.decode(rawMessage);
}
@Override
public void onClose() {
listeningDecoder.close();
}
}
final class NoopFragmentListener implements FragmentListener {
static final FragmentListener NOOP = new NoopFragmentListener();
private NoopFragmentListener() {}
@Override
public void onFragmentMessage(InputStream rawMessage) {}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/MethodMetadata.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/MethodMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.ReflectionMethodDescriptor;
import org.apache.dubbo.rpc.model.StubMethodDescriptor;
public class MethodMetadata {
private final Class<?>[] actualRequestTypes;
private final Class<?> actualResponseType;
private MethodMetadata(Class<?>[] actualRequestTypes, Class<?> actualResponseType) {
this.actualRequestTypes = actualRequestTypes;
this.actualResponseType = actualResponseType;
}
public Class<?>[] getActualRequestTypes() {
return actualRequestTypes;
}
public Class<?> getActualResponseType() {
return actualResponseType;
}
public static MethodMetadata fromMethodDescriptor(MethodDescriptor method) {
if (method instanceof ReflectionMethodDescriptor) {
return doResolveReflection((ReflectionMethodDescriptor) method);
}
if (method instanceof StubMethodDescriptor) {
return doResolveStub((StubMethodDescriptor) method);
}
throw new IllegalStateException("Can not reach here");
}
private static MethodMetadata doResolveStub(StubMethodDescriptor method) {
Class<?>[] actualRequestTypes = method.getParameterClasses();
Class<?> actualResponseType = method.getReturnClass();
return new MethodMetadata(actualRequestTypes, actualResponseType);
}
private static MethodMetadata doResolveReflection(ReflectionMethodDescriptor method) {
Class<?>[] actualRequestTypes;
Class<?> actualResponseType;
switch (method.getRpcType()) {
case CLIENT_STREAM:
case BI_STREAM:
case SERVER_STREAM:
actualRequestTypes = method.getActualRequestTypes();
actualResponseType = method.getActualResponseType();
return new MethodMetadata(actualRequestTypes, actualResponseType);
case UNARY:
actualRequestTypes = method.getParameterClasses();
actualResponseType = (Class<?>) method.getReturnTypes()[0];
return new MethodMetadata(actualRequestTypes, actualResponseType);
}
throw new IllegalStateException("Can not reach here");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/DefaultHttpResult.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/DefaultHttpResult.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
import org.apache.dubbo.common.utils.DateUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.HttpHeaderNames;
import org.apache.dubbo.remoting.http12.HttpHeaders;
import org.apache.dubbo.remoting.http12.HttpResult;
import org.apache.dubbo.remoting.http12.HttpStatus;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class DefaultHttpResult<T> implements HttpResult<T> {
private static final long serialVersionUID = 1L;
private int status;
private Map<String, List<String>> headers;
private T body;
@Override
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
@Override
public Map<String, List<String>> getHeaders() {
return headers;
}
public void setHeaders(Map<String, List<String>> headers) {
this.headers = headers;
}
@Override
public T getBody() {
return body;
}
public void setBody(T body) {
this.body = body;
}
@Override
public String toString() {
return "DefaultHttpResult{" + "status=" + status + ", headers=" + headers + ", body=" + body + '}';
}
public static final class Builder<T> {
private int status;
private Map<String, List<String>> headers;
private T body;
public Builder<T> status(int status) {
this.status = status;
return this;
}
public Builder<T> status(HttpStatus status) {
this.status = status.getCode();
return this;
}
public Builder<T> ok() {
return status(HttpStatus.OK.getCode());
}
public Builder<T> moved(String url) {
return status(HttpStatus.MOVED_PERMANENTLY).header(HttpHeaderNames.LOCATION.getName(), url);
}
public Builder<T> found(String url) {
return status(HttpStatus.FOUND).header(HttpHeaderNames.LOCATION.getName(), url);
}
public Builder<T> error() {
return status(HttpStatus.INTERNAL_SERVER_ERROR);
}
public Builder<T> headers(Map<String, List<String>> headers) {
if (headers == null || headers.isEmpty()) {
return this;
}
Map<String, List<String>> hrs = this.headers;
if (hrs == null) {
this.headers = new LinkedHashMap<>(headers);
} else {
hrs.putAll(headers);
}
return this;
}
public Builder<T> headers(HttpHeaders headers) {
if (headers == null || headers.isEmpty()) {
return this;
}
Map<String, List<String>> hrs = this.headers;
if (hrs == null) {
this.headers = hrs = new LinkedHashMap<>(headers.size());
}
for (Entry<CharSequence, String> entry : headers) {
CharSequence key = entry.getKey();
if (HttpHeaderNames.SET_COOKIE.getKey().equals(key)) {
hrs.computeIfAbsent(key.toString(), k -> new ArrayList<>(1)).add(entry.getValue());
} else {
hrs.put(key.toString(), Collections.singletonList(entry.getValue()));
}
}
return this;
}
public Builder<T> header(String key, List<String> values) {
headers().put(key, values);
return this;
}
public Builder<T> header(String key, String... values) {
headers().put(key, Arrays.asList(values));
return this;
}
public Builder<T> header(String key, String value) {
headers().put(key, Collections.singletonList(value));
return this;
}
public Builder<T> headerIf(String key, String value) {
return StringUtils.isEmpty(value) ? this : header(key, value);
}
public Builder<T> header(String key, Date value) {
return header(key, DateUtils.formatHeader(value));
}
public Builder<T> header(String key, Object value) {
return header(key, String.valueOf(value));
}
public Builder<T> headerIf(String key, Object value) {
return value == null ? this : header(key, value);
}
public Builder<T> addHeader(String key, String value) {
headers().computeIfAbsent(key, k -> new ArrayList<>()).add(value);
return this;
}
public Builder<T> contentType(String value) {
return headerIf(HttpHeaderNames.CONTENT_TYPE.getName(), value);
}
public Builder<T> from(HttpResult<T> result) {
status = result.getStatus();
headers = result.getHeaders() == null ? null : new LinkedHashMap<>(result.getHeaders());
body = result.getBody();
return this;
}
private Map<String, List<String>> headers() {
Map<String, List<String>> headers = this.headers;
if (headers == null) {
this.headers = headers = new LinkedHashMap<>();
}
return headers;
}
public Builder<T> body(T body) {
this.body = body;
return this;
}
public DefaultHttpResult<T> build() {
DefaultHttpResult<T> result = new DefaultHttpResult<>();
result.setStatus(status);
result.setHeaders(headers);
result.setBody(body);
return result;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/DefaultStreamingDecoder.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/DefaultStreamingDecoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message;
import org.apache.dubbo.remoting.http12.CompositeInputStream;
import org.apache.dubbo.remoting.http12.exception.DecodeException;
import java.io.IOException;
import java.io.InputStream;
public class DefaultStreamingDecoder implements StreamingDecoder {
private boolean closed;
protected final CompositeInputStream accumulate = new CompositeInputStream();
protected FragmentListener listener = NoopFragmentListener.NOOP;
@Override
public void request(int numMessages) {
// do nothing
}
@Override
public void decode(InputStream inputStream) throws DecodeException {
if (closed) {
// ignored
return;
}
accumulate.addInputStream(inputStream);
}
@Override
public void close() {
try {
if (closed) {
return;
}
closed = true;
listener.onFragmentMessage(accumulate);
accumulate.close();
listener.onClose();
} catch (IOException e) {
throw new DecodeException(e);
}
}
@Override
public void onStreamClosed() {
if (closed) {
return;
}
closed = true;
try {
accumulate.close();
} catch (IOException e) {
throw new DecodeException(e);
}
}
@Override
public void setFragmentListener(FragmentListener listener) {
this.listener = listener;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/YamlCodec.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/YamlCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message.codec;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.DefaultSerializeClassChecker;
import org.apache.dubbo.remoting.http12.HttpJsonUtils;
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 java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.Iterator;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.representer.Representer;
@SuppressWarnings({"unchecked", "rawtypes"})
public class YamlCodec implements HttpMessageCodec {
public static final YamlCodec INSTANCE = new YamlCodec();
private final HttpJsonUtils httpJsonUtils;
private YamlCodec() {
this(FrameworkModel.defaultModel());
}
public YamlCodec(FrameworkModel frameworkModel) {
httpJsonUtils = frameworkModel.getBeanFactory().getOrRegisterBean(HttpJsonUtils.class);
}
@Override
public Object decode(InputStream is, Class<?> targetType, Charset charset) throws DecodeException {
try (InputStreamReader reader = new InputStreamReader(is, charset)) {
return createYaml().loadAs(reader, (Class) targetType);
} catch (HttpStatusException e) {
throw e;
} catch (Throwable t) {
throw new DecodeException("Error decoding yaml", t);
}
}
@Override
public Object decode(InputStream is, Type targetType, Charset charset) throws DecodeException {
if (targetType instanceof Class) {
return decode(is, (Class<?>) targetType, charset);
}
try (InputStreamReader reader = new InputStreamReader(is, charset)) {
return httpJsonUtils.convertObject(createYaml().load(reader), targetType);
} catch (HttpStatusException e) {
throw e;
} catch (Throwable t) {
throw new DecodeException("Error decoding yaml", t);
}
}
@Override
public Object[] decode(InputStream is, Class<?>[] targetTypes, Charset charset) throws DecodeException {
try (InputStreamReader reader = new InputStreamReader(is, charset)) {
Yaml yaml = createYaml();
Iterator<Object> iterator = yaml.loadAll(reader).iterator();
int len = targetTypes.length;
Object[] results = new Object[len];
for (int i = 0; i < len; i++) {
if (iterator.hasNext()) {
Object result = iterator.next();
Class targetType = targetTypes[i];
if (targetType.isInstance(result)) {
results[i] = result;
} else {
results[i] = yaml.loadAs(yaml.dump(result), targetType);
}
} else {
throw new DecodeException("Not enough yaml documents in the stream");
}
}
return results;
} catch (HttpStatusException e) {
throw e;
} catch (Throwable t) {
throw new DecodeException("Error decoding yaml", t);
}
}
@Override
public void encode(OutputStream os, Object data, Charset charset) throws EncodeException {
try (OutputStreamWriter writer = new OutputStreamWriter(os, charset)) {
createYaml().dump(data, writer);
} catch (HttpStatusException e) {
throw e;
} catch (Throwable t) {
throw new EncodeException("Error encoding yaml", t);
}
}
@Override
public void encode(OutputStream os, Object[] data, Charset charset) throws EncodeException {
try (OutputStreamWriter writer = new OutputStreamWriter(os, charset)) {
createYaml().dump(data, writer);
} catch (HttpStatusException e) {
throw e;
} catch (Throwable t) {
throw new EncodeException("Error encoding yaml", t);
}
}
@Override
public MediaType mediaType() {
return MediaType.APPLICATION_YAML;
}
private Yaml createYaml() {
LoaderOptions options = new LoaderOptions();
options.setAllowDuplicateKeys(false);
DumperOptions dumperOptions = new DumperOptions();
return new Yaml(new FilteringConstructor(options), new Representer(dumperOptions), dumperOptions, options);
}
private static final class FilteringConstructor extends Constructor {
FilteringConstructor(LoaderOptions loaderOptions) {
super(loaderOptions);
}
@Override
protected Class<?> getClassForName(String name) throws ClassNotFoundException {
return DefaultSerializeClassChecker.getInstance().loadClass(ClassUtils.getClassLoader(), name);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/JsonPbCodec.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/JsonPbCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message.codec;
import org.apache.dubbo.common.io.StreamUtils;
import org.apache.dubbo.common.utils.MethodUtils;
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.rpc.model.FrameworkModel;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import com.google.protobuf.Message;
import com.google.protobuf.Message.Builder;
import com.google.protobuf.util.JsonFormat;
public final class JsonPbCodec extends JsonCodec {
public static final JsonPbCodec INSTANCE = new JsonPbCodec();
private JsonPbCodec() {}
public JsonPbCodec(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
public void encode(OutputStream os, Object data, Charset charset) throws EncodeException {
try {
if (data instanceof Message) {
String jsonString =
JsonFormat.printer().omittingInsignificantWhitespace().print((Message) data);
os.write(jsonString.getBytes(charset));
return;
}
} catch (IOException e) {
throw new EncodeException("Error encoding jsonPb", e);
}
super.encode(os, data, charset);
}
@Override
public Object decode(InputStream is, Class<?> targetType, Charset charset) throws DecodeException {
try {
if (isProtobuf(targetType)) {
Builder newBuilder = (Builder)
MethodUtils.findMethod(targetType, "newBuilder").invoke(null);
JsonFormat.parser().ignoringUnknownFields().merge(StreamUtils.toString(is, charset), newBuilder);
return newBuilder.build();
}
} catch (HttpStatusException e) {
throw e;
} catch (Throwable e) {
throw new DecodeException("Error decoding jsonPb", e);
}
return super.decode(is, targetType, charset);
}
@Override
public Object decode(InputStream is, Type targetType, Charset charset) throws DecodeException {
return targetType instanceof Class
? decode(is, (Class<?>) targetType, charset)
: super.decode(is, targetType, charset);
}
@Override
public Object[] decode(InputStream is, Class<?>[] targetTypes, Charset charset) throws DecodeException {
try {
if (hasProtobuf(targetTypes)) {
// protobuf only support one parameter
return new Object[] {decode(is, targetTypes[0], charset)};
}
} catch (HttpStatusException e) {
throw e;
} catch (Throwable e) {
throw new DecodeException("Error decoding jsonPb", e);
}
return super.decode(is, targetTypes, charset);
}
private static boolean isProtobuf(Class<?> targetType) {
if (targetType == null) {
return false;
}
return Message.class.isAssignableFrom(targetType);
}
private static boolean hasProtobuf(Class<?>[] classes) {
for (Class<?> clazz : classes) {
if (isProtobuf(clazz)) {
return true;
}
}
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/JsonPbCodecFactory.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/JsonPbCodecFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message.codec;
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.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(order = -100, onClass = CommonConstants.PROTOBUF_MESSAGE_CLASS_NAME)
public final class JsonPbCodecFactory implements HttpMessageEncoderFactory, HttpMessageDecoderFactory {
@Override
public HttpMessageCodec createCodec(URL url, FrameworkModel frameworkModel, String mediaType) {
return frameworkModel == FrameworkModel.defaultModel() ? JsonPbCodec.INSTANCE : new JsonPbCodec(frameworkModel);
}
@Override
public MediaType mediaType() {
return MediaType.APPLICATION_JSON;
}
@Override
public boolean supports(String mediaType) {
return mediaType.startsWith(mediaType().getName()) || mediaType.startsWith(MediaType.TEXT_JSON.getName());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/HtmlCodecFactory.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/HtmlCodecFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message.codec;
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 final class HtmlCodecFactory implements HttpMessageEncoderFactory, HttpMessageDecoderFactory {
@Override
public HttpMessageCodec createCodec(URL url, FrameworkModel frameworkModel, String mediaType) {
return frameworkModel == FrameworkModel.defaultModel() ? HtmlCodec.INSTANCE : new HtmlCodec(frameworkModel);
}
@Override
public MediaType mediaType() {
return MediaType.TEXT_HTML;
}
@Override
public boolean supports(String mediaType) {
return mediaType.startsWith(mediaType().getName()) || mediaType.startsWith("application/xhtml");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/JsonCodecFactory.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/JsonCodecFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message.codec;
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 final class JsonCodecFactory implements HttpMessageEncoderFactory, HttpMessageDecoderFactory {
@Override
public HttpMessageCodec createCodec(URL url, FrameworkModel frameworkModel, String mediaType) {
return frameworkModel == FrameworkModel.defaultModel() ? JsonCodec.INSTANCE : new JsonCodec(frameworkModel);
}
@Override
public MediaType mediaType() {
return MediaType.APPLICATION_JSON;
}
@Override
public boolean supports(String mediaType) {
return mediaType.startsWith(mediaType().getName()) || mediaType.startsWith(MediaType.TEXT_JSON.getName());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/XmlCodec.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/XmlCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message.codec;
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 javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import org.xml.sax.InputSource;
public class XmlCodec implements HttpMessageCodec {
@Override
public void encode(OutputStream os, Object data, Charset charset) throws EncodeException {
try {
Marshaller marshaller = JAXBContext.newInstance(data.getClass()).createMarshaller();
try (OutputStreamWriter writer = new OutputStreamWriter(os, charset)) {
marshaller.marshal(data, writer);
}
} catch (HttpStatusException e) {
throw e;
} catch (Exception e) {
throw new EncodeException("Error encoding xml", e);
}
}
@Override
public Object decode(InputStream is, Class<?> targetType, Charset charset) throws DecodeException {
try {
try (InputStreamReader reader = new InputStreamReader(is, charset)) {
InputSource inputSource = new InputSource(reader);
inputSource.setEncoding(charset.name());
Source xmlSource = new SAXSource(newSAXParser().getXMLReader(), inputSource);
JAXBContext context = JAXBContext.newInstance(targetType);
Unmarshaller unmarshaller = context.createUnmarshaller();
return unmarshaller.unmarshal(xmlSource);
}
} catch (HttpStatusException e) {
throw e;
} catch (Exception e) {
throw new DecodeException("Error decoding xml", e);
}
}
private SAXParser newSAXParser() throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
spf.setXIncludeAware(false);
return spf.newSAXParser();
}
@Override
public MediaType mediaType() {
return MediaType.APPLICATION_XML;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/PlainTextCodecFactory.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/PlainTextCodecFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message.codec;
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(order = 10000)
public final class PlainTextCodecFactory implements HttpMessageEncoderFactory, HttpMessageDecoderFactory {
@Override
public HttpMessageCodec createCodec(URL url, FrameworkModel frameworkModel, String mediaType) {
return frameworkModel == FrameworkModel.defaultModel()
? PlainTextCodec.INSTANCE
: new PlainTextCodec(frameworkModel);
}
@Override
public MediaType mediaType() {
return MediaType.TEXT_PLAIN;
}
@Override
public boolean supports(String mediaType) {
return mediaType.startsWith("text/");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/XmlCodecFactory.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/XmlCodecFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message.codec;
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(onClass = "javax.xml.bind.Marshaller")
public final class XmlCodecFactory implements HttpMessageEncoderFactory, HttpMessageDecoderFactory {
private static final HttpMessageCodec INSTANCE = new XmlCodec();
@Override
public HttpMessageCodec createCodec(URL url, FrameworkModel frameworkModel, String mediaType) {
return INSTANCE;
}
@Override
public MediaType mediaType() {
return MediaType.APPLICATION_XML;
}
@Override
public boolean supports(String mediaType) {
return mediaType.startsWith(mediaType().getName()) || mediaType.startsWith(MediaType.TEXT_XML.getName());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/JsonCodec.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/JsonCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message.codec;
import org.apache.dubbo.common.io.StreamUtils;
import org.apache.dubbo.remoting.http12.HttpJsonUtils;
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 java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.List;
public class JsonCodec implements HttpMessageCodec {
public static final JsonCodec INSTANCE = new JsonCodec();
private final HttpJsonUtils httpJsonUtils;
protected JsonCodec() {
this(FrameworkModel.defaultModel());
}
public JsonCodec(FrameworkModel frameworkModel) {
httpJsonUtils = frameworkModel.getBeanFactory().getOrRegisterBean(HttpJsonUtils.class);
}
public void encode(OutputStream os, Object data, Charset charset) throws EncodeException {
try {
os.write(httpJsonUtils.toJson(data).getBytes(charset));
} catch (HttpStatusException e) {
throw e;
} catch (Throwable t) {
throw new EncodeException("Error encoding json", t);
}
}
public void encode(OutputStream os, Object[] data, Charset charset) throws EncodeException {
try {
os.write(httpJsonUtils.toJson(data).getBytes(charset));
} catch (HttpStatusException e) {
throw e;
} catch (Throwable t) {
throw new EncodeException("Error encoding json", t);
}
}
@Override
public Object decode(InputStream is, Class<?> targetType, Charset charset) throws DecodeException {
try {
return httpJsonUtils.toJavaObject(StreamUtils.toString(is, charset), targetType);
} catch (HttpStatusException e) {
throw e;
} catch (Throwable t) {
throw new DecodeException("Error decoding json", t);
}
}
@Override
public Object decode(InputStream is, Type targetType, Charset charset) throws DecodeException {
try {
return httpJsonUtils.toJavaObject(StreamUtils.toString(is, charset), targetType);
} catch (HttpStatusException e) {
throw e;
} catch (Throwable t) {
throw new DecodeException("Error decoding json", t);
}
}
@Override
public Object[] decode(InputStream is, Class<?>[] targetTypes, Charset charset) throws DecodeException {
try {
int len = targetTypes.length;
if (len == 0) {
return new Object[0];
}
Object obj = httpJsonUtils.toJavaObject(StreamUtils.toString(is, charset), Object.class);
if (obj instanceof List) {
List<?> list = (List<?>) obj;
if (list.size() == len) {
Object[] results = new Object[len];
for (int i = 0; i < len; i++) {
results[i] = httpJsonUtils.convertObject(list.get(i), targetTypes[i]);
}
return results;
}
throw new DecodeException(
"Json array size [" + list.size() + "] must equals arguments count [" + len + "]");
}
if (len == 1) {
return new Object[] {httpJsonUtils.convertObject(obj, targetTypes[0])};
}
throw new DecodeException("Json must be array");
} catch (HttpStatusException e) {
throw e;
} catch (Throwable t) {
throw new DecodeException("Error decoding json", t);
}
}
@Override
public MediaType mediaType() {
return MediaType.APPLICATION_JSON;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/BinaryCodecFactory.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/BinaryCodecFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message.codec;
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 final class BinaryCodecFactory implements HttpMessageEncoderFactory, HttpMessageDecoderFactory {
private static final BinaryCodec INSTANCE = new BinaryCodec();
@Override
public HttpMessageCodec createCodec(URL url, FrameworkModel frameworkModel, String mediaType) {
return INSTANCE;
}
@Override
public MediaType mediaType() {
return MediaType.APPLICATION_OCTET_STREAM;
}
@Override
public boolean supports(String mediaType) {
return mediaType.startsWith(MediaType.APPLICATION_OCTET_STREAM.getName()) || mediaType.startsWith("image/");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/PlainTextCodec.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/PlainTextCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message.codec;
import org.apache.dubbo.common.io.StreamUtils;
import org.apache.dubbo.remoting.http12.HttpJsonUtils;
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 java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
public final class PlainTextCodec implements HttpMessageCodec {
public static final PlainTextCodec INSTANCE = new PlainTextCodec();
private final HttpJsonUtils httpJsonUtils;
private PlainTextCodec() {
this(FrameworkModel.defaultModel());
}
public PlainTextCodec(FrameworkModel frameworkModel) {
httpJsonUtils = frameworkModel.getBeanFactory().getOrRegisterBean(HttpJsonUtils.class);
}
@Override
public void encode(OutputStream os, Object data, Charset charset) throws EncodeException {
if (data == null) {
return;
}
try {
if (data instanceof CharSequence) {
os.write((data.toString()).getBytes(charset));
return;
}
os.write(httpJsonUtils.toJson(data).getBytes(charset));
} catch (HttpStatusException e) {
throw e;
} catch (Throwable t) {
throw new EncodeException("Error encoding plain text", t);
}
}
@Override
public Object decode(InputStream is, Class<?> targetType, Charset charset) throws DecodeException {
try {
if (targetType == String.class) {
return StreamUtils.toString(is, charset);
}
} catch (HttpStatusException e) {
throw e;
} catch (Throwable t) {
throw new EncodeException("Error decoding plain text", t);
}
throw new DecodeException("'text/plain' media-type only supports String as method param.");
}
@Override
public MediaType mediaType() {
return MediaType.TEXT_PLAIN;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/BinaryCodec.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/BinaryCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message.codec;
import org.apache.dubbo.common.io.StreamUtils;
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 java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
public class BinaryCodec implements HttpMessageCodec {
@Override
public void encode(OutputStream os, Object data, Charset charset) throws EncodeException {
if (data == null) {
return;
}
try {
if (data instanceof byte[]) {
os.write((byte[]) data);
return;
}
} catch (IOException e) {
throw new EncodeException(e);
}
throw new EncodeException("'application/octet-stream' media-type only supports byte[] return type.");
}
@Override
public Object decode(InputStream is, Class<?> targetType, Charset charset) throws DecodeException {
try {
return StreamUtils.readBytes(is);
} catch (HttpStatusException e) {
throw e;
} catch (Exception e) {
throw new DecodeException(e);
}
}
@Override
public MediaType mediaType() {
return MediaType.APPLICATION_OCTET_STREAM;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/HtmlCodec.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/HtmlCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message.codec;
import org.apache.dubbo.common.io.StreamUtils;
import org.apache.dubbo.remoting.http12.HttpJsonUtils;
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 java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
public final class HtmlCodec implements HttpMessageCodec {
public static final HtmlCodec INSTANCE = new HtmlCodec();
private final HttpJsonUtils httpJsonUtils;
private HtmlCodec() {
this(FrameworkModel.defaultModel());
}
public HtmlCodec(FrameworkModel frameworkModel) {
httpJsonUtils = frameworkModel.getBeanFactory().getOrRegisterBean(HttpJsonUtils.class);
}
@Override
public void encode(OutputStream os, Object data, Charset charset) throws EncodeException {
if (data == null) {
return;
}
try {
if (data instanceof CharSequence) {
os.write((data.toString()).getBytes(charset));
return;
}
os.write(httpJsonUtils.toJson(data).getBytes(charset));
} catch (HttpStatusException e) {
throw e;
} catch (Throwable t) {
throw new EncodeException("Error encoding html", t);
}
}
@Override
public Object decode(InputStream is, Class<?> targetType, Charset charset) throws DecodeException {
try {
if (targetType == String.class) {
return StreamUtils.toString(is, charset);
}
} catch (HttpStatusException e) {
throw e;
} catch (Throwable t) {
throw new EncodeException("Error decoding html", t);
}
throw new DecodeException("'text/html' media-type only supports String as method param.");
}
@Override
public MediaType mediaType() {
return MediaType.TEXT_HTML;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/CodecUtils.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/CodecUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message.codec;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.Configuration;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.exception.UnsupportedMediaTypeException;
import org.apache.dubbo.remoting.http12.message.HttpMessageDecoder;
import org.apache.dubbo.remoting.http12.message.HttpMessageDecoderFactory;
import org.apache.dubbo.remoting.http12.message.HttpMessageEncoder;
import org.apache.dubbo.remoting.http12.message.HttpMessageEncoderFactory;
import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public final class CodecUtils {
private final FrameworkModel frameworkModel;
private final List<HttpMessageDecoderFactory> decoderFactories;
private final List<HttpMessageEncoderFactory> encoderFactories;
private final ConcurrentHashMap<String, Optional<HttpMessageEncoderFactory>> encoderCache =
new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Optional<HttpMessageDecoderFactory>> decoderCache =
new ConcurrentHashMap<>();
private Set<String> disallowedContentTypes = Collections.emptySet();
public CodecUtils(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
decoderFactories = frameworkModel.getActivateExtensions(HttpMessageDecoderFactory.class);
encoderFactories = frameworkModel.getActivateExtensions(HttpMessageEncoderFactory.class);
Configuration configuration = ConfigurationUtils.getGlobalConfiguration(frameworkModel.defaultApplication());
String contentTypes = configuration.getString(Constants.H2_SETTINGS_DISALLOWED_CONTENT_TYPES, null);
if (contentTypes != null) {
disallowedContentTypes = new HashSet<>(StringUtils.tokenizeToList(contentTypes));
}
}
public HttpMessageDecoder determineHttpMessageDecoder(URL url, String mediaType) {
return determineHttpMessageDecoderFactory(mediaType)
.orElseThrow(() -> new UnsupportedMediaTypeException(mediaType))
.createCodec(url, frameworkModel, mediaType);
}
public HttpMessageDecoder determineHttpMessageDecoder(String mediaType) {
return determineHttpMessageDecoder(null, mediaType);
}
public HttpMessageEncoder determineHttpMessageEncoder(URL url, String mediaType) {
return determineHttpMessageEncoderFactory(mediaType)
.orElseThrow(() -> new UnsupportedMediaTypeException(mediaType))
.createCodec(url, frameworkModel, mediaType);
}
public HttpMessageEncoder determineHttpMessageEncoder(String mediaType) {
return determineHttpMessageEncoder(null, mediaType);
}
public Optional<HttpMessageDecoderFactory> determineHttpMessageDecoderFactory(String mediaType) {
Assert.notNull(mediaType, "mediaType must not be null");
return ConcurrentHashMapUtils.computeIfAbsent(decoderCache, mediaType, k -> {
for (HttpMessageDecoderFactory factory : decoderFactories) {
if (factory.supports(k)
&& !disallowedContentTypes.contains(factory.mediaType().getName())) {
return Optional.of(factory);
}
}
return Optional.empty();
});
}
public Optional<HttpMessageEncoderFactory> determineHttpMessageEncoderFactory(String mediaType) {
Assert.notNull(mediaType, "mediaType must not be null");
return ConcurrentHashMapUtils.computeIfAbsent(encoderCache, mediaType, k -> {
for (HttpMessageEncoderFactory factory : encoderFactories) {
if (factory.supports(k)
&& !disallowedContentTypes.contains(factory.mediaType().getName())) {
return Optional.of(factory);
}
}
return Optional.empty();
});
}
public List<HttpMessageDecoderFactory> getDecoderFactories() {
return decoderFactories;
}
public List<HttpMessageEncoderFactory> getEncoderFactories() {
return encoderFactories;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/YamlCodecFactory.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/YamlCodecFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.message.codec;
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(onClass = "org.yaml.snakeyaml.Yaml")
public final class YamlCodecFactory implements HttpMessageEncoderFactory, HttpMessageDecoderFactory {
@Override
public HttpMessageCodec createCodec(URL url, FrameworkModel frameworkModel, String mediaType) {
return frameworkModel == FrameworkModel.defaultModel() ? YamlCodec.INSTANCE : new YamlCodec(frameworkModel);
}
@Override
public MediaType mediaType() {
return MediaType.APPLICATION_YAML;
}
@Override
public boolean supports(String mediaType) {
return mediaType.startsWith(mediaType().getName()) || mediaType.startsWith(MediaType.TEXT_YAML.getName());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/NettyHttpHeaders.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/NettyHttpHeaders.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.netty4;
import org.apache.dubbo.remoting.http12.HttpHeaders;
import org.apache.dubbo.remoting.http12.message.HttpHeadersMapAdapter;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import io.netty.handler.codec.Headers;
@SuppressWarnings({"unchecked", "rawtypes"})
public class NettyHttpHeaders<T extends Headers<CharSequence, CharSequence, ?>> implements HttpHeaders {
private final T headers;
public NettyHttpHeaders(T headers) {
this.headers = headers;
}
@Override
public final int size() {
return headers.size();
}
@Override
public final boolean isEmpty() {
return headers.isEmpty();
}
@Override
public final boolean containsKey(CharSequence key) {
return headers.contains(key);
}
@Override
public final String getFirst(CharSequence name) {
CharSequence value = headers.get(name);
return value == null ? null : value.toString();
}
@Override
public final List<String> get(CharSequence key) {
List<CharSequence> all = headers.getAll(key);
if (all.isEmpty()) {
return Collections.emptyList();
}
ListIterator<CharSequence> it = all.listIterator();
while (it.hasNext()) {
CharSequence next = it.next();
if (next != null && next.getClass() != String.class) {
it.set(next.toString());
}
}
return (List) all;
}
@Override
public final HttpHeaders add(CharSequence name, String value) {
headers.add(name, value);
return this;
}
public final HttpHeaders add(CharSequence name, Iterable<String> values) {
headers.add(name, values);
return this;
}
@Override
public final HttpHeaders add(CharSequence name, String... values) {
if (values != null && values.length != 0) {
headers.add(name, Arrays.asList(values));
}
return this;
}
@Override
public final HttpHeaders add(Map<? extends CharSequence, ? extends Iterable<String>> map) {
for (Entry<? extends CharSequence, ? extends Iterable<String>> entry : map.entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
return this;
}
@Override
public final HttpHeaders add(HttpHeaders headers) {
for (Entry<CharSequence, String> entry : headers) {
this.headers.add(entry.getKey(), entry.getValue());
}
return this;
}
@Override
public final HttpHeaders set(CharSequence name, String value) {
headers.set(name, value);
return this;
}
public final HttpHeaders set(CharSequence name, Iterable<String> values) {
headers.set(name, values);
return this;
}
@Override
public final HttpHeaders set(CharSequence name, String... values) {
if (values != null && values.length != 0) {
headers.set(name, Arrays.asList(values));
}
return this;
}
@Override
public final HttpHeaders set(Map<? extends CharSequence, ? extends Iterable<String>> map) {
for (Entry<? extends CharSequence, ? extends Iterable<String>> entry : map.entrySet()) {
headers.set(entry.getKey(), entry.getValue());
}
return this;
}
@Override
public final HttpHeaders set(HttpHeaders headers) {
for (Entry<CharSequence, String> entry : headers) {
this.headers.set(entry.getKey(), entry.getValue());
}
return this;
}
@Override
public final List<String> remove(CharSequence key) {
return (List) headers.getAllAndRemove(key);
}
@Override
public final void clear() {
headers.clear();
}
@Override
public final Set<String> names() {
Set<CharSequence> names = headers.names();
return new AbstractSet<String>() {
@Override
public Iterator<String> iterator() {
Iterator<CharSequence> it = names.iterator();
return new Iterator<String>() {
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public String next() {
CharSequence next = it.next();
return next == null ? null : next.toString();
}
@Override
public void remove() {
it.remove();
}
};
}
@Override
public int size() {
return names.size();
}
@Override
public boolean contains(Object o) {
return names.contains(o);
}
};
}
@Override
public Set<CharSequence> nameSet() {
return headers.names();
}
@Override
public final Map<String, List<String>> asMap() {
return headers.isEmpty() ? Collections.emptyMap() : new HttpHeadersMapAdapter(this);
}
@Override
public final Iterator<Entry<CharSequence, String>> iterator() {
return new StringValueIterator(headers.iterator());
}
public final T getHeaders() {
return headers;
}
@Override
public boolean equals(Object obj) {
return obj instanceof NettyHttpHeaders && headers.equals(((NettyHttpHeaders<?>) obj).headers);
}
@Override
public int hashCode() {
return headers.hashCode();
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" + "headers=" + headers + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/HttpWriteQueueHandler.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/HttpWriteQueueHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.netty4;
import org.apache.dubbo.remoting.http12.command.HttpWriteQueue;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;
public class HttpWriteQueueHandler extends ChannelInboundHandlerAdapter {
private HttpWriteQueue writeQueue;
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
EventLoop eventLoop = ctx.channel().eventLoop();
this.writeQueue = new HttpWriteQueue(eventLoop);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
this.writeQueue = null;
}
public HttpWriteQueue getWriteQueue() {
return writeQueue;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/StringValueIterator.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/StringValueIterator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.netty4;
import java.util.Iterator;
import java.util.Map.Entry;
public final class StringValueIterator implements Iterator<Entry<CharSequence, String>> {
private final Iterator<Entry<CharSequence, CharSequence>> iterator;
public StringValueIterator(Iterator<Entry<CharSequence, CharSequence>> iterator) {
this.iterator = iterator;
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Entry<CharSequence, String> next() {
return new ValueEntry(iterator.next());
}
@Override
public void remove() {
iterator.remove();
}
private static final class ValueEntry implements Entry<CharSequence, String> {
private final Entry<CharSequence, CharSequence> entry;
private String value;
ValueEntry(Entry<CharSequence, CharSequence> entry) {
this.entry = entry;
}
@Override
public CharSequence getKey() {
return entry.getKey();
}
@Override
public String getValue() {
if (value == null) {
CharSequence cs = entry.getValue();
if (cs != null) {
value = cs.toString();
}
}
return value;
}
@Override
public String setValue(String value) {
String old = getValue();
entry.setValue(value);
return old;
}
@Override
public String toString() {
return entry.toString();
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/NettyHttpChannelFutureListener.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/NettyHttpChannelFutureListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.netty4;
import java.util.concurrent.CompletableFuture;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
public class NettyHttpChannelFutureListener extends CompletableFuture<Void> implements ChannelFutureListener {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
Throwable cause = future.cause();
this.completeExceptionally(cause);
} else {
this.complete(null);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2FrameCodec.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2FrameCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.netty4.h2;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.remoting.http12.h2.Http2Header;
import org.apache.dubbo.remoting.http12.h2.Http2InputMessage;
import org.apache.dubbo.remoting.http12.h2.Http2InputMessageFrame;
import org.apache.dubbo.remoting.http12.h2.Http2MetadataFrame;
import org.apache.dubbo.remoting.http12.h2.Http2OutputMessage;
import org.apache.dubbo.remoting.http12.message.DefaultHttpHeaders;
import org.apache.dubbo.remoting.http12.netty4.NettyHttpHeaders;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.util.concurrent.ScheduledFuture;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_TIMEOUT_SERVER;
public class NettyHttp2FrameCodec extends ChannelDuplexHandler {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(NettyHttp2FrameCodec.class);
private static final long SETTINGS_FRAME_ARRIVAL_TIMEOUT = 3;
private final NettyHttp2SettingsHandler nettyHttp2SettingsHandler;
private final List<CachedMsg> cachedMsgList = new LinkedList<>();
private boolean settingsFrameArrived;
private ScheduledFuture<?> settingsFrameArrivalTimeoutFuture;
public NettyHttp2FrameCodec(NettyHttp2SettingsHandler nettyHttp2SettingsHandler) {
this.nettyHttp2SettingsHandler = nettyHttp2SettingsHandler;
if (!nettyHttp2SettingsHandler.subscribeSettingsFrameArrival(this)) {
settingsFrameArrived = true;
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof Http2HeadersFrame) {
super.channelRead(ctx, onHttp2HeadersFrame(((Http2HeadersFrame) msg)));
} else if (msg instanceof Http2DataFrame) {
super.channelRead(ctx, onHttp2DataFrame(((Http2DataFrame) msg)));
} else {
super.channelRead(ctx, msg);
}
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (settingsFrameArrived) {
if (msg instanceof Http2Header) {
super.write(ctx, encodeHttp2HeadersFrame((Http2Header) msg), promise);
} else if (msg instanceof Http2OutputMessage) {
super.write(ctx, encodeHttp2DataFrame((Http2OutputMessage) msg), promise);
} else {
super.write(ctx, msg, promise);
}
return;
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Cache writing msg before client connection preface arrival: {}", msg);
}
cachedMsgList.add(new CachedMsg(ctx, msg, promise));
if (settingsFrameArrivalTimeoutFuture == null) {
// close ctx and release resources if client connection preface does not arrive in time.
settingsFrameArrivalTimeoutFuture = ctx.executor()
.schedule(
() -> {
LOGGER.error(
PROTOCOL_TIMEOUT_SERVER,
"",
"",
"client connection preface does not arrive in time.");
// send RST_STREAM instead of GO_AWAY by calling close method to avoid client hanging.
ctx.close();
nettyHttp2SettingsHandler.unsubscribeSettingsFrameArrival(this);
cachedMsgList.clear();
},
SETTINGS_FRAME_ARRIVAL_TIMEOUT,
TimeUnit.SECONDS);
}
}
public void notifySettingsFrameArrival() throws Exception {
if (settingsFrameArrived) {
return;
}
settingsFrameArrived = true;
if (settingsFrameArrivalTimeoutFuture != null) {
settingsFrameArrivalTimeoutFuture.cancel(false);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Begin cached channel msg writing when client connection preface arrived.");
}
for (CachedMsg cached : cachedMsgList) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Cached channel msg writing, ctx: {} msg: {}", cached.ctx, cached.msg);
}
if (cached.msg instanceof Http2Header) {
super.write(cached.ctx, encodeHttp2HeadersFrame(((Http2Header) cached.msg)), cached.promise);
} else if (cached.msg instanceof Http2OutputMessage) {
super.write(cached.ctx, encodeHttp2DataFrame(((Http2OutputMessage) cached.msg)), cached.promise);
} else {
super.write(cached.ctx, cached.msg, cached.promise);
}
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("End cached channel msg writing.");
}
cachedMsgList.clear();
}
private Http2Header onHttp2HeadersFrame(Http2HeadersFrame headersFrame) {
return new Http2MetadataFrame(
headersFrame.stream().id(), new DefaultHttpHeaders(headersFrame.headers()), headersFrame.isEndStream());
}
private Http2InputMessage onHttp2DataFrame(Http2DataFrame dataFrame) {
return new Http2InputMessageFrame(
dataFrame.stream().id(), new ByteBufInputStream(dataFrame.content(), true), dataFrame.isEndStream());
}
@SuppressWarnings("unchecked")
private Http2HeadersFrame encodeHttp2HeadersFrame(Http2Header http2Header) {
return new DefaultHttp2HeadersFrame(
((NettyHttpHeaders<Http2Headers>) http2Header.headers()).getHeaders(), http2Header.isEndStream());
}
private Http2DataFrame encodeHttp2DataFrame(Http2OutputMessage outputMessage) {
OutputStream body = outputMessage.getBody();
if (body == null) {
return new DefaultHttp2DataFrame(outputMessage.isEndStream());
}
if (body instanceof ByteBufOutputStream) {
ByteBuf buffer = ((ByteBufOutputStream) body).buffer();
return new DefaultHttp2DataFrame(buffer, outputMessage.isEndStream());
}
throw new IllegalArgumentException("Http2OutputMessage body must be ByteBufOutputStream");
}
private static class CachedMsg {
private final ChannelHandlerContext ctx;
private final Object msg;
private final ChannelPromise promise;
public CachedMsg(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
this.ctx = ctx;
this.msg = msg;
this.promise = promise;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2SettingsHandler.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2SettingsHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.netty4.h2;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import java.util.HashSet;
import java.util.Set;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http2.Http2SettingsFrame;
/**
* Add NettyHttp2SettingsHandler to pipeline because NettyHttp2FrameCodec could not receive Http2SettingsFrame.
* Http2SettingsFrame does not belong to Http2StreamFrame or Http2GoAwayFrame that Http2MultiplexHandler
* could process, NettyHttp2FrameCodec is wrapped in Http2MultiplexHandler as a child handler.
*/
public class NettyHttp2SettingsHandler extends SimpleChannelInboundHandler<Http2SettingsFrame> {
private static final Logger logger = LoggerFactory.getLogger(NettyHttp2SettingsHandler.class);
/**
* Http2SettingsFrame arrival notification subscribers.
*/
private final Set<NettyHttp2FrameCodec> settingsFrameArrivalSubscribers = new HashSet<>();
private boolean settingsFrameArrived;
@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2SettingsFrame msg) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Receive client Http2 Settings frame of "
+ ctx.channel().localAddress() + " <- " + ctx.channel().remoteAddress());
}
settingsFrameArrived = true;
// Notify all subscribers that Http2SettingsFrame is arrived.
for (NettyHttp2FrameCodec nettyHttp2FrameCodec : settingsFrameArrivalSubscribers) {
nettyHttp2FrameCodec.notifySettingsFrameArrival();
}
settingsFrameArrivalSubscribers.clear();
ctx.pipeline().remove(this);
}
/**
* Save Http2SettingsFrame arrival notification subscriber if Http2SettingsFrame is not arrived.
* @param nettyHttp2FrameCodec the netty HTTP2 frame codec that will be notified.
* @return true: subscribe successful, false: Http2SettingsFrame arrived.
*/
public boolean subscribeSettingsFrameArrival(NettyHttp2FrameCodec nettyHttp2FrameCodec) {
if (!settingsFrameArrived) {
settingsFrameArrivalSubscribers.add(nettyHttp2FrameCodec);
return true;
}
return false;
}
public void unsubscribeSettingsFrameArrival(NettyHttp2FrameCodec nettyHttp2FrameCodec) {
settingsFrameArrivalSubscribers.remove(nettyHttp2FrameCodec);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyH2StreamChannel.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyH2StreamChannel.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.netty4.h2;
import org.apache.dubbo.config.nested.TripleConfig;
import org.apache.dubbo.remoting.http12.HttpMetadata;
import org.apache.dubbo.remoting.http12.HttpOutputMessage;
import org.apache.dubbo.remoting.http12.LimitedByteBufOutputStream;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http12.h2.Http2OutputMessage;
import org.apache.dubbo.remoting.http12.h2.Http2OutputMessageFrame;
import org.apache.dubbo.remoting.http12.netty4.NettyHttpChannelFutureListener;
import java.net.SocketAddress;
import java.util.concurrent.CompletableFuture;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
import io.netty.handler.codec.http2.Http2StreamChannel;
public class NettyH2StreamChannel implements H2StreamChannel {
private final Http2StreamChannel http2StreamChannel;
private final TripleConfig tripleConfig;
public NettyH2StreamChannel(Http2StreamChannel http2StreamChannel, TripleConfig tripleConfig) {
this.http2StreamChannel = http2StreamChannel;
this.tripleConfig = tripleConfig;
}
@Override
public CompletableFuture<Void> writeHeader(HttpMetadata httpMetadata) {
// WriteQueue.enqueue header frame
NettyHttpChannelFutureListener nettyHttpChannelFutureListener = new NettyHttpChannelFutureListener();
http2StreamChannel.write(httpMetadata).addListener(nettyHttpChannelFutureListener);
return nettyHttpChannelFutureListener;
}
@Override
public CompletableFuture<Void> writeMessage(HttpOutputMessage httpOutputMessage) {
NettyHttpChannelFutureListener nettyHttpChannelFutureListener = new NettyHttpChannelFutureListener();
http2StreamChannel.write(httpOutputMessage).addListener(nettyHttpChannelFutureListener);
return nettyHttpChannelFutureListener;
}
@Override
public Http2OutputMessage newOutputMessage(boolean endStream) {
ByteBuf buffer = http2StreamChannel.alloc().buffer();
ByteBufOutputStream outputStream =
new LimitedByteBufOutputStream(buffer, tripleConfig.getMaxResponseBodySizeOrDefault());
return new Http2OutputMessageFrame(outputStream, endStream);
}
@Override
public SocketAddress remoteAddress() {
return this.http2StreamChannel.remoteAddress();
}
@Override
public SocketAddress localAddress() {
return this.http2StreamChannel.localAddress();
}
@Override
public void flush() {
this.http2StreamChannel.flush();
}
@Override
public CompletableFuture<Void> writeResetFrame(long errorCode) {
DefaultHttp2ResetFrame resetFrame = new DefaultHttp2ResetFrame(errorCode);
NettyHttpChannelFutureListener nettyHttpChannelFutureListener = new NettyHttpChannelFutureListener();
http2StreamChannel.write(resetFrame).addListener(nettyHttpChannelFutureListener);
return nettyHttpChannelFutureListener;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2FrameHandler.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2FrameHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.netty4.h2;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.remoting.http12.HttpStatus;
import org.apache.dubbo.remoting.http12.exception.HttpStatusException;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http12.h2.Http2Header;
import org.apache.dubbo.remoting.http12.h2.Http2InputMessage;
import org.apache.dubbo.remoting.http12.h2.Http2TransportListener;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http2.Http2ResetFrame;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_RESPONSE;
public class NettyHttp2FrameHandler extends ChannelDuplexHandler {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(NettyHttp2FrameHandler.class);
private final H2StreamChannel h2StreamChannel;
private final Http2TransportListener transportListener;
public NettyHttp2FrameHandler(H2StreamChannel h2StreamChannel, Http2TransportListener transportListener) {
this.h2StreamChannel = h2StreamChannel;
this.transportListener = transportListener;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof Http2Header) {
transportListener.onMetadata((Http2Header) msg);
} else if (msg instanceof Http2InputMessage) {
transportListener.onData((Http2InputMessage) msg);
} else {
super.channelRead(ctx, msg);
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
// reset frame
if (evt instanceof Http2ResetFrame) {
long errorCode = ((Http2ResetFrame) evt).errorCode();
transportListener.cancelByRemote(errorCode);
} else {
super.userEventTriggered(ctx, evt);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn(PROTOCOL_FAILED_RESPONSE, "", "", "Exception in processing triple message", cause);
}
int statusCode = HttpStatus.INTERNAL_SERVER_ERROR.getCode();
if (cause instanceof HttpStatusException) {
statusCode = ((HttpStatusException) cause).getStatusCode();
}
h2StreamChannel.writeResetFrame(statusCode);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2ProtocolSelectorHandler.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2ProtocolSelectorHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.netty4.h2;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.config.nested.TripleConfig;
import org.apache.dubbo.remoting.http12.HttpMetadata;
import org.apache.dubbo.remoting.http12.command.HttpWriteQueue;
import org.apache.dubbo.remoting.http12.exception.UnsupportedMediaTypeException;
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.remoting.http12.h2.command.Http2WriteQueueChannel;
import org.apache.dubbo.remoting.http12.netty4.HttpWriteQueueHandler;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Set;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http2.Http2StreamChannel;
public class NettyHttp2ProtocolSelectorHandler extends SimpleChannelInboundHandler<HttpMetadata> {
private static final String TRANSPORT_LISTENER_FACTORY_CACHE = "TRANSPORT_LISTENER_FACTORY_CACHE";
private final URL url;
private final FrameworkModel frameworkModel;
private final TripleConfig tripleConfig;
private final Http2ServerTransportListenerFactory defaultHttp2ServerTransportListenerFactory;
public NettyHttp2ProtocolSelectorHandler(
URL url,
FrameworkModel frameworkModel,
TripleConfig tripleConfig,
Http2ServerTransportListenerFactory defaultHttp2ServerTransportListenerFactory) {
this.url = url;
this.frameworkModel = frameworkModel;
this.tripleConfig = tripleConfig;
this.defaultHttp2ServerTransportListenerFactory = defaultHttp2ServerTransportListenerFactory;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpMetadata metadata) {
String contentType = metadata.contentType();
Http2ServerTransportListenerFactory factory = UrlUtils.computeServiceAttribute(
url,
TRANSPORT_LISTENER_FACTORY_CACHE,
url -> CollectionUtils.<String, Http2ServerTransportListenerFactory>newConcurrentHashMap())
.computeIfAbsent(
contentType == null ? StringUtils.EMPTY_STRING : contentType,
key -> determineHttp2ServerTransportListenerFactory(contentType));
if (factory == null) {
throw new UnsupportedMediaTypeException(contentType);
}
Channel channel = ctx.channel();
H2StreamChannel h2StreamChannel = new NettyH2StreamChannel((Http2StreamChannel) channel, tripleConfig);
HttpWriteQueueHandler writeQueueHandler = channel.parent().pipeline().get(HttpWriteQueueHandler.class);
if (writeQueueHandler != null) {
HttpWriteQueue writeQueue = writeQueueHandler.getWriteQueue();
h2StreamChannel = new Http2WriteQueueChannel(h2StreamChannel, writeQueue);
}
Http2TransportListener http2TransportListener = factory.newInstance(h2StreamChannel, url, frameworkModel);
channel.closeFuture().addListener(future -> http2TransportListener.close());
ctx.pipeline()
.addLast(new NettyHttp2FrameHandler(h2StreamChannel, http2TransportListener))
.remove(this);
ctx.fireChannelRead(metadata);
}
private Http2ServerTransportListenerFactory determineHttp2ServerTransportListenerFactory(String contentType) {
Set<Http2ServerTransportListenerFactory> http2ServerTransportListenerFactories = frameworkModel
.getExtensionLoader(Http2ServerTransportListenerFactory.class)
.getSupportedExtensionInstances();
for (Http2ServerTransportListenerFactory factory : http2ServerTransportListenerFactories) {
if (factory.supportContentType(contentType)) {
return factory;
}
}
return defaultHttp2ServerTransportListenerFactory;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1ConnectionHandler.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1ConnectionHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.netty4.h1;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.nested.TripleConfig;
import org.apache.dubbo.remoting.http12.h1.Http1Request;
import org.apache.dubbo.remoting.http12.h1.Http1ServerTransportListener;
import org.apache.dubbo.remoting.http12.h1.Http1ServerTransportListenerFactory;
import org.apache.dubbo.rpc.model.FrameworkModel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class NettyHttp1ConnectionHandler extends SimpleChannelInboundHandler<Http1Request> {
private final URL url;
private final FrameworkModel frameworkModel;
private final Http1ServerTransportListenerFactory http1ServerTransportListenerFactory;
private final TripleConfig tripleConfig;
public NettyHttp1ConnectionHandler(
URL url,
FrameworkModel frameworkModel,
TripleConfig tripleConfig,
Http1ServerTransportListenerFactory http1ServerTransportListenerFactory) {
this.url = url;
this.frameworkModel = frameworkModel;
this.tripleConfig = tripleConfig;
this.http1ServerTransportListenerFactory = http1ServerTransportListenerFactory;
}
/**
* process h1 request
*/
protected void channelRead0(ChannelHandlerContext ctx, Http1Request http1Request) {
Http1ServerTransportListener http1TransportListener = http1ServerTransportListenerFactory.newInstance(
new NettyHttp1Channel(ctx.channel(), tripleConfig), url, frameworkModel);
http1TransportListener.onMetadata(http1Request);
http1TransportListener.onData(http1Request);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1Codec.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1Codec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.netty4.h1;
import org.apache.dubbo.common.utils.CollectionUtils;
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.h1.DefaultHttp1Request;
import org.apache.dubbo.remoting.http12.h1.Http1InputMessage;
import org.apache.dubbo.remoting.http12.h1.Http1RequestMetadata;
import java.io.OutputStream;
import java.util.List;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
public class NettyHttp1Codec extends ChannelDuplexHandler {
private boolean keepAlive;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// decode FullHttpRequest
if (msg instanceof FullHttpRequest) {
FullHttpRequest request = (FullHttpRequest) msg;
keepAlive = HttpUtil.isKeepAlive(request);
super.channelRead(
ctx,
new DefaultHttp1Request(
new Http1RequestMetadata(
new NettyHttp1HttpHeaders(request.headers()),
request.method().name(),
request.uri()),
new Http1InputMessage(new ByteBufInputStream(request.content(), true))));
return;
}
super.channelRead(ctx, msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof HttpMetadata) {
doWriteHeader(ctx, ((HttpMetadata) msg), promise);
return;
}
if (msg instanceof HttpOutputMessage) {
doWriteMessage(ctx, ((HttpOutputMessage) msg), promise);
return;
}
super.write(ctx, msg, promise);
}
private void doWriteHeader(ChannelHandlerContext ctx, HttpMetadata msg, ChannelPromise promise) {
// process status
NettyHttp1HttpHeaders headers = (NettyHttp1HttpHeaders) msg.headers();
List<String> statusHeaders = headers.remove(HttpHeaderNames.STATUS.getKey());
HttpResponseStatus status = HttpResponseStatus.OK;
if (CollectionUtils.isNotEmpty(statusHeaders)) {
status = HttpResponseStatus.valueOf(Integer.parseInt(statusHeaders.get(0)));
}
if (keepAlive) {
headers.add(HttpHeaderNames.CONNECTION.getKey(), String.valueOf(HttpHeaderValues.KEEP_ALIVE));
} else {
headers.add(HttpHeaderNames.CONNECTION.getKey(), String.valueOf(HttpHeaderValues.CLOSE));
}
// process normal headers
ctx.writeAndFlush(new DefaultHttpResponse(HttpVersion.HTTP_1_1, status, headers.getHeaders()), promise);
}
private void doWriteMessage(ChannelHandlerContext ctx, HttpOutputMessage msg, ChannelPromise promise) {
if (HttpOutputMessage.EMPTY_MESSAGE == msg) {
if (keepAlive) {
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT, promise);
} else {
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT, promise).addListener(ChannelFutureListener.CLOSE);
}
return;
}
OutputStream body = msg.getBody();
if (body instanceof ByteBufOutputStream) {
ByteBuf buffer = ((ByteBufOutputStream) body).buffer();
ctx.writeAndFlush(buffer, promise);
return;
}
throw new IllegalArgumentException("HttpOutputMessage body must be 'io.netty.buffer.ByteBufOutputStream'");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1Channel.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1Channel.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.netty4.h1;
import org.apache.dubbo.config.nested.TripleConfig;
import org.apache.dubbo.remoting.http12.HttpChannel;
import org.apache.dubbo.remoting.http12.HttpMetadata;
import org.apache.dubbo.remoting.http12.HttpOutputMessage;
import org.apache.dubbo.remoting.http12.LimitedByteBufOutputStream;
import org.apache.dubbo.remoting.http12.h1.Http1OutputMessage;
import org.apache.dubbo.remoting.http12.netty4.NettyHttpChannelFutureListener;
import java.net.SocketAddress;
import java.util.concurrent.CompletableFuture;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
public class NettyHttp1Channel implements HttpChannel {
private final Channel channel;
private final TripleConfig tripleConfig;
public NettyHttp1Channel(Channel channel, TripleConfig tripleConfig) {
this.channel = channel;
this.tripleConfig = tripleConfig;
}
@Override
public CompletableFuture<Void> writeHeader(HttpMetadata httpMetadata) {
NettyHttpChannelFutureListener nettyHttpChannelFutureListener = new NettyHttpChannelFutureListener();
this.channel.writeAndFlush(httpMetadata).addListener(nettyHttpChannelFutureListener);
return nettyHttpChannelFutureListener;
}
@Override
public CompletableFuture<Void> writeMessage(HttpOutputMessage httpOutputMessage) {
NettyHttpChannelFutureListener nettyHttpChannelFutureListener = new NettyHttpChannelFutureListener();
this.channel.writeAndFlush(httpOutputMessage).addListener((ChannelFuture future) -> {
if (!future.isSuccess()) {
httpOutputMessage.close();
}
nettyHttpChannelFutureListener.operationComplete(future);
});
return nettyHttpChannelFutureListener;
}
@Override
public HttpOutputMessage newOutputMessage() {
return new Http1OutputMessage(new LimitedByteBufOutputStream(
channel.alloc().buffer(), tripleConfig.getMaxResponseBodySizeOrDefault()));
}
@Override
public SocketAddress remoteAddress() {
return channel.remoteAddress();
}
@Override
public SocketAddress localAddress() {
return channel.localAddress();
}
@Override
public void flush() {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1HttpHeaders.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1HttpHeaders.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.netty4.h1;
import org.apache.dubbo.remoting.http12.HttpHeaders;
import org.apache.dubbo.remoting.http12.message.HttpHeadersMapAdapter;
import org.apache.dubbo.remoting.http12.netty4.StringValueIterator;
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.Map.Entry;
import java.util.Set;
import io.netty.handler.codec.http.DefaultHttpHeaders;
public final class NettyHttp1HttpHeaders implements HttpHeaders {
private final io.netty.handler.codec.http.HttpHeaders headers;
public NettyHttp1HttpHeaders(io.netty.handler.codec.http.HttpHeaders headers) {
this.headers = headers;
}
@SuppressWarnings("deprecation")
public NettyHttp1HttpHeaders() {
this(new DefaultHttpHeaders(false));
}
@Override
public int size() {
return headers.size();
}
@Override
public boolean isEmpty() {
return headers.isEmpty();
}
@Override
public boolean containsKey(CharSequence key) {
return headers.contains(key);
}
@Override
public String getFirst(CharSequence name) {
return headers.get(name);
}
@Override
public List<String> get(CharSequence key) {
return headers.getAll(key);
}
@Override
public HttpHeaders add(CharSequence name, String value) {
headers.add(name, value);
return this;
}
public HttpHeaders add(CharSequence name, Iterable<String> values) {
headers.add(name, values);
return this;
}
@Override
public HttpHeaders add(CharSequence name, String... values) {
headers.add(name, Arrays.asList(values));
return this;
}
@Override
public HttpHeaders add(Map<? extends CharSequence, ? extends Iterable<String>> map) {
for (Entry<? extends CharSequence, ? extends Iterable<String>> entry : map.entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
return this;
}
@Override
public HttpHeaders add(HttpHeaders headers) {
for (Entry<CharSequence, String> entry : headers) {
this.headers.add(entry.getKey(), entry.getValue());
}
return this;
}
@Override
public HttpHeaders set(CharSequence name, String value) {
headers.set(name, value);
return this;
}
public HttpHeaders set(CharSequence name, Iterable<String> values) {
headers.set(name, values);
return this;
}
@Override
public HttpHeaders set(CharSequence name, String... values) {
headers.set(name, Arrays.asList(values));
return this;
}
@Override
public HttpHeaders set(Map<? extends CharSequence, ? extends Iterable<String>> map) {
for (Entry<? extends CharSequence, ? extends Iterable<String>> entry : map.entrySet()) {
headers.set(entry.getKey(), entry.getValue());
}
return this;
}
@Override
public HttpHeaders set(HttpHeaders headers) {
for (Entry<CharSequence, String> entry : headers) {
this.headers.set(entry.getKey(), entry.getValue());
}
return this;
}
@Override
public List<String> remove(CharSequence key) {
List<String> all = headers.getAll(key);
headers.remove(key);
return all;
}
@Override
public void clear() {
headers.clear();
}
@Override
public Set<String> names() {
return headers.names();
}
@Override
public Set<CharSequence> nameSet() {
if (isEmpty()) {
return Collections.emptySet();
}
Set<CharSequence> names = new LinkedHashSet<>(headers.size());
for (Entry<CharSequence, String> entry : this) {
names.add(entry.getKey());
}
return names;
}
@Override
public Map<String, List<String>> asMap() {
return headers.isEmpty() ? Collections.emptyMap() : new HttpHeadersMapAdapter(this);
}
@Override
public Iterator<Entry<CharSequence, String>> iterator() {
return new StringValueIterator(headers.iteratorCharSequence());
}
public DefaultHttpHeaders getHeaders() {
return (DefaultHttpHeaders) headers;
}
@Override
public boolean equals(Object obj) {
return obj instanceof NettyHttp1HttpHeaders && headers.equals(((NettyHttp1HttpHeaders) obj).headers);
}
@Override
public int hashCode() {
return headers.hashCode();
}
@Override
public String toString() {
return "NettyHttp1HttpHeaders{" + "headers=" + headers + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/rest/Schema.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/rest/Schema.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.rest;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation for defining a schema in the OpenAPI specification for Dubbo services.
*
* <p>Example usage:</p>
* <pre>
* @Schema(title = "User Schema", required = true)
* public class User {
* @Schema(title = "User name", example = "Tom")
* private String name;
* ...
* }
* </pre>
*/
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Schema {
/**
* Alias for {@link #title()}.
*/
String value() default "";
/**
* The schema group.
*/
String group() default "";
/**
* The schema version.
*/
String version() default "";
/**
* The type of the schema.
*/
String type() default "";
/**
* The schema's format
*/
String format() default "";
/**
* The name of the schema or property.
**/
String name() default "";
/**
* A title to explain the purpose of the schema.
**/
String title() default "";
/**
* The schema's description
**/
String description() default "";
/**
* The maximum value or length of this schema
**/
String max() default "";
/**
* The minimum value or length of this schema
**/
String min() default "";
/**
* The pattern of this schema.
**/
String pattern() default "";
/**
* An example of this schema.
**/
String example() default "";
/**
* A class that implements this schema.
**/
Class<?> implementation() default Void.class;
/**
* A list of allowed schema values
**/
String[] enumeration() default {};
/**
* Whether this schema is required
**/
boolean required() default false;
/**
* The default value of this schema
**/
String defaultValue() default "";
/**
* Whether this schema is read only
**/
boolean readOnly() default false;
/**
* Whether this schema is written only
*/
boolean writeOnly() default false;
/**
* Whether to flatten the inherited fields from the parent class into the schema.
* If set to {@code true}, the fields from the parent class will be included directly in the schema,
* instead of being treated as a separate schema.
*/
boolean flatten() default false;
/**
* Whether this schema is nullable
*/
boolean nullable() default false;
/**
* Whether this operation is deprecated
*/
boolean deprecated() default false;
/**
* Whether this schema is hidden.
*/
boolean hidden() default false;
/**
* The extensions of the OpenAPI.
*/
String[] extensions() default {};
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/rest/Param.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/rest/Param.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.rest;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation for defining parameters on Dubbo service method parameters.
* Provides metadata such as parameter type, default value, and whether the parameter is required.
*
* <p>Example usage:</p>
* <pre>
* @Param(value = "x-version", type = ParamType.Header, required = false) String version
* </pre>
* @see <a href="https://dubbo-next.staged.apache.org/zh-cn/overview/mannual/java-sdk/reference-manual/protocol/tripe-rest-manual/#kmCzf">Tripe Rest Manual</a>
*/
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Param {
String DEFAULT_NONE = "\n\t\t\n\t\t\n_DEFAULT_NONE_\n\t\t\t\t\n";
/**
* The name of the parameter.
* If not specified, the parameter name is derived from the method signature or field name.
*/
String value() default "";
/**
* The type of the parameter, such as query, header, or path variable.
* Defaults to {@link ParamType#Param}.
*/
ParamType type() default ParamType.Param;
/**
* Indicates whether the parameter is required.
* Defaults to {@code true}. If set to {@code false}, the parameter is optional.
*/
boolean required() default true;
/**
* Specifies a default value for the parameter.
* Defaults to {@link #DEFAULT_NONE}, indicating that there is no default value.
*/
String defaultValue() default DEFAULT_NONE;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/rest/OpenAPIService.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/rest/OpenAPIService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.rest;
import java.util.Collection;
public interface OpenAPIService {
Collection<String> getOpenAPIGroups();
String getDocument(OpenAPIRequest request);
void refresh();
void export();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/rest/Operation.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/rest/Operation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.rest;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation for defining an operation in the OpenAPI specification for Dubbo services.
*
* <p>Example usage:</p>
* <pre>
* @Operation(method = "GET", summary = "Retrieve user", tags = {"user", "retrieve"})
* public User getUser(String id) {
* ...
* }
* </pre>
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Operation {
/**
* Alias for {@link #summary()}.
*/
String value() default "";
/**
* The operation group.
*/
String group() default "";
/**
* The operation version.
*/
String version() default "";
/**
* The HTTP method for this operation.
*/
String method() default "";
/**
* The operation tags.
*/
String[] tags() default {};
/**
* The ID of this operation.
**/
String id() default "";
/**
* A brief description of this operation. Should be 120 characters or fewer.
*/
String summary() default "";
/**
* A verbose description of the operation.
*/
String description() default "";
/**
* Whether this operation is deprecated
*/
boolean deprecated() default false;
/**
* Indicates whether the operation is hidden in OpenAPI.
*/
String hidden() default "";
/**
* The extensions of the OpenAPI.
*/
String[] extensions() default {};
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/rest/OpenAPIRequest.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/rest/OpenAPIRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.rest;
import org.apache.dubbo.common.utils.ToStringUtils;
import java.io.Serializable;
/**
* OpenAPI request model.
*/
public class OpenAPIRequest implements Serializable {
private static final long serialVersionUID = 1L;
/**
* The openAPI group.
*/
private String group;
/**
* The openAPI version, using a major.minor.patch versioning scheme
* e.g. 1.0.1
*/
private String version;
/**
* The openAPI tags. Each tag is an or condition.
*/
private String[] tag;
/**
* The openAPI services. Each service is an or condition.
*/
private String[] service;
/**
* The openAPI specification version, using a major.minor.patch versioning scheme
* e.g. 3.0.1, 3.1.0
* <p>The default value is '3.0.1'.
*/
@Schema(enumeration = {"3.0.1", "3.1.0"})
private String openapi;
/**
* The format of the response.
* <p>The default value is 'json'.
*/
@Schema(enumeration = {"json", "yaml", "proto"})
private String format;
/**
* Whether to pretty print for json.
* <p>The default value is {@code false}.
*/
private Boolean pretty;
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String[] getTag() {
return tag;
}
public void setTag(String[] tag) {
this.tag = tag;
}
public String[] getService() {
return service;
}
public void setService(String[] service) {
this.service = service;
}
public String getOpenapi() {
return openapi;
}
public void setOpenapi(String openapi) {
this.openapi = openapi;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public Boolean getPretty() {
return pretty;
}
public void setPretty(Boolean pretty) {
this.pretty = pretty;
}
@Override
public String toString() {
return ToStringUtils.printToString(this);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/rest/OpenAPI.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/rest/OpenAPI.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.rest;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation for defining OpenAPI on Dubbo service interface.
*
* <p>Example usage:</p>
* <pre>
* @OpenAPI(tags = {"user=User API"}, title = "User Service", description = "User Service API", version = "1.0.0")
* public interface UserService {
* ...
* }
* </pre>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OpenAPI {
/**
* The openAPI groups.
*/
String group() default "";
/**
* The openAPI tags.
* <h5>Supported Syntax</h5>
* <ul>
* <li>{@code "name"}</li>
* <li>{@code "name=description"}</li>
* </ul>
* e.g. user=User API
*/
String[] tags() default {};
/**
* The title of the application.
**/
String infoTitle() default "";
/**
* A short description of the application.
**/
String infoDescription() default "";
/**
* The version of the API definition.
**/
String infoVersion() default "";
/**
* A description of the external documentation.
*/
String docDescription() default "";
/**
* The URL of the external documentation.
*/
String docUrl() default "";
/**
* Indicates whether the mapping is hidden in OpenAPI.
*/
String hidden() default "";
/**
* Ordering info.
*/
int order() default 0;
/**
* The extensions of the OpenAPI.
*/
String[] extensions() default {};
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/rest/Mapping.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/rest/Mapping.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.rest;
import org.apache.dubbo.remoting.http12.HttpMethods;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation for mapping Dubbo services to Rest endpoints.
*
* <p>
* Example usage:
* <pre>
* @Mapping(value = "/example", method = HttpMethods.GET, produces = "application/json")
* String handleExample();
* </pre>
* @see <a href="https://dubbo-next.staged.apache.org/zh-cn/overview/mannual/java-sdk/reference-manual/protocol/tripe-rest-manual/#Q6XyG">Tripe Rest Manual</a>
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Mapping {
/**
* Alias for {@link #path()}.
* The path patterns to be mapped.
* If not specified, the method or class name is used as the default.
*/
String[] value() default {};
/**
* Specifies the path patterns to be mapped.
* If not specified, the method or class name is used as the default.
*/
String[] path() default {};
/**
* Defines the HTTP methods supported by the mapped handler.
* Supports values like GET, POST, etc.
*/
HttpMethods[] method() default {};
/**
* Specifies the request parameters that must be present for this mapping to be invoked.
* Example: "param1=value1", "param2".
*/
String[] params() default {};
/**
* Specifies the request headers that must be present for this mapping to be invoked.
* Example: "content-type=application/json".
*/
String[] headers() default {};
/**
* Specifies the media types that the mapped handler consumes.
* Example: "application/json", "text/plain".
*/
String[] consumes() default {};
/**
* Specifies the media types that the mapped handler produces.
* Example: "application/json", "text/html".
*/
String[] produces() default {};
/**
* Indicates whether the mapping is enabled.
* Defaults to {@code true}. If set to {@code false}, the mapping will be ignored.
*/
boolean enabled() default true;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/rest/ParamType.java | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/rest/ParamType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.http12.rest;
public enum ParamType {
PathVariable,
MatrixVariable,
Param,
Form,
Header,
Cookie,
Attribute,
Part,
Body
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter;
import org.apache.dubbo.remoting.transport.dispatcher.execution.ExecutionDispatcher;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADPOOL;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS;
import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT;
import static org.apache.dubbo.remoting.Constants.BUFFER_KEY;
import static org.apache.dubbo.remoting.Constants.DEFAULT_BUFFER_SIZE;
/**
* PerformanceServer
* <p>
* mvn clean test -Dtest=*PerformanceServerTest -Dport=9911
*/
class PerformanceServerTest {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(PerformanceServerTest.class);
private static ExchangeServer server = null;
private static void restartServer(int times, int alive, int sleep) throws Exception {
if (server != null && !server.isClosed()) {
server.close();
Thread.sleep(100);
}
for (int i = 0; i < times; i++) {
logger.info("restart times:" + i);
server = statServer();
if (alive > 0) Thread.sleep(alive);
server.close();
if (sleep > 0) Thread.sleep(sleep);
}
server = statServer();
}
private static ExchangeServer statServer() throws Exception {
final int port = PerformanceUtils.getIntProperty("port", 9911);
final String transporter =
PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER);
final String serialization = PerformanceUtils.getProperty(
Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization());
final String threadpool = PerformanceUtils.getProperty(THREADPOOL_KEY, DEFAULT_THREADPOOL);
final int threads = PerformanceUtils.getIntProperty(THREADS_KEY, DEFAULT_THREADS);
final int iothreads = PerformanceUtils.getIntProperty(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS);
final int buffer = PerformanceUtils.getIntProperty(BUFFER_KEY, DEFAULT_BUFFER_SIZE);
final String channelHandler = PerformanceUtils.getProperty(Constants.DISPATCHER_KEY, ExecutionDispatcher.NAME);
// Start server
ExchangeServer server = Exchangers.bind(
"exchange://0.0.0.0:" + port + "?transporter="
+ transporter + "&serialization="
+ serialization + "&threadpool=" + threadpool
+ "&threads=" + threads + "&iothreads=" + iothreads + "&buffer=" + buffer + "&channel.handler="
+ channelHandler,
new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) {
public String telnet(Channel channel, String message) throws RemotingException {
return "echo: " + message + "\r\ntelnet> ";
}
public CompletableFuture<Object> reply(ExchangeChannel channel, Object request)
throws RemotingException {
if ("environment".equals(request)) {
return CompletableFuture.completedFuture(PerformanceUtils.getEnvironment());
}
if ("scene".equals(request)) {
List<String> scene = new ArrayList<String>();
scene.add("Transporter: " + transporter);
scene.add("Service Threads: " + threads);
return CompletableFuture.completedFuture(scene);
}
return CompletableFuture.completedFuture(request);
}
});
return server;
}
private static ExchangeServer statTelnetServer(int port) throws Exception {
// Start server
ExchangeServer telnetserver = Exchangers.bind(
"exchange://0.0.0.0:" + port, new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) {
public String telnet(Channel channel, String message) throws RemotingException {
if (message.equals("help")) {
return "support cmd: \r\n\tstart \r\n\tstop \r\n\tshutdown \r\n\trestart times [alive] [sleep] \r\ntelnet>";
} else if (message.equals("stop")) {
logger.info("server closed:" + server);
server.close();
return "stop server\r\ntelnet>";
} else if (message.startsWith("start")) {
try {
restartServer(0, 0, 0);
} catch (Exception e) {
e.printStackTrace();
}
return "start server\r\ntelnet>";
} else if (message.startsWith("shutdown")) {
System.exit(0);
return "start server\r\ntelnet>";
} else if (message.startsWith("channels")) {
return "server.getExchangeChannels():"
+ server.getExchangeChannels().size() + "\r\ntelnet>";
} else if (message.startsWith("restart ")) { // r times [sleep] r 10 or r 10 100
String[] args = message.split(" ");
int times = Integer.parseInt(args[1]);
int alive = args.length > 2 ? Integer.parseInt(args[2]) : 0;
int sleep = args.length > 3 ? Integer.parseInt(args[3]) : 100;
try {
restartServer(times, alive, sleep);
} catch (Exception e) {
e.printStackTrace();
}
return "restart server,times:" + times + " stop alive time: " + alive + ",sleep time: "
+ sleep + " usage:r times [alive] [sleep] \r\ntelnet>";
} else {
return "echo: " + message + "\r\ntelnet> ";
}
}
});
return telnetserver;
}
@Test
void testServer() throws Exception {
// Read port from property
if (PerformanceUtils.getProperty("port", null) == null) {
logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dport=9911");
return;
}
final int port = PerformanceUtils.getIntProperty("port", 9911);
final boolean telnet = PerformanceUtils.getBooleanProperty("telnet", true);
if (telnet) statTelnetServer(port + 1);
server = statServer();
synchronized (PerformanceServerTest.class) {
while (true) {
try {
PerformanceServerTest.class.wait();
} catch (InterruptedException e) {
}
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientMain.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientMain.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
public class PerformanceClientMain {
public static void main(String[] args) throws Throwable {
new PerformanceClientTest().testClient();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerMain.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerMain.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
public class PerformanceServerMain {
public static void main(String[] args) throws Exception {
new PerformanceServerTest().testServer();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/TransportersTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/TransportersTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import org.apache.dubbo.common.URL;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class TransportersTest {
private String url = "dubbo://127.0.0.1:12345?transporter=mockTransporter";
private ChannelHandler channel = Mockito.mock(ChannelHandler.class);
@Test
void testBind() throws RemotingException {
Assertions.assertThrows(RuntimeException.class, () -> Transporters.bind((String) null));
Assertions.assertThrows(RuntimeException.class, () -> Transporters.bind((URL) null));
Assertions.assertThrows(RuntimeException.class, () -> Transporters.bind(url));
Assertions.assertNotNull(Transporters.bind(url, channel));
Assertions.assertNotNull(Transporters.bind(url, channel, channel));
}
@Test
void testConnect() throws RemotingException {
Assertions.assertThrows(RuntimeException.class, () -> Transporters.connect((String) null));
Assertions.assertThrows(RuntimeException.class, () -> Transporters.connect((URL) null));
Assertions.assertNotNull(Transporters.connect(url));
Assertions.assertNotNull(Transporters.connect(url, channel));
Assertions.assertNotNull(Transporters.connect(url, channel, channel));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector;
import org.apache.dubbo.remoting.exchange.ExchangeClient;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT;
import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY;
/**
* PerformanceClientTest
* <p>
* mvn clean test -Dtest=*PerformanceClientTest -Dserver=10.20.153.187:9911
*/
class PerformanceClientTest {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(PerformanceClientTest.class);
@Test
@SuppressWarnings("unchecked")
public void testClient() throws Throwable {
// read server info from property
if (PerformanceUtils.getProperty("server", null) == null) {
logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dserver=127.0.0.1:9911");
return;
}
final String server = System.getProperty("server", "127.0.0.1:9911");
final String transporter =
PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER);
final String serialization = PerformanceUtils.getProperty(
Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization());
final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT);
final int length = PerformanceUtils.getIntProperty("length", 1024);
final int connections = PerformanceUtils.getIntProperty(CONNECTIONS_KEY, 1);
final int concurrent = PerformanceUtils.getIntProperty("concurrent", 100);
int r = PerformanceUtils.getIntProperty("runs", 10000);
final int runs = r > 0 ? r : Integer.MAX_VALUE;
final String onerror = PerformanceUtils.getProperty("onerror", "continue");
final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization
+ "&timeout=" + timeout;
// Create clients and build connections
final ExchangeClient[] exchangeClients = new ExchangeClient[connections];
for (int i = 0; i < connections; i++) {
// exchangeClients[i] = Exchangers.connect(url,handler);
exchangeClients[i] = Exchangers.connect(url);
}
List<String> serverEnvironment =
(List<String>) exchangeClients[0].request("environment").get();
List<String> serverScene =
(List<String>) exchangeClients[0].request("scene").get();
// Create some data for test
StringBuilder buf = new StringBuilder(length);
for (int i = 0; i < length; i++) {
buf.append('A');
}
final String data = buf.toString();
// counters
final AtomicLong count = new AtomicLong();
final AtomicLong error = new AtomicLong();
final AtomicLong time = new AtomicLong();
final AtomicLong all = new AtomicLong();
// Start multiple threads
final CountDownLatch latch = new CountDownLatch(concurrent);
for (int i = 0; i < concurrent; i++) {
new Thread(new Runnable() {
public void run() {
try {
AtomicInteger index = new AtomicInteger();
long init = System.currentTimeMillis();
for (int i = 0; i < runs; i++) {
try {
count.incrementAndGet();
ExchangeClient client = exchangeClients[index.getAndIncrement() % connections];
long start = System.currentTimeMillis();
String result =
(String) client.request(data).get();
long end = System.currentTimeMillis();
if (!data.equals(result)) {
throw new IllegalStateException("Invalid result " + result);
}
time.addAndGet(end - start);
} catch (Exception e) {
error.incrementAndGet();
e.printStackTrace();
if ("exit".equals(onerror)) {
System.exit(-1);
} else if ("break".equals(onerror)) {
break;
} else if ("sleep".equals(onerror)) {
try {
Thread.sleep(30000);
} catch (InterruptedException e1) {
}
}
}
}
all.addAndGet(System.currentTimeMillis() - init);
} finally {
latch.countDown();
}
}
})
.start();
}
// Output, tps is not for accuracy, but it reflects the situation to a certain extent.
new Thread(new Runnable() {
public void run() {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
long lastCount = count.get();
long sleepTime = 2000;
long elapsd = sleepTime / 1000;
boolean bfirst = true;
while (latch.getCount() > 0) {
long c = count.get() - lastCount;
if (!bfirst) // The first time is inaccurate.
logger.info("[" + dateFormat.format(new Date()) + "] count: " + count.get()
+ ", error: " + error.get() + ",tps:" + (c / elapsd));
bfirst = false;
lastCount = count.get();
Thread.sleep(sleepTime);
}
} catch (Exception e) {
e.printStackTrace();
}
}
})
.start();
latch.await();
for (ExchangeClient client : exchangeClients) {
if (client.isConnected()) {
client.close();
}
}
long total = count.get();
long failed = error.get();
long succeeded = total - failed;
long elapsed = time.get();
long allElapsed = all.get();
long clientElapsed = allElapsed - elapsed;
long art = 0;
long qps = 0;
long throughput = 0;
if (elapsed > 0) {
art = elapsed / succeeded;
qps = concurrent * succeeded * 1000 / elapsed;
throughput = concurrent * succeeded * length * 2 * 1000 / elapsed;
}
PerformanceUtils.printBorder();
PerformanceUtils.printHeader("Dubbo Remoting Performance Test Report");
PerformanceUtils.printBorder();
PerformanceUtils.printHeader("Test Environment");
PerformanceUtils.printSeparator();
for (String item : serverEnvironment) {
PerformanceUtils.printBody("Server " + item);
}
PerformanceUtils.printSeparator();
List<String> clientEnvironment = PerformanceUtils.getEnvironment();
for (String item : clientEnvironment) {
PerformanceUtils.printBody("Client " + item);
}
PerformanceUtils.printSeparator();
PerformanceUtils.printHeader("Test Scene");
PerformanceUtils.printSeparator();
for (String item : serverScene) {
PerformanceUtils.printBody("Server " + item);
}
PerformanceUtils.printBody("Client Transporter: " + transporter);
PerformanceUtils.printBody("Serialization: " + serialization);
PerformanceUtils.printBody("Response Timeout: " + timeout + " ms");
PerformanceUtils.printBody("Data Length: " + length + " bytes");
PerformanceUtils.printBody("Client Shared Connections: " + connections);
PerformanceUtils.printBody("Client Concurrent Threads: " + concurrent);
PerformanceUtils.printBody("Run Times Per Thread: " + runs);
PerformanceUtils.printSeparator();
PerformanceUtils.printHeader("Test Result");
PerformanceUtils.printSeparator();
PerformanceUtils.printBody(
"Succeeded Requests: " + DecimalFormat.getIntegerInstance().format(succeeded));
PerformanceUtils.printBody("Failed Requests: " + failed);
PerformanceUtils.printBody("Client Elapsed Time: " + clientElapsed + " ms");
PerformanceUtils.printBody("Average Response Time: " + art + " ms");
PerformanceUtils.printBody("Requests Per Second: " + qps + "/s");
PerformanceUtils.printBody(
"Throughput Per Second: " + DecimalFormat.getIntegerInstance().format(throughput) + " bytes/s");
PerformanceUtils.printBorder();
}
static class PeformanceTestHandler extends ExchangeHandlerAdapter {
public PeformanceTestHandler() {
super(FrameworkModel.defaultModel());
}
@Override
public void connected(Channel channel) throws RemotingException {
logger.info("connected event,channel;" + channel);
}
@Override
public void disconnected(Channel channel) throws RemotingException {
logger.info("disconnected event,channel;" + channel);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/MockTransporter.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/MockTransporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import org.apache.dubbo.common.URL;
import org.mockito.Mockito;
public class MockTransporter implements Transporter {
private RemotingServer server = Mockito.mock(RemotingServer.class);
private Client client = Mockito.mock(Client.class);
@Override
public RemotingServer bind(URL url, ChannelHandler handler) throws RemotingException {
return server;
}
@Override
public Client connect(URL url, ChannelHandler handler) throws RemotingException {
return client;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceUtils.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
public class PerformanceUtils {
private static final int WIDTH = 64;
public static String getProperty(String key, String defaultValue) {
String value = System.getProperty(key);
if (value == null || value.trim().length() == 0 || value.startsWith("$")) {
return defaultValue;
}
return value.trim();
}
public static int getIntProperty(String key, int defaultValue) {
String value = System.getProperty(key);
if (value == null || value.trim().length() == 0 || value.startsWith("$")) {
return defaultValue;
}
return Integer.parseInt(value.trim());
}
public static boolean getBooleanProperty(String key, boolean defaultValue) {
String value = System.getProperty(key);
if (value == null || value.trim().length() == 0 || value.startsWith("$")) {
return defaultValue;
}
return Boolean.parseBoolean(value.trim());
}
public static List<String> getEnvironment() {
List<String> environment = new ArrayList<String>();
environment.add("OS: "
+ SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.SYSTEM_OS_NAME) + " "
+ SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.SYSTEM_OS_VERSION) + " "
+ SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.OS_ARCH, ""));
environment.add("CPU: " + Runtime.getRuntime().availableProcessors() + " cores");
environment.add("JVM: "
+ SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.JAVA_VM_NAME) + " "
+ SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.JAVA_RUNTIME_VERSION));
environment.add("Memory: "
+ DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().totalMemory()) + " bytes (Max: "
+ DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().maxMemory()) + " bytes)");
NetworkInterface ni = PerformanceUtils.getNetworkInterface();
if (ni != null) {
environment.add("Network: " + ni.getDisplayName());
}
return environment;
}
public static void printSeparator() {
StringBuilder pad = new StringBuilder();
for (int i = 0; i < WIDTH; i++) {
pad.append('-');
}
}
public static void printBorder() {
StringBuilder pad = new StringBuilder();
for (int i = 0; i < WIDTH; i++) {
pad.append('=');
}
}
public static void printBody(String msg) {
StringBuilder pad = new StringBuilder();
int len = WIDTH - msg.length() - 1;
if (len > 0) {
for (int i = 0; i < len; i++) {
pad.append(' ');
}
}
}
public static void printHeader(String msg) {
StringBuilder pad = new StringBuilder();
int len = WIDTH - msg.length();
if (len > 0) {
int half = len / 2;
for (int i = 0; i < half; i++) {
pad.append(' ');
}
}
}
public static NetworkInterface getNetworkInterface() {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
if (interfaces != null) {
while (interfaces.hasMoreElements()) {
try {
return interfaces.nextElement();
} catch (Throwable e) {
}
}
}
} catch (SocketException e) {
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector;
import org.apache.dubbo.remoting.exchange.ExchangeClient;
import org.apache.dubbo.remoting.exchange.Exchangers;
import java.util.ArrayList;
import java.util.Random;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT;
import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY;
class PerformanceClientFixedTest {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(PerformanceClientTest.class);
@Test
void testClient() throws Exception {
// read the parameters
if (PerformanceUtils.getProperty("server", null) == null) {
logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dserver=127.0.0.1:9911");
return;
}
final String server = System.getProperty("server", "127.0.0.1:9911");
final String transporter =
PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER);
final String serialization = PerformanceUtils.getProperty(
Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization());
final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT);
// final int length = PerformanceUtils.getIntProperty("length", 1024);
final int connectionCount = PerformanceUtils.getIntProperty(CONNECTIONS_KEY, 1);
// final int concurrent = PerformanceUtils.getIntProperty("concurrent", 100);
// int r = PerformanceUtils.getIntProperty("runs", 10000);
// final int runs = r > 0 ? r : Integer.MAX_VALUE;
// final String onerror = PerformanceUtils.getProperty("onerror", "continue");
final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization
+ "&timeout=" + timeout;
// int idx = server.indexOf(':');
Random rd = new Random(connectionCount);
ArrayList<ExchangeClient> arrays = new ArrayList<ExchangeClient>();
String oneKBlock = null;
String messageBlock = null;
int s = 0;
int f = 0;
logger.info("initialize arrays " + url);
while (s < connectionCount) {
ExchangeClient client = null;
try {
logger.info("open connection " + s + " " + url + arrays.size());
client = Exchangers.connect(url);
logger.info("run after open");
if (client.isConnected()) {
arrays.add(client);
s++;
logger.info("open client success " + s);
} else {
logger.info("open client failed, try again.");
}
} catch (Throwable t) {
t.printStackTrace();
} finally {
if (client != null && !client.isConnected()) {
f++;
logger.info("open client failed, try again " + f);
client.close();
}
}
}
StringBuilder sb1 = new StringBuilder();
Random rd2 = new Random();
char[] numbersAndLetters =
("0123456789abcdefghijklmnopqrstuvwxyz" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
int size1 = numbersAndLetters.length;
for (int j = 0; j < 1024; j++) {
sb1.append(numbersAndLetters[rd2.nextInt(size1)]);
}
oneKBlock = sb1.toString();
for (int j = 0; j < Integer.MAX_VALUE; j++) {
try {
String size = "10";
int request_size = 10;
try {
request_size = Integer.parseInt(size);
} catch (Throwable t) {
request_size = 10;
}
if (messageBlock == null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < request_size; i++) {
sb.append(oneKBlock);
}
messageBlock = sb.toString();
logger.info("set messageBlock to " + messageBlock);
}
int index = rd.nextInt(connectionCount);
ExchangeClient client = arrays.get(index);
// ExchangeClient client = arrays.get(0);
String output = (String) client.request(messageBlock).get();
if (output.lastIndexOf(messageBlock) < 0) {
logger.info("send messageBlock;get " + output);
throw new Throwable("return results invalid");
} else {
if (j % 100 == 0) logger.info("OK: " + j);
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChannelHandlerTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChannelHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector;
import org.apache.dubbo.remoting.exchange.ExchangeClient;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT;
/**
* ChannelHandlerTest
* <p>
* mvn clean test -Dtest=*PerformanceClientTest -Dserver=10.20.153.187:9911
*/
class ChannelHandlerTest {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ChannelHandlerTest.class);
public static ExchangeClient initClient(String url) {
// Create client and build connection
ExchangeClient exchangeClient = null;
PeformanceTestHandler handler = new PeformanceTestHandler(url);
boolean run = true;
while (run) {
try {
exchangeClient = Exchangers.connect(url, handler);
} catch (Throwable t) {
if (t != null
&& t.getCause() != null
&& t.getCause().getClass() != null
&& (t.getCause().getClass() == java.net.ConnectException.class
|| t.getCause().getClass() == java.net.ConnectException.class)) {
} else {
t.printStackTrace();
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (exchangeClient != null) {
run = false;
}
}
return exchangeClient;
}
public static void closeClient(ExchangeClient client) {
if (client.isConnected()) {
client.close();
}
}
@Test
void testClient() throws Throwable {
// read server info from property
if (PerformanceUtils.getProperty("server", null) == null) {
logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dserver=127.0.0.1:9911");
return;
}
final String server = System.getProperty("server", "127.0.0.1:9911");
final String transporter =
PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER);
final String serialization = PerformanceUtils.getProperty(
Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization());
final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT);
int sleep = PerformanceUtils.getIntProperty("sleep", 60 * 1000 * 60);
final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization
+ "&timeout=" + timeout;
ExchangeClient exchangeClient = initClient(url);
Thread.sleep(sleep);
closeClient(exchangeClient);
}
static class PeformanceTestHandler extends ExchangeHandlerAdapter {
String url = "";
/**
* @param url
*/
public PeformanceTestHandler(String url) {
super(FrameworkModel.defaultModel());
this.url = url;
}
@Override
public void connected(Channel channel) throws RemotingException {
logger.info("connected event,channel;" + channel);
}
@Override
public void disconnected(Channel channel) throws RemotingException {
logger.info("disconnected event,channel;" + channel);
initClient(url);
}
/* (non-Javadoc)
* @see org.apache.dubbo.remoting.transport.support.ChannelHandlerAdapter#caught(org.apache.dubbo.remoting.Channel, java.lang.Throwable)
*/
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/TelnetServer.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/TelnetServer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter;
public class TelnetServer {
public static void main(String[] args) throws Exception {
Transporters.bind("telnet://0.0.0.0:23", new ChannelHandlerAdapter() {
@Override
public void connected(Channel channel) throws RemotingException {
channel.send("telnet> ");
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
channel.send("Echo: " + message + "\r\n");
channel.send("telnet> ");
}
});
// Prevent JVM from exiting
synchronized (TelnetServer.class) {
while (true) {
try {
TelnetServer.class.wait();
} catch (InterruptedException e) {
}
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector;
import org.apache.dubbo.remoting.exchange.ExchangeClient;
import org.apache.dubbo.remoting.exchange.Exchangers;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT;
/**
* ProformanceClient
* The test class will report abnormal thread pool, because the judgment on the thread pool concurrency problems produced in DefaultChannelHandler (connected event has been executed asynchronously, judgment, then closed the thread pool, thread pool and execution error, this problem can be specified through the Constants.CHANNEL_HANDLER_KEY=connection.)
*/
class PerformanceClientCloseTest {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(PerformanceClientCloseTest.class);
@Test
void testClient() throws Throwable {
// read server info from property
if (PerformanceUtils.getProperty("server", null) == null) {
logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dserver=127.0.0.1:9911");
return;
}
final String server = System.getProperty("server", "127.0.0.1:9911");
final String transporter =
PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER);
final String serialization = PerformanceUtils.getProperty(
Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization());
final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT);
final int concurrent = PerformanceUtils.getIntProperty("concurrent", 1);
final int runs = PerformanceUtils.getIntProperty("runs", Integer.MAX_VALUE);
final String onerror = PerformanceUtils.getProperty("onerror", "continue");
final String url = "exchange://" + server + "?transporter=" + transporter
+ "&serialization=" + serialization
// + "&"+Constants.CHANNEL_HANDLER_KEY+"=connection"
+ "&timeout=" + timeout;
final AtomicInteger count = new AtomicInteger();
final AtomicInteger error = new AtomicInteger();
for (int n = 0; n < concurrent; n++) {
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < runs; i++) {
ExchangeClient client = null;
try {
client = Exchangers.connect(url);
int c = count.incrementAndGet();
if (c % 100 == 0) {
logger.info("count: {}, error: {}", count.get(), error.get());
}
} catch (Exception e) {
error.incrementAndGet();
e.printStackTrace();
logger.info("count: {}, error: {}", count.get(), error.get());
if ("exit".equals(onerror)) {
System.exit(-1);
} else if ("break".equals(onerror)) {
break;
} else if ("sleep".equals(onerror)) {
try {
Thread.sleep(30000);
} catch (InterruptedException e1) {
}
}
} finally {
if (client != null) {
client.close();
}
}
}
}
})
.start();
}
synchronized (PerformanceServerTest.class) {
while (true) {
try {
PerformanceServerTest.class.wait();
} catch (InterruptedException e) {
}
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/TelnetCodecTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/TelnetCodecTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.codec;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Codec2;
import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import org.apache.dubbo.remoting.buffer.ChannelBuffers;
import org.apache.dubbo.remoting.telnet.codec.TelnetCodec;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class TelnetCodecTest {
protected Codec2 codec;
byte[] UP = new byte[] {27, 91, 65};
byte[] DOWN = new byte[] {27, 91, 66};
// ======================================================
URL url = URL.valueOf("dubbo://10.20.30.40:20880");
/**
* @throws java.lang.Exception
*/
@BeforeEach
public void setUp() throws Exception {
codec = new TelnetCodec();
}
protected AbstractMockChannel getServerSideChannel(URL url) {
url = url.addParameter(AbstractMockChannel.LOCAL_ADDRESS, url.getAddress())
.addParameter(AbstractMockChannel.REMOTE_ADDRESS, "127.0.0.1:12345");
AbstractMockChannel channel = new AbstractMockChannel(url);
return channel;
}
protected AbstractMockChannel getClientSideChannel(URL url) {
url = url.addParameter(AbstractMockChannel.LOCAL_ADDRESS, "127.0.0.1:12345")
.addParameter(AbstractMockChannel.REMOTE_ADDRESS, url.getAddress());
AbstractMockChannel channel = new AbstractMockChannel(url);
return channel;
}
protected byte[] join(byte[] in1, byte[] in2) {
byte[] ret = new byte[in1.length + in2.length];
System.arraycopy(in1, 0, ret, 0, in1.length);
System.arraycopy(in2, 0, ret, in1.length, in2.length);
return ret;
}
protected byte[] objectToByte(Object obj) {
byte[] bytes;
if (obj instanceof String) {
bytes = ((String) obj).getBytes(StandardCharsets.UTF_8);
} else if (obj instanceof byte[]) {
bytes = (byte[]) obj;
} else {
try {
// object to bytearray
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
bytes = bo.toByteArray();
bo.close();
oo.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return bytes;
}
protected Object byteToObject(byte[] objBytes) throws Exception {
if (objBytes == null || objBytes.length == 0) {
return null;
}
ByteArrayInputStream bi = new ByteArrayInputStream(objBytes);
ObjectInputStream oi = new ObjectInputStream(bi);
return oi.readObject();
}
protected void testDecode_assertEquals(byte[] request, Object ret) throws IOException {
testDecode_assertEquals(request, ret, true);
}
protected void testDecode_assertEquals(byte[] request, Object ret, boolean isServerside) throws IOException {
// init channel
Channel channel = isServerside ? getServerSideChannel(url) : getClientSideChannel(url);
// init request string
ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request);
// decode
Object obj = codec.decode(channel, buffer);
Assertions.assertEquals(ret, obj);
}
protected void testEecode_assertEquals(Object request, byte[] ret, boolean isServerside) throws IOException {
// init channel
Channel channel = isServerside ? getServerSideChannel(url) : getClientSideChannel(url);
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(1024);
codec.encode(channel, buffer, request);
byte[] data = new byte[buffer.readableBytes()];
buffer.readBytes(data);
Assertions.assertEquals(ret.length, data.length);
for (int i = 0; i < ret.length; i++) {
if (ret[i] != data[i]) {
Assertions.fail();
}
}
}
protected void testDecode_assertEquals(Object request, Object ret) throws IOException {
testDecode_assertEquals(request, ret, null);
}
private void testDecode_assertEquals(Object request, Object ret, Object channelReceive) throws IOException {
testDecode_assertEquals(null, request, ret, channelReceive);
}
private void testDecode_assertEquals(
AbstractMockChannel channel, Object request, Object expectRet, Object channelReceive) throws IOException {
// init channel
if (channel == null) {
channel = getServerSideChannel(url);
}
byte[] buf = objectToByte(request);
ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(buf);
// decode
Object obj = codec.decode(channel, buffer);
Assertions.assertEquals(expectRet, obj);
Assertions.assertEquals(channelReceive, channel.getReceivedMessage());
}
private void testDecode_PersonWithEnterByte(byte[] enterBytes, boolean isNeedMore) throws IOException {
// init channel
Channel channel = getServerSideChannel(url);
// init request string
Person request = new Person();
byte[] newBuf = join(objectToByte(request), enterBytes);
ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(newBuf);
// decode
Object obj = codec.decode(channel, buffer);
if (isNeedMore) {
Assertions.assertEquals(Codec2.DecodeResult.NEED_MORE_INPUT, obj);
} else {
Assertions.assertTrue(obj instanceof String, "return must string ");
}
}
private void testDecode_WithExitByte(byte[] exitbytes, boolean isChannelClose) throws IOException {
// init channel
Channel channel = getServerSideChannel(url);
ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(exitbytes);
// decode
codec.decode(channel, buffer);
Assertions.assertEquals(isChannelClose, channel.isClosed());
}
@Test
void testDecode_String_ClientSide() throws IOException {
testDecode_assertEquals("aaa".getBytes(), "aaa", false);
}
@Test
void testDecode_BlankMessage() throws IOException {
testDecode_assertEquals(new byte[] {}, Codec2.DecodeResult.NEED_MORE_INPUT);
}
@Test
void testDecode_String_NoEnter() throws IOException {
testDecode_assertEquals("aaa", Codec2.DecodeResult.NEED_MORE_INPUT);
}
@Test
void testDecode_String_WithEnter() throws IOException {
testDecode_assertEquals("aaa\n", "aaa");
}
@Test
void testDecode_String_MiddleWithEnter() throws IOException {
testDecode_assertEquals("aaa\r\naaa", Codec2.DecodeResult.NEED_MORE_INPUT);
}
@Test
void testDecode_Person_ObjectOnly() throws IOException {
testDecode_assertEquals(new Person(), Codec2.DecodeResult.NEED_MORE_INPUT);
}
@Test
void testDecode_Person_WithEnter() throws IOException {
testDecode_PersonWithEnterByte(new byte[] {'\r', '\n'}, false); // windows end
testDecode_PersonWithEnterByte(new byte[] {'\n', '\r'}, true);
testDecode_PersonWithEnterByte(new byte[] {'\n'}, false); // linux end
testDecode_PersonWithEnterByte(new byte[] {'\r'}, true);
testDecode_PersonWithEnterByte(new byte[] {'\r', 100}, true);
}
@Test
void testDecode_WithExitByte() throws IOException {
HashMap<byte[], Boolean> exitBytes = new HashMap<byte[], Boolean>();
exitBytes.put(new byte[] {3}, true); /* Windows Ctrl+C */
exitBytes.put(new byte[] {1, 3}, false); // must equal the bytes
exitBytes.put(new byte[] {-1, -12, -1, -3, 6}, true); /* Linux Ctrl+C */
exitBytes.put(new byte[] {1, -1, -12, -1, -3, 6}, false); // must equal the bytes
exitBytes.put(new byte[] {-1, -19, -1, -3, 6}, true); /* Linux Pause */
for (Map.Entry<byte[], Boolean> entry : exitBytes.entrySet()) {
testDecode_WithExitByte(entry.getKey(), entry.getValue());
}
}
@Test
void testDecode_Backspace() throws IOException {
// 32 8 first add space and then add backspace.
testDecode_assertEquals(new byte[] {'\b'}, Codec2.DecodeResult.NEED_MORE_INPUT, new String(new byte[] {32, 8}));
// test chinese
byte[] chineseBytes = "中".getBytes(StandardCharsets.UTF_8);
byte[] request = join(chineseBytes, new byte[] {'\b'});
testDecode_assertEquals(request, Codec2.DecodeResult.NEED_MORE_INPUT, new String(new byte[] {32, 32, 8, 8}));
// There may be some problem handling chinese (negative number recognition). Ignoring this problem, the
// backspace key is only meaningfully input in a real telnet program.
testDecode_assertEquals(
new byte[] {'a', 'x', -1, 'x', '\b'},
Codec2.DecodeResult.NEED_MORE_INPUT,
new String(new byte[] {32, 32, 8, 8}));
}
@Test
void testDecode_Backspace_WithError() throws IOException {
Assertions.assertThrows(IOException.class, () -> {
url = url.addParameter(AbstractMockChannel.ERROR_WHEN_SEND, Boolean.TRUE.toString());
testDecode_Backspace();
url = url.removeParameter(AbstractMockChannel.ERROR_WHEN_SEND);
});
}
@Test
void testDecode_History_UP() throws IOException {
// init channel
AbstractMockChannel channel = getServerSideChannel(url);
testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, null);
String request1 = "aaa\n";
Object expected1 = "aaa";
// init history
testDecode_assertEquals(channel, request1, expected1, null);
testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, expected1);
}
@Test
void testDecode_UPorDOWN_WithError() throws IOException {
Assertions.assertThrows(IOException.class, () -> {
url = url.addParameter(AbstractMockChannel.ERROR_WHEN_SEND, Boolean.TRUE.toString());
// init channel
AbstractMockChannel channel = getServerSideChannel(url);
testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, null);
String request1 = "aaa\n";
Object expected1 = "aaa";
// init history
testDecode_assertEquals(channel, request1, expected1, null);
testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, expected1);
url = url.removeParameter(AbstractMockChannel.ERROR_WHEN_SEND);
});
}
// =============================================================================================================================
@Test
void testEncode_String_ClientSide() throws IOException {
testEecode_assertEquals("aaa", "aaa\r\n".getBytes(), false);
}
/*@Test
public void testDecode_History_UP_DOWN_MULTI() throws IOException{
AbstractMockChannel channel = getServerSideChannel(url);
String request1 = "aaa\n";
Object expected1 = request1.replace("\n", "");
//init history
testDecode_assertEquals(channel, request1, expected1, null);
String request2 = "bbb\n";
Object expected2 = request2.replace("\n", "");
//init history
testDecode_assertEquals(channel, request2, expected2, null);
String request3 = "ccc\n";
Object expected3= request3.replace("\n", "");
//init history
testDecode_assertEquals(channel, request3, expected3, null);
byte[] UP = new byte[] {27, 91, 65};
byte[] DOWN = new byte[] {27, 91, 66};
//history[aaa,bbb,ccc]
testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected3);
testDecode_assertEquals(channel, DOWN, Codec.NEED_MORE_INPUT, expected3);
testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected2);
testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected1);
testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected1);
testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected1);
testDecode_assertEquals(channel, DOWN, Codec.NEED_MORE_INPUT, expected2);
testDecode_assertEquals(channel, DOWN, Codec.NEED_MORE_INPUT, expected3);
testDecode_assertEquals(channel, DOWN, Codec.NEED_MORE_INPUT, expected3);
testDecode_assertEquals(channel, DOWN, Codec.NEED_MORE_INPUT, expected3);
testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected2);
}*/
// ======================================================
public static class Person implements Serializable {
private static final long serialVersionUID = 3362088148941547337L;
public String name;
public String sex;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((sex == null) ? 0 : sex.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Person other = (Person) obj;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
if (sex == null) {
if (other.sex != null) return false;
} else if (!sex.equals(other.sex)) return false;
return true;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/CodecAdapterTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/CodecAdapterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.codec;
import org.apache.dubbo.remoting.transport.codec.CodecAdapter;
import org.junit.jupiter.api.BeforeEach;
class CodecAdapterTest extends ExchangeCodecTest {
@BeforeEach
public void setUp() throws Exception {
codec = new CodecAdapter(new DeprecatedExchangeCodec());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedTelnetCodec.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedTelnetCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.codec;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.ObjectOutput;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Codec;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.transport.CodecSupport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_EXCEED_PAYLOAD_LIMIT;
import static org.apache.dubbo.remoting.Constants.CHARSET_KEY;
public class DeprecatedTelnetCodec implements Codec {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DeprecatedTelnetCodec.class);
private static final String HISTORY_LIST_KEY = "telnet.history.list";
private static final String HISTORY_INDEX_KEY = "telnet.history.index";
private static final byte[] UP = new byte[] {27, 91, 65};
private static final byte[] DOWN = new byte[] {27, 91, 66};
private static final List<?> ENTER = Arrays.asList(
new Object[] {new byte[] {'\r', '\n'} /* Windows Enter */, new byte[] {'\n'} /* Linux Enter */});
private static final List<?> EXIT = Arrays.asList(new Object[] {
new byte[] {3} /* Windows Ctrl+C */,
new byte[] {-1, -12, -1, -3, 6} /* Linux Ctrl+C */,
new byte[] {-1, -19, -1, -3, 6} /* Linux Pause */
});
static void checkPayload(Channel channel, long size) throws IOException {
int payload = Constants.DEFAULT_PAYLOAD;
if (channel != null && channel.getUrl() != null) {
payload = channel.getUrl().getPositiveParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD);
}
if (size > payload) {
IOException e = new IOException(
"Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel);
logger.error(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", e.getMessage(), e);
throw e;
}
}
private static Charset getCharset(Channel channel) {
if (channel != null) {
Object attribute = channel.getAttribute(CHARSET_KEY);
if (attribute instanceof String) {
try {
return Charset.forName((String) attribute);
} catch (Throwable t) {
logger.warn(t.getMessage(), t);
}
} else if (attribute instanceof Charset) {
return (Charset) attribute;
}
URL url = channel.getUrl();
if (url != null) {
String parameter = url.getParameter(CHARSET_KEY);
if (StringUtils.isNotEmpty(parameter)) {
try {
return Charset.forName(parameter);
} catch (Throwable t) {
logger.warn(t.getMessage(), t);
}
}
}
}
try {
return Charset.forName("GBK");
} catch (Throwable t) {
logger.warn(t.getMessage(), t);
}
return Charset.defaultCharset();
}
private static String toString(byte[] message, Charset charset) throws UnsupportedEncodingException {
byte[] copy = new byte[message.length];
int index = 0;
for (int i = 0; i < message.length; i++) {
byte b = message[i];
if (b == '\b') { // backspace
if (index > 0) {
index--;
}
if (i > 2 && message[i - 2] < 0) { // double byte char
if (index > 0) {
index--;
}
}
} else if (b == 27) { // escape
if (i < message.length - 4 && message[i + 4] == 126) {
i = i + 4;
} else if (i < message.length - 3 && message[i + 3] == 126) {
i = i + 3;
} else if (i < message.length - 2) {
i = i + 2;
}
} else if (b == -1
&& i < message.length - 2
&& (message[i + 1] == -3 || message[i + 1] == -5)) { // handshake
i = i + 2;
} else {
copy[index++] = message[i];
}
}
if (index == 0) {
return "";
}
return new String(copy, 0, index, charset.name()).trim();
}
private static boolean isEquals(byte[] message, byte[] command) throws IOException {
return message.length == command.length && endsWith(message, command);
}
private static boolean endsWith(byte[] message, byte[] command) throws IOException {
if (message.length < command.length) {
return false;
}
int offset = message.length - command.length;
for (int i = command.length - 1; i >= 0; i--) {
if (message[offset + i] != command[i]) {
return false;
}
}
return true;
}
protected boolean isClientSide(Channel channel) {
String side = (String) channel.getAttribute(SIDE_KEY);
if ("client".equals(side)) {
return true;
} else if ("server".equals(side)) {
return false;
} else {
InetSocketAddress address = channel.getRemoteAddress();
URL url = channel.getUrl();
boolean client = url.getPort() == address.getPort()
&& NetUtils.filterLocalHost(url.getIp())
.equals(NetUtils.filterLocalHost(
address.getAddress().getHostAddress()));
channel.setAttribute(SIDE_KEY, client ? "client" : "server");
return client;
}
}
public void encode(Channel channel, OutputStream output, Object message) throws IOException {
if (message instanceof String) {
if (isClientSide(channel)) {
message = message + "\r\n";
}
byte[] msgData = ((String) message).getBytes(getCharset(channel).name());
output.write(msgData);
output.flush();
} else {
ObjectOutput objectOutput =
CodecSupport.getSerialization(channel.getUrl()).serialize(channel.getUrl(), output);
objectOutput.writeObject(message);
objectOutput.flushBuffer();
}
}
public Object decode(Channel channel, InputStream is) throws IOException {
int readable = is.available();
byte[] message = new byte[readable];
is.read(message);
return decode(channel, is, readable, message);
}
@SuppressWarnings("unchecked")
protected Object decode(Channel channel, InputStream is, int readable, byte[] message) throws IOException {
if (isClientSide(channel)) {
return toString(message, getCharset(channel));
}
checkPayload(channel, readable);
if (message == null || message.length == 0) {
return NEED_MORE_INPUT;
}
if (message[message.length - 1] == '\b') { // Windows backspace echo
try {
boolean doublechar = message.length >= 3 && message[message.length - 3] < 0; // double byte char
channel.send(new String(
doublechar ? new byte[] {32, 32, 8, 8} : new byte[] {32, 8},
getCharset(channel).name()));
} catch (RemotingException e) {
throw new IOException(StringUtils.toString(e));
}
return NEED_MORE_INPUT;
}
for (Object command : EXIT) {
if (isEquals(message, (byte[]) command)) {
if (logger.isInfoEnabled()) {
logger.info(new Exception(
"Close channel " + channel + " on exit command: " + Arrays.toString((byte[]) command)));
}
channel.close();
return null;
}
}
boolean up = endsWith(message, UP);
boolean down = endsWith(message, DOWN);
if (up || down) {
LinkedList<String> history = (LinkedList<String>) channel.getAttribute(HISTORY_LIST_KEY);
if (history == null || history.size() == 0) {
return NEED_MORE_INPUT;
}
Integer index = (Integer) channel.getAttribute(HISTORY_INDEX_KEY);
Integer old = index;
if (index == null) {
index = history.size() - 1;
} else {
if (up) {
index = index - 1;
if (index < 0) {
index = history.size() - 1;
}
} else {
index = index + 1;
if (index > history.size() - 1) {
index = 0;
}
}
}
if (old == null || !old.equals(index)) {
channel.setAttribute(HISTORY_INDEX_KEY, index);
String value = history.get(index);
if (old != null && old >= 0 && old < history.size()) {
String ov = history.get(old);
StringBuilder buf = new StringBuilder();
for (int i = 0; i < ov.length(); i++) {
buf.append('\b');
}
for (int i = 0; i < ov.length(); i++) {
buf.append(' ');
}
for (int i = 0; i < ov.length(); i++) {
buf.append('\b');
}
value = buf.toString() + value;
}
try {
channel.send(value);
} catch (RemotingException e) {
throw new IOException(StringUtils.toString(e));
}
}
return NEED_MORE_INPUT;
}
for (Object command : EXIT) {
if (isEquals(message, (byte[]) command)) {
if (logger.isInfoEnabled()) {
logger.info(new Exception("Close channel " + channel + " on exit command " + command));
}
channel.close();
return null;
}
}
byte[] enter = null;
for (Object command : ENTER) {
if (endsWith(message, (byte[]) command)) {
enter = (byte[]) command;
break;
}
}
if (enter == null) {
return NEED_MORE_INPUT;
}
LinkedList<String> history = (LinkedList<String>) channel.getAttribute(HISTORY_LIST_KEY);
Integer index = (Integer) channel.getAttribute(HISTORY_INDEX_KEY);
channel.removeAttribute(HISTORY_INDEX_KEY);
if (history != null && history.size() > 0 && index != null && index >= 0 && index < history.size()) {
String value = history.get(index);
if (value != null) {
byte[] b1 = value.getBytes(StandardCharsets.UTF_8);
if (message != null && message.length > 0) {
byte[] b2 = new byte[b1.length + message.length];
System.arraycopy(b1, 0, b2, 0, b1.length);
System.arraycopy(message, 0, b2, b1.length, message.length);
message = b2;
} else {
message = b1;
}
}
}
String result = toString(message, getCharset(channel));
if (result != null && result.trim().length() > 0) {
if (history == null) {
history = new LinkedList<String>();
channel.setAttribute(HISTORY_LIST_KEY, history);
}
if (history.size() == 0) {
history.addLast(result);
} else if (!result.equals(history.getLast())) {
history.remove(result);
history.addLast(result);
if (history.size() > 10) {
history.removeFirst();
}
}
}
return result;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedExchangeCodec.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedExchangeCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.codec;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.io.Bytes;
import org.apache.dubbo.common.io.StreamUtils;
import org.apache.dubbo.common.io.UnsafeByteArrayInputStream;
import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.ObjectInput;
import org.apache.dubbo.common.serialize.ObjectOutput;
import org.apache.dubbo.common.serialize.Serialization;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Codec;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.Request;
import org.apache.dubbo.remoting.exchange.Response;
import org.apache.dubbo.remoting.exchange.support.DefaultFuture;
import org.apache.dubbo.remoting.transport.CodecSupport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RESPONSE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_SKIP_UNUSED_STREAM;
final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Codec {
// header length.
protected static final int HEADER_LENGTH = 16;
// magic header.
protected static final short MAGIC = (short) 0xdabb;
protected static final byte MAGIC_HIGH = Bytes.short2bytes(MAGIC)[0];
protected static final byte MAGIC_LOW = Bytes.short2bytes(MAGIC)[1];
// message flag.
protected static final byte FLAG_REQUEST = (byte) 0x80;
protected static final byte FLAG_TWOWAY = (byte) 0x40;
protected static final byte FLAG_EVENT = (byte) 0x20;
protected static final int SERIALIZATION_MASK = 0x1f;
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DeprecatedExchangeCodec.class);
public Short getMagicCode() {
return MAGIC;
}
public void encode(Channel channel, OutputStream os, Object msg) throws IOException {
if (msg instanceof Request) {
encodeRequest(channel, os, (Request) msg);
} else if (msg instanceof Response) {
encodeResponse(channel, os, (Response) msg);
} else {
super.encode(channel, os, msg);
}
}
public Object decode(Channel channel, InputStream is) throws IOException {
int readable = is.available();
byte[] header = new byte[Math.min(readable, HEADER_LENGTH)];
is.read(header);
return decode(channel, is, readable, header);
}
protected Object decode(Channel channel, InputStream is, int readable, byte[] header) throws IOException {
// check magic number.
if (readable > 0 && header[0] != MAGIC_HIGH || readable > 1 && header[1] != MAGIC_LOW) {
int length = header.length;
if (header.length < readable) {
header = Bytes.copyOf(header, readable);
is.read(header, length, readable - length);
}
for (int i = 1; i < header.length - 1; i++) {
if (header[i] == MAGIC_HIGH && header[i + 1] == MAGIC_LOW) {
UnsafeByteArrayInputStream bis = ((UnsafeByteArrayInputStream) is);
bis.position(bis.position() - header.length + i);
header = Bytes.copyOf(header, i);
break;
}
}
return super.decode(channel, is, readable, header);
}
// check length.
if (readable < HEADER_LENGTH) {
return NEED_MORE_INPUT;
}
// get data length.
int len = Bytes.bytes2int(header, 12);
checkPayload(channel, len);
int tt = len + HEADER_LENGTH;
if (readable < tt) {
return NEED_MORE_INPUT;
}
// limit input stream.
if (readable != tt) is = StreamUtils.limitedInputStream(is, len);
try {
return decodeBody(channel, is, header);
} finally {
if (is.available() > 0) {
try {
if (logger.isWarnEnabled()) {
logger.warn(TRANSPORT_SKIP_UNUSED_STREAM, "", "", "Skip input stream " + is.available());
}
StreamUtils.skipUnusedStream(is);
} catch (IOException e) {
logger.warn(TRANSPORT_SKIP_UNUSED_STREAM, "", "", e.getMessage(), e);
}
}
}
}
protected Object decodeBody(Channel channel, InputStream is, byte[] header) throws IOException {
byte flag = header[2], proto = (byte) (flag & SERIALIZATION_MASK);
// get request id.
long id = Bytes.bytes2long(header, 4);
if ((flag & FLAG_REQUEST) == 0) {
// decode response.
Response res = new Response(id);
if ((flag & FLAG_EVENT) != 0) {
res.setEvent(true);
}
// get status.
byte status = header[3];
res.setStatus(status);
try {
ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto);
if (status == Response.OK) {
Object data;
if (res.isHeartbeat()) {
data = decodeHeartbeatData(channel, in);
} else if (res.isEvent()) {
data = decodeEventData(channel, in);
} else {
data = decodeResponseData(channel, in, getRequestData(id));
}
res.setResult(data);
} else {
res.setErrorMessage(in.readUTF());
}
} catch (Throwable t) {
res.setStatus(Response.CLIENT_ERROR);
res.setErrorMessage(StringUtils.toString(t));
}
return res;
} else {
// decode request.
Request req = new Request(id);
req.setVersion(Version.getProtocolVersion());
req.setTwoWay((flag & FLAG_TWOWAY) != 0);
if ((flag & FLAG_EVENT) != 0) {
req.setEvent(true);
}
try {
ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto);
Object data;
if (req.isHeartbeat()) {
data = decodeHeartbeatData(channel, in);
} else if (req.isEvent()) {
data = decodeEventData(channel, in);
} else {
data = decodeRequestData(channel, in);
}
req.setData(data);
} catch (Throwable t) {
// bad request
req.setBroken(true);
req.setData(t);
}
return req;
}
}
protected Object getRequestData(long id) {
DefaultFuture future = DefaultFuture.getFuture(id);
if (future == null) return null;
Request req = future.getRequest();
if (req == null) return null;
return req.getData();
}
protected void encodeRequest(Channel channel, OutputStream os, Request req) throws IOException {
Serialization serialization = CodecSupport.getSerialization(channel.getUrl());
// header.
byte[] header = new byte[HEADER_LENGTH];
// set magic number.
Bytes.short2bytes(MAGIC, header);
// set request and serialization flag.
header[2] = (byte) (FLAG_REQUEST | serialization.getContentTypeId());
if (req.isTwoWay()) header[2] |= FLAG_TWOWAY;
if (req.isEvent()) header[2] |= FLAG_EVENT;
// set request id.
Bytes.long2bytes(req.getId(), header, 4);
// encode request data.
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024);
ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
if (req.isEvent()) {
encodeEventData(channel, out, req.getData());
} else {
encodeRequestData(channel, out, req.getData());
}
out.flushBuffer();
bos.flush();
bos.close();
byte[] data = bos.toByteArray();
checkPayload(channel, data.length);
Bytes.int2bytes(data.length, header, 12);
// write
os.write(header); // write header.
os.write(data); // write data.
}
protected void encodeResponse(Channel channel, OutputStream os, Response res) throws IOException {
try {
Serialization serialization = CodecSupport.getSerialization(channel.getUrl());
// header.
byte[] header = new byte[HEADER_LENGTH];
// set magic number.
Bytes.short2bytes(MAGIC, header);
// set request and serialization flag.
header[2] = serialization.getContentTypeId();
if (res.isHeartbeat()) header[2] |= FLAG_EVENT;
// set response status.
byte status = res.getStatus();
header[3] = status;
// set request id.
Bytes.long2bytes(res.getId(), header, 4);
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024);
ObjectOutput out = serialization.serialize(channel.getUrl(), bos);
// encode response data or error message.
if (status == Response.OK) {
if (res.isHeartbeat()) {
encodeHeartbeatData(channel, out, res.getResult());
} else {
encodeResponseData(channel, out, res.getResult());
}
} else out.writeUTF(res.getErrorMessage());
out.flushBuffer();
bos.flush();
bos.close();
byte[] data = bos.toByteArray();
checkPayload(channel, data.length);
Bytes.int2bytes(data.length, header, 12);
// write
os.write(header); // write header.
os.write(data); // write data.
} catch (Throwable t) {
// send error message to Consumer, otherwise, Consumer will wait until timeout.
if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) {
try {
// FIXME log error info in Codec and put all error handle logic in IoHanndler?
logger.warn(
TRANSPORT_FAILED_RESPONSE,
"",
"",
"Fail to encode response: " + res + ", send bad_response info instead, cause: "
+ t.getMessage(),
t);
Response r = new Response(res.getId(), res.getVersion());
if (t instanceof IOException) {
r.setStatus(Response.SERIALIZATION_ERROR);
} else {
r.setStatus(Response.BAD_RESPONSE);
}
r.setErrorMessage("Failed to send response: " + res + ", cause: " + StringUtils.toString(t));
channel.send(r);
return;
} catch (RemotingException e) {
logger.warn(
TRANSPORT_FAILED_RESPONSE,
"",
"",
"Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(),
e);
}
}
// Rethrow exception
if (t instanceof IOException) {
throw (IOException) t;
} else if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else if (t instanceof Error) {
throw (Error) t;
} else {
throw new RuntimeException(t.getMessage(), t);
}
}
}
protected Object decodeData(ObjectInput in) throws IOException {
return decodeRequestData(in);
}
@Deprecated
protected Object decodeHeartbeatData(ObjectInput in) throws IOException {
try {
return in.readObject();
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.toString("Read object failed.", e));
}
}
protected Object decodeRequestData(ObjectInput in) throws IOException {
try {
return in.readObject();
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.toString("Read object failed.", e));
}
}
protected Object decodeResponseData(ObjectInput in) throws IOException {
try {
return in.readObject();
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.toString("Read object failed.", e));
}
}
protected void encodeData(ObjectOutput out, Object data) throws IOException {
encodeRequestData(out, data);
}
private void encodeEventData(ObjectOutput out, Object data) throws IOException {
out.writeObject(data);
}
@Deprecated
protected void encodeHeartbeatData(ObjectOutput out, Object data) throws IOException {
encodeEventData(out, data);
}
protected void encodeRequestData(ObjectOutput out, Object data) throws IOException {
out.writeObject(data);
}
protected void encodeResponseData(ObjectOutput out, Object data) throws IOException {
out.writeObject(data);
}
protected Object decodeData(Channel channel, ObjectInput in) throws IOException {
return decodeRequestData(channel, in);
}
protected Object decodeEventData(Channel channel, ObjectInput in) throws IOException {
try {
return in.readObject();
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.toString("Read object failed.", e));
}
}
@Deprecated
protected Object decodeHeartbeatData(Channel channel, ObjectInput in) throws IOException {
try {
return in.readObject();
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.toString("Read object failed.", e));
}
}
protected Object decodeRequestData(Channel channel, ObjectInput in) throws IOException {
return decodeRequestData(in);
}
protected Object decodeResponseData(Channel channel, ObjectInput in) throws IOException {
return decodeResponseData(in);
}
protected Object decodeResponseData(Channel channel, ObjectInput in, Object requestData) throws IOException {
return decodeResponseData(channel, in);
}
protected void encodeData(Channel channel, ObjectOutput out, Object data) throws IOException {
encodeRequestData(channel, out, data);
}
private void encodeEventData(Channel channel, ObjectOutput out, Object data) throws IOException {
encodeEventData(out, data);
}
@Deprecated
protected void encodeHeartbeatData(Channel channel, ObjectOutput out, Object data) throws IOException {
encodeHeartbeatData(out, data);
}
protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) throws IOException {
encodeRequestData(out, data);
}
protected void encodeResponseData(Channel channel, ObjectOutput out, Object data) throws IOException {
encodeResponseData(out, data);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/AbstractMockChannel.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/AbstractMockChannel.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.codec;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
public class AbstractMockChannel implements Channel {
public static final String LOCAL_ADDRESS = "local";
public static final String REMOTE_ADDRESS = "remote";
public static final String ERROR_WHEN_SEND = "error_when_send";
InetSocketAddress localAddress;
InetSocketAddress remoteAddress;
private URL remoteUrl;
private ChannelHandler handler;
private boolean isClosed;
private volatile boolean closing;
private Map<String, Object> attributes = new HashMap<String, Object>(1);
private volatile Object receivedMessage = null;
public AbstractMockChannel() {}
public AbstractMockChannel(URL remoteUrl) {
this.remoteUrl = remoteUrl;
this.remoteAddress = NetUtils.toAddress(remoteUrl.getParameter(REMOTE_ADDRESS));
this.localAddress = NetUtils.toAddress(remoteUrl.getParameter(LOCAL_ADDRESS));
}
public AbstractMockChannel(ChannelHandler handler) {
this.handler = handler;
}
@Override
public URL getUrl() {
return remoteUrl;
}
@Override
public ChannelHandler getChannelHandler() {
return handler;
}
@Override
public InetSocketAddress getLocalAddress() {
return localAddress;
}
@Override
public void send(Object message) throws RemotingException {
if (remoteUrl.getParameter(ERROR_WHEN_SEND, Boolean.FALSE)) {
receivedMessage = null;
throw new RemotingException(localAddress, remoteAddress, "mock error");
} else {
receivedMessage = message;
}
}
@Override
public void send(Object message, boolean sent) throws RemotingException {
send(message);
}
@Override
public void close() {
close(0);
}
@Override
public void close(int timeout) {
isClosed = true;
}
@Override
public void startClose() {
closing = true;
}
@Override
public boolean isClosed() {
return isClosed;
}
@Override
public InetSocketAddress getRemoteAddress() {
return remoteAddress;
}
@Override
public boolean isConnected() {
return isClosed;
}
@Override
public boolean hasAttribute(String key) {
return attributes.containsKey(key);
}
@Override
public Object getAttribute(String key) {
return attributes.get(key);
}
@Override
public void setAttribute(String key, Object value) {
attributes.put(key, value);
}
@Override
public void removeAttribute(String key) {
attributes.remove(key);
}
public Object getReceivedMessage() {
return receivedMessage;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.codec;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.io.Bytes;
import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream;
import org.apache.dubbo.common.serialize.ObjectOutput;
import org.apache.dubbo.common.serialize.Serialization;
import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import org.apache.dubbo.remoting.buffer.ChannelBuffers;
import org.apache.dubbo.remoting.exchange.Request;
import org.apache.dubbo.remoting.exchange.Response;
import org.apache.dubbo.remoting.exchange.codec.ExchangeCodec;
import org.apache.dubbo.remoting.exchange.support.DefaultFuture;
import org.apache.dubbo.remoting.telnet.codec.TelnetCodec;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.READONLY_EVENT;
/**
*
* byte 16
* 0-1 magic code
* 2 flag
* 8 - 1-request/0-response
* 7 - two way
* 6 - heartbeat
* 1-5 serialization id
* 3 status
* 20 ok
* 90 error?
* 4-11 id (long)
* 12 -15 datalength
*/
class ExchangeCodecTest extends TelnetCodecTest {
// magic header.
private static final short MAGIC = (short) 0xdabb;
private static final byte MAGIC_HIGH = (byte) Bytes.short2bytes(MAGIC)[0];
private static final byte MAGIC_LOW = (byte) Bytes.short2bytes(MAGIC)[1];
Serialization serialization = getSerialization(DefaultSerializationSelector.getDefaultRemotingSerialization());
private static final byte SERIALIZATION_BYTE = FrameworkModel.defaultModel()
.getExtension(Serialization.class, DefaultSerializationSelector.getDefaultRemotingSerialization())
.getContentTypeId();
private static Serialization getSerialization(String name) {
Serialization serialization =
ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(name);
return serialization;
}
private Object decode(byte[] request) throws IOException {
ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request);
AbstractMockChannel channel = getServerSideChannel(url);
// decode
Object obj = codec.decode(channel, buffer);
return obj;
}
private byte[] getRequestBytes(Object obj, byte[] header) throws IOException {
// encode request data.
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024);
ObjectOutput out = serialization.serialize(url, bos);
out.writeObject(obj);
out.flushBuffer();
bos.flush();
bos.close();
byte[] data = bos.toByteArray();
byte[] len = Bytes.int2bytes(data.length);
System.arraycopy(len, 0, header, 12, 4);
byte[] request = join(header, data);
return request;
}
private byte[] getReadonlyEventRequestBytes(Object obj, byte[] header) throws IOException {
// encode request data.
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024);
ObjectOutput out = serialization.serialize(url, bos);
out.writeObject(obj);
out.flushBuffer();
bos.flush();
bos.close();
byte[] data = bos.toByteArray();
// byte[] len = Bytes.int2bytes(data.length);
System.arraycopy(data, 0, header, 12, data.length);
byte[] request = join(header, data);
return request;
}
private byte[] assemblyDataProtocol(byte[] header) {
Person request = new Person();
byte[] newbuf = join(header, objectToByte(request));
return newbuf;
}
// ===================================================================================
@BeforeEach
public void setUp() throws Exception {
codec = new ExchangeCodec();
}
@Test
void test_Decode_Error_MagicNum() throws IOException {
HashMap<byte[], Object> inputBytes = new HashMap<byte[], Object>();
inputBytes.put(new byte[] {0}, TelnetCodec.DecodeResult.NEED_MORE_INPUT);
inputBytes.put(new byte[] {MAGIC_HIGH, 0}, TelnetCodec.DecodeResult.NEED_MORE_INPUT);
inputBytes.put(new byte[] {0, MAGIC_LOW}, TelnetCodec.DecodeResult.NEED_MORE_INPUT);
for (Map.Entry<byte[], Object> entry : inputBytes.entrySet()) {
testDecode_assertEquals(assemblyDataProtocol(entry.getKey()), entry.getValue());
}
}
@Test
void test_Decode_Error_Length() throws IOException {
DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null);
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Person person = new Person();
byte[] request = getRequestBytes(person, header);
Channel channel = getServerSideChannel(url);
byte[] baddata = new byte[] {1, 2};
ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(join(request, baddata));
Response obj = (Response) codec.decode(channel, buffer);
Assertions.assertEquals(person, obj.getResult());
// only decode necessary bytes
Assertions.assertEquals(request.length, buffer.readerIndex());
future.cancel();
}
@Test
void test_Decode_Error_Response_Object() throws IOException {
// 00000010-response/oneway/heartbeat=true |20-stats=ok|id=0|length=0
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Person person = new Person();
byte[] request = getRequestBytes(person, header);
// bad object
byte[] badbytes = new byte[] {-1, -2, -3, -4, -3, -4, -3, -4, -3, -4, -3, -4};
System.arraycopy(badbytes, 0, request, 21, badbytes.length);
Response obj = (Response) decode(request);
Assertions.assertEquals(90, obj.getStatus());
}
@Test
void testInvalidSerializaitonId() throws Exception {
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, (byte) 0x8F, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Object obj = decode(header);
Assertions.assertTrue(obj instanceof Request);
Request request = (Request) obj;
Assertions.assertTrue(request.isBroken());
Assertions.assertTrue(request.getData() instanceof IOException);
header = new byte[] {MAGIC_HIGH, MAGIC_LOW, (byte) 0x1F, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
obj = decode(header);
Assertions.assertTrue(obj instanceof Response);
Response response = (Response) obj;
Assertions.assertEquals(response.getStatus(), Response.CLIENT_ERROR);
Assertions.assertTrue(response.getErrorMessage().contains("IOException"));
}
@Test
void test_Decode_Check_Payload() throws IOException {
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
byte[] request = assemblyDataProtocol(header);
try {
Channel channel = getServerSideChannel(url);
ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request);
Object obj = codec.decode(channel, buffer);
Assertions.assertTrue(obj instanceof Response);
Assertions.assertTrue(((Response) obj)
.getErrorMessage()
.startsWith("Data length too large: " + Bytes.bytes2int(new byte[] {1, 1, 1, 1})));
} catch (IOException expected) {
Assertions.assertTrue(expected.getMessage()
.startsWith("Data length too large: " + Bytes.bytes2int(new byte[] {1, 1, 1, 1})));
}
}
@Test
void test_Decode_Header_Need_Readmore() throws IOException {
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0};
testDecode_assertEquals(header, TelnetCodec.DecodeResult.NEED_MORE_INPUT);
}
@Test
void test_Decode_Body_Need_Readmore() throws IOException {
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 'a', 'a'};
testDecode_assertEquals(header, TelnetCodec.DecodeResult.NEED_MORE_INPUT);
}
@Test
void test_Decode_MigicCodec_Contain_ExchangeHeader() throws IOException {
byte[] header = new byte[] {0, 0, MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Channel channel = getServerSideChannel(url);
ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(header);
Object obj = codec.decode(channel, buffer);
Assertions.assertEquals(TelnetCodec.DecodeResult.NEED_MORE_INPUT, obj);
// If the telnet data and request data are in the same data packet, we should guarantee that the receipt of
// request data won't be affected by the factor that telnet does not have an end characters.
Assertions.assertEquals(2, buffer.readerIndex());
}
@Test
void test_Decode_Return_Response_Person() throws IOException {
DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null);
// 00000010-response/oneway/heartbeat=false/hessian |20-stats=ok|id=0|length=0
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Person person = new Person();
byte[] request = getRequestBytes(person, header);
Response obj = (Response) decode(request);
Assertions.assertEquals(20, obj.getStatus());
Assertions.assertEquals(person, obj.getResult());
future.cancel();
}
@Test // The status input has a problem, and the read information is wrong when the serialization is serialized.
public void test_Decode_Return_Response_Error() throws IOException {
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
String errorString = "encode request data error ";
byte[] request = getRequestBytes(errorString, header);
Response obj = (Response) decode(request);
Assertions.assertEquals(90, obj.getStatus());
Assertions.assertEquals(errorString, obj.getErrorMessage());
}
@Test
@Disabled("Event should not be object.")
void test_Decode_Return_Request_Event_Object() throws IOException {
// |10011111|20-stats=ok|id=0|length=0
byte[] header = new byte[] {
MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
Person person = new Person();
byte[] request = getRequestBytes(person, header);
System.setProperty("deserialization.event.size", "100");
Request obj = (Request) decode(request);
Assertions.assertEquals(person, obj.getData());
Assertions.assertTrue(obj.isTwoWay());
Assertions.assertTrue(obj.isEvent());
Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion());
System.clearProperty("deserialization.event.size");
}
@Test
void test_Decode_Return_Request_Event_String() throws IOException {
// |10011111|20-stats=ok|id=0|length=0
byte[] header = new byte[] {
MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
String event = READONLY_EVENT;
byte[] request = getRequestBytes(event, header);
Request obj = (Request) decode(request);
Assertions.assertEquals(event, obj.getData());
Assertions.assertTrue(obj.isTwoWay());
Assertions.assertTrue(obj.isEvent());
Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion());
}
@Test
void test_Decode_Return_Request_Heartbeat_Object() throws IOException {
// |10011111|20-stats=ok|id=0|length=0
byte[] header = new byte[] {
MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
byte[] request = getRequestBytes(null, header);
Request obj = (Request) decode(request);
Assertions.assertNull(obj.getData());
Assertions.assertTrue(obj.isTwoWay());
Assertions.assertTrue(obj.isHeartbeat());
Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion());
}
@Test
@Disabled("Event should not be object.")
void test_Decode_Return_Request_Object() throws IOException {
// |10011111|20-stats=ok|id=0|length=0
byte[] header = new byte[] {
MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
Person person = new Person();
byte[] request = getRequestBytes(person, header);
System.setProperty("deserialization.event.size", "100");
Request obj = (Request) decode(request);
Assertions.assertEquals(person, obj.getData());
Assertions.assertTrue(obj.isTwoWay());
Assertions.assertFalse(obj.isHeartbeat());
Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion());
System.clearProperty("deserialization.event.size");
}
@Test
void test_Decode_Error_Request_Object() throws IOException {
// 00000010-response/oneway/heartbeat=true |20-stats=ok|id=0|length=0
byte[] header = new byte[] {
MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
Person person = new Person();
byte[] request = getRequestBytes(person, header);
// bad object
byte[] badbytes = new byte[] {-1, -2, -3, -4, -3, -4, -3, -4, -3, -4, -3, -4};
System.arraycopy(badbytes, 0, request, 21, badbytes.length);
Request obj = (Request) decode(request);
Assertions.assertTrue(obj.isBroken());
Assertions.assertTrue(obj.getData() instanceof Throwable);
}
@Test
void test_Header_Response_NoSerializationFlag() throws IOException {
DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null);
// 00000010-response/oneway/heartbeat=false/noset |20-stats=ok|id=0|length=0
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Person person = new Person();
byte[] request = getRequestBytes(person, header);
Response obj = (Response) decode(request);
Assertions.assertEquals(20, obj.getStatus());
Assertions.assertEquals(person, obj.getResult());
future.cancel();
}
@Test
void test_Header_Response_Heartbeat() throws IOException {
DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null);
// 00000010-response/oneway/heartbeat=true |20-stats=ok|id=0|length=0
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Person person = new Person();
byte[] request = getRequestBytes(person, header);
Response obj = (Response) decode(request);
Assertions.assertEquals(20, obj.getStatus());
Assertions.assertEquals(person, obj.getResult());
future.cancel();
}
@Test
void test_Encode_Request() throws IOException {
ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(2014);
Channel channel = getClientSideChannel(url);
Request request = new Request();
Person person = new Person();
request.setData(person);
codec.encode(channel, encodeBuffer, request);
// encode resault check need decode
byte[] data = new byte[encodeBuffer.writerIndex()];
encodeBuffer.readBytes(data);
ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data);
Request obj = (Request) codec.decode(channel, decodeBuffer);
Assertions.assertEquals(request.isBroken(), obj.isBroken());
Assertions.assertEquals(request.isHeartbeat(), obj.isHeartbeat());
Assertions.assertEquals(request.isTwoWay(), obj.isTwoWay());
Assertions.assertEquals(person, obj.getData());
}
@Test
@Disabled("Event should not be object.")
void test_Encode_Response() throws IOException {
DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(1001), 100000, null);
ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024);
Channel channel = getClientSideChannel(url);
Response response = new Response();
response.setHeartbeat(true);
response.setId(1001L);
response.setStatus((byte) 20);
response.setVersion("11");
Person person = new Person();
response.setResult(person);
codec.encode(channel, encodeBuffer, response);
byte[] data = new byte[encodeBuffer.writerIndex()];
encodeBuffer.readBytes(data);
// encode resault check need decode
ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data);
Response obj = (Response) codec.decode(channel, decodeBuffer);
Assertions.assertEquals(response.getId(), obj.getId());
Assertions.assertEquals(response.getStatus(), obj.getStatus());
Assertions.assertEquals(response.isHeartbeat(), obj.isHeartbeat());
Assertions.assertEquals(person, obj.getResult());
// encode response version ??
// Assertions.assertEquals(response.getProtocolVersion(), obj.getVersion());
future.cancel();
}
@Test
void test_Encode_Error_Response() throws IOException {
ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024);
Channel channel = getClientSideChannel(url);
Response response = new Response();
response.setHeartbeat(true);
response.setId(1001L);
response.setStatus((byte) 10);
response.setVersion("11");
String badString = "bad";
response.setErrorMessage(badString);
Person person = new Person();
response.setResult(person);
codec.encode(channel, encodeBuffer, response);
byte[] data = new byte[encodeBuffer.writerIndex()];
encodeBuffer.readBytes(data);
// encode resault check need decode
ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data);
Response obj = (Response) codec.decode(channel, decodeBuffer);
Assertions.assertEquals(response.getId(), obj.getId());
Assertions.assertEquals(response.getStatus(), obj.getStatus());
Assertions.assertEquals(response.isHeartbeat(), obj.isHeartbeat());
Assertions.assertEquals(badString, obj.getErrorMessage());
Assertions.assertNull(obj.getResult());
// Assertions.assertEquals(response.getProtocolVersion(), obj.getVersion());
}
@Test
void testMessageLengthGreaterThanMessageActualLength() throws Exception {
Channel channel = getClientSideChannel(url);
Request request = new Request(1L);
request.setVersion(Version.getProtocolVersion());
Date date = new Date();
request.setData(date);
ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024);
codec.encode(channel, encodeBuffer, request);
byte[] bytes = new byte[encodeBuffer.writerIndex()];
encodeBuffer.readBytes(bytes);
int len = Bytes.bytes2int(bytes, 12);
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
out.write(bytes, 0, 12);
/*
* The fill length can not be less than 256, because by default, hessian reads 256 bytes from the stream each time.
* Refer Hessian2Input.readBuffer for more details
*/
int padding = 512;
out.write(Bytes.int2bytes(len + padding));
out.write(bytes, 16, bytes.length - 16);
for (int i = 0; i < padding; i++) {
out.write(1);
}
out.write(bytes);
/* request|1111...|request */
ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(out.toByteArray());
Request decodedRequest = (Request) codec.decode(channel, decodeBuffer);
Assertions.assertEquals(date, decodedRequest.getData());
Assertions.assertEquals(bytes.length + padding, decodeBuffer.readerIndex());
decodedRequest = (Request) codec.decode(channel, decodeBuffer);
Assertions.assertEquals(date, decodedRequest.getData());
}
@Test
void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception {
Request request = new Request(1L);
request.setData("hello");
ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(512);
AbstractMockChannel channel = getClientSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4));
try {
codec.encode(channel, encodeBuffer, request);
Assertions.fail();
} catch (IOException e) {
Assertions.assertTrue(e.getMessage().startsWith("Data length too large: "));
Assertions.assertTrue(e.getMessage()
.contains("max payload: 4, channel: org.apache.dubbo.remoting.codec.AbstractMockChannel"));
}
Response response = new Response(1L);
response.setResult("hello");
encodeBuffer = ChannelBuffers.dynamicBuffer(512);
channel = getServerSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4));
codec.encode(channel, encodeBuffer, response);
Assertions.assertTrue(channel.getReceivedMessage() instanceof Response);
Response receiveMessage = (Response) channel.getReceivedMessage();
Assertions.assertEquals(Response.SERIALIZATION_ERROR, receiveMessage.getStatus());
Assertions.assertTrue(receiveMessage.getErrorMessage().contains("Data length too large: "));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/MockExchanger.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/MockExchanger.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.RemotingException;
import org.mockito.Mockito;
public class MockExchanger implements Exchanger {
private ExchangeServer exchangeServer = Mockito.mock(ExchangeServer.class);
private ExchangeClient exchangeClient = Mockito.mock(ExchangeClient.class);
@Override
public ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException {
return exchangeServer;
}
@Override
public ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException {
return exchangeClient;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/ResponseTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/ResponseTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT;
class ResponseTest {
@Test
void test() {
Response response = new Response();
response.setStatus(Response.OK);
response.setId(1);
response.setVersion("1.0.0");
response.setResult("test");
response.setEvent(HEARTBEAT_EVENT);
response.setErrorMessage("errorMsg");
Assertions.assertTrue(response.isEvent());
Assertions.assertTrue(response.isHeartbeat());
Assertions.assertEquals(response.getVersion(), "1.0.0");
Assertions.assertEquals(response.getId(), 1);
Assertions.assertEquals(response.getResult(), HEARTBEAT_EVENT);
Assertions.assertEquals(response.getErrorMessage(), "errorMsg");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/RequestTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/RequestTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class RequestTest {
@Test
void test() {
Request requestStart = new Request();
Request request = new Request();
request.setTwoWay(true);
request.setBroken(true);
request.setVersion("1.0.0");
request.setEvent(true);
request.setData("data");
request.setPayload(1024);
Assertions.assertTrue(request.isTwoWay());
Assertions.assertTrue(request.isBroken());
Assertions.assertTrue(request.isEvent());
Assertions.assertEquals(request.getVersion(), "1.0.0");
Assertions.assertEquals(request.getData(), "data");
Assertions.assertEquals(requestStart.getId() + 1, request.getId());
Assertions.assertEquals(1024, request.getPayload());
request.setHeartbeat(true);
Assertions.assertTrue(request.isHeartbeat());
Request copiedRequest = request.copy();
Assertions.assertEquals(copiedRequest.toString(), request.toString());
Request copyWithoutData = request.copyWithoutData();
Assertions.assertNull(copyWithoutData.getData());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/ExchangersTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/ExchangersTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerDispatcher;
import org.apache.dubbo.remoting.exchange.support.Replier;
import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class ExchangersTest {
@Test
void testBind() throws RemotingException {
String url = "dubbo://127.0.0.1:12345?exchanger=mockExchanger";
Exchangers.bind(url, Mockito.mock(Replier.class));
Exchangers.bind(url, new ChannelHandlerAdapter(), Mockito.mock(Replier.class));
Exchangers.bind(url, new ExchangeHandlerDispatcher());
Assertions.assertThrows(
RuntimeException.class, () -> Exchangers.bind((URL) null, new ExchangeHandlerDispatcher()));
Assertions.assertThrows(RuntimeException.class, () -> Exchangers.bind(url, (ExchangeHandlerDispatcher) null));
}
@Test
void testConnect() throws RemotingException {
String url = "dubbo://127.0.0.1:12345?exchanger=mockExchanger";
Exchangers.connect(url);
Exchangers.connect(url, Mockito.mock(Replier.class));
Exchangers.connect(URL.valueOf(url), Mockito.mock(Replier.class));
Exchangers.connect(url, new ChannelHandlerAdapter(), Mockito.mock(Replier.class));
Exchangers.connect(url, new ExchangeHandlerDispatcher());
Assertions.assertThrows(
RuntimeException.class, () -> Exchangers.connect((URL) null, new ExchangeHandlerDispatcher()));
Assertions.assertThrows(
RuntimeException.class, () -> Exchangers.connect(url, (ExchangeHandlerDispatcher) null));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/DefaultFutureTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/DefaultFutureTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.threadpool.ThreadlessExecutor;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.TimeoutException;
import org.apache.dubbo.remoting.exchange.Request;
import org.apache.dubbo.remoting.handler.MockedChannel;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class DefaultFutureTest {
private static final Logger logger = LoggerFactory.getLogger(DefaultFutureTest.class);
private static final AtomicInteger index = new AtomicInteger();
@Test
void newFuture() {
DefaultFuture future = defaultFuture(3000);
Assertions.assertNotNull(future, "new future return null");
}
@Test
void isDone() {
DefaultFuture future = defaultFuture(3000);
Assertions.assertTrue(!future.isDone(), "init future is finished!");
// cancel a future
future.cancel();
Assertions.assertTrue(future.isDone(), "cancel a future failed!");
}
/**
* for example, it will print like this:
* before a future is create , time is : 2018-06-21 15:06:17
* after a future is timeout , time is : 2018-06-21 15:06:22
* <p>
* The exception info print like:
* Sending request timeout in client-side by scan timer.
* start time: 2018-06-21 15:13:02.215, end time: 2018-06-21 15:13:07.231...
*/
@Test
@Disabled
public void timeoutNotSend() throws Exception {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
logger.info(
"before a future is create , time is : {}", LocalDateTime.now().format(formatter));
// timeout after 5 seconds.
DefaultFuture f = defaultFuture(5000);
while (!f.isDone()) {
// spin
Thread.sleep(100);
}
logger.info(
"after a future is timeout , time is : {}", LocalDateTime.now().format(formatter));
// get operate will throw a timeout exception, because the future is timeout.
try {
f.get();
} catch (Exception e) {
Assertions.assertTrue(
e.getCause() instanceof TimeoutException, "catch exception is not timeout exception!");
logger.error(e.getMessage());
}
}
/**
* for example, it will print like this:
* before a future is created, time is : 2023-09-03 18:20:14.535
* after a future is timeout, time is : 2023-09-03 18:20:14.669
* <p>
* The exception info print like:
* Sending request timeout in client-side by scan timer.
* start time: 2023-09-03 18:20:14.544, end time: 2023-09-03 18:20:14.598...
*/
@Test
public void clientTimeoutSend() throws Exception {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
logger.info(
"before a future is create , time is : {}", LocalDateTime.now().format(formatter));
// timeout after 5 milliseconds.
Channel channel = new MockedChannel();
Request request = new Request(10);
DefaultFuture f = DefaultFuture.newFuture(channel, request, 5, null);
System.gc(); // events such as Full GC will increase the time required to send messages.
// mark the future is sent
DefaultFuture.sent(channel, request);
while (!f.isDone()) {
// spin
Thread.sleep(100);
}
logger.info(
"after a future is timeout , time is : {}", LocalDateTime.now().format(formatter));
// get operate will throw a timeout exception, because the future is timeout.
try {
f.get();
} catch (Exception e) {
Assertions.assertTrue(
e.getCause() instanceof TimeoutException, "catch exception is not timeout exception!");
logger.error(e.getMessage());
Assertions.assertTrue(e.getMessage()
.startsWith(
e.getCause().getClass().getCanonicalName() + ": Sending request timeout in client-side"));
}
}
/**
* for example, it will print like this:
* before a future is create , time is : 2018-06-21 15:11:31
* after a future is timeout , time is : 2018-06-21 15:11:36
* <p>
* The exception info print like:
* Waiting server-side response timeout by scan timer.
* start time: 2018-06-21 15:12:38.337, end time: 2018-06-21 15:12:43.354...
*/
@Test
@Disabled
public void timeoutSend() throws Exception {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
logger.info(
"before a future is create , time is : {}", LocalDateTime.now().format(formatter));
// timeout after 5 seconds.
Channel channel = new MockedChannel();
Request request = new Request(10);
DefaultFuture f = DefaultFuture.newFuture(channel, request, 5000, null);
// mark the future is sent
DefaultFuture.sent(channel, request);
while (!f.isDone()) {
// spin
Thread.sleep(100);
}
logger.info(
"after a future is timeout , time is : {}", LocalDateTime.now().format(formatter));
// get operate will throw a timeout exception, because the future is timeout.
try {
f.get();
} catch (Exception e) {
Assertions.assertTrue(
e.getCause() instanceof TimeoutException, "catch exception is not timeout exception!");
logger.error(e.getMessage());
}
}
/**
* for example, it will print like this:
* before a future is created , time is : 2021-01-22 10:55:03
* null
* after a future is timeout , time is : 2021-01-22 10:55:05
*/
@Test
void interruptSend() throws Exception {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
logger.info(
"before a future is create , time is : {}", LocalDateTime.now().format(formatter));
// timeout after 1 seconds.
Channel channel = new MockedChannel();
int channelId = 10;
Request request = new Request(channelId);
ThreadlessExecutor executor = new ThreadlessExecutor();
DefaultFuture f = DefaultFuture.newFuture(channel, request, 1000, executor);
// mark the future is sent
DefaultFuture.sent(channel, request);
// get operate will throw a interrupted exception, because the thread is interrupted.
try {
new InterruptThread(Thread.currentThread()).start();
while (!f.isDone()) {
executor.waitAndDrain(Long.MAX_VALUE);
}
f.get();
} catch (Exception e) {
Assertions.assertTrue(e instanceof InterruptedException, "catch exception is not interrupted exception!");
logger.error(e.getMessage());
} finally {
executor.shutdown();
}
// waiting timeout check task finished
Thread.sleep(1500);
logger.info(
"after a future is timeout , time is : {}", LocalDateTime.now().format(formatter));
DefaultFuture future = DefaultFuture.getFuture(channelId);
// waiting future should be removed by time out check task
Assertions.assertNull(future);
}
@Test
void testClose1() {
Channel channel = new MockedChannel();
Request request = new Request(123);
ExecutorService executor = ExtensionLoader.getExtensionLoader(ExecutorRepository.class)
.getDefaultExtension()
.createExecutorIfAbsent(URL.valueOf("dubbo://127.0.0.1:23456"));
DefaultFuture.newFuture(channel, request, 1000, executor);
DefaultFuture.closeChannel(channel, 0);
Assertions.assertFalse(executor.isTerminated());
}
@Test
void testTimeoutWithRejectedExecution() throws Exception {
// Create a ThreadPoolExecutor with a queue capacity of 1
ThreadPoolExecutor customExecutor = new ThreadPoolExecutor(
1, // corePoolSize
1, // maxPoolSize
60L,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1), // queue capacity is 1
new ThreadPoolExecutor.AbortPolicy() // default rejection policy: throws exception
);
// Submit two tasks to occupy the thread and the queue
customExecutor.submit(() -> {
try {
Thread.sleep(500); // occupy the thread for a while
} catch (InterruptedException ignored) {
}
});
customExecutor.submit(() -> {
try {
Thread.sleep(500); // occupy the queue
} catch (InterruptedException ignored) {
}
});
// Create a Dubbo Mock Channel and a request
Channel channel = new MockedChannel();
Request request = new Request(999);
// Use Dubbo's newFuture and pass in the custom thread pool
DefaultFuture future = DefaultFuture.newFuture(channel, request, 100, customExecutor);
// Mark the request as sent
DefaultFuture.sent(channel, request);
// Wait for the timeout task to trigger
Thread.sleep(300);
Assertions.assertNull(DefaultFuture.getFuture(999), "Future should be removed from FUTURES after timeout");
customExecutor.shutdown();
}
@Test
void testClose2() {
Channel channel = new MockedChannel();
Request request = new Request(123);
ThreadlessExecutor threadlessExecutor = new ThreadlessExecutor();
DefaultFuture.newFuture(channel, request, 1000, threadlessExecutor);
DefaultFuture.closeChannel(channel, 0);
Assertions.assertTrue(threadlessExecutor.isTerminated());
}
/**
* mock a default future
*/
private DefaultFuture defaultFuture(int timeout) {
Channel channel = new MockedChannel();
Request request = new Request(index.getAndIncrement());
return DefaultFuture.newFuture(channel, request, timeout, null);
}
/**
* mock a thread interrupt another thread which is waiting waitAndDrain() to return.
*/
static class InterruptThread extends Thread {
private Thread parent;
public InterruptThread(Thread parent) {
this.parent = parent;
}
@Override
public void run() {
super.run();
try {
// interrupt waiting thread before timeout
Thread.sleep(500);
parent.interrupt();
} catch (InterruptedException e) {
logger.error(e.getMessage());
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/MultiMessageTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/MultiMessageTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange.support;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* {@link MultiMessage}
*/
class MultiMessageTest {
@Test
void test() {
MultiMessage multiMessage = MultiMessage.create();
Assertions.assertTrue(multiMessage instanceof Iterable);
multiMessage.addMessage("test1");
multiMessage.addMessages(Arrays.asList("test2", "test3"));
Assertions.assertEquals(multiMessage.size(), 3);
Assertions.assertFalse(multiMessage.isEmpty());
Assertions.assertEquals(multiMessage.get(0), "test1");
Assertions.assertEquals(multiMessage.get(1), "test2");
Assertions.assertEquals(multiMessage.get(2), "test3");
Collection messages = multiMessage.getMessages();
Assertions.assertTrue(messages.contains("test1"));
Assertions.assertTrue(messages.contains("test2"));
Assertions.assertTrue(messages.contains("test3"));
Iterator iterator = messages.iterator();
Assertions.assertTrue(iterator.hasNext());
Assertions.assertEquals(iterator.next(), "test1");
Assertions.assertEquals(iterator.next(), "test2");
Assertions.assertEquals(iterator.next(), "test3");
Collection removedCollection = multiMessage.removeMessages();
Assertions.assertArrayEquals(removedCollection.toArray(), messages.toArray());
messages = multiMessage.getMessages();
Assertions.assertTrue(messages.isEmpty());
MultiMessage multiMessage1 = MultiMessage.createFromCollection(Arrays.asList("test1", "test2"));
MultiMessage multiMessage2 = MultiMessage.createFromArray("test1", "test2");
Assertions.assertArrayEquals(
multiMessage1.getMessages().toArray(),
multiMessage2.getMessages().toArray());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerDispatcherTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerDispatcherTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange.support;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.telnet.support.TelnetHandlerAdapter;
import java.lang.reflect.Field;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class ExchangeHandlerDispatcherTest {
@Test
void test() throws Exception {
ExchangeHandlerDispatcher exchangeHandlerDispatcher = new ExchangeHandlerDispatcher();
ChannelHandler channelHandler = Mockito.mock(ChannelHandler.class);
Replier replier = Mockito.mock(Replier.class);
TelnetHandlerAdapter telnetHandlerAdapter = Mockito.mock(TelnetHandlerAdapter.class);
exchangeHandlerDispatcher.addChannelHandler(channelHandler);
exchangeHandlerDispatcher.addReplier(ExchangeHandlerDispatcherTest.class, replier);
Field telnetHandlerField = exchangeHandlerDispatcher.getClass().getDeclaredField("telnetHandler");
telnetHandlerField.setAccessible(true);
telnetHandlerField.set(exchangeHandlerDispatcher, telnetHandlerAdapter);
Channel channel = Mockito.mock(Channel.class);
ExchangeChannel exchangeChannel = Mockito.mock(ExchangeChannel.class);
exchangeHandlerDispatcher.connected(channel);
exchangeHandlerDispatcher.disconnected(channel);
exchangeHandlerDispatcher.sent(channel, null);
exchangeHandlerDispatcher.received(channel, null);
exchangeHandlerDispatcher.caught(channel, null);
ExchangeHandlerDispatcherTest obj = new ExchangeHandlerDispatcherTest();
exchangeHandlerDispatcher.reply(exchangeChannel, obj);
exchangeHandlerDispatcher.telnet(channel, null);
Mockito.verify(channelHandler, Mockito.times(1)).connected(channel);
Mockito.verify(channelHandler, Mockito.times(1)).disconnected(channel);
Mockito.verify(channelHandler, Mockito.times(1)).sent(channel, null);
Mockito.verify(channelHandler, Mockito.times(1)).received(channel, null);
Mockito.verify(channelHandler, Mockito.times(1)).caught(channel, null);
Mockito.verify(replier, Mockito.times(1)).reply(exchangeChannel, obj);
Mockito.verify(telnetHandlerAdapter, Mockito.times(1)).telnet(channel, null);
exchangeHandlerDispatcher.removeChannelHandler(channelHandler);
exchangeHandlerDispatcher.removeReplier(ExchangeHandlerDispatcherTest.class);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTaskTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTaskTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange.support.header;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.timer.HashedWheelTimer;
import org.apache.dubbo.remoting.Channel;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK;
/**
* {@link CloseTimerTask}
*/
class CloseTimerTaskTest {
private URL url = URL.valueOf("dubbo://localhost:20880");
private MockChannel channel;
private CloseTimerTask closeTimerTask;
private HashedWheelTimer closeTimer;
@BeforeEach
public void setup() throws Exception {
long tickDuration = 1000;
closeTimer = new HashedWheelTimer(tickDuration / HEARTBEAT_CHECK_TICK, TimeUnit.MILLISECONDS);
channel = new MockChannel() {
@Override
public URL getUrl() {
return url;
}
};
AbstractTimerTask.ChannelProvider cp = () -> Collections.<Channel>singletonList(channel);
closeTimerTask = new CloseTimerTask(cp, closeTimer, tickDuration / HEARTBEAT_CHECK_TICK, (int) tickDuration);
}
@AfterEach
public void teardown() {
closeTimerTask.cancel();
}
@Test
void testClose() throws Exception {
long now = System.currentTimeMillis();
url = url.addParameter(DUBBO_VERSION_KEY, "2.1.1");
channel.setAttribute(HeartbeatHandler.KEY_READ_TIMESTAMP, now - 1000);
channel.setAttribute(HeartbeatHandler.KEY_WRITE_TIMESTAMP, now - 1000);
closeTimer.newTimeout(closeTimerTask, 250, TimeUnit.MILLISECONDS);
Thread.sleep(2000L);
Assertions.assertTrue(channel.isClosed());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTaskTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTaskTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange.support.header;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.timer.HashedWheelTimer;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK;
class ReconnectTimerTaskTest {
private URL url = URL.valueOf("dubbo://localhost:20880");
private MockChannel channel;
private ReconnectTimerTask reconnectTimerTask;
private HashedWheelTimer reconnectTimer;
private boolean isConnected = false;
@BeforeEach
public void setup() throws Exception {
long tickDuration = 1000;
reconnectTimer = new HashedWheelTimer(tickDuration / HEARTBEAT_CHECK_TICK, TimeUnit.MILLISECONDS);
channel = new MockChannel() {
@Override
public URL getUrl() {
return url;
}
@Override
public boolean isConnected() {
return isConnected;
}
};
reconnectTimerTask = new ReconnectTimerTask(
() -> Collections.singleton(channel), reconnectTimer, tickDuration / HEARTBEAT_CHECK_TICK, (int)
tickDuration);
}
@AfterEach
public void teardown() {
reconnectTimerTask.cancel();
}
@Test
void testReconnect() throws Exception {
long now = System.currentTimeMillis();
url = url.addParameter(DUBBO_VERSION_KEY, "2.1.1");
channel.setAttribute(HeartbeatHandler.KEY_READ_TIMESTAMP, now - 1000);
channel.setAttribute(HeartbeatHandler.KEY_WRITE_TIMESTAMP, now - 1000);
Thread.sleep(2000L);
Assertions.assertTrue(channel.getReconnectCount() > 0);
isConnected = true;
Thread.sleep(2000L);
Assertions.assertTrue(channel.getReconnectCount() > 1);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/MockChannel.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/MockChannel.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange.support.header;
import org.apache.dubbo.common.Parameters;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Client;
import org.apache.dubbo.remoting.RemotingException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MockChannel implements Channel, Client {
private Map<String, Object> attributes = new HashMap<String, Object>();
private volatile boolean closed = false;
private volatile boolean closing = false;
private volatile int reconnectCount = 0;
private List<Object> sentObjects = new ArrayList<Object>();
@Override
public InetSocketAddress getRemoteAddress() {
return null;
}
@Override
public boolean isConnected() {
return false;
}
@Override
public boolean hasAttribute(String key) {
return attributes.containsKey(key);
}
@Override
public Object getAttribute(String key) {
return attributes.get(key);
}
@Override
public void setAttribute(String key, Object value) {
attributes.put(key, value);
}
@Override
public void removeAttribute(String key) {
attributes.remove(key);
}
@Override
public URL getUrl() {
return null;
}
@Override
public ChannelHandler getChannelHandler() {
return null;
}
@Override
public InetSocketAddress getLocalAddress() {
return null;
}
@Override
public void send(Object message) throws RemotingException {
sentObjects.add(message);
}
@Override
public void send(Object message, boolean sent) throws RemotingException {
sentObjects.add(message);
}
@Override
public void close() {
closed = true;
}
@Override
public void close(int timeout) {
closed = true;
}
@Override
public void startClose() {
closing = true;
}
@Override
public boolean isClosed() {
return closed;
}
public List<Object> getSentObjects() {
return Collections.unmodifiableList(sentObjects);
}
public boolean isClosing() {
return closing;
}
@Override
public void reset(URL url) {}
@Override
public void reconnect() throws RemotingException {
reconnectCount++;
}
@Override
public void reset(Parameters parameters) {}
public int getReconnectCount() {
return reconnectCount;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServerTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange.support.header;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.RemotingServer;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Collection;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
/**
* {@link HeaderExchangeServer}
*/
class HeaderExchangeServerTest {
@Test
void test() throws InterruptedException, RemotingException {
RemotingServer server = Mockito.mock(RemotingServer.class);
URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 20881);
Mockito.when(server.getUrl()).thenReturn(url);
Mockito.when(server.canHandleIdle()).thenReturn(false);
HeaderExchangeServer headerExchangeServer = new HeaderExchangeServer(server);
Assertions.assertEquals(headerExchangeServer.getServer(), server);
Assertions.assertEquals(headerExchangeServer.getUrl(), url);
// test getChannels() and getExchangeChannels()
Channel channel1 = Mockito.mock(Channel.class);
Channel channel2 = Mockito.mock(Channel.class);
Channel exchangeChannel1 = new HeaderExchangeChannel(channel1);
Channel exchangeChannel2 = new HeaderExchangeChannel(channel2);
Mockito.when(channel1.getAttribute(HeaderExchangeChannel.class.getName() + ".CHANNEL"))
.thenReturn(exchangeChannel1);
Mockito.when(channel2.getAttribute(HeaderExchangeChannel.class.getName() + ".CHANNEL"))
.thenReturn(exchangeChannel2);
Collection<Channel> exChannels = Arrays.asList(exchangeChannel1, exchangeChannel2);
Mockito.when(server.getChannels()).thenReturn(Arrays.asList(channel1, channel2));
Assertions.assertEquals(headerExchangeServer.getChannels(), exChannels);
Assertions.assertEquals(headerExchangeServer.getExchangeChannels(), exChannels);
// test getChannel(InetSocketAddress) and getExchangeChannel(InetSocketAddress)
InetSocketAddress address1 = Mockito.mock(InetSocketAddress.class);
InetSocketAddress address2 = Mockito.mock(InetSocketAddress.class);
Mockito.when(server.getChannel(Mockito.eq(address1))).thenReturn(channel1);
Mockito.when(server.getChannel(Mockito.eq(address2))).thenReturn(channel2);
Assertions.assertEquals(headerExchangeServer.getChannel(address1), exchangeChannel1);
Assertions.assertEquals(headerExchangeServer.getChannel(address2), exchangeChannel2);
Assertions.assertEquals(headerExchangeServer.getExchangeChannel(address1), exchangeChannel1);
Assertions.assertEquals(headerExchangeServer.getExchangeChannel(address2), exchangeChannel2);
// test send(Object message) and send(Object message, boolean sent)
headerExchangeServer.send("test");
Mockito.verify(server, Mockito.times(1)).send("test");
headerExchangeServer.send("test", true);
Mockito.verify(server, Mockito.times(1)).send("test", true);
// test reset(URL url)
url = url.addParameter(Constants.HEARTBEAT_KEY, 3000).addParameter(Constants.HEARTBEAT_TIMEOUT_KEY, 3000 * 3);
headerExchangeServer.reset(url);
// test close(int timeout)
Mockito.when(exchangeChannel1.isConnected()).thenReturn(true);
headerExchangeServer.close(1000);
Mockito.verify(server, Mockito.times(1)).startClose();
Thread.sleep(1000);
Mockito.verify(server, Mockito.times(1)).close(1000);
Assertions.assertThrows(RemotingException.class, () -> headerExchangeServer.send("test"));
Assertions.assertThrows(RemotingException.class, () -> headerExchangeServer.send("test", true));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannelTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannelTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange.support.header;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.Request;
import org.apache.dubbo.remoting.exchange.support.DefaultFuture;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class HeaderExchangeChannelTest {
private HeaderExchangeChannel header;
private MockChannel channel;
private URL url = URL.valueOf("dubbo://localhost:20880");
private static final String CHANNEL_KEY = HeaderExchangeChannel.class.getName() + ".CHANNEL";
@BeforeEach
public void setup() {
channel = new MockChannel() {
@Override
public URL getUrl() {
return url;
}
};
header = new HeaderExchangeChannel(channel);
}
@Test
void getOrAddChannelTest00() {
channel.setAttribute("CHANNEL_KEY", "attribute");
HeaderExchangeChannel ret = HeaderExchangeChannel.getOrAddChannel(channel);
Assertions.assertNotNull(ret);
}
@Test
void getOrAddChannelTest01() {
channel = new MockChannel() {
@Override
public URL getUrl() {
return url;
}
@Override
public boolean isConnected() {
return true;
}
};
Assertions.assertNull(channel.getAttribute(CHANNEL_KEY));
HeaderExchangeChannel ret = HeaderExchangeChannel.getOrAddChannel(channel);
Assertions.assertNotNull(ret);
Assertions.assertNotNull(channel.getAttribute(CHANNEL_KEY));
Assertions.assertEquals(channel.getAttribute(CHANNEL_KEY).getClass(), HeaderExchangeChannel.class);
}
@Test
void getOrAddChannelTest02() {
channel = null;
HeaderExchangeChannel ret = HeaderExchangeChannel.getOrAddChannel(channel);
Assertions.assertNull(ret);
}
@Test
void removeChannelIfDisconnectedTest() {
Assertions.assertNull(channel.getAttribute(CHANNEL_KEY));
channel.setAttribute(CHANNEL_KEY, header);
channel.close();
HeaderExchangeChannel.removeChannelIfDisconnected(channel);
Assertions.assertNull(channel.getAttribute(CHANNEL_KEY));
}
@Test
void sendTest00() {
boolean sent = true;
String message = "this is a test message";
try {
header.close(1);
header.send(message, sent);
} catch (Exception e) {
Assertions.assertTrue(e instanceof RemotingException);
}
}
@Test
void sendTest01() throws RemotingException {
boolean sent = true;
String message = "this is a test message";
header.send(message, sent);
List<Object> objects = channel.getSentObjects();
Assertions.assertEquals(objects.get(0), "this is a test message");
}
@Test
void sendTest02() throws RemotingException {
boolean sent = true;
int message = 1;
header.send(message, sent);
List<Object> objects = channel.getSentObjects();
Assertions.assertEquals(objects.get(0).getClass(), Request.class);
Request request = (Request) objects.get(0);
Assertions.assertEquals(request.getVersion(), "2.0.2");
}
@Test
void sendTest04() throws RemotingException {
String message = "this is a test message";
header.send(message);
List<Object> objects = channel.getSentObjects();
Assertions.assertEquals(objects.get(0), "this is a test message");
}
@Test
void requestTest01() throws RemotingException {
Assertions.assertThrows(RemotingException.class, () -> {
header.close(1000);
Object requestObject = new Object();
header.request(requestObject);
});
}
@Test
void requestTest02() throws RemotingException {
Channel channel = Mockito.mock(MockChannel.class);
header = new HeaderExchangeChannel(channel);
when(channel.getUrl()).thenReturn(url);
Object requestObject = new Object();
header.request(requestObject);
ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class);
verify(channel, times(1)).send(argumentCaptor.capture());
Assertions.assertEquals(argumentCaptor.getValue().getData(), requestObject);
}
@Test
void requestTest03() throws RemotingException {
Assertions.assertThrows(RemotingException.class, () -> {
channel = new MockChannel() {
@Override
public void send(Object req) throws RemotingException {
throw new RemotingException(channel.getLocalAddress(), channel.getRemoteAddress(), "throw error");
}
};
header = new HeaderExchangeChannel(channel);
Object requestObject = new Object();
header.request(requestObject, 1000);
});
}
@Test
void isClosedTest() {
Assertions.assertFalse(header.isClosed());
}
@Test
void closeTest() {
Assertions.assertFalse(channel.isClosed());
header.close();
Assertions.assertTrue(channel.isClosed());
}
@Test
void closeWithTimeoutTest02() {
Assertions.assertFalse(channel.isClosed());
Request request = new Request();
DefaultFuture.newFuture(channel, request, 100, null);
header.close(100);
// return directly
header.close(1000);
}
@Test
void startCloseTest() {
try {
boolean isClosing = channel.isClosing();
Assertions.assertFalse(isClosing);
header.startClose();
isClosing = channel.isClosing();
Assertions.assertTrue(isClosing);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
void getLocalAddressTest() {
Assertions.assertNull(header.getLocalAddress());
}
@Test
void getRemoteAddressTest() {
Assertions.assertNull(header.getRemoteAddress());
}
@Test
void getUrlTest() {
Assertions.assertEquals(header.getUrl(), URL.valueOf("dubbo://localhost:20880"));
}
@Test
void isConnectedTest() {
Assertions.assertFalse(header.isConnected());
}
@Test
void getChannelHandlerTest() {
Assertions.assertNull(header.getChannelHandler());
}
@Test
void getExchangeHandlerTest() {
Assertions.assertNull(header.getExchangeHandler());
}
@Test
void getAttributeAndSetAttributeTest() {
header.setAttribute("test", "test");
Assertions.assertEquals(header.getAttribute("test"), "test");
Assertions.assertTrue(header.hasAttribute("test"));
}
@Test
void removeAttributeTest() {
header.setAttribute("test", "test");
Assertions.assertEquals(header.getAttribute("test"), "test");
header.removeAttribute("test");
Assertions.assertFalse(header.hasAttribute("test"));
}
@Test
void hasAttributeTest() {
Assertions.assertFalse(header.hasAttribute("test"));
header.setAttribute("test", "test");
Assertions.assertTrue(header.hasAttribute("test"));
}
@Test
void hashCodeTest() {
final int prime = 31;
int result = 1;
result = prime * result + ((channel == null) ? 0 : channel.hashCode());
Assertions.assertEquals(header.hashCode(), result);
}
@Test
void equalsTest() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
Assertions.assertEquals(header, new HeaderExchangeChannel(channel));
header = new HeaderExchangeChannel(null);
Assertions.assertNotEquals(header, new HeaderExchangeChannel(channel));
});
}
@Test
void toStringTest() {
Assertions.assertEquals(header.toString(), channel.toString());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClientTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClientTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange.support.header;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.Client;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
public class HeaderExchangeClientTest {
@Test
void testReconnect() {
HeaderExchangeClient headerExchangeClient = new HeaderExchangeClient(Mockito.mock(Client.class), false);
Assertions.assertTrue(headerExchangeClient.shouldReconnect(URL.valueOf("localhost")));
Assertions.assertTrue(headerExchangeClient.shouldReconnect(URL.valueOf("localhost?reconnect=true")));
Assertions.assertTrue(headerExchangeClient.shouldReconnect(URL.valueOf("localhost?reconnect=tRue")));
Assertions.assertTrue(headerExchangeClient.shouldReconnect(URL.valueOf("localhost?reconnect=30000")));
Assertions.assertTrue(headerExchangeClient.shouldReconnect(URL.valueOf("localhost?reconnect=0")));
Assertions.assertTrue(headerExchangeClient.shouldReconnect(URL.valueOf("localhost?reconnect=-1")));
Assertions.assertFalse(headerExchangeClient.shouldReconnect(URL.valueOf("localhost?reconnect=false")));
Assertions.assertFalse(headerExchangeClient.shouldReconnect(URL.valueOf("localhost?reconnect=FALSE")));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange.support.header;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.timer.HashedWheelTimer;
import org.apache.dubbo.remoting.exchange.Request;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK;
class HeartBeatTaskTest {
private URL url = URL.valueOf("dubbo://localhost:20880");
private MockChannel channel;
private HeartbeatTimerTask heartbeatTimerTask;
private HashedWheelTimer heartbeatTimer;
@BeforeEach
public void setup() throws Exception {
long tickDuration = 1000;
heartbeatTimer = new HashedWheelTimer(tickDuration / HEARTBEAT_CHECK_TICK, TimeUnit.MILLISECONDS);
channel = new MockChannel() {
@Override
public URL getUrl() {
return url;
}
};
heartbeatTimerTask = new HeartbeatTimerTask(
() -> Collections.singleton(channel), heartbeatTimer, tickDuration / HEARTBEAT_CHECK_TICK, (int)
tickDuration);
}
@AfterEach
public void teardown() {
heartbeatTimerTask.cancel();
}
@Test
void testHeartBeat() throws Exception {
long now = System.currentTimeMillis();
url = url.addParameter(DUBBO_VERSION_KEY, "2.1.1");
channel.setAttribute(HeartbeatHandler.KEY_READ_TIMESTAMP, now);
channel.setAttribute(HeartbeatHandler.KEY_WRITE_TIMESTAMP, now);
Thread.sleep(2000L);
List<Object> objects = channel.getSentObjects();
Assertions.assertTrue(objects.size() > 0);
Object obj = objects.get(0);
Assertions.assertTrue(obj instanceof Request);
Request request = (Request) obj;
Assertions.assertTrue(request.isHeartbeat());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/TelnetUtilsTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/TelnetUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.telnet;
import org.apache.dubbo.remoting.telnet.support.TelnetUtils;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class TelnetUtilsTest {
/**
* abc - abc - abc
* 1 - 2 - 3
* x - y - z
*/
@Test
void testToList() {
List<List<String>> table = new LinkedList<>();
table.add(Arrays.asList("abc", "abc", "abc"));
table.add(Arrays.asList("1", "2", "3"));
table.add(Arrays.asList("x", "y", "z"));
String toList = TelnetUtils.toList(table);
Assertions.assertTrue(toList.contains("abc - abc - abc"));
Assertions.assertTrue(toList.contains("1 - 2 - 3"));
Assertions.assertTrue(toList.contains("x - y - z"));
}
/**
* +-----+-----+-----+
* | A | B | C |
* +-----+-----+-----+
* | abc | abc | abc |
* | 1 | 2 | 3 |
* | x | y | z |
* +-----+-----+-----+
*/
@Test
void testToTable() {
List<List<String>> table = new LinkedList<>();
table.add(Arrays.asList("abc", "abc", "abc"));
table.add(Arrays.asList("1", "2", "3"));
table.add(Arrays.asList("x", "y", "z"));
String toTable = TelnetUtils.toTable(new String[] {"A", "B", "C"}, table);
Assertions.assertTrue(toTable.contains("| A | B | C |"));
Assertions.assertTrue(toTable.contains("| abc | abc | abc |"));
Assertions.assertTrue(toTable.contains("| 1 | 2 | 3 |"));
Assertions.assertTrue(toTable.contains("| x | y | z |"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/StatusTelnetHandlerTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/StatusTelnetHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.telnet.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.telnet.support.command.StatusTelnetHandler;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class StatusTelnetHandlerTest {
@Test
void test() {
Channel channel = Mockito.mock(Channel.class);
Mockito.when(channel.getUrl()).thenReturn(URL.valueOf("dubbo://127.0.0.1:12345"));
StatusTelnetHandler statusTelnetHandler = new StatusTelnetHandler();
Assertions.assertNotNull(statusTelnetHandler.telnet(channel, ""));
Assertions.assertNotNull(statusTelnetHandler.telnet(channel, "-l"));
String errorPrompt = "Unsupported parameter ";
Assertions.assertTrue(statusTelnetHandler.telnet(channel, "other").contains(errorPrompt));
Mockito.when(channel.getUrl()).thenReturn(URL.valueOf("dubbo://127.0.0.1:12345?status=load,memory"));
Assertions.assertNotNull(statusTelnetHandler.telnet(channel, ""));
Assertions.assertNotNull(statusTelnetHandler.telnet(channel, "-l"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/ExitTelnetHandlerTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/ExitTelnetHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.telnet.support;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.telnet.support.command.ExitTelnetHandler;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
class ExitTelnetHandlerTest {
@Test
void test() {
Channel channel = Mockito.mock(Channel.class);
ExitTelnetHandler exitTelnetHandler = new ExitTelnetHandler();
exitTelnetHandler.telnet(channel, null);
verify(channel, times(1)).close();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/ClearTelnetHandlerTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/ClearTelnetHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.telnet.support;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.telnet.support.command.ClearTelnetHandler;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class ClearTelnetHandlerTest {
@Test
void test() {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < 50; i++) {
buf.append("\r\n");
}
ClearTelnetHandler telnetHandler = new ClearTelnetHandler();
Assertions.assertEquals(buf.toString(), telnetHandler.telnet(Mockito.mock(Channel.class), "50"));
// Illegal Input
Assertions.assertTrue(
telnetHandler.telnet(Mockito.mock(Channel.class), "Illegal").contains("Illegal"));
for (int i = 0; i < 50; i++) {
buf.append("\r\n");
}
Assertions.assertEquals(buf.toString(), telnetHandler.telnet(Mockito.mock(Channel.class), ""));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapterTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.telnet.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class TelnetHandlerAdapterTest {
@Test
void testTelnet() throws RemotingException {
Channel channel = Mockito.mock(Channel.class);
Map<String, String> param = new HashMap<>();
param.put("telnet", "status");
URL url = new URL("p1", "127.0.0.1", 12345, "path1", param);
Mockito.when(channel.getUrl()).thenReturn(url);
TelnetHandlerAdapter telnetHandlerAdapter = new TelnetHandlerAdapter(FrameworkModel.defaultModel());
String message = "--no-prompt status ";
String expectedResult = "OK\r\n";
Assertions.assertEquals(expectedResult, telnetHandlerAdapter.telnet(channel, message));
message = "--no-prompt status test";
expectedResult = "Unsupported parameter test for status.\r\n";
Assertions.assertEquals(expectedResult, telnetHandlerAdapter.telnet(channel, message));
message = "--no-prompt test";
expectedResult = "Unsupported command: test\r\n";
Assertions.assertEquals(expectedResult, telnetHandlerAdapter.telnet(channel, message));
message = "--no-prompt help";
expectedResult =
"Command: help disabled for security reasons, please enable support by listing the commands through 'telnet'\r\n";
Assertions.assertEquals(expectedResult, telnetHandlerAdapter.telnet(channel, message));
message = "--no-prompt";
expectedResult = StringUtils.EMPTY_STRING;
Assertions.assertEquals(expectedResult, telnetHandlerAdapter.telnet(channel, message));
message = "help";
expectedResult =
"Command: help disabled for security reasons, please enable support by listing the commands through 'telnet'\r\ndubbo>";
Assertions.assertEquals(expectedResult, telnetHandlerAdapter.telnet(channel, message));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/HelpTelnetHandlerTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/HelpTelnetHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.telnet.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.telnet.support.command.HelpTelnetHandler;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class HelpTelnetHandlerTest {
@Test
void test() {
Channel channel = Mockito.mock(Channel.class);
Mockito.when(channel.getUrl()).thenReturn(URL.valueOf("dubbo://127.0.0.1:12345"));
HelpTelnetHandler helpTelnetHandler = new HelpTelnetHandler(FrameworkModel.defaultModel());
// default output
String prompt = "Please input \"help [command]\" show detail.\r\n";
Assertions.assertTrue(helpTelnetHandler.telnet(channel, "").contains(prompt));
// "help" command output
String demoOutput = "Command:\r\n" + " help [command]\r\n"
+ "Summary:\r\n"
+ " Show help.\r\n"
+ "Detail:\r\n"
+ " Show help.";
Assertions.assertEquals(helpTelnetHandler.telnet(channel, "help"), demoOutput);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/utils/UrlUtilsTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/utils/UrlUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.utils;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class UrlUtilsTest {
@Test
void testGetIdleTimeout() {
URL url1 = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000");
URL url2 = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000&heartbeat.timeout=50000");
URL url3 = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000&heartbeat.timeout=10000");
Assertions.assertEquals(UrlUtils.getIdleTimeout(url1), 30000);
Assertions.assertEquals(UrlUtils.getIdleTimeout(url2), 50000);
Assertions.assertThrows(RuntimeException.class, () -> UrlUtils.getIdleTimeout(url3));
}
@Test
void testGetHeartbeat() {
URL url = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000");
Assertions.assertEquals(UrlUtils.getHeartbeat(url), 10000);
}
@Test
void testConfiguredHeartbeat() {
SystemPropertyConfigUtils.setSystemProperty(CommonConstants.DubboProperty.DUBBO_HEARTBEAT_CONFIG_KEY, "200");
URL url = URL.valueOf("dubbo://127.0.0.1:12345");
Assertions.assertEquals(200, UrlUtils.getHeartbeat(url));
SystemPropertyConfigUtils.clearSystemProperty(CommonConstants.DubboProperty.DUBBO_HEARTBEAT_CONFIG_KEY);
}
@Test
void testGetCloseTimeout() {
URL url1 = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000");
URL url2 = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000&heartbeat.timeout=50000");
URL url3 = URL.valueOf("dubbo://127.0.0.1:12345?heartbeat=10000&heartbeat.timeout=10000");
URL url4 = URL.valueOf("dubbo://127.0.0.1:12345?close.timeout=30000&heartbeat=10000&heartbeat.timeout=10000");
URL url5 = URL.valueOf("dubbo://127.0.0.1:12345?close.timeout=40000&heartbeat=10000&heartbeat.timeout=50000");
URL url6 = URL.valueOf("dubbo://127.0.0.1:12345?close.timeout=10000&heartbeat=10000&heartbeat.timeout=10000");
Assertions.assertEquals(30000, UrlUtils.getCloseTimeout(url1));
Assertions.assertEquals(50000, UrlUtils.getCloseTimeout(url2));
Assertions.assertThrows(RuntimeException.class, () -> UrlUtils.getCloseTimeout(url3));
Assertions.assertThrows(RuntimeException.class, () -> UrlUtils.getCloseTimeout(url4));
Assertions.assertEquals(40000, UrlUtils.getCloseTimeout(url5));
Assertions.assertThrows(RuntimeException.class, () -> UrlUtils.getCloseTimeout(url6));
}
@Test
void testConfiguredClose() {
SystemPropertyConfigUtils.setSystemProperty(
CommonConstants.DubboProperty.DUBBO_CLOSE_TIMEOUT_CONFIG_KEY, "180000");
URL url = URL.valueOf("dubbo://127.0.0.1:12345");
Assertions.assertEquals(180000, UrlUtils.getCloseTimeout(url));
SystemPropertyConfigUtils.clearSystemProperty(CommonConstants.DubboProperty.DUBBO_CLOSE_TIMEOUT_CONFIG_KEY);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/utils/PayloadDropperTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/utils/PayloadDropperTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.utils;
import org.apache.dubbo.remoting.exchange.Request;
import org.apache.dubbo.remoting.exchange.Response;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class PayloadDropperTest {
@Test
void test() {
Request request = new Request(1);
request.setData(new Object());
Request requestWithoutData = (Request) PayloadDropper.getRequestWithoutData(request);
Assertions.assertEquals(requestWithoutData.getId(), request.getId());
Assertions.assertNull(requestWithoutData.getData());
Response response = new Response(1);
response.setResult(new Object());
Response responseWithoutData = (Response) PayloadDropper.getRequestWithoutData(response);
Assertions.assertEquals(responseWithoutData.getId(), response.getId());
Assertions.assertNull(responseWithoutData.getResult());
Object object = new Object();
Assertions.assertEquals(object, PayloadDropper.getRequestWithoutData(object));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/api/EmptyProtocol.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/api/EmptyProtocol.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.api;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.api.pu.ChannelOperator;
import org.apache.dubbo.remoting.api.ssl.ContextOperator;
public class EmptyProtocol implements WireProtocol {
@Override
public ProtocolDetector detector() {
return null;
}
@Override
public void configServerProtocolHandler(URL url, ChannelOperator operator) {}
@Override
public void configClientPipeline(URL url, ChannelOperator operator, ContextOperator contextOperator) {}
@Override
public void close() {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/DecodeHandlerTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/DecodeHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Decodeable;
import org.apache.dubbo.remoting.exchange.Request;
import org.apache.dubbo.remoting.exchange.Response;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
/**
* {@link DecodeHandler}
*/
class DecodeHandlerTest {
@Test
void test() throws Exception {
ChannelHandler handler = Mockito.mock(ChannelHandler.class);
Channel channel = Mockito.mock(Channel.class);
DecodeHandler decodeHandler = new DecodeHandler(handler);
MockData mockData = new MockData();
decodeHandler.received(channel, mockData);
Assertions.assertTrue(mockData.isDecoded());
MockData mockRequestData = new MockData();
Request request = new Request(1);
request.setData(mockRequestData);
decodeHandler.received(channel, request);
Assertions.assertTrue(mockRequestData.isDecoded());
MockData mockResponseData = new MockData();
Response response = new Response(1);
response.setResult(mockResponseData);
decodeHandler.received(channel, response);
Assertions.assertTrue(mockResponseData.isDecoded());
mockData.setThrowEx(true);
decodeHandler.received(channel, mockData);
}
class MockData implements Decodeable {
private boolean isDecoded = false;
private boolean throwEx = false;
@Override
public void decode() throws Exception {
if (throwEx) {
throw new RuntimeException();
}
isDecoded = true;
}
public boolean isDecoded() {
return isDecoded;
}
public void setThrowEx(boolean throwEx) {
this.throwEx = throwEx;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/MultiMessageHandlerTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/MultiMessageHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.exchange.support.MultiMessage;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
/**
* {@link MultiMessageHandler}
*/
class MultiMessageHandlerTest {
@Test
void test() throws Exception {
ChannelHandler handler = Mockito.mock(ChannelHandler.class);
Channel channel = Mockito.mock(Channel.class);
MultiMessageHandler multiMessageHandler = new MultiMessageHandler(handler);
MultiMessage multiMessage = MultiMessage.createFromArray("test1", "test2");
multiMessageHandler.received(channel, multiMessage);
// verify
ArgumentCaptor<Channel> channelArgumentCaptor = ArgumentCaptor.forClass(Channel.class);
ArgumentCaptor<Object> objectArgumentCaptor = ArgumentCaptor.forClass(Object.class);
Mockito.verify(handler, Mockito.times(2))
.received(channelArgumentCaptor.capture(), objectArgumentCaptor.capture());
Assertions.assertEquals(objectArgumentCaptor.getAllValues().get(0), "test1");
Assertions.assertEquals(objectArgumentCaptor.getAllValues().get(1), "test2");
Assertions.assertEquals(channelArgumentCaptor.getValue(), channel);
Object obj = new Object();
multiMessageHandler.received(channel, obj);
// verify
Mockito.verify(handler, Mockito.times(3))
.received(channelArgumentCaptor.capture(), objectArgumentCaptor.capture());
Assertions.assertEquals(objectArgumentCaptor.getValue(), obj);
Assertions.assertEquals(channelArgumentCaptor.getValue(), channel);
RuntimeException runtimeException = new RuntimeException();
Mockito.doThrow(runtimeException).when(handler).received(Mockito.any(), Mockito.any());
multiMessageHandler.received(channel, multiMessage);
// verify
ArgumentCaptor<Throwable> throwableArgumentCaptor = ArgumentCaptor.forClass(Throwable.class);
Mockito.verify(handler, Mockito.times(2))
.caught(channelArgumentCaptor.capture(), throwableArgumentCaptor.capture());
Assertions.assertEquals(throwableArgumentCaptor.getAllValues().get(0), runtimeException);
Assertions.assertEquals(throwableArgumentCaptor.getAllValues().get(1), runtimeException);
Assertions.assertEquals(channelArgumentCaptor.getValue(), channel);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/CodecSupportTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/CodecSupportTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport;
import org.apache.dubbo.common.serialize.ObjectOutput;
import org.apache.dubbo.common.serialize.Serialization;
import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class CodecSupportTest {
@Test
void testHeartbeat() throws Exception {
Byte proto = CodecSupport.getIDByName(DefaultSerializationSelector.getDefaultRemotingSerialization());
Serialization serialization = CodecSupport.getSerializationById(proto);
byte[] nullBytes = CodecSupport.getNullBytesOf(serialization);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutput out = serialization.serialize(null, baos);
out.writeObject(null);
out.flushBuffer();
InputStream is = new ByteArrayInputStream(baos.toByteArray());
baos.close();
byte[] payload = CodecSupport.getPayload(is);
Assertions.assertArrayEquals(nullBytes, payload);
Assertions.assertTrue(CodecSupport.isHeartBeat(payload, proto));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcherTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcherTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class ChannelHandlerDispatcherTest {
@AfterEach
public void tearDown() {
MockChannelHandler.reset();
}
@Test
void test() {
ChannelHandlerDispatcher channelHandlerDispatcher = new ChannelHandlerDispatcher();
MockChannelHandler channelHandler1 = new MockChannelHandler();
MockChannelHandler channelHandler2 = new MockChannelHandler();
channelHandlerDispatcher.addChannelHandler(channelHandler1);
channelHandlerDispatcher.addChannelHandler(channelHandler2);
Collection<ChannelHandler> channelHandlers = channelHandlerDispatcher.getChannelHandlers();
Assertions.assertTrue(channelHandlers.contains(channelHandler1));
Assertions.assertTrue(channelHandlers.contains(channelHandler2));
Channel channel = Mockito.mock(Channel.class);
channelHandlerDispatcher.sent(channel, "test");
channelHandlerDispatcher.connected(channel);
channelHandlerDispatcher.disconnected(channel);
channelHandlerDispatcher.caught(channel, null);
channelHandlerDispatcher.received(channel, "test");
Assertions.assertEquals(MockChannelHandler.getSentCount(), 2);
Assertions.assertEquals(MockChannelHandler.getConnectedCount(), 2);
Assertions.assertEquals(MockChannelHandler.getDisconnectedCount(), 2);
Assertions.assertEquals(MockChannelHandler.getCaughtCount(), 2);
Assertions.assertEquals(MockChannelHandler.getReceivedCount(), 2);
channelHandlerDispatcher = channelHandlerDispatcher.removeChannelHandler(channelHandler1);
Assertions.assertFalse(channelHandlerDispatcher.getChannelHandlers().contains(channelHandler1));
}
@Test
void constructorNullObjectTest() {
ChannelHandlerDispatcher channelHandlerDispatcher = new ChannelHandlerDispatcher(null, null);
Assertions.assertEquals(0, channelHandlerDispatcher.getChannelHandlers().size());
ChannelHandlerDispatcher channelHandlerDispatcher1 = new ChannelHandlerDispatcher((MockChannelHandler) null);
Assertions.assertEquals(
0, channelHandlerDispatcher1.getChannelHandlers().size());
ChannelHandlerDispatcher channelHandlerDispatcher2 =
new ChannelHandlerDispatcher(null, new MockChannelHandler());
Assertions.assertEquals(
1, channelHandlerDispatcher2.getChannelHandlers().size());
ChannelHandlerDispatcher channelHandlerDispatcher3 =
new ChannelHandlerDispatcher(Collections.singleton(new MockChannelHandler()));
Assertions.assertEquals(
1, channelHandlerDispatcher3.getChannelHandlers().size());
Collection<ChannelHandler> mockChannelHandlers = new HashSet<>();
mockChannelHandlers.add(new MockChannelHandler());
mockChannelHandlers.add(null);
ChannelHandlerDispatcher channelHandlerDispatcher4 = new ChannelHandlerDispatcher(mockChannelHandlers);
Assertions.assertEquals(
1, channelHandlerDispatcher4.getChannelHandlers().size());
}
}
class MockChannelHandler extends ChannelHandlerAdapter {
private static int sentCount = 0;
private static int connectedCount = 0;
private static int disconnectedCount = 0;
private static int receivedCount = 0;
private static int caughtCount = 0;
@Override
public void connected(Channel channel) throws RemotingException {
connectedCount++;
super.connected(channel);
}
@Override
public void disconnected(Channel channel) throws RemotingException {
disconnectedCount++;
super.disconnected(channel);
}
@Override
public void sent(Channel channel, Object message) throws RemotingException {
sentCount++;
super.sent(channel, message);
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
receivedCount++;
super.received(channel, message);
}
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {
caughtCount++;
super.caught(channel, exception);
}
public static int getSentCount() {
return sentCount;
}
public static int getConnectedCount() {
return connectedCount;
}
public static int getDisconnectedCount() {
return disconnectedCount;
}
public static int getReceivedCount() {
return receivedCount;
}
public static int getCaughtCount() {
return caughtCount;
}
public static void reset() {
sentCount = 0;
connectedCount = 0;
disconnectedCount = 0;
receivedCount = 0;
caughtCount = 0;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/AbstractCodecTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/AbstractCodecTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.junit.jupiter.api.Test;
import org.mockito.internal.verification.VerificationModeFactory;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
class AbstractCodecTest {
@Test
void testCheckPayloadDefault8M() throws Exception {
Channel channel = mock(Channel.class);
given(channel.getUrl()).willReturn(URL.valueOf("dubbo://1.1.1.1"));
AbstractCodec.checkPayload(channel, 1 * 1024 * 1024);
try {
AbstractCodec.checkPayload(channel, 15 * 1024 * 1024);
} catch (IOException expected) {
assertThat(
expected.getMessage(),
allOf(
containsString("Data length too large: "),
containsString("max payload: " + 8 * 1024 * 1024)));
}
verify(channel, VerificationModeFactory.atLeastOnce()).getUrl();
}
@Test
void testCheckProviderPayload() throws Exception {
Channel channel = mock(Channel.class);
given(channel.getUrl()).willReturn(URL.valueOf("dubbo://1.1.1.1"));
AbstractCodec.checkPayload(channel, 1024 * 1024 + 1, 1024 * 1024);
try {
AbstractCodec.checkPayload(channel, 1024 * 1024, 1024 * 1024);
} catch (IOException expected) {
assertThat(
expected.getMessage(),
allOf(containsString("Data length too large: "), containsString("max payload: " + 1024 * 1024)));
}
try {
AbstractCodec.checkPayload(channel, 0, 15 * 1024 * 1024);
} catch (IOException expected) {
assertThat(
expected.getMessage(),
allOf(
containsString("Data length too large: "),
containsString("max payload: " + 8 * 1024 * 1024)));
}
verify(channel, VerificationModeFactory.atLeastOnce()).getUrl();
}
@Test
void tesCheckPayloadMinusPayloadNoLimit() throws Exception {
Channel channel = mock(Channel.class);
given(channel.getUrl()).willReturn(URL.valueOf("dubbo://1.1.1.1?payload=-1"));
AbstractCodec.checkPayload(channel, 15 * 1024 * 1024);
verify(channel, VerificationModeFactory.atLeastOnce()).getUrl();
}
@Test
void testIsClientSide() {
AbstractCodec codec = getAbstractCodec();
Channel channel = mock(Channel.class);
given(channel.getRemoteAddress()).willReturn(new InetSocketAddress("172.24.157.13", 9103));
given(channel.getUrl()).willReturn(URL.valueOf("dubbo://172.24.157.13:9103"));
assertThat(codec.isClientSide(channel), is(true));
assertThat(codec.isServerSide(channel), is(false));
given(channel.getRemoteAddress()).willReturn(new InetSocketAddress("172.24.157.14", 9103));
given(channel.getUrl()).willReturn(URL.valueOf("dubbo://172.24.157.13:9103"));
assertThat(codec.isClientSide(channel), is(false));
assertThat(codec.isServerSide(channel), is(true));
}
private AbstractCodec getAbstractCodec() {
AbstractCodec codec = new AbstractCodec() {
@Override
public void encode(Channel channel, ChannelBuffer buffer, Object message) {}
@Override
public Object decode(Channel channel, ChannelBuffer buffer) {
return null;
}
};
return codec;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnableTest.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnableTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.dispatcher;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import java.util.Arrays;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
/**
* {@link ChannelEventRunnable}
*/
class ChannelEventRunnableTest {
@Test
void test() throws Exception {
ChannelEventRunnable.ChannelState[] values = ChannelEventRunnable.ChannelState.values();
Assertions.assertEquals(Arrays.toString(values), "[CONNECTED, DISCONNECTED, SENT, RECEIVED, CAUGHT]");
Channel channel = Mockito.mock(Channel.class);
ChannelHandler handler = Mockito.mock(ChannelHandler.class);
ChannelEventRunnable connectRunnable =
new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.CONNECTED);
ChannelEventRunnable disconnectRunnable =
new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.DISCONNECTED);
ChannelEventRunnable sentRunnable =
new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.SENT);
ChannelEventRunnable receivedRunnable =
new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.RECEIVED, "");
ChannelEventRunnable caughtRunnable = new ChannelEventRunnable(
channel, handler, ChannelEventRunnable.ChannelState.CAUGHT, new RuntimeException());
connectRunnable.run();
disconnectRunnable.run();
sentRunnable.run();
receivedRunnable.run();
caughtRunnable.run();
ArgumentCaptor<Channel> channelArgumentCaptor = ArgumentCaptor.forClass(Channel.class);
ArgumentCaptor<Throwable> throwableArgumentCaptor = ArgumentCaptor.forClass(Throwable.class);
ArgumentCaptor<Object> objectArgumentCaptor = ArgumentCaptor.forClass(Object.class);
Mockito.verify(handler, Mockito.times(1)).connected(channelArgumentCaptor.capture());
Mockito.verify(handler, Mockito.times(1)).disconnected(channelArgumentCaptor.capture());
Mockito.verify(handler, Mockito.times(1)).sent(channelArgumentCaptor.capture(), Mockito.any());
Mockito.verify(handler, Mockito.times(1))
.received(channelArgumentCaptor.capture(), objectArgumentCaptor.capture());
Mockito.verify(handler, Mockito.times(1))
.caught(channelArgumentCaptor.capture(), throwableArgumentCaptor.capture());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/MockedChannelHandler.java | dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/MockedChannelHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.handler;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import java.util.Collections;
import java.util.Set;
public class MockedChannelHandler implements ChannelHandler {
// ConcurrentMap<String, Channel> channels = new ConcurrentHashMap<String, Channel>();
ConcurrentHashSet<Channel> channels = new ConcurrentHashSet<Channel>();
@Override
public void connected(Channel channel) throws RemotingException {
channels.add(channel);
}
@Override
public void disconnected(Channel channel) throws RemotingException {
channels.remove(channel);
}
@Override
public void sent(Channel channel, Object message) throws RemotingException {
channel.send(message);
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
// echo
channel.send(message);
}
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {
throw new RemotingException(channel, exception);
}
public Set<Channel> getChannels() {
return Collections.unmodifiableSet(channels);
}
}
| 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.