repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/basic/ParamArgumentResolver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/basic/ParamArgumentResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.support.basic;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.io.StreamUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.HttpCookie;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpRequest.FileUpload;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.remoting.http12.rest.Param;
import org.apache.dubbo.rpc.protocol.tri.rest.Messages;
import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants;
import org.apache.dubbo.rpc.protocol.tri.rest.RestException;
import org.apache.dubbo.rpc.protocol.tri.rest.RestParameterException;
import org.apache.dubbo.rpc.protocol.tri.rest.argument.AbstractAnnotationBaseArgumentResolver;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Activate
public class ParamArgumentResolver extends AbstractAnnotationBaseArgumentResolver {
@Override
protected NamedValueMeta createNamedValueMeta(ParameterMeta param, AnnotationMeta<Annotation> anno) {
String defaultValue = anno.getString("defaultValue");
if (Param.DEFAULT_NONE.equals(defaultValue)) {
defaultValue = null;
}
return new NamedValueMeta(anno.getValue(), anno.getBoolean("required"), defaultValue)
.setParamType(anno.getEnum("type"));
}
@Override
public Class<Annotation> accept() {
return Annotations.Param.type();
}
@Override
protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) {
switch (meta.paramType()) {
case PathVariable:
return resolvePathVariable(meta, request);
case MatrixVariable:
return CollectionUtils.first(resolveMatrixVariable(meta, request));
case Param:
return request.parameter(meta.name());
case Form:
return request.formParameter(meta.name());
case Header:
return request.header(meta.name());
case Cookie:
return request.cookie(meta.name());
case Attribute:
return request.attribute(meta.name());
case Part:
return request.part(meta.name());
case Body:
if (RequestUtils.isFormOrMultiPart(request)) {
return request.formParameter(meta.name());
}
return RequestUtils.decodeBody(request, meta.genericType());
}
return null;
}
@Override
protected Object filterValue(Object value, NamedValueMeta meta) {
return StringUtils.EMPTY_STRING.equals(value) ? meta.defaultValue() : value;
}
@Override
protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) {
switch (meta.paramType()) {
case PathVariable:
String value = resolvePathVariable(meta, request);
return value == null ? Collections.emptyList() : Collections.singletonList(value);
case MatrixVariable:
return resolveMatrixVariable(meta, request);
case Param:
return request.parameterValues(meta.name());
case Form:
return request.formParameterValues(meta.name());
case Header:
return request.headerValues(meta.name());
case Cookie:
Collection<HttpCookie> cookies = request.cookies();
if (cookies.isEmpty()) {
return Collections.emptyList();
}
String name = meta.name();
List<HttpCookie> result = new ArrayList<>(cookies.size());
for (HttpCookie cookie : cookies) {
if (name.equals(cookie.name())) {
result.add(cookie);
}
}
return result;
case Attribute:
return request.attribute(meta.name());
case Part:
return meta.type() == byte[].class ? request.part(meta.name()) : request.parts();
case Body:
Class<?> type = meta.type();
if (type == byte[].class) {
try {
return StreamUtils.readBytes(request.inputStream());
} catch (IOException e) {
throw new RestException(e);
}
}
if (RequestUtils.isFormOrMultiPart(request)) {
return request.formParameterValues(meta.name());
}
return RequestUtils.decodeBody(request, meta.genericType());
}
return null;
}
@Override
protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) {
switch (meta.paramType()) {
case PathVariable:
String value = resolvePathVariable(meta, request);
return value == null ? Collections.emptyMap() : Collections.singletonMap(meta.name(), value);
case MatrixVariable:
return CollectionUtils.first(resolveMatrixVariable(meta, request));
case Param:
return RequestUtils.getParametersMap(request);
case Form:
return RequestUtils.getFormParametersMap(request);
case Header:
return request.headers().asMap();
case Cookie:
Collection<HttpCookie> cookies = request.cookies();
if (cookies.isEmpty()) {
return Collections.emptyMap();
}
Map<String, List<HttpCookie>> mapValue = CollectionUtils.newLinkedHashMap(cookies.size());
for (HttpCookie cookie : cookies) {
mapValue.computeIfAbsent(cookie.name(), k -> new ArrayList<>())
.add(cookie);
}
return mapValue;
case Attribute:
return request.attributes();
case Part:
Collection<FileUpload> parts = request.parts();
if (parts.isEmpty()) {
return Collections.emptyMap();
}
Map<String, FileUpload> result = new LinkedHashMap<>(parts.size());
for (FileUpload part : parts) {
result.put(part.name(), part);
}
return result;
case Body:
if (RequestUtils.isFormOrMultiPart(request)) {
return RequestUtils.getFormParametersMap(request);
}
return RequestUtils.decodeBody(request, meta.genericType());
}
return null;
}
private static String resolvePathVariable(NamedValueMeta meta, HttpRequest request) {
Map<String, String> variableMap = request.attribute(RestConstants.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
if (variableMap == null) {
if (meta.required()) {
throw new RestParameterException(Messages.ARGUMENT_VALUE_MISSING, meta.name(), meta.type());
}
return null;
}
String value = variableMap.get(meta.name());
if (value == null) {
return null;
}
int index = value.indexOf(';');
return RequestUtils.decodeURL(index == -1 ? value : value.substring(0, index));
}
private static List<String> resolveMatrixVariable(NamedValueMeta meta, HttpRequest request) {
Map<String, String> variableMap = request.attribute(RestConstants.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
return RequestUtils.parseMatrixVariableValues(variableMap, meta.name());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/basic/BasicRestToolKit.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/basic/BasicRestToolKit.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.support.basic;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.util.AbstractRestToolKit;
final class BasicRestToolKit extends AbstractRestToolKit {
private final BeanArgumentBinder binder;
public BasicRestToolKit(FrameworkModel frameworkModel) {
super(frameworkModel);
binder = new BeanArgumentBinder(argumentResolver);
}
@Override
public int getDialect() {
return RestConstants.DIALECT_BASIC;
}
@Override
public Object bind(ParameterMeta parameter, HttpRequest request, HttpResponse response) {
return binder.bind(parameter, request, response);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/basic/BasicRequestMappingResolver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/basic/BasicRequestMappingResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.support.basic;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.nested.RestConfig;
import org.apache.dubbo.remoting.http12.rest.Mapping;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.rest.cors.CorsUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMapping;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMapping.Builder;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMappingResolver;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.CorsMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ServiceMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RestToolKit;
import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils;
import java.lang.reflect.Method;
@Activate
public class BasicRequestMappingResolver implements RequestMappingResolver {
private final RestToolKit toolKit;
private RestConfig restConfig;
private CorsMeta globalCorsMeta;
public BasicRequestMappingResolver(FrameworkModel frameworkModel) {
toolKit = new BasicRestToolKit(frameworkModel);
}
@Override
public RestToolKit getRestToolKit() {
return toolKit;
}
@Override
public void setRestConfig(RestConfig restConfig) {
this.restConfig = restConfig;
}
@Override
public boolean accept(MethodMeta methodMeta) {
AnnotationMeta<Mapping> mapping = methodMeta.findAnnotation(Mapping.class);
return mapping != null ? mapping.getAnnotation().enabled() : methodMeta.getMethodDescriptor() != null;
}
@Override
public RequestMapping resolve(ServiceMeta serviceMeta) {
AnnotationMeta<Mapping> mapping = serviceMeta.findAnnotation(Mapping.class);
Builder builder = builder(mapping);
String[] paths = resolvePaths(mapping);
if (paths.length == 0) {
builder.path(serviceMeta.getServiceInterface());
} else {
builder.path(paths);
}
return builder.name(serviceMeta.getType().getSimpleName())
.contextPath(serviceMeta.getContextPath())
.build();
}
@Override
public RequestMapping resolve(MethodMeta methodMeta) {
Method method = methodMeta.getMethod();
AnnotationMeta<Mapping> mapping = methodMeta.findAnnotation(Mapping.class);
if (mapping != null) {
if (!mapping.getAnnotation().enabled()) {
return null;
}
} else {
Boolean enabled = restConfig.getEnableDefaultMapping();
if (enabled != null && !enabled) {
return null;
}
}
Builder builder = builder(mapping);
String[] paths = resolvePaths(mapping);
if (paths.length == 0) {
builder.path('/' + methodMeta.getMethodName()).sig(TypeUtils.buildSig(method));
} else {
builder.path(paths);
}
ServiceMeta serviceMeta = methodMeta.getServiceMeta();
if (globalCorsMeta == null) {
globalCorsMeta = CorsUtils.getGlobalCorsMeta(restConfig);
}
return builder.name(method.getName())
.service(serviceMeta.getServiceGroup(), serviceMeta.getServiceVersion())
.cors(globalCorsMeta)
.build();
}
private Builder builder(AnnotationMeta<?> mapping) {
Builder builder = RequestMapping.builder();
if (mapping == null) {
return builder;
}
builder.method(mapping.getStringArray("method"))
.param(mapping.getStringArray("params"))
.header(mapping.getStringArray("headers"))
.consume(mapping.getStringArray("consumes"))
.produce(mapping.getStringArray("produces"));
return builder;
}
private static String[] resolvePaths(AnnotationMeta<?> mapping) {
if (mapping == null) {
return StringUtils.EMPTY_STRING_ARRAY;
}
String[] paths = mapping.getStringArray("path");
if (paths.length > 0) {
return paths;
}
return mapping.getValueArray();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/basic/Annotations.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/basic/Annotations.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.support.basic;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationEnum;
import java.lang.annotation.Annotation;
public enum Annotations implements AnnotationEnum {
Mapping,
Param,
OpenAPI,
Operation,
Schema,
Nonnull("javax.annotation.Nonnull");
private final String className;
private Class<Annotation> type;
Annotations(String className) {
this.className = className;
}
Annotations() {
className = "org.apache.dubbo.remoting.http12.rest." + name();
}
public String className() {
return className;
}
@Override
public Class<Annotation> type() {
if (type == null) {
type = loadType();
}
return type;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/MethodWalker.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/MethodWalker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.util;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
public final class MethodWalker {
private final Set<Class<?>> classes = new LinkedHashSet<>();
private final Map<Key, List<Method>> methodsMap = new HashMap<>();
public void walk(Class<?> clazz, BiConsumer<Set<Class<?>>, Consumer<Consumer<List<Method>>>> visitor) {
if (clazz.getName().contains("$$")) {
clazz = clazz.getSuperclass();
}
walkHierarchy(clazz);
visitor.accept(classes, consumer -> {
for (Map.Entry<Key, List<Method>> entry : methodsMap.entrySet()) {
consumer.accept(entry.getValue());
}
});
}
private void walkHierarchy(Class<?> clazz) {
if (classes.isEmpty() || clazz.getDeclaredAnnotations().length > 0) {
classes.add(clazz);
}
for (Method method : clazz.getDeclaredMethods()) {
int modifiers = method.getModifiers();
if ((modifiers & (Modifier.PUBLIC | Modifier.STATIC)) == Modifier.PUBLIC) {
methodsMap
.computeIfAbsent(Key.of(method), k -> new ArrayList<>())
.add(method);
}
}
Class<?> superClass = clazz.getSuperclass();
if (superClass != null && superClass != Object.class) {
walkHierarchy(superClass);
}
for (Class<?> itf : clazz.getInterfaces()) {
walkHierarchy(itf);
}
}
private static final class Key {
private final String name;
private final Class<?>[] parameterTypes;
private Key(String name, Class<?>[] parameterTypes) {
this.name = name;
this.parameterTypes = parameterTypes;
}
private static Key of(Method method) {
return new Key(method.getName(), method.getParameterTypes());
}
@Override
@SuppressWarnings({"EqualsWhichDoesntCheckParameterClass", "EqualsDoesntCheckParameterClass"})
public boolean equals(Object obj) {
Key key = (Key) obj;
return name.equals(key.name) && Arrays.equals(parameterTypes, key.parameterTypes);
}
@Override
public int hashCode() {
int result = name.hashCode();
for (Class<?> type : parameterTypes) {
result = 31 * result + type.hashCode();
}
return result;
}
@Override
public String toString() {
return name + Arrays.toString(parameterTypes);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/RequestUtils.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/RequestUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.util;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.exception.DecodeException;
import org.apache.dubbo.remoting.http12.exception.EncodeException;
import org.apache.dubbo.remoting.http12.message.HttpMessageDecoder;
import org.apache.dubbo.remoting.http12.message.MediaType;
import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
public final class RequestUtils {
public static final String EMPTY_BODY = "";
private RequestUtils() {}
public static boolean isRestRequest(HttpRequest request) {
return request != null && request.hasAttribute(RestConstants.PATH_ATTRIBUTE);
}
public static boolean isMultiPart(HttpRequest request) {
String contentType = request.contentType();
return contentType != null && contentType.startsWith(MediaType.MULTIPART_FORM_DATA.getName());
}
public static boolean isFormOrMultiPart(HttpRequest request) {
String contentType = request.contentType();
if (contentType == null) {
return false;
}
return contentType.startsWith(MediaType.APPLICATION_FROM_URLENCODED.getName())
|| contentType.startsWith(MediaType.MULTIPART_FORM_DATA.getName());
}
public static String decodeURL(String value) {
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new DecodeException(e);
}
}
public static String encodeURL(String value) {
try {
return URLEncoder.encode(value, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new EncodeException(e);
}
}
public static Map<String, List<String>> getParametersMap(HttpRequest request) {
Collection<String> paramNames = request.parameterNames();
if (paramNames.isEmpty()) {
return Collections.emptyMap();
}
Map<String, List<String>> params = CollectionUtils.newLinkedHashMap(paramNames.size());
for (String paramName : paramNames) {
params.put(paramName, request.parameterValues(paramName));
}
return params;
}
public static Map<String, List<String>> getFormParametersMap(HttpRequest request) {
Collection<String> paramNames = request.formParameterNames();
if (paramNames.isEmpty()) {
return Collections.emptyMap();
}
Map<String, List<String>> params = CollectionUtils.newLinkedHashMap(paramNames.size());
for (String paramName : paramNames) {
params.put(paramName, request.formParameterValues(paramName));
}
return params;
}
public static Map<String, Object> getParametersMapStartingWith(HttpRequest request, String prefix) {
Collection<String> paramNames = request.parameterNames();
if (paramNames.isEmpty()) {
return Collections.emptyMap();
}
if (prefix == null) {
prefix = StringUtils.EMPTY_STRING;
}
Map<String, Object> params = CollectionUtils.newLinkedHashMap(paramNames.size());
for (String paramName : paramNames) {
if (prefix.isEmpty() || paramName.startsWith(prefix)) {
String name = paramName.substring(prefix.length());
List<String> values = request.parameterValues(paramName);
if (CollectionUtils.isEmpty(values)) {
continue;
}
params.put(name, values.size() == 1 ? values.get(0) : values);
}
}
return params;
}
public static String getPathVariable(HttpRequest request, String name) {
Map<String, String> variableMap = request.attribute(RestConstants.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
if (variableMap == null) {
return null;
}
String value = variableMap.get(name);
if (value == null) {
return null;
}
int index = value.indexOf(';');
return decodeURL(index == -1 ? value : value.substring(0, index));
}
public static Map<String, List<String>> parseMatrixVariables(String matrixVariables) {
Map<String, List<String>> result = null;
StringTokenizer pairs = new StringTokenizer(matrixVariables, ";");
while (pairs.hasMoreTokens()) {
String pair = pairs.nextToken();
int index = pair.indexOf('=');
if (index == -1) {
if (result == null) {
result = new LinkedHashMap<>();
}
result.computeIfAbsent(pair, k -> new ArrayList<>()).add(StringUtils.EMPTY_STRING);
continue;
}
String name = pair.substring(0, index);
if ("jsessionid".equalsIgnoreCase(name)) {
continue;
}
if (result == null) {
result = new LinkedHashMap<>();
}
for (String value : StringUtils.tokenize(pair.substring(index + 1), ',')) {
result.computeIfAbsent(name, k -> new ArrayList<>()).add(decodeURL(value));
}
}
return result;
}
public static List<String> parseMatrixVariableValues(Map<String, String> variableMap, String name) {
if (variableMap == null) {
return Collections.emptyList();
}
List<String> result = null;
for (Map.Entry<String, String> entry : variableMap.entrySet()) {
Map<String, List<String>> matrixVariables = parseMatrixVariables(entry.getValue());
if (matrixVariables == null) {
continue;
}
List<String> values = matrixVariables.get(name);
if (values == null) {
continue;
}
if (result == null) {
result = new ArrayList<>();
}
result.addAll(values);
}
return result == null ? Collections.emptyList() : result;
}
public static Object decodeBody(HttpRequest request, Type type) {
HttpMessageDecoder decoder = request.attribute(RestConstants.BODY_DECODER_ATTRIBUTE);
if (decoder == null) {
return null;
}
if (decoder.mediaType().isPureText()) {
type = String.class;
}
InputStream is = request.inputStream();
try {
int available = is.available();
if (available == 0) {
if (type instanceof Class) {
Class<?> clazz = (Class<?>) type;
if (clazz == String.class) {
return EMPTY_BODY;
}
if (clazz == byte[].class) {
return new byte[0];
}
}
return null;
}
} catch (IOException e) {
throw new DecodeException("Error reading is", e);
}
boolean canMark = is.markSupported();
try {
if (canMark) {
is.mark(Integer.MAX_VALUE);
}
return decoder.decode(is, type, request.charsetOrDefault());
} finally {
try {
if (canMark) {
is.reset();
} else {
is.close();
}
} catch (IOException ignored) {
}
}
}
public static Object decodeBodyAsObject(HttpRequest request) {
Object value = request.attribute(RestConstants.BODY_ATTRIBUTE);
if (value == null) {
value = decodeBody(request, Object.class);
if (value != null) {
request.setAttribute(RestConstants.BODY_ATTRIBUTE, value);
}
}
return value;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/KeyString.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/KeyString.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.util;
import java.nio.charset.StandardCharsets;
import io.netty.util.internal.MathUtil;
import io.netty.util.internal.PlatformDependent;
/**
* Zero-copy string as map key.
*/
public final class KeyString implements CharSequence {
public static final KeyString EMPTY = new KeyString("");
private final byte[] value;
private final int offset;
private final int length;
private final boolean caseSensitive;
private int hash;
public KeyString(CharSequence value) {
this(value, false);
}
public KeyString(CharSequence value, boolean caseSensitive) {
this.value = toBytes(value);
offset = 0;
length = this.value.length;
this.caseSensitive = caseSensitive;
}
private KeyString(byte[] value, int start, int end, boolean caseSensitive) {
this.value = value;
offset = start;
length = end - start;
this.caseSensitive = caseSensitive;
}
@Override
public int length() {
return length;
}
@Override
public char charAt(int index) {
if (index < 0 || index >= length) {
throw new IndexOutOfBoundsException("index: " + index + " must be in the range [0," + length + ")");
}
return (char) (PlatformDependent.getByte(value, index + offset) & 0xFF);
}
public byte[] array() {
return value;
}
public int offset() {
return offset;
}
public KeyString subSequence(int start) {
return subSequence(start, length);
}
public KeyString subSequence(int start, int end) {
int len = length;
if (end < 0) {
end = len;
}
if (MathUtil.isOutOfBounds(start, end - start, len)) {
throw new IndexOutOfBoundsException(
"expected: 0 <= start(" + start + ") <= end (" + end + ") <= len(" + len + ')');
}
if (start == 0 && end == len) {
return this;
}
if (end == start) {
return EMPTY;
}
return new KeyString(value, start + offset, end + offset, caseSensitive);
}
public int indexOf(char ch, int start) {
if (ch < 256) {
if (start < 0) {
start = 0;
}
byte b = (byte) ch;
byte[] value = this.value;
int offset = this.offset;
for (int i = start + offset, len = length + offset; i < len; i++) {
if (value[i] == b) {
return i - offset;
}
}
}
return -1;
}
public int lastIndexOf(char ch, int start) {
if (ch < 256) {
if (start < 0 || start >= length) {
start = length - 1;
}
byte b = (byte) ch;
byte[] value = this.value;
int offset = this.offset;
for (int i = offset + start; i >= offset; i--) {
if (value[i] == b) {
return i - offset;
}
}
}
return -1;
}
public boolean regionMatches(int start, KeyString other) {
return regionMatches(start, other, 0, other.length());
}
public boolean regionMatches(int start, KeyString other, int otherStart, int length) {
if (other == null) {
throw new NullPointerException("other");
}
if (otherStart < 0 || length > other.length() - otherStart) {
return false;
}
if (start < 0 || length > length() - start) {
return false;
}
if (caseSensitive) {
return PlatformDependent.equals(value, offset, other.value, other.offset, length);
}
byte[] value = this.value, otherValue = other.value;
byte a, b;
for (int i = start + offset, j = otherStart + other.offset, end = i + length; i < end; i++, j++) {
a = value[i];
b = otherValue[j];
if (a == b || toLowerCase(a) == toLowerCase(b)) {
continue;
}
return false;
}
return true;
}
@Override
public int hashCode() {
int h = hash;
if (h == 0) {
h = PlatformDependent.hashCodeAscii(value, offset, length);
hash = h;
}
return h;
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != KeyString.class) {
return false;
}
if (this == obj) {
return true;
}
KeyString other = (KeyString) obj;
int len = length;
if (len != other.length) {
return false;
}
if (caseSensitive) {
return PlatformDependent.equals(value, offset, other.value, other.offset, len);
}
byte[] value = this.value, otherValue = other.value;
byte a, b;
for (int i = offset, j = other.offset, end = i + len; i < end; i++, j++) {
a = value[i];
b = otherValue[j];
if (a == b || toLowerCase(a) == toLowerCase(b)) {
continue;
}
return false;
}
return true;
}
@Override
public String toString() {
return toString(0, length);
}
public String toString(int start) {
return toString(start, length);
}
@SuppressWarnings("deprecation")
public String toString(int start, int end) {
int len = length;
if (end == -1) {
end = len;
}
int count = end - start;
if (count == 0) {
return "";
}
if (MathUtil.isOutOfBounds(start, count, len)) {
throw new IndexOutOfBoundsException(
"expected: " + "0 <= start(" + start + ") <= srcIdx + count(" + count + ") <= srcLen(" + len + ')');
}
return new String(value, 0, start + offset, count);
}
private static byte[] toBytes(CharSequence value) {
if (value.getClass() == String.class) {
return ((String) value).getBytes(StandardCharsets.ISO_8859_1);
}
int len = value.length();
byte[] array = PlatformDependent.allocateUninitializedArray(len);
for (int i = 0; i < len; i++) {
char c = value.charAt(i);
array[i] = (byte) (c > 255 ? '?' : c);
}
return array;
}
private static byte toLowerCase(byte value) {
return value >= 'A' && value <= 'Z' ? (byte) (value + 32) : value;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/PathUtils.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/PathUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.util;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.Messages;
import org.apache.dubbo.rpc.protocol.tri.rest.PathParserException;
import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.PathExpression;
import javax.annotation.Nonnull;
public final class PathUtils {
private PathUtils() {}
public static String getContextPath(URL url) {
String path = url.getPath();
if (path == null) {
return StringUtils.EMPTY_STRING;
}
int len = path.length();
if (len == 0) {
return StringUtils.EMPTY_STRING;
}
String ifName = url.getParameter(CommonConstants.INTERFACE_KEY);
if (ifName == null || path.equalsIgnoreCase(ifName)) {
return StringUtils.EMPTY_STRING;
}
int index = path.lastIndexOf(ifName);
if (index + ifName.length() == len) {
return path.substring(0, index - 1);
}
return path.charAt(len - 1) == '/' ? path.substring(0, len - 1) : path;
}
public static boolean isDirectPath(@Nonnull String path) {
boolean braceStart = false;
for (int i = 0, len = path.length(); i < len; i++) {
switch (path.charAt(i)) {
case '*':
case '?':
return false;
case '{':
braceStart = true;
continue;
case '}':
if (braceStart) {
return false;
}
break;
default:
}
}
return true;
}
public static String join(String path1, String path2) {
if (StringUtils.isEmpty(path1)) {
return StringUtils.isEmpty(path2) ? StringUtils.EMPTY_STRING : path2;
}
if (StringUtils.isEmpty(path2)) {
return path1;
}
if (path1.charAt(path1.length() - 1) == '/') {
if (path2.charAt(0) == '/') {
return path1 + path2.substring(1);
}
return path1 + path2;
}
if (path2.charAt(0) == '/') {
return path1 + path2;
}
return path1 + '/' + path2;
}
/**
* See
* <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/AntPathMatcher.html#combine(java.lang.String,java.lang.String)">AntPathMatcher#combine</a>
*/
public static String combine(@Nonnull String path1, @Nonnull String path2) {
if (path1.isEmpty()) {
return path2.isEmpty() ? StringUtils.EMPTY_STRING : path2;
}
if (path2.isEmpty()) {
return path1;
}
int len1 = path1.length();
char last1 = path1.charAt(len1 - 1);
if (len1 == 1) {
if (last1 == '/' || last1 == '*') {
return path2;
}
} else if (path1.indexOf('{') == -1) {
if (path1.indexOf('*') != -1) {
if (PathExpression.parse(path1).match(path2) != null) {
return path2;
}
}
int starDotPos1 = path1.lastIndexOf("*.");
if (starDotPos1 > -1) {
String ext1 = path1.substring(starDotPos1 + 1);
int dotPos2 = path2.lastIndexOf('.');
String file2, ext2;
if (dotPos2 == -1) {
file2 = path2;
ext2 = StringUtils.EMPTY_STRING;
} else {
file2 = path2.substring(0, dotPos2);
ext2 = path2.substring(dotPos2);
}
boolean ext1All = ext1.equals(".*") || ext1.isEmpty();
boolean ext2All = ext2.equals(".*") || ext2.isEmpty();
if (!ext1All && !ext2All) {
throw new PathParserException(Messages.CANNOT_COMBINE_PATHS, path1, path2);
}
return file2 + (ext1All ? ext2 : ext1);
}
}
if (last1 == '*' && path1.charAt(len1 - 2) == '/') {
path1 = path1.substring(0, len1 - 2);
}
boolean slash1 = last1 == '/';
boolean slash2 = path2.charAt(0) == '/';
if (slash2 && path2.length() > 1 && path2.charAt(1) == '/') {
return path2.substring(1);
}
if (slash1) {
return slash2 ? path1 + path2.substring(1) : path1 + path2;
}
if (slash2) {
return path1 + path2;
}
return path1 + '/' + path2;
}
public static String normalize(String contextPath, String path) {
if (StringUtils.isEmpty(contextPath)) {
return StringUtils.isEmpty(path) ? RestConstants.SLASH : normalize(path);
}
if (StringUtils.isEmpty(path)) {
return normalize(contextPath);
}
if (path.charAt(0) != '/') {
contextPath += '/';
}
return normalize(contextPath + path);
}
public static String normalize(@Nonnull String path) {
int len = path.length();
if (len == 0) {
return RestConstants.SLASH;
}
int state = State.INITIAL;
int start = -1, end = 0;
StringBuilder buf = null;
out:
for (int i = 0; i < len; i++) {
char c = path.charAt(i);
switch (c) {
case ' ':
case '\t':
case '\n':
case '\r':
continue;
case '/':
switch (state) {
case State.SLASH:
if (start != -1) {
if (buf == null) {
buf = new StringBuilder(len);
}
buf.append(path, start, i);
}
start = -1;
continue;
case State.DOT:
state = State.SLASH;
if (buf == null) {
buf = new StringBuilder(len);
}
buf.append(path, start, i - 1);
start = -1;
continue;
case State.DOT_DOT:
state = State.SLASH;
if (buf == null) {
buf = new StringBuilder(len);
}
if (end > 2) {
buf.append(path, start, i - 2);
int bLen = buf.length();
if (bLen > 1) {
int index = buf.lastIndexOf(RestConstants.SLASH, bLen - 2);
if (!"/../".equals(buf.substring(index))) {
buf.setLength(index + 1);
start = -1;
continue;
}
}
}
buf.append(path, start, i + 1);
start = -1;
continue;
default:
state = State.SLASH;
break;
}
break;
case '.':
switch (state) {
case State.INITIAL:
if (buf == null) {
buf = new StringBuilder(len);
}
buf.append('/');
case State.SLASH:
state = State.DOT;
break;
case State.DOT:
state = State.DOT_DOT;
break;
case State.DOT_DOT:
state = State.NORMAL;
break;
default:
}
break;
case '?':
case '#':
break out;
default:
switch (state) {
case State.INITIAL:
if (buf == null) {
buf = new StringBuilder(len);
}
buf.append('/');
case State.SLASH:
case State.DOT:
case State.DOT_DOT:
state = State.NORMAL;
break;
default:
}
break;
}
if (start == -1) {
start = i;
}
end = i;
}
switch (state) {
case State.DOT:
end--;
break;
case State.DOT_DOT:
if (buf == null) {
buf = new StringBuilder(len);
}
if (end > 2) {
buf.append(path, start, end - 2);
buf.setLength(buf.lastIndexOf(RestConstants.SLASH) + 1);
start = -1;
}
break;
default:
}
if (buf == null) {
return start == -1 ? path : path.substring(start, end + 1);
}
if (start != -1) {
buf.append(path, start, end + 1);
}
return buf.toString();
}
private interface State {
int INITIAL = 0;
int NORMAL = 1;
int SLASH = 2;
int DOT = 3;
int DOT_DOT = 4;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/RestToolKit.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/RestToolKit.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.util;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import javax.annotation.Nullable;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Map;
public interface RestToolKit {
int getDialect();
String resolvePlaceholders(String text);
Object convert(Object value, ParameterMeta parameter);
Object bind(ParameterMeta parameter, HttpRequest request, HttpResponse response);
NamedValueMeta getNamedValueMeta(ParameterMeta parameter);
@Nullable
String[] getParameterNames(Method method);
@Nullable
String[] getParameterNames(Constructor<?> ctor);
Map<String, Object> getAttributes(AnnotatedElement element, Annotation annotation);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/RestUtils.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/RestUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.util;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.lang.Prioritized;
import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestExtension;
import java.util.function.Function;
public final class RestUtils {
private RestUtils() {}
public static boolean hasPlaceholder(String text) {
if (text == null) {
return false;
}
int len = text.length();
if (len < 4) {
return false;
}
int state = 0;
for (int i = 0; i < len; i++) {
char c = text.charAt(i);
if (c == '$') {
state = 1;
} else if (c == '{') {
if (state == 1) {
if (text.charAt(i - 1) != '$') {
return false;
}
state = 2;
}
} else if (c == '}' && state == 2) {
return true;
}
}
return false;
}
public static String replacePlaceholder(String text, Function<String, String> resolver) {
if (text == null) {
return null;
}
int len = text.length();
if (len < 2) {
return text;
}
int p = 0, nameStart = 0, nameEnd = 0, valueStart = 0, valueEnd = 0;
String value;
StringBuilder buf = null;
int state = State.START;
for (int i = 0; i < len; i++) {
char c = text.charAt(i);
switch (c) {
case '$':
if (state == State.START) {
if (buf == null) {
buf = new StringBuilder(len);
}
buf.append(text, p, i);
p = i;
state = State.DOLLAR;
} else if (state == State.DOLLAR) {
if (buf == null) {
buf = new StringBuilder(len);
}
buf.append(text, p, i - 1);
p = i;
state = State.START;
}
break;
case '{':
state = state == State.DOLLAR ? State.BRACE_OPEN : State.START;
break;
case ':':
state = state == State.NAME_START ? State.COLON : State.START;
break;
case '}':
switch (state) {
case State.DOLLAR:
case State.BRACE_OPEN:
state = State.START;
break;
case State.COLON:
state = State.START;
valueStart = i;
break;
case State.DOLLAR_NAME_START:
case State.NAME_START:
case State.VALUE_START:
value = resolver.apply(text.substring(nameStart, nameEnd));
if (buf == null) {
buf = new StringBuilder(len);
}
if (value == null) {
if (state == State.VALUE_START) {
buf.append(text, valueStart, valueEnd);
} else {
buf.append(text, p, i + 1);
}
} else {
buf.append(value);
}
p = i + 1;
state = State.START;
break;
default:
}
break;
case ' ':
case '\t':
case '\n':
case '\r':
if (state == State.DOLLAR_NAME_START) {
state = State.START;
value = resolver.apply(text.substring(nameStart, nameEnd));
if (buf == null) {
buf = new StringBuilder(len);
}
if (value == null) {
buf.append(text, p, i);
} else {
buf.append(value);
}
p = i;
}
break;
default:
switch (state) {
case State.DOLLAR:
state = State.DOLLAR_NAME_START;
nameStart = i;
break;
case State.BRACE_OPEN:
state = State.NAME_START;
nameStart = i;
break;
case State.COLON:
state = State.VALUE_START;
valueStart = i;
break;
case State.DOLLAR_NAME_START:
case State.NAME_START:
nameEnd = i + 1;
break;
case State.VALUE_START:
valueEnd = i + 1;
break;
default:
}
}
}
if (state == State.DOLLAR_NAME_START) {
value = resolver.apply(text.substring(nameStart, nameEnd));
if (buf == null) {
buf = new StringBuilder(len);
}
if (value == null) {
buf.append(text, p, len);
} else {
buf.append(value);
}
} else {
if (buf == null) {
return text;
}
buf.append(text, p, len);
}
return buf.toString();
}
private interface State {
int START = 0;
int DOLLAR = 1;
int BRACE_OPEN = 2;
int COLON = 3;
int DOLLAR_NAME_START = 4;
int NAME_START = 5;
int VALUE_START = 6;
}
public static boolean isMaybeJSONObject(String str) {
if (str == null) {
return false;
}
int i = 0, n = str.length();
if (n < 3) {
return false;
}
char expected = 0;
for (; i < n; i++) {
char c = str.charAt(i);
if (Character.isWhitespace(c)) {
continue;
}
if (c == '{') {
expected = '}';
break;
}
return false;
}
for (int j = n - 1; j > i; j--) {
char c = str.charAt(j);
if (Character.isWhitespace(c)) {
continue;
}
return c == expected;
}
return false;
}
public static int getPriority(Object obj) {
if (obj instanceof Prioritized) {
int priority = ((Prioritized) obj).getPriority();
if (priority != 0) {
return priority;
}
}
Activate activate = obj.getClass().getAnnotation(Activate.class);
return activate == null ? 0 : activate.order();
}
public static String[] getPattens(Object obj) {
return obj instanceof RestExtension ? ((RestExtension) obj).getPatterns() : null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/AbstractRestToolKit.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/AbstractRestToolKit.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.util;
import org.apache.dubbo.common.utils.AnnotationUtils;
import org.apache.dubbo.common.utils.DefaultParameterNameReader;
import org.apache.dubbo.common.utils.ParameterNameReader;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.rest.Messages;
import org.apache.dubbo.rpc.protocol.tri.rest.RestException;
import org.apache.dubbo.rpc.protocol.tri.rest.argument.CompositeArgumentResolver;
import org.apache.dubbo.rpc.protocol.tri.rest.argument.GeneralTypeConverter;
import org.apache.dubbo.rpc.protocol.tri.rest.argument.TypeConverter;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import javax.annotation.Nullable;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Map;
public abstract class AbstractRestToolKit implements RestToolKit {
protected final FrameworkModel frameworkModel;
protected final TypeConverter typeConverter;
protected final ParameterNameReader parameterNameReader;
protected final CompositeArgumentResolver argumentResolver;
public AbstractRestToolKit(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
typeConverter = frameworkModel.getOrRegisterBean(GeneralTypeConverter.class);
parameterNameReader = frameworkModel.getOrRegisterBean(DefaultParameterNameReader.class);
argumentResolver = frameworkModel.getOrRegisterBean(CompositeArgumentResolver.class);
}
@Override
public String resolvePlaceholders(String text) {
return RestUtils.replacePlaceholder(text, k -> frameworkModel
.defaultApplication()
.modelEnvironment()
.getConfiguration()
.getString(k));
}
@Override
public Object convert(Object value, ParameterMeta parameter) {
Object target = typeConverter.convert(value, parameter.getGenericType());
if (target == null && value != null) {
throw new RestException(
Messages.ARGUMENT_CONVERT_ERROR,
parameter.getName(),
value,
value.getClass(),
parameter.getGenericType());
}
return target;
}
@Override
public NamedValueMeta getNamedValueMeta(ParameterMeta parameter) {
return argumentResolver.getNamedValueMeta(parameter);
}
@Override
public String[] getParameterNames(Method method) {
return parameterNameReader.readParameterNames(method);
}
@Nullable
@Override
public String[] getParameterNames(Constructor<?> ctor) {
return parameterNameReader.readParameterNames(ctor);
}
@Override
public Map<String, Object> getAttributes(AnnotatedElement element, Annotation annotation) {
return AnnotationUtils.getAttributes(annotation, false);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/TypeUtils.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/TypeUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.util;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.net.InetAddress;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.time.ZoneId;
import java.time.temporal.Temporal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Currency;
import java.util.Date;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Pattern;
public final class TypeUtils {
private static final Set<Class<?>> SIMPLE_TYPES = new ConcurrentHashSet<>();
private static final List<String> SYSTEM_PREFIXES = new CopyOnWriteArrayList<>();
static {
Collections.addAll(
SIMPLE_TYPES,
Void.class,
void.class,
String.class,
URI.class,
URL.class,
UUID.class,
Locale.class,
Currency.class,
Pattern.class,
Class.class);
Collections.addAll(SYSTEM_PREFIXES, "java.", "javax.", "sun.", "com.sun.", "com.google.protobuf.");
}
private TypeUtils() {}
public static boolean isSimpleProperty(Class<?> type) {
return type == null || isSimpleValueType(type) || type.isArray() && isSimpleValueType(type.getComponentType());
}
private static boolean isSimpleValueType(Class<?> type) {
if (type.isPrimitive() || ClassUtils.isPrimitiveWrapper(type)) {
return true;
}
if (SIMPLE_TYPES.contains(type)) {
return true;
}
if (Enum.class.isAssignableFrom(type)
|| CharSequence.class.isAssignableFrom(type)
|| Number.class.isAssignableFrom(type)
|| Date.class.isAssignableFrom(type)
|| Temporal.class.isAssignableFrom(type)
|| ZoneId.class.isAssignableFrom(type)
|| TimeZone.class.isAssignableFrom(type)
|| File.class.isAssignableFrom(type)
|| Path.class.isAssignableFrom(type)
|| Charset.class.isAssignableFrom(type)
|| InetAddress.class.isAssignableFrom(type)) {
SIMPLE_TYPES.add(type);
return true;
}
return false;
}
public static void addSimpleTypes(Class<?>... types) {
SIMPLE_TYPES.addAll(Arrays.asList(types));
}
public static List<String> getSystemPrefixes() {
return SYSTEM_PREFIXES;
}
public static void addSystemPrefixes(String... prefixes) {
for (String prefix : prefixes) {
if (StringUtils.isNotEmpty(prefix)) {
SYSTEM_PREFIXES.add(prefix);
}
}
}
public static boolean isSystemType(Class<?> type) {
String name = type.getName();
List<String> systemPrefixes = getSystemPrefixes();
for (int i = systemPrefixes.size() - 1; i >= 0; i--) {
String prefix = systemPrefixes.get(i);
if (prefix.charAt(0) == '!') {
if (name.regionMatches(0, prefix, 1, prefix.length() - 1)) {
return false;
}
} else if (name.startsWith(prefix)) {
return true;
}
}
return false;
}
public static boolean isWrapperType(Class<?> type) {
return type == Optional.class || type == CompletableFuture.class || type == StreamObserver.class;
}
public static Class<?> getMapValueType(Class<?> targetClass) {
for (Type gi : targetClass.getGenericInterfaces()) {
if (gi instanceof ParameterizedType) {
ParameterizedType type = (ParameterizedType) gi;
if (type.getRawType() == Map.class) {
return getActualType(type.getActualTypeArguments()[1]);
}
}
}
return null;
}
public static Class<?> getSuperGenericType(Class<?> clazz, int index) {
Class<?> result = getNestedActualType(clazz.getGenericSuperclass(), index);
return result == null ? getNestedActualType(ArrayUtils.first(clazz.getGenericInterfaces()), index) : result;
}
public static Class<?> getSuperGenericType(Class<?> clazz) {
return getSuperGenericType(clazz, 0);
}
public static Class<?>[] getNestedActualTypes(Type type) {
if (type instanceof ParameterizedType) {
Type[] typeArgs = ((ParameterizedType) type).getActualTypeArguments();
int len = typeArgs.length;
Class<?>[] nestedTypes = new Class<?>[len];
for (int i = 0; i < len; i++) {
nestedTypes[i] = getActualType(typeArgs[i]);
}
return nestedTypes;
}
return null;
}
public static Class<?> getNestedActualType(Type type, int index) {
if (type instanceof ParameterizedType) {
Type[] typeArgs = ((ParameterizedType) type).getActualTypeArguments();
if (index < typeArgs.length) {
return getActualType(typeArgs[index]);
}
}
return null;
}
public static Class<?> getActualType(Type type) {
if (type instanceof Class) {
return (Class<?>) type;
}
if (type instanceof ParameterizedType) {
return getActualType(((ParameterizedType) type).getRawType());
}
if (type instanceof TypeVariable) {
return getActualType(((TypeVariable<?>) type).getBounds()[0]);
}
if (type instanceof WildcardType) {
return getActualType(((WildcardType) type).getUpperBounds()[0]);
}
if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
return Array.newInstance(getActualType(componentType), 0).getClass();
}
return null;
}
public static Type getNestedGenericType(Type type, int index) {
if (type instanceof ParameterizedType) {
Type[] typeArgs = ((ParameterizedType) type).getActualTypeArguments();
if (index < typeArgs.length) {
return getActualGenericType(typeArgs[index]);
}
}
return null;
}
public static Type getActualGenericType(Type type) {
if (type instanceof TypeVariable) {
return ((TypeVariable<?>) type).getBounds()[0];
}
if (type instanceof WildcardType) {
return ((WildcardType) type).getUpperBounds()[0];
}
return type;
}
public static Object nullDefault(Class<?> targetClass) {
if (targetClass == long.class) {
return 0L;
}
if (targetClass == int.class) {
return 0;
}
if (targetClass == boolean.class) {
return Boolean.FALSE;
}
if (targetClass == double.class) {
return 0D;
}
if (targetClass == float.class) {
return 0F;
}
if (targetClass == byte.class) {
return (byte) 0;
}
if (targetClass == short.class) {
return (short) 0;
}
if (targetClass == char.class) {
return (char) 0;
}
if (targetClass == Optional.class) {
return Optional.empty();
}
return null;
}
public static Object longToObject(long value, Class<?> targetClass) {
if (targetClass == Long.class) {
return value;
}
if (targetClass == Integer.class) {
return (int) value;
}
if (targetClass == Short.class) {
return (short) value;
}
if (targetClass == Character.class) {
return (char) value;
}
if (targetClass == Byte.class) {
return (byte) value;
}
return null;
}
@SuppressWarnings("rawtypes")
public static Collection createCollection(Class targetClass) {
if (targetClass.isInterface()) {
if (targetClass == List.class || targetClass == Collection.class) {
return new ArrayList<>();
}
if (targetClass == Set.class) {
return new HashSet<>();
}
if (targetClass == SortedSet.class) {
return new LinkedHashSet<>();
}
if (targetClass == Queue.class || targetClass == Deque.class) {
return new LinkedList<>();
}
} else if (Collection.class.isAssignableFrom(targetClass)) {
if (targetClass == ArrayList.class) {
return new ArrayList<>();
}
if (targetClass == LinkedList.class) {
return new LinkedList();
}
if (targetClass == HashSet.class) {
return new HashSet<>();
}
if (targetClass == LinkedHashSet.class) {
return new LinkedHashSet<>();
}
if (!Modifier.isAbstract(targetClass.getModifiers())) {
try {
Constructor sizeCt = null;
for (Constructor ct : targetClass.getConstructors()) {
switch (ct.getParameterCount()) {
case 0:
return (Collection) ct.newInstance();
case 1:
if (ct.getParameterTypes()[0] == int.class) {
sizeCt = ct;
}
break;
default:
}
}
if (sizeCt != null) {
return (Collection) sizeCt.newInstance(16);
}
} catch (Exception ignored) {
}
}
}
throw new IllegalArgumentException("Unsupported collection type: " + targetClass.getName());
}
@SuppressWarnings("rawtypes")
public static Map createMap(Class targetClass) {
if (targetClass.isInterface()) {
if (targetClass == Map.class) {
return new HashMap<>();
}
if (targetClass == ConcurrentMap.class) {
return new ConcurrentHashMap<>();
}
if (SortedMap.class.isAssignableFrom(targetClass)) {
return new TreeMap<>();
}
} else if (Map.class.isAssignableFrom(targetClass)) {
if (targetClass == HashMap.class) {
return new HashMap<>();
}
if (targetClass == LinkedHashMap.class) {
return new LinkedHashMap<>();
}
if (targetClass == TreeMap.class) {
return new TreeMap<>();
}
if (targetClass == ConcurrentHashMap.class) {
return new ConcurrentHashMap<>();
}
if (!Modifier.isAbstract(targetClass.getModifiers())) {
try {
Constructor sizeCt = null;
for (Constructor ct : targetClass.getConstructors()) {
if (Modifier.isPublic(ct.getModifiers())) {
switch (ct.getParameterCount()) {
case 0:
return (Map) ct.newInstance();
case 1:
if (ct.getParameterTypes()[0] == int.class) {
sizeCt = ct;
}
break;
default:
}
}
}
if (sizeCt != null) {
return (Map) sizeCt.newInstance(16);
}
} catch (Throwable ignored) {
}
}
}
throw new IllegalArgumentException("Unsupported map type: " + targetClass.getName());
}
public static String buildSig(Method method) {
if (method.getParameterCount() == 0) {
return null;
}
StringBuilder sb = new StringBuilder(8);
for (Class<?> type : method.getParameterTypes()) {
String name = type.getName();
sb.append(name.charAt(name.lastIndexOf('.') + 1));
}
return sb.toString();
}
public static String toTypeString(Type type) {
if (type instanceof Class) {
Class<?> clazz = (Class<?>) type;
return clazz.isArray() ? clazz.getComponentType().getName() + "[]" : clazz.getName();
}
StringBuilder result = new StringBuilder(32);
buildGenericTypeString(type, result);
return result.toString();
}
private static void buildGenericTypeString(Type type, StringBuilder sb) {
if (type instanceof Class<?>) {
Class<?> clazz = (Class<?>) type;
if (clazz.isArray()) {
buildGenericTypeString(clazz.getComponentType(), sb);
sb.append("[]");
} else {
sb.append(clazz.getName());
}
} else if (type instanceof ParameterizedType) {
ParameterizedType pzType = (ParameterizedType) type;
Type[] typeArgs = pzType.getActualTypeArguments();
buildGenericTypeString(pzType.getRawType(), sb);
sb.append('<');
for (int i = 0, len = typeArgs.length; i < len; i++) {
if (i > 0) {
sb.append(", ");
}
buildGenericTypeString(typeArgs[i], sb);
}
sb.append('>');
} else if (type instanceof WildcardType) {
WildcardType wildcardType = (WildcardType) type;
Type[] upperBounds = wildcardType.getUpperBounds();
Type[] lowerBounds = wildcardType.getLowerBounds();
if (lowerBounds.length > 0) {
sb.append("? super ");
buildGenericTypeString(lowerBounds[0], sb);
} else if (upperBounds.length > 0 && upperBounds[0] != Object.class) {
sb.append("? extends ");
buildGenericTypeString(upperBounds[0], sb);
} else {
sb.append('?');
}
} else if (type instanceof GenericArrayType) {
GenericArrayType genericArrayType = (GenericArrayType) type;
buildGenericTypeString(genericArrayType.getGenericComponentType(), sb);
sb.append("[]");
} else if (type instanceof TypeVariable) {
TypeVariable<?> typeVariable = (TypeVariable<?>) type;
sb.append(typeVariable.getName());
Type[] bounds = typeVariable.getBounds();
int len = bounds.length;
if (len > 0 && !(len == 1 && bounds[0] == Object.class)) {
sb.append(" extends ");
for (int i = 0; i < len; i++) {
if (i > 0) {
sb.append(" & ");
}
buildGenericTypeString(bounds[i], sb);
}
}
} else {
sb.append(type.toString());
}
}
public static Object getMethodDescriptor(MethodMeta methodMeta) {
StringBuilder sb = new StringBuilder(64);
sb.append(toTypeString(methodMeta.getGenericReturnType()))
.append(' ')
.append(methodMeta.getMethod().getName())
.append('(');
ParameterMeta[] parameters = methodMeta.getParameters();
for (int i = 0, len = parameters.length; i < len; i++) {
if (i > 0) {
sb.append(", ");
}
ParameterMeta paramMeta = parameters[i];
String name = paramMeta.getName();
sb.append(toTypeString(paramMeta.getGenericType())).append(' ');
if (name == null) {
sb.append("arg").append(i + 1);
} else {
sb.append(name);
}
}
sb.append(')');
return sb.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/RestExtensionExecutionFilter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/RestExtensionExecutionFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.beans.support.InstantiationStrategy;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.extension.ExtensionAccessorAware;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.ClassUtils;
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.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.protocol.tri.ExceptionUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.Messages;
import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants;
import org.apache.dubbo.rpc.protocol.tri.rest.RestInitializeException;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RadixTree;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RadixTree.Match;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RestUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
@Activate(group = CommonConstants.PROVIDER, order = 1000)
public class RestExtensionExecutionFilter extends RestFilterAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(RestExtensionExecutionFilter.class);
private static final String KEY = RestExtensionExecutionFilter.class.getSimpleName();
private static final String REST_FILTER_CACHE = "REST_FILTER_CACHE";
private final Map<RestFilter, RadixTree<Boolean>> filterTreeCache = CollectionUtils.newConcurrentHashMap();
private final ApplicationModel applicationModel;
private final List<RestExtensionAdapter<Object>> extensionAdapters;
@SuppressWarnings({"unchecked", "rawtypes"})
public RestExtensionExecutionFilter(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
extensionAdapters = (List) applicationModel.getActivateExtensions(RestExtensionAdapter.class);
}
@Override
protected Result invoke(Invoker<?> invoker, Invocation invocation, HttpRequest request, HttpResponse response)
throws RpcException {
RestFilter[] filters = matchFilters(getFilters(invoker), request.path());
DefaultFilterChain chain = new DefaultFilterChain(filters, invocation, () -> invoker.invoke(invocation));
invocation.put(KEY, chain);
try {
Result result = chain.execute(request, response);
if (result != null) {
return result;
}
Object body = response.body();
if (body instanceof Throwable) {
response.setBody(null);
return AsyncRpcResult.newDefaultAsyncResult((Throwable) body, invocation);
}
if (body instanceof CompletableFuture) {
CompletableFuture<?> future = (CompletableFuture<?>) body;
response.setBody(null);
return new AsyncRpcResult(
future.handleAsync((v, t) -> {
AppResponse r = new AppResponse(invocation);
if (t != null) {
r.setException(t);
} else {
r.setValue(v);
}
return r;
}),
invocation);
}
return AsyncRpcResult.newDefaultAsyncResult(invocation);
} catch (Throwable t) {
throw ExceptionUtils.wrap(t);
}
}
@Override
protected void onResponse(
Result result, Invoker<?> invoker, Invocation invocation, HttpRequest request, HttpResponse response) {
DefaultFilterChain chain = (DefaultFilterChain) invocation.get(KEY);
if (chain == null) {
return;
}
chain.onResponse(result, request, response);
if (result.hasException()) {
Object body = response.body();
if (body != null) {
if (body instanceof Throwable) {
result.setException((Throwable) body);
} else {
result.setValue(body);
result.setException(null);
}
response.setBody(null);
}
}
}
@Override
protected void onError(
Throwable t, Invoker<?> invoker, Invocation invocation, HttpRequest request, HttpResponse response) {
DefaultFilterChain chain = (DefaultFilterChain) invocation.get(KEY);
if (chain == null) {
return;
}
chain.onError(t, request, response);
}
private RestFilter[] matchFilters(RestFilter[] filters, String path) {
int len = filters.length;
BitSet bitSet = new BitSet(len);
for (int i = 0; i < len; i++) {
RestFilter filter = filters[i];
String[] patterns = filter.getPatterns();
if (ArrayUtils.isEmpty(patterns)) {
continue;
}
RadixTree<Boolean> filterTree = filterTreeCache.computeIfAbsent(filter, f -> {
RadixTree<Boolean> tree = new RadixTree<>();
for (String pattern : patterns) {
if (StringUtils.isNotEmpty(pattern)) {
if (pattern.charAt(0) == '!') {
tree.addPath(pattern.substring(1), false);
} else {
tree.addPath(pattern, true);
}
}
}
return tree;
});
List<Match<Boolean>> matches = filterTree.match(path);
int size = matches.size();
if (size > 0) {
if (size > 1) {
Collections.sort(matches);
}
if (matches.get(0).getValue()) {
continue;
}
}
bitSet.set(i);
}
if (bitSet.isEmpty()) {
return filters;
}
RestFilter[] matched = new RestFilter[len - bitSet.cardinality()];
for (int i = 0, j = 0; i < len; i++) {
if (!bitSet.get(i)) {
matched[j++] = filters[i];
}
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Matched filters for path '{}' is {}", path, Arrays.toString(matched));
}
return matched;
}
private RestFilter[] getFilters(Invoker<?> invoker) {
return UrlUtils.computeServiceAttribute(invoker.getUrl(), REST_FILTER_CACHE, this::loadFilters);
}
private RestFilter[] loadFilters(URL url) {
List<RestFilter> extensions = new ArrayList<>();
// 1. load from extension config
String extensionConfig = url.getParameter(RestConstants.EXTENSION_KEY);
InstantiationStrategy strategy = new InstantiationStrategy(() -> applicationModel);
for (String className : StringUtils.tokenize(extensionConfig)) {
try {
Object extension = strategy.instantiate(ClassUtils.loadClass(className));
if (extension instanceof ExtensionAccessorAware) {
((ExtensionAccessorAware) extension).setExtensionAccessor(applicationModel);
}
adaptExtension(extension, extensions);
} catch (Throwable t) {
throw new RestInitializeException(t, Messages.EXTENSION_INIT_FAILED, className, url);
}
}
// 2. load from extension loader
List<RestExtension> restExtensions = applicationModel
.getExtensionLoader(RestExtension.class)
.getActivateExtension(url, RestConstants.REST_FILTER_KEY);
for (RestExtension extension : restExtensions) {
adaptExtension(extension, extensions);
}
// 3. sorts by order
extensions.sort(Comparator.comparingInt(RestUtils::getPriority));
LOGGER.info("Rest filters for [{}] loaded: {}", url, extensions);
return extensions.toArray(new RestFilter[0]);
}
private void adaptExtension(Object extension, List<RestFilter> extensions) {
if (extension instanceof Supplier) {
extension = ((Supplier<?>) extension).get();
}
if (extension instanceof RestFilter) {
addRestFilter(extension, (RestFilter) extension, extensions);
return;
}
for (RestExtensionAdapter<Object> adapter : extensionAdapters) {
if (adapter.accept(extension)) {
addRestFilter(extension, adapter.adapt(extension), extensions);
}
}
}
private void addRestFilter(Object extension, RestFilter filter, List<RestFilter> extensions) {
extensions.add(filter);
if (!LOGGER.isInfoEnabled()) {
return;
}
StringBuilder sb = new StringBuilder(64);
sb.append("Rest filter [").append(extension).append("] loaded");
if (filter.getPriority() != 0) {
sb.append(", priority=").append(filter.getPriority());
}
if (ArrayUtils.isNotEmpty(filter.getPatterns())) {
sb.append(", patterns=").append(Arrays.toString(filter.getPatterns()));
}
LOGGER.info(sb.toString());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/RestExtensionAdapter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/RestExtensionAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.filter;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface RestExtensionAdapter<T> {
boolean accept(Object extension);
RestFilter adapt(T extension);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/RestHeaderFilterAdapter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/RestHeaderFilterAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.filter;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.rpc.HeaderFilter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.protocol.tri.TripleConstants;
public abstract class RestHeaderFilterAdapter implements HeaderFilter {
@Override
public RpcInvocation invoke(Invoker<?> invoker, RpcInvocation invocation) throws RpcException {
if (TripleConstants.TRIPLE_HANDLER_TYPE_REST.equals(invocation.get(TripleConstants.HANDLER_TYPE_KEY))) {
HttpRequest request = (HttpRequest) invocation.get(TripleConstants.HTTP_REQUEST_KEY);
HttpResponse response = (HttpResponse) invocation.get(TripleConstants.HTTP_RESPONSE_KEY);
invoke(invoker, invocation, request, response);
}
return invocation;
}
protected abstract void invoke(
Invoker<?> invoker, RpcInvocation invocation, HttpRequest request, HttpResponse response)
throws RpcException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/RestExtension.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/RestExtension.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.filter;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.lang.Prioritized;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface RestExtension extends Prioritized {
default String[] getPatterns() {
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/RestFilter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/RestFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.filter;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.rpc.Result;
import java.util.concurrent.CompletableFuture;
public interface RestFilter extends RestExtension {
default void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws Exception {
chain.doFilter(request, response);
}
interface Listener {
default void onResponse(Result result, HttpRequest request, HttpResponse response) throws Exception {}
default void onError(Throwable t, HttpRequest request, HttpResponse response) throws Exception {}
}
interface FilterChain {
void doFilter(HttpRequest request, HttpResponse response) throws Exception;
CompletableFuture<Boolean> doFilterAsync(HttpRequest request, HttpResponse response);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/AbstractRestFilter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/AbstractRestFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.filter;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RestUtils;
import java.util.Arrays;
public abstract class AbstractRestFilter<E> implements RestFilter {
protected final E extension;
public AbstractRestFilter(E extension) {
this.extension = extension;
}
@Override
public int getPriority() {
return RestUtils.getPriority(extension);
}
@Override
public String[] getPatterns() {
return RestUtils.getPattens(extension);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("RestFilter{extension=");
sb.append(extension);
int priority = getPriority();
if (priority != 0) {
sb.append(", priority=").append(priority);
}
String[] patterns = getPatterns();
if (ArrayUtils.isNotEmpty(patterns)) {
sb.append(", patterns=").append(Arrays.toString(patterns));
}
return sb.append('}').toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/DefaultFilterChain.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/DefaultFilterChain.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.filter;
import org.apache.dubbo.common.logger.FluentLogger;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter.FilterChain;
import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter.Listener;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
final class DefaultFilterChain implements FilterChain, Listener {
private static final FluentLogger LOGGER = FluentLogger.of(DefaultFilterChain.class);
private final RestFilter[] filters;
private final Invocation invocation;
private final Supplier<Result> action;
private int cursor;
private Result result;
private CompletableFuture<AppResponse> resultFuture;
DefaultFilterChain(RestFilter[] filters, Invocation invocation, Supplier<Result> action) {
this.filters = filters;
this.invocation = invocation;
this.action = action;
}
public Result execute(HttpRequest request, HttpResponse response) throws Exception {
doFilter(request, response);
return result;
}
@Override
public void doFilter(HttpRequest request, HttpResponse response) throws Exception {
if (cursor < filters.length) {
filters[cursor++].doFilter(request, response, this);
return;
}
if (resultFuture == null) {
result = action.get();
} else {
action.get().whenCompleteWithContext((r, e) -> {
if (e == null) {
resultFuture.complete(new AppResponse(r));
} else {
resultFuture.complete(new AppResponse(e));
}
});
}
}
@Override
public CompletableFuture<Boolean> doFilterAsync(HttpRequest request, HttpResponse response) {
if (resultFuture == null) {
resultFuture = new CompletableFuture<>();
result = new AsyncRpcResult(resultFuture, invocation);
}
CompletableFuture<Boolean> future = new CompletableFuture<>();
future.whenComplete((v, t) -> {
if (t == null) {
if (v != null && v) {
try {
doFilter(request, response);
} catch (Exception e) {
resultFuture.complete(new AppResponse(e));
}
} else {
resultFuture.complete(new AppResponse());
}
} else {
resultFuture.complete(new AppResponse(t));
}
});
return future;
}
@Override
public void onResponse(Result result, HttpRequest request, HttpResponse response) {
for (int i = cursor - 1; i > -1; i--) {
RestFilter filter = filters[i];
if (filter instanceof Listener) {
try {
((Listener) filter).onResponse(result, request, response);
} catch (Throwable t) {
LOGGER.internalError("Call onResponse for filter [{}] error", filter);
}
}
}
}
@Override
public void onError(Throwable t, HttpRequest request, HttpResponse response) {
for (int i = cursor - 1; i > -1; i--) {
RestFilter filter = filters[i];
if (filter instanceof Listener) {
try {
((Listener) filter).onError(t, request, response);
} catch (Throwable th) {
LOGGER.internalError("Call onError for filter [{}] error", filter);
}
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/RestFilterAdapter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/RestFilterAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.filter;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.rpc.BaseFilter;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.protocol.tri.TripleConstants;
public abstract class RestFilterAdapter implements Filter, BaseFilter.Listener {
@Override
public final Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
if (TripleConstants.TRIPLE_HANDLER_TYPE_REST.equals(invocation.get(TripleConstants.HANDLER_TYPE_KEY))) {
HttpRequest request = (HttpRequest) invocation.get(TripleConstants.HTTP_REQUEST_KEY);
HttpResponse response = (HttpResponse) invocation.get(TripleConstants.HTTP_RESPONSE_KEY);
return invoke(invoker, invocation, request, response);
}
return invoker.invoke(invocation);
}
@Override
public final void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
if (TripleConstants.TRIPLE_HANDLER_TYPE_REST.equals(invocation.get(TripleConstants.HANDLER_TYPE_KEY))) {
HttpRequest request = (HttpRequest) invocation.get(TripleConstants.HTTP_REQUEST_KEY);
HttpResponse response = (HttpResponse) invocation.get(TripleConstants.HTTP_RESPONSE_KEY);
onResponse(appResponse, invoker, invocation, request, response);
}
}
@Override
public final void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
if (TripleConstants.TRIPLE_HANDLER_TYPE_REST.equals(invocation.get(TripleConstants.HANDLER_TYPE_KEY))) {
HttpRequest request = (HttpRequest) invocation.get(TripleConstants.HTTP_REQUEST_KEY);
HttpResponse response = (HttpResponse) invocation.get(TripleConstants.HTTP_RESPONSE_KEY);
onError(t, invoker, invocation, request, response);
}
}
protected abstract Result invoke(
Invoker<?> invoker, Invocation invocation, HttpRequest request, HttpResponse response) throws RpcException;
protected void onResponse(
Result result, Invoker<?> invoker, Invocation invocation, HttpRequest request, HttpResponse response) {}
protected void onError(
Throwable t, Invoker<?> invoker, Invocation invocation, HttpRequest request, HttpResponse response) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/cors/CorsHeaderFilter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/cors/CorsHeaderFilter.java | /*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.cors;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.HttpConstants;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.remoting.http12.HttpResult;
import org.apache.dubbo.remoting.http12.HttpStatus;
import org.apache.dubbo.remoting.http12.exception.HttpResultPayloadException;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants;
import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestHeaderFilterAdapter;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMapping;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.CorsMeta;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
/**
* See: <a href="https://github.com/spring-projects/spring-framework/blob/main/spring-web/src/main/java/org/springframework/web/cors/DefaultCorsProcessor.java">DefaultCorsProcessor</a>
*/
@Activate(group = CommonConstants.PROVIDER, order = 1000)
public class CorsHeaderFilter extends RestHeaderFilterAdapter {
public static final String VARY = "vary";
public static final String ORIGIN = "origin";
public static final String ACCESS_CONTROL_REQUEST_METHOD = "access-control-request-method";
public static final String ACCESS_CONTROL_REQUEST_HEADERS = "access-control-request-headers";
public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "access-control-allow-credentials";
public static final String ACCESS_CONTROL_EXPOSE_HEADERS = "access-control-expose-headers";
public static final String ACCESS_CONTROL_MAX_AGE = "access-control-max-age";
public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "access-control-allow-origin";
public static final String ACCESS_CONTROL_ALLOW_METHODS = "access-control-allow-methods";
public static final String ACCESS_CONTROL_ALLOW_HEADERS = "access-control-allow-headers";
public static final String SEP = ", ";
@Override
protected void invoke(
Invoker<?> invoker,
RpcInvocation invocation,
HttpRequest request,
HttpResponse response) throws RpcException {
RequestMapping mapping = request.attribute(RestConstants.MAPPING_ATTRIBUTE);
CorsMeta cors = mapping.getCors();
String origin = request.header(ORIGIN);
if (cors == null) {
if (isPreFlightRequest(request, origin)) {
throw new HttpResultPayloadException(HttpResult.builder()
.status(HttpStatus.FORBIDDEN)
.body("Invalid CORS request")
.build());
}
return;
}
if (process(cors, request, response)) {
return;
}
throw new HttpResultPayloadException(HttpResult.builder()
.status(HttpStatus.FORBIDDEN)
.body("Invalid CORS request")
.headers(response.headers())
.build());
}
private boolean process(CorsMeta cors, HttpRequest request, HttpResponse response) {
setVaryHeader(response);
String origin = request.header(ORIGIN);
if (isNotCorsRequest(request, origin)) {
return true;
}
if (response.header(ACCESS_CONTROL_ALLOW_ORIGIN) != null) {
return true;
}
String allowOrigin = checkOrigin(cors, origin);
if (allowOrigin == null) {
return false;
}
boolean preFlight = isPreFlightRequest(request, origin);
List<String> allowMethods = checkMethods(cors, preFlight ? request.header(ACCESS_CONTROL_REQUEST_METHOD) : request.method());
if (allowMethods == null) {
return false;
}
List<String> allowHeaders = null;
if (preFlight) {
allowHeaders = checkHeaders(cors, request.headerValues(ACCESS_CONTROL_REQUEST_HEADERS));
if (allowHeaders == null) {
return false;
}
}
response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, allowOrigin);
if (ArrayUtils.isNotEmpty(cors.getExposedHeaders())) {
response.setHeader(ACCESS_CONTROL_EXPOSE_HEADERS, StringUtils.join(cors.getExposedHeaders(), SEP));
}
if (Boolean.TRUE.equals(cors.getAllowCredentials())) {
response.setHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, Boolean.TRUE.toString());
}
if (preFlight) {
response.setHeader(ACCESS_CONTROL_ALLOW_METHODS, StringUtils.join(allowMethods, SEP));
if (!allowHeaders.isEmpty()) {
response.setHeader(ACCESS_CONTROL_ALLOW_HEADERS, StringUtils.join(allowHeaders, SEP));
}
if (cors.getMaxAge() != null) {
response.setHeader(ACCESS_CONTROL_MAX_AGE, cors.getMaxAge().toString());
}
throw new HttpResultPayloadException(HttpResult.builder()
.status(HttpStatus.NO_CONTENT)
.headers(response.headers())
.build());
}
return true;
}
private static void setVaryHeader(HttpResponse response) {
List<String> varyHeaders = response.headerValues(VARY);
String varyValue;
if (varyHeaders == null) {
varyValue = ORIGIN + SEP + ACCESS_CONTROL_REQUEST_METHOD + SEP + ACCESS_CONTROL_REQUEST_HEADERS;
} else {
Set<String> varHeadersSet = new LinkedHashSet<>(varyHeaders);
varHeadersSet.add(ORIGIN);
varHeadersSet.add(ACCESS_CONTROL_REQUEST_METHOD);
varHeadersSet.add(ACCESS_CONTROL_REQUEST_HEADERS);
varyValue = StringUtils.join(varHeadersSet, SEP);
}
response.setHeader(VARY, varyValue);
}
private static String checkOrigin(CorsMeta cors, String origin) {
if (StringUtils.isBlank(origin)) {
return null;
}
origin = CorsUtils.formatOrigin(origin);
String[] allowedOrigins = cors.getAllowedOrigins();
if (ArrayUtils.isNotEmpty(allowedOrigins)) {
if (ArrayUtils.contains(allowedOrigins, ANY_VALUE)) {
if (Boolean.TRUE.equals(cors.getAllowCredentials())) {
throw new IllegalArgumentException("When allowCredentials is true, allowedOrigins cannot contain the special value \"*\"");
}
return ANY_VALUE;
}
for (String allowedOrigin : allowedOrigins) {
if (origin.equalsIgnoreCase(allowedOrigin)) {
return origin;
}
}
}
if (ArrayUtils.isNotEmpty(cors.getAllowedOriginsPatterns())) {
for (Pattern pattern : cors.getAllowedOriginsPatterns()) {
if (pattern.matcher(origin).matches()) {
return origin;
}
}
}
return null;
}
private static List<String> checkMethods(CorsMeta cors, String method) {
if (method == null) {
return null;
}
String[] allowedMethods = cors.getAllowedMethods();
if (ArrayUtils.contains(allowedMethods, ANY_VALUE)) {
return Collections.singletonList(method);
}
for (String allowedMethod : allowedMethods) {
if (method.equalsIgnoreCase(allowedMethod)) {
return Arrays.asList(allowedMethods);
}
}
return null;
}
private static List<String> checkHeaders(CorsMeta cors, Collection<String> headers) {
if (headers == null || headers.isEmpty()) {
return Collections.emptyList();
}
String[] allowedHeaders = cors.getAllowedHeaders();
if (ArrayUtils.isEmpty(allowedHeaders)) {
return null;
}
boolean allowAny = ArrayUtils.contains(allowedHeaders, ANY_VALUE);
List<String> result = new ArrayList<>(headers.size());
for (String header : headers) {
if (allowAny) {
result.add(header);
continue;
}
for (String allowedHeader : allowedHeaders) {
if (header.equalsIgnoreCase(allowedHeader)) {
result.add(header);
break;
}
}
}
return result.isEmpty() ? null : result;
}
private static boolean isNotCorsRequest(HttpRequest request, String origin) {
if (origin == null) {
return true;
}
try {
URI uri = new URI(origin);
return request.scheme().equals(uri.getScheme()) && request.serverName().equals(uri.getHost())
&& getPort(request.scheme(), request.serverPort()) == getPort(uri.getScheme(), uri.getPort());
} catch (URISyntaxException e) {
return false;
}
}
private static boolean isPreFlightRequest(HttpRequest request, String origin) {
return HttpMethods.OPTIONS.is(request.method())
&& origin != null
&& request.hasHeader(ACCESS_CONTROL_REQUEST_METHOD);
}
private static int getPort(String scheme, int port) {
if (port == -1) {
if (HttpConstants.HTTP.equals(scheme)) {
return 80;
}
if (HttpConstants.HTTPS.equals(scheme)) {
return 443;
}
}
return port;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/cors/CorsUtils.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/cors/CorsUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.cors;
import org.apache.dubbo.config.nested.CorsConfig;
import org.apache.dubbo.config.nested.RestConfig;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.CorsMeta;
public class CorsUtils {
private CorsUtils() {}
public static CorsMeta getGlobalCorsMeta(RestConfig restConfig) {
CorsConfig config = restConfig.getCorsOrDefault();
return CorsMeta.builder()
.allowedOrigins(config.getAllowedOrigins())
.allowedMethods(config.getAllowedMethods())
.allowedHeaders(config.getAllowedHeaders())
.allowCredentials(config.getAllowCredentials())
.exposedHeaders(config.getExposedHeaders())
.maxAge(config.getMaxAge())
.build();
}
public static String formatOrigin(String value) {
value = value.trim();
int last = value.length() - 1;
return last > -1 && value.charAt(last) == '/' ? value.substring(0, last) : value;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/AbstractArgumentResolver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/AbstractArgumentResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.argument;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
public abstract class AbstractArgumentResolver extends NamedValueArgumentResolverSupport implements ArgumentResolver {
@Override
public Object resolve(ParameterMeta parameter, HttpRequest request, HttpResponse response) {
return resolve(getNamedValueMeta(parameter), request, response);
}
public final NamedValueMeta getNamedValueMeta(ParameterMeta parameter) {
return cache.computeIfAbsent(parameter, k -> updateNamedValueMeta(k, createNamedValueMeta(k)));
}
protected abstract NamedValueMeta createNamedValueMeta(ParameterMeta parameter);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/ArgumentConverter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/ArgumentConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.argument;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface ArgumentConverter<S, T> {
T convert(S value, ParameterMeta parameter);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/AbstractAnnotationBaseArgumentResolver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/AbstractAnnotationBaseArgumentResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.argument;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import java.lang.annotation.Annotation;
public abstract class AbstractAnnotationBaseArgumentResolver extends NamedValueArgumentResolverSupport
implements AnnotationBaseArgumentResolver<Annotation> {
@Override
public Object resolve(
ParameterMeta parameter,
AnnotationMeta<Annotation> annotation,
HttpRequest request,
HttpResponse response) {
return resolve(getNamedValueMeta(parameter, annotation), request, response);
}
@Override
public final NamedValueMeta getNamedValueMeta(ParameterMeta parameter, AnnotationMeta<Annotation> annotation) {
return cache.computeIfAbsent(parameter, k -> updateNamedValueMeta(k, createNamedValueMeta(k, annotation)));
}
protected abstract NamedValueMeta createNamedValueMeta(ParameterMeta param, AnnotationMeta<Annotation> anno);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/CompositeArgumentResolver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/CompositeArgumentResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.argument;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.remoting.http12.rest.ParamType;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.rest.Messages;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings({"rawtypes", "unchecked"})
public final class CompositeArgumentResolver implements ArgumentResolver {
private final Map<Class, AnnotationBaseArgumentResolver> resolverMap = new HashMap<>();
private final ArgumentResolver[] resolvers;
private final ArgumentConverter argumentConverter;
public CompositeArgumentResolver(FrameworkModel frameworkModel) {
List<ArgumentResolver> extensions = frameworkModel.getActivateExtensions(ArgumentResolver.class);
List<ArgumentResolver> resolvers = new ArrayList<>(extensions.size());
for (ArgumentResolver resolver : extensions) {
if (resolver instanceof AnnotationBaseArgumentResolver) {
AnnotationBaseArgumentResolver aar = (AnnotationBaseArgumentResolver) resolver;
resolverMap.put(aar.accept(), aar);
} else {
resolvers.add(resolver);
}
}
this.resolvers = resolvers.toArray(new ArgumentResolver[0]);
argumentConverter = new CompositeArgumentConverter(frameworkModel);
}
public ArgumentConverter getArgumentConverter() {
return argumentConverter;
}
@Override
public boolean accept(ParameterMeta parameter) {
return true;
}
@Override
public Object resolve(ParameterMeta parameter, HttpRequest request, HttpResponse response) {
for (AnnotationMeta annotation : parameter.findAnnotations()) {
AnnotationBaseArgumentResolver resolver = resolverMap.get(annotation.getAnnotationType());
if (resolver != null) {
Object value = resolver.resolve(parameter, annotation, request, response);
return argumentConverter.convert(value, parameter);
}
}
for (ArgumentResolver resolver : resolvers) {
if (resolver.accept(parameter)) {
Object value = resolver.resolve(parameter, request, response);
return argumentConverter.convert(value, parameter);
}
}
throw new IllegalStateException(Messages.ARGUMENT_COULD_NOT_RESOLVED.format(parameter.getDescription()));
}
public NamedValueMeta getNamedValueMeta(ParameterMeta parameter) {
for (AnnotationMeta annotation : parameter.findAnnotations()) {
AnnotationBaseArgumentResolver resolver = resolverMap.get(annotation.getAnnotationType());
if (resolver != null) {
return resolver.getNamedValueMeta(parameter, annotation);
}
}
for (ArgumentResolver resolver : resolvers) {
if (resolver.accept(parameter)) {
if (resolver instanceof AbstractArgumentResolver) {
return ((AbstractArgumentResolver) resolver).getNamedValueMeta(parameter);
} else {
return new NamedValueMeta().setParamType(ParamType.Attribute);
}
}
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/AnnotationBaseArgumentResolver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/AnnotationBaseArgumentResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.argument;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import java.lang.annotation.Annotation;
public interface AnnotationBaseArgumentResolver<T extends Annotation> extends ArgumentResolver {
Class<T> accept();
NamedValueMeta getNamedValueMeta(ParameterMeta parameter, AnnotationMeta<Annotation> annotation);
Object resolve(ParameterMeta parameter, AnnotationMeta<T> annotation, HttpRequest request, HttpResponse response);
default boolean accept(ParameterMeta parameter) {
return true;
}
@Override
default Object resolve(ParameterMeta parameter, HttpRequest request, HttpResponse response) {
throw new UnsupportedOperationException("Resolve without annotation is unsupported");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/MiscArgumentResolver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/MiscArgumentResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.argument;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
@Activate
public class MiscArgumentResolver implements ArgumentResolver {
private static final Set<Class<?>> SUPPORTED_TYPES = new HashSet<>();
static {
SUPPORTED_TYPES.add(HttpRequest.class);
SUPPORTED_TYPES.add(HttpResponse.class);
SUPPORTED_TYPES.add(HttpMethods.class);
SUPPORTED_TYPES.add(Locale.class);
SUPPORTED_TYPES.add(InputStream.class);
SUPPORTED_TYPES.add(OutputStream.class);
}
@Override
public boolean accept(ParameterMeta parameter) {
return SUPPORTED_TYPES.contains(parameter.getActualType());
}
@Override
public Object resolve(ParameterMeta parameter, HttpRequest request, HttpResponse response) {
Class<?> type = parameter.getActualType();
if (type == HttpRequest.class) {
return request;
}
if (type == HttpResponse.class) {
return response;
}
if (type == HttpMethods.class) {
return HttpMethods.of(request.method());
}
if (type == Locale.class) {
return request.locale();
}
if (type == InputStream.class) {
return request.inputStream();
}
if (type == OutputStream.class) {
return response.outputStream();
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/ArgumentResolver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/ArgumentResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.argument;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface ArgumentResolver {
boolean accept(ParameterMeta parameter);
Object resolve(ParameterMeta parameter, HttpRequest request, HttpResponse response);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/GeneralTypeConverter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/GeneralTypeConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.argument;
import org.apache.dubbo.common.io.StreamUtils;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.DateUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.HttpCookie;
import org.apache.dubbo.remoting.http12.HttpJsonUtils;
import org.apache.dubbo.remoting.http12.HttpRequest.FileUpload;
import org.apache.dubbo.remoting.http12.HttpUtils;
import org.apache.dubbo.remoting.http12.message.MediaType;
import org.apache.dubbo.remoting.http12.message.codec.CodecUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.ExceptionUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.RestParameterException;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.StringReader;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.URI;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.TemporalAccessor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Currency;
import java.util.Date;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.Properties;
import java.util.Queue;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Pattern;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.dubbo.common.utils.StringUtils.tokenizeToList;
import static org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils.getActualGenericType;
import static org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils.getActualType;
import static org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils.nullDefault;
@SuppressWarnings({"unchecked", "rawtypes"})
public class GeneralTypeConverter implements TypeConverter {
private static final Logger LOGGER = LoggerFactory.getLogger(GeneralTypeConverter.class);
private final CompositeArgumentConverter converter;
private final CodecUtils codecUtils;
private final HttpJsonUtils httpJsonUtils;
public GeneralTypeConverter(FrameworkModel frameworkModel) {
converter = frameworkModel.getOrRegisterBean(CompositeArgumentConverter.class);
codecUtils = frameworkModel.getOrRegisterBean(CodecUtils.class);
httpJsonUtils = frameworkModel.getOrRegisterBean(HttpJsonUtils.class);
}
@Override
public <T> T convert(Object source, Class<T> targetClass) {
try {
return targetClass == null ? (T) source : (T) doConvert(source, targetClass);
} catch (Exception e) {
throw ExceptionUtils.wrap(e);
}
}
@Override
public <T> T convert(Object source, Type targetType) {
try {
return targetType == null ? (T) source : (T) doConvert(source, targetType);
} catch (Exception e) {
throw ExceptionUtils.wrap(e);
}
}
private <T> Object doConvert(Object source, Class<T> targetClass) throws Exception {
if (source == null) {
return nullDefault(targetClass);
}
if (targetClass.isInstance(source)) {
return source;
}
if (targetClass == Optional.class) {
return Optional.of(source);
}
Class sourceClass = source.getClass();
if (sourceClass == Optional.class) {
source = ((Optional<?>) source).orElse(null);
if (source == null) {
return nullDefault(targetClass);
}
if (targetClass.isInstance(source)) {
return source;
}
}
Object target = customConvert(source, targetClass);
if (target != null) {
return target;
}
if (source instanceof CharSequence) {
String str = source.toString();
if (targetClass == String.class) {
return str;
}
if (str.isEmpty() || "null".equals(str) || "NULL".equals(str)) {
return emptyDefault(targetClass);
}
switch (targetClass.getName()) {
case "java.lang.Double":
case "double":
return Double.valueOf(str);
case "java.lang.Float":
case "float":
return Float.valueOf(str);
case "java.lang.Long":
case "long":
return isHexNumber(str) ? Long.decode(str) : Long.valueOf(str);
case "java.lang.Integer":
case "int":
return isHexNumber(str) ? Integer.decode(str) : Integer.valueOf(str);
case "java.lang.Short":
case "short":
return isHexNumber(str) ? Short.decode(str) : Short.valueOf(str);
case "java.lang.Character":
case "char":
if (str.length() == 1) {
return str.charAt(0);
}
throw new RestParameterException("Can not convert String(" + str + ") to char, must only 1 char");
case "java.lang.Byte":
case "byte":
return isHexNumber(str) ? Byte.decode(str) : Byte.valueOf(str);
case "java.lang.Boolean":
return toBoolean(str);
case "boolean":
return toBoolean(str) == Boolean.TRUE;
case "java.math.BigInteger":
return new BigInteger(str);
case "java.math.BigDecimal":
return new BigDecimal(str);
case "java.lang.Number":
return str.indexOf('.') == -1 ? doConvert(str, Long.class) : doConvert(str, Double.class);
case "java.util.Date":
return DateUtils.parse(str);
case "java.util.Calendar":
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(DateUtils.parse(str).getTime());
return cal;
case "java.sql.Timestamp":
return new Timestamp(DateUtils.parse(str).getTime());
case "java.time.Instant":
return DateUtils.parse(str).toInstant();
case "java.time.ZonedDateTime":
return toZonedDateTime(str);
case "java.time.LocalDate":
return toZonedDateTime(str).toLocalDate();
case "java.time.LocalTime":
return toZonedDateTime(str).toLocalTime();
case "java.time.LocalDateTime":
return toZonedDateTime(str).toLocalDateTime();
case "java.time.ZoneId":
return TimeZone.getTimeZone(str).toZoneId();
case "java.util.TimeZone":
return TimeZone.getTimeZone(str);
case "java.io.File":
return new File(str);
case "java.nio.file.Path":
return Paths.get(str);
case "java.nio.charset.Charset":
return Charset.forName(str);
case "java.net.InetAddress":
return InetAddress.getByName(str);
case "java.net.URI":
return new URI(str);
case "java.net.URL":
return new URL(str);
case "java.util.UUID":
return UUID.fromString(str);
case "java.util.Locale":
String[] parts = StringUtils.tokenize(str, '-', '_');
switch (parts.length) {
case 2:
return new Locale(parts[0], parts[1]);
case 3:
return new Locale(parts[0], parts[1], parts[2]);
default:
return new Locale(parts[0]);
}
case "java.util.Currency":
return Currency.getInstance(str);
case "java.util.regex.Pattern":
return Pattern.compile(str);
case "java.lang.Class":
return ClassUtils.loadClass(str);
case "[B":
return str.getBytes(UTF_8);
case "[C":
return str.toCharArray();
case "java.util.OptionalInt":
return OptionalInt.of(isHexNumber(str) ? Integer.decode(str) : Integer.parseInt(str));
case "java.util.OptionalLong":
return OptionalLong.of(isHexNumber(str) ? Long.decode(str) : Long.parseLong(str));
case "java.util.OptionalDouble":
return OptionalDouble.of(Double.parseDouble(str));
case "java.util.Properties":
Properties properties = new Properties();
properties.load(new StringReader(str));
return properties;
default:
}
if (targetClass.isEnum()) {
try {
return Enum.valueOf((Class<Enum>) targetClass, str);
} catch (Exception ignored) {
}
}
target = jsonToObject(str, targetClass);
if (target != null) {
return target;
}
if (targetClass.isArray()) {
List<String> list = tokenizeToList(str);
int n = list.size();
Class itemType = targetClass.getComponentType();
if (itemType == String.class) {
return list.toArray(StringUtils.EMPTY_STRING_ARRAY);
}
Object arr = Array.newInstance(itemType, n);
for (int i = 0; i < n; i++) {
Array.set(arr, i, doConvert(list.get(i), itemType));
}
return arr;
} else if (Collection.class.isAssignableFrom(targetClass)) {
target = convertCollection(tokenizeToList(str), targetClass);
if (target != null) {
return target;
}
} else if (Map.class.isAssignableFrom(targetClass)) {
target = convertMap(tokenizeToMap(str), targetClass);
if (target != null) {
return target;
}
}
} else if (source instanceof Number) {
Number num = (Number) source;
switch (targetClass.getName()) {
case "java.lang.String":
return source.toString();
case "java.lang.Double":
case "double":
return num.doubleValue();
case "java.lang.Float":
case "float":
return num.floatValue();
case "java.lang.Long":
case "long":
return num.longValue();
case "java.lang.Integer":
case "int":
return num.intValue();
case "java.lang.Short":
case "short":
return num.shortValue();
case "java.lang.Character":
case "char":
return (char) num.intValue();
case "java.lang.Byte":
case "byte":
return num.byteValue();
case "java.lang.Boolean":
case "boolean":
return toBoolean(num);
case "java.math.BigInteger":
return BigInteger.valueOf(num.longValue());
case "java.math.BigDecimal":
return BigDecimal.valueOf(num.doubleValue());
case "java.util.Date":
return new Date(num.longValue());
case "java.util.Calendar":
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(num.longValue());
return cal;
case "java.sql.Timestamp":
return new Timestamp(num.longValue());
case "java.time.Instant":
return Instant.ofEpochMilli(num.longValue());
case "java.time.ZonedDateTime":
return toZonedDateTime(num);
case "java.time.LocalDate":
return toZonedDateTime(num).toLocalDate();
case "java.time.LocalTime":
return toZonedDateTime(num).toLocalTime();
case "java.time.LocalDateTime":
return toZonedDateTime(num).toLocalDateTime();
case "java.util.TimeZone":
return toTimeZone(num.intValue());
case "[B":
return toBytes(num);
case "[C":
return new char[] {(char) num.intValue()};
case "java.util.OptionalInt":
return OptionalInt.of(num.intValue());
case "java.util.OptionalLong":
return OptionalLong.of(num.longValue());
case "java.util.OptionalDouble":
return OptionalDouble.of(num.doubleValue());
default:
}
if (targetClass.isEnum()) {
for (T e : targetClass.getEnumConstants()) {
if (((Enum) e).ordinal() == num.intValue()) {
return e;
}
}
}
} else if (source instanceof Date) {
Date date = (Date) source;
switch (targetClass.getName()) {
case "java.lang.String":
return DateUtils.format(date);
case "java.lang.Long":
case "long":
return date.getTime();
case "java.lang.Integer":
case "int":
return (int) (date.getTime() / 1000);
case "java.util.Calendar":
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(date.getTime());
return cal;
case "java.time.Instant":
return date.toInstant();
case "java.time.ZonedDateTime":
return toZonedDateTime(date.getTime());
case "java.time.LocalDate":
return toZonedDateTime(date.getTime()).toLocalDate();
case "java.time.LocalTime":
return toZonedDateTime(date.getTime()).toLocalTime();
case "java.time.LocalDateTime":
return toZonedDateTime(date.getTime()).toLocalDateTime();
default:
}
} else if (source instanceof TemporalAccessor) {
return doConvert(DateUtils.toDate((TemporalAccessor) source), targetClass);
} else if (source instanceof Enum) {
Enum en = (Enum) source;
if (targetClass == String.class) {
return en.toString();
}
if (targetClass == int.class || targetClass == Integer.class) {
return en.ordinal();
}
if (Number.class.isAssignableFrom(targetClass)) {
return doConvert(en.ordinal(), targetClass);
}
if (targetClass.isEnum()) {
return Enum.valueOf((Class<Enum>) targetClass, en.name());
}
} else if (source instanceof byte[]) {
byte[] bytes = (byte[]) source;
if (bytes.length == 0) {
return emptyDefault(targetClass);
}
switch (targetClass.getName()) {
case "java.lang.String":
return new String(bytes, UTF_8);
case "java.lang.Double":
case "double":
return ByteBuffer.wrap(bytes).getDouble();
case "java.lang.Float":
case "float":
return ByteBuffer.wrap(bytes).getFloat();
case "java.lang.Long":
case "long":
return ByteBuffer.wrap(bytes).getLong();
case "java.lang.Integer":
case "int":
return ByteBuffer.wrap(bytes).getInt();
case "java.lang.Short":
case "short":
return ByteBuffer.wrap(bytes).getShort();
case "java.lang.Character":
case "char":
return ByteBuffer.wrap(bytes).getChar();
case "java.lang.Byte":
case "byte":
return bytes[0];
case "java.lang.Boolean":
case "boolean":
return bytes[0] == (byte) 0 ? Boolean.FALSE : Boolean.TRUE;
case "java.math.BigInteger":
return new BigInteger(bytes);
case "java.util.Properties":
Properties properties = new Properties();
properties.load(new ByteArrayInputStream(bytes));
return properties;
default:
}
target = jsonToObject(new String(bytes, StandardCharsets.ISO_8859_1), targetClass);
if (target != null) {
return target;
}
}
if (targetClass.isArray()) {
if (targetClass == byte[].class) {
if (source instanceof InputStream) {
try (InputStream is = (InputStream) source) {
return StreamUtils.readBytes(is);
}
}
if (source instanceof FileUpload) {
try (InputStream is = ((FileUpload) source).inputStream()) {
return StreamUtils.readBytes(is);
}
}
if (source instanceof Character) {
char c = (Character) source;
return new byte[] {(byte) (c >> 8), (byte) c};
}
if (source instanceof Boolean) {
boolean b = (Boolean) source;
return new byte[] {b ? (byte) 1 : (byte) 0};
}
}
Class itemType = targetClass.getComponentType();
if (source instanceof Collection) {
Collection c = (Collection) source;
int i = 0;
Object arr = Array.newInstance(itemType, c.size());
for (Object item : c) {
Array.set(arr, i++, item == null ? null : doConvert(item, itemType));
}
return arr;
}
if (source instanceof Iterable) {
List list = new ArrayList();
for (Object item : (Iterable) source) {
list.add(item == null ? null : doConvert(item, itemType));
}
return list.toArray((Object[]) Array.newInstance(itemType, 0));
}
if (sourceClass.isArray()) {
int len = Array.getLength(source);
Object arr = Array.newInstance(itemType, len);
for (int i = 0; i < len; i++) {
Object item = Array.get(source, i);
Array.set(arr, i, item == null ? null : doConvert(item, itemType));
}
return arr;
}
Object arr = Array.newInstance(itemType, 1);
Array.set(arr, 0, doConvert(source, itemType));
return arr;
}
if (Collection.class.isAssignableFrom(targetClass)) {
target = convertCollection(toCollection(source), targetClass);
if (target != null) {
return target;
}
}
if (Map.class.isAssignableFrom(targetClass) && source instanceof Map) {
target = convertMap((Map) source, targetClass);
if (target != null) {
return target;
}
}
if (sourceClass.isArray()) {
if (Array.getLength(source) == 0) {
return nullDefault(targetClass);
}
return doConvert(Array.get(source, 0), targetClass);
}
if (source instanceof List) {
List list = (List) source;
if (list.isEmpty()) {
return nullDefault(targetClass);
}
return doConvert(list.get(0), targetClass);
}
if (source instanceof Iterable) {
Iterator it = ((Iterable) source).iterator();
if (!it.hasNext()) {
return nullDefault(targetClass);
}
return doConvert(it.next(), targetClass);
}
if (targetClass == String.class) {
if (sourceClass == HttpCookie.class) {
return ((HttpCookie) source).value();
}
if (source instanceof InputStream) {
try (InputStream is = (InputStream) source) {
return StreamUtils.toString(is);
}
}
if (source instanceof FileUpload) {
FileUpload fu = (FileUpload) source;
try (InputStream is = fu.inputStream()) {
String contentType = fu.contentType();
if (contentType != null) {
int index = contentType.lastIndexOf(HttpUtils.CHARSET_PREFIX);
if (index > 0) {
return StreamUtils.toString(
is,
Charset.forName(
contentType.substring(index + 8).trim()));
}
}
return StreamUtils.toString(is);
}
}
return source.toString();
}
if (!Modifier.isAbstract(targetClass.getModifiers())) {
try {
for (Constructor ct : targetClass.getConstructors()) {
if (ct.getParameterCount() == 1) {
if (ct.getParameterTypes()[0].isAssignableFrom(sourceClass)) {
return ct.newInstance(source);
}
}
}
} catch (Throwable ignored) {
}
}
if (sourceClass == String.class) {
try {
Method valueOf = targetClass.getMethod("valueOf", String.class);
//noinspection JavaReflectionInvocation
return valueOf.invoke(null, source);
} catch (Throwable ignored) {
}
return null;
}
try {
return httpJsonUtils.convertObject(source, targetClass);
} catch (Throwable t) {
String msg = "JSON convert value '{}' from type [{}] to type [{}] failed";
LOGGER.debug(msg, source, sourceClass, targetClass, t);
}
return null;
}
private Object doConvert(Object source, Type targetType) throws Exception {
if (targetType instanceof Class) {
return doConvert(source, (Class) targetType);
}
if (source == null) {
return nullDefault(getActualType(targetType));
}
if (source.getClass() == Optional.class) {
source = ((Optional<?>) source).orElse(null);
if (source == null) {
return nullDefault(getActualType(targetType));
}
}
if (source instanceof CharSequence) {
String str = source.toString();
if (str.isEmpty() || "null".equals(str) || "NULL".equals(str)) {
return emptyDefault(getActualType(targetType));
}
Object target = jsonToObject(str, targetType);
if (target != null) {
return target;
}
}
if (targetType instanceof ParameterizedType) {
ParameterizedType type = (ParameterizedType) targetType;
Type rawType = type.getRawType();
if (rawType instanceof Class) {
Class targetClass = (Class) rawType;
Type[] argTypes = type.getActualTypeArguments();
if (Collection.class.isAssignableFrom(targetClass)) {
Type itemType = getActualGenericType(argTypes[0]);
if (itemType instanceof Class && targetClass.isInstance(source)) {
boolean same = true;
Class<?> itemClass = (Class<?>) itemType;
for (Object item : (Collection) source) {
if (item != null && !itemClass.isInstance(item)) {
same = false;
break;
}
}
if (same) {
return source;
}
}
Collection items = toCollection(source);
Collection targetItems = createCollection(targetClass, items.size());
for (Object item : items) {
targetItems.add(doConvert(item, itemType));
}
return targetItems;
}
if (Map.class.isAssignableFrom(targetClass)) {
Type keyType = argTypes[0];
Type valueType = argTypes[1];
if (keyType instanceof Class && valueType instanceof Class && targetClass.isInstance(source)) {
boolean same = true;
Class<?> keyClass = (Class<?>) keyType;
Class<?> valueClass = (Class<?>) valueType;
for (Map.Entry entry : ((Map<Object, Object>) source).entrySet()) {
Object key = entry.getKey();
if (key != null && !keyClass.isInstance(key)) {
same = false;
break;
}
Object value = entry.getValue();
if (value != null && !valueClass.isInstance(value)) {
same = false;
break;
}
}
if (same) {
return source;
}
}
Class<?> mapValueClass = TypeUtils.getMapValueType(targetClass);
boolean multiValue = mapValueClass != null && Collection.class.isAssignableFrom(mapValueClass);
if (source instanceof CharSequence) {
source = tokenizeToMap(source.toString());
}
if (source instanceof Map) {
Map<?, ?> map = (Map) source;
Map targetMap = createMap(targetClass, map.size());
for (Map.Entry entry : map.entrySet()) {
Object key = doConvert(entry.getKey(), keyType);
if (multiValue) {
Collection items = toCollection(entry.getValue());
Collection targetItems = createCollection(mapValueClass, items.size());
for (Object item : items) {
targetItems.add(doConvert(item, valueType));
}
targetMap.put(key, targetItems);
} else {
targetMap.put(key, doConvert(entry.getValue(), valueType));
}
}
return targetMap;
}
}
if (targetClass == Optional.class) {
return Optional.ofNullable(doConvert(source, argTypes[0]));
}
}
} else if (targetType instanceof TypeVariable) {
return doConvert(source, ((TypeVariable<?>) targetType).getBounds()[0]);
} else if (targetType instanceof WildcardType) {
return doConvert(source, ((WildcardType) targetType).getUpperBounds()[0]);
} else if (targetType instanceof GenericArrayType) {
Type itemType = ((GenericArrayType) targetType).getGenericComponentType();
Class<?> itemClass = getActualType(itemType);
Collection items = toCollection(source);
Object target = Array.newInstance(itemClass, items.size());
int i = 0;
for (Object item : items) {
Array.set(target, i++, doConvert(item, itemType));
}
return target;
}
try {
return httpJsonUtils.convertObject(source, targetType);
} catch (Throwable t) {
String msg = "JSON convert value '{}' from type [{}] to type [{}] failed";
LOGGER.debug(msg, source, source.getClass(), targetType, t);
}
return null;
}
protected Object customConvert(Object source, Class<?> targetClass) {
return converter.convert(source, targetClass);
}
protected Collection customCreateCollection(Class targetClass, int size) {
return (Collection) converter.convert(size, targetClass);
}
protected Map customCreateMap(Class targetClass, int size) {
return (Map) converter.convert(size, targetClass);
}
private Collection createCollection(Class targetClass, int size) {
if (targetClass.isInterface()) {
if (targetClass == List.class || targetClass == Collection.class) {
return new ArrayList<>(size);
}
if (targetClass == Set.class) {
return CollectionUtils.newHashSet(size);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/NamedValueArgumentResolverSupport.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/NamedValueArgumentResolverSupport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.argument;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.remoting.http12.rest.ParamType;
import org.apache.dubbo.rpc.protocol.tri.rest.Messages;
import org.apache.dubbo.rpc.protocol.tri.rest.RestParameterException;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
public abstract class NamedValueArgumentResolverSupport {
protected final Map<ParameterMeta, NamedValueMeta> cache = CollectionUtils.newConcurrentHashMap();
protected final Object resolve(NamedValueMeta meta, HttpRequest request, HttpResponse response) {
Class<?> type = meta.type();
if (type.isArray() || Collection.class.isAssignableFrom(type)) {
return resolveCollectionValue(meta, request, response);
}
if (Map.class.isAssignableFrom(type)) {
return resolveMapValue(meta, request, response);
}
Object arg = resolveValue(meta, request, response);
if (arg != null) {
return filterValue(arg, meta);
}
arg = meta.defaultValue();
if (arg != null) {
return arg;
}
if (meta.required()) {
throw new RestParameterException(Messages.ARGUMENT_VALUE_MISSING, meta.name(), type);
}
return null;
}
protected final NamedValueMeta updateNamedValueMeta(ParameterMeta parameter, NamedValueMeta meta) {
if (meta.isNameEmpty()) {
meta.setName(parameter.getName());
}
if (meta.paramType() == null) {
meta.setParamType(getParamType(meta));
}
Class<?> type = parameter.getActualType();
meta.setType(type);
meta.setGenericType(parameter.getActualGenericType());
if (type.isArray()) {
meta.setNestedTypes(new Class<?>[] {type});
} else {
meta.setNestedTypes(TypeUtils.getNestedActualTypes(meta.genericType()));
}
meta.setParameter(parameter);
return meta;
}
protected ParamType getParamType(NamedValueMeta meta) {
return null;
}
protected String emptyDefaultValue(NamedValueMeta meta) {
return meta.defaultValue();
}
protected abstract Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response);
protected Object filterValue(Object value, NamedValueMeta meta) {
return value;
}
protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) {
return resolveValue(meta, request, response);
}
protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) {
Object value = resolveValue(meta, request, response);
return value instanceof Map ? value : Collections.singletonMap(meta.name(), value);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/CompositeArgumentConverter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/CompositeArgumentConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.argument;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Pair;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.TypeParameterMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@SuppressWarnings({"rawtypes", "unchecked"})
public final class CompositeArgumentConverter implements ArgumentConverter {
private static final Logger LOGGER = LoggerFactory.getLogger(CompositeArgumentConverter.class);
private final List<ArgumentConverter> converters;
private final Map<Pair<Class, Class>, List<ArgumentConverter>> cache = CollectionUtils.newConcurrentHashMap();
public CompositeArgumentConverter(FrameworkModel frameworkModel) {
converters = frameworkModel.getActivateExtensions(ArgumentConverter.class);
}
@Override
public Object convert(Object value, ParameterMeta parameter) {
Class<?> type = parameter.getType();
if (value == null) {
return TypeUtils.nullDefault(type);
}
if (type.isInstance(value)) {
if (parameter.getGenericType() instanceof Class) {
return value;
}
return parameter.getToolKit().convert(value, parameter);
}
List<ArgumentConverter> converters = getSuitableConverters(value.getClass(), type);
Object target;
for (int i = 0, size = converters.size(); i < size; i++) {
target = converters.get(i).convert(value, parameter);
if (target != null) {
return target;
}
}
return parameter.getToolKit().convert(value, parameter);
}
public Object convert(Object value, Class<?> type) {
if (value == null) {
return null;
}
if (type.isInstance(value)) {
return value;
}
TypeParameterMeta parameter = new TypeParameterMeta(type);
List<ArgumentConverter> converters = getSuitableConverters(value.getClass(), type);
Object target;
for (int i = 0, size = converters.size(); i < size; i++) {
target = converters.get(i).convert(value, parameter);
if (target != null) {
return target;
}
}
return null;
}
private List<ArgumentConverter> getSuitableConverters(Class sourceType, Class targetType) {
return cache.computeIfAbsent(Pair.of(sourceType, targetType), k -> {
List<ArgumentConverter> result = new ArrayList<>();
for (ArgumentConverter converter : converters) {
Class<?> supportSourceType = TypeUtils.getSuperGenericType(converter.getClass(), 0);
if (supportSourceType == null) {
continue;
}
Class<?> supportTargetType = TypeUtils.getSuperGenericType(converter.getClass(), 1);
if (supportTargetType == null) {
continue;
}
if (supportSourceType.isAssignableFrom(sourceType) && targetType.isAssignableFrom(supportTargetType)) {
result.add(converter);
}
}
if (result.isEmpty()) {
return Collections.emptyList();
}
LOGGER.info("Found suitable ArgumentConverter for [{}], converters: {}", sourceType, result);
return result;
});
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/TypeConverter.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/argument/TypeConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.argument;
import javax.annotation.Nullable;
import java.lang.reflect.Type;
public interface TypeConverter {
@Nullable
<T> T convert(Object source, Class<T> targetClass);
@Nullable
<T> T convert(Object source, Type targetType);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandler.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.transport;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.TriRpcStatus;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2ResetFrame;
import io.netty.handler.codec.http2.Http2StreamFrame;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_SERIALIZE_TRIPLE;
public final class TripleHttp2ClientResponseHandler extends SimpleChannelInboundHandler<Http2StreamFrame> {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(TripleHttp2ClientResponseHandler.class);
private final H2TransportListener transportListener;
public TripleHttp2ClientResponseHandler(H2TransportListener listener) {
super(false);
this.transportListener = listener;
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
super.userEventTriggered(ctx, evt);
if (evt instanceof Http2GoAwayFrame) {
Http2GoAwayFrame event = (Http2GoAwayFrame) evt;
ctx.close();
LOGGER.debug(
"Event triggered, event name is: " + event.name() + ", last stream id is: " + event.lastStreamId());
} else if (evt instanceof Http2ResetFrame) {
onResetRead(ctx, (Http2ResetFrame) evt);
}
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2StreamFrame msg) throws Exception {
if (msg instanceof Http2HeadersFrame) {
final Http2HeadersFrame headers = (Http2HeadersFrame) msg;
transportListener.onHeader(headers.headers(), headers.isEndStream());
} else if (msg instanceof Http2DataFrame) {
final Http2DataFrame data = (Http2DataFrame) msg;
transportListener.onData(data.content(), data.isEndStream());
} else {
super.channelRead(ctx, msg);
}
}
private void onResetRead(ChannelHandlerContext ctx, Http2ResetFrame resetFrame) {
LOGGER.warn(
PROTOCOL_FAILED_SERIALIZE_TRIPLE,
"",
"",
"Triple Client received remote reset errorCode=" + resetFrame.errorCode());
transportListener.cancelByRemote(resetFrame.errorCode());
ctx.close();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
transportListener.onClose();
ctx.close();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
final TriRpcStatus status = TriRpcStatus.INTERNAL.withCause(cause);
LOGGER.warn(
PROTOCOL_FAILED_SERIALIZE_TRIPLE,
"",
"",
"Meet Exception on ClientResponseHandler, status code is: " + status.code,
cause);
transportListener.cancelByRemote(Http2Error.INTERNAL_ERROR.code());
ctx.close();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleIsolationExecutorSupportFactory.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleIsolationExecutorSupportFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.transport;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.executor.ExecutorSupport;
import org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory;
public class TripleIsolationExecutorSupportFactory implements IsolationExecutorSupportFactory {
@Override
public ExecutorSupport createIsolationExecutorSupport(URL url) {
return new TripleIsolationExecutorSupport(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleCommandOutBoundHandler.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleCommandOutBoundHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.transport;
import org.apache.dubbo.rpc.protocol.tri.command.QueuedCommand;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
public class TripleCommandOutBoundHandler extends ChannelOutboundHandlerAdapter {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof QueuedCommand) {
QueuedCommand command = (QueuedCommand) msg;
command.send(ctx, promise);
} else {
super.write(ctx, msg, promise);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleWriteQueue.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleWriteQueue.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.transport;
import org.apache.dubbo.common.BatchExecutorQueue;
import org.apache.dubbo.rpc.protocol.tri.command.QueuedCommand;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelPromise;
public class TripleWriteQueue extends BatchExecutorQueue<QueuedCommand> {
public TripleWriteQueue() {}
public TripleWriteQueue(int chunkSize) {
super(chunkSize);
}
public ChannelFuture enqueue(QueuedCommand command, boolean rst) {
return enqueue(command);
}
public ChannelFuture enqueue(QueuedCommand command) {
return this.enqueueFuture(command, command.channel().eventLoop());
}
public ChannelFuture enqueueFuture(QueuedCommand command, Executor executor) {
ChannelPromise promise = command.promise();
if (promise == null) {
Channel ch = command.channel();
promise = ch.newPromise();
command.promise(promise);
}
super.enqueue(command, executor);
return promise;
}
@Override
protected void prepare(QueuedCommand item) {
try {
Channel channel = item.channel();
item.run(channel);
} catch (CompletionException e) {
item.promise().tryFailure(e.getCause());
}
}
@Override
protected void flush(QueuedCommand item) {
try {
Channel channel = item.channel();
item.run(channel);
channel.flush();
} catch (CompletionException e) {
item.promise().tryFailure(e.getCause());
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleServerConnectionHandler.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleServerConnectionHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.transport;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import java.io.IOException;
import java.net.SocketException;
import java.util.HashSet;
import java.util.Set;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
import io.netty.handler.codec.http2.Http2ChannelDuplexHandler;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
import io.netty.handler.codec.http2.Http2PingFrame;
import io.netty.util.ReferenceCountUtil;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_RESPONSE;
import static org.apache.dubbo.rpc.protocol.tri.transport.GracefulShutdown.GRACEFUL_SHUTDOWN_PING;
public class TripleServerConnectionHandler extends Http2ChannelDuplexHandler {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(TripleServerConnectionHandler.class);
// Some exceptions are not very useful and add too much noise to the log
private static final Set<String> QUIET_EXCEPTIONS = new HashSet<>();
private static final Set<Class<?>> QUIET_EXCEPTIONS_CLASS = new HashSet<>();
static {
QUIET_EXCEPTIONS.add("NativeIoException");
QUIET_EXCEPTIONS_CLASS.add(IOException.class);
QUIET_EXCEPTIONS_CLASS.add(SocketException.class);
}
private GracefulShutdown gracefulShutdown;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof Http2PingFrame) {
if (((Http2PingFrame) msg).content() == GRACEFUL_SHUTDOWN_PING) {
if (gracefulShutdown == null) {
// this should never happen
logger.warn(
PROTOCOL_FAILED_RESPONSE,
"",
"",
"Received GRACEFUL_SHUTDOWN_PING Ack but gracefulShutdown is null");
} else {
gracefulShutdown.secondGoAwayAndClose(ctx);
}
}
} else if (msg instanceof Http2GoAwayFrame) {
ReferenceCountUtil.release(msg);
} else {
super.channelRead(ctx, msg);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
// reset all active stream on connection close
forEachActiveStream(stream -> {
// ignore remote side close
if (!stream.state().remoteSideOpen()) {
return true;
}
DefaultHttp2ResetFrame resetFrame = new DefaultHttp2ResetFrame(Http2Error.NO_ERROR).stream(stream);
ctx.fireChannelRead(resetFrame);
return true;
});
}
private boolean isQuiteException(Throwable t) {
if (QUIET_EXCEPTIONS_CLASS.contains(t.getClass())) {
return true;
}
return QUIET_EXCEPTIONS.contains(t.getClass().getSimpleName());
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
super.userEventTriggered(ctx, evt);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// this may be change in future follow https://github.com/apache/dubbo/pull/8644
if (isQuiteException(cause)) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("Channel:%s Error", ctx.channel()), cause);
}
} else {
logger.warn(PROTOCOL_FAILED_RESPONSE, "", "", String.format("Channel:%s Error", ctx.channel()), cause);
}
ctx.close();
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
if (gracefulShutdown == null) {
gracefulShutdown = new GracefulShutdown(ctx, "app_requested", promise);
}
gracefulShutdown.gracefulShutdown();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.transport;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.rpc.TriRpcStatus;
import org.apache.dubbo.rpc.protocol.tri.TripleConstants;
import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
import org.apache.dubbo.rpc.protocol.tri.stream.StreamUtils;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
import io.netty.handler.codec.http2.Http2Headers;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_PARSE;
public abstract class AbstractH2TransportListener implements H2TransportListener {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(AbstractH2TransportListener.class);
/**
* Parse metadata to a KV pairs map.
*
* @param trailers the metadata from remote
* @return KV pairs map
*/
protected Map<String, Object> headersToMap(Http2Headers trailers, Supplier<Object> convertUpperHeaderSupplier) {
if (trailers == null) {
return Collections.emptyMap();
}
Map<String, Object> attachments = new HashMap<>(trailers.size());
for (Map.Entry<CharSequence, CharSequence> header : trailers) {
String key = header.getKey().toString();
if (key.endsWith(TripleConstants.HEADER_BIN_SUFFIX)
&& key.length() > TripleConstants.HEADER_BIN_SUFFIX.length()) {
try {
String realKey = key.substring(0, key.length() - TripleConstants.HEADER_BIN_SUFFIX.length());
byte[] value = StreamUtils.decodeASCIIByte(header.getValue().toString());
attachments.put(realKey, value);
} catch (Exception e) {
LOGGER.error(PROTOCOL_FAILED_PARSE, "", "", "Failed to parse response attachment key=" + key, e);
}
} else {
attachments.put(key, header.getValue().toString());
}
}
// try converting upper key
Object obj = convertUpperHeaderSupplier.get();
if (obj == null) {
return attachments;
}
if (obj instanceof String) {
String json = TriRpcStatus.decodeMessage((String) obj);
Map<String, String> map = JsonUtils.toJavaObject(json, Map.class);
for (Map.Entry<String, String> entry : map.entrySet()) {
Object val = attachments.remove(entry.getKey());
if (val != null) {
attachments.put(entry.getValue(), val);
}
}
} else {
// If convertUpperHeaderSupplier does not return String, just fail...
// Internal invocation, use INTERNAL_ERROR instead.
LOGGER.error(
INTERNAL_ERROR,
"wrong internal invocation",
"",
"Triple convertNoLowerCaseHeader error, obj is not String");
}
return attachments;
}
protected Map<CharSequence, String> filterReservedHeaders(Http2Headers trailers) {
if (trailers == null) {
return Collections.emptyMap();
}
Map<CharSequence, String> excludeHeaders = new HashMap<>(trailers.size());
for (Map.Entry<CharSequence, CharSequence> header : trailers) {
CharSequence key = header.getKey();
if (TripleHeaderEnum.containsExcludeAttachments(key.toString())) {
excludeHeaders.put(key, trailers.getAndRemove(key).toString());
}
}
return excludeHeaders;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/GracefulShutdown.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/GracefulShutdown.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.transport;
import java.util.concurrent.TimeUnit;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame;
import io.netty.handler.codec.http2.DefaultHttp2PingFrame;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
import io.netty.handler.codec.http2.Http2PingFrame;
import io.netty.util.concurrent.Future;
public class GracefulShutdown {
static final long GRACEFUL_SHUTDOWN_PING = 0x97ACEF001L;
private static final long GRACEFUL_SHUTDOWN_PING_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(10);
private final ChannelHandlerContext ctx;
private final ChannelPromise originPromise;
private final String goAwayMessage;
private boolean pingAckedOrTimeout;
private Future<?> pingFuture;
public GracefulShutdown(ChannelHandlerContext ctx, String goAwayMessage, ChannelPromise originPromise) {
this.ctx = ctx;
this.goAwayMessage = goAwayMessage;
this.originPromise = originPromise;
}
public void gracefulShutdown() {
Http2GoAwayFrame goAwayFrame =
new DefaultHttp2GoAwayFrame(Http2Error.NO_ERROR, ByteBufUtil.writeAscii(ctx.alloc(), goAwayMessage));
goAwayFrame.setExtraStreamIds(Integer.MAX_VALUE);
ctx.writeAndFlush(goAwayFrame);
pingFuture = ctx.executor()
.schedule(() -> secondGoAwayAndClose(ctx), GRACEFUL_SHUTDOWN_PING_TIMEOUT_NANOS, TimeUnit.NANOSECONDS);
Http2PingFrame pingFrame = new DefaultHttp2PingFrame(GRACEFUL_SHUTDOWN_PING, false);
ctx.writeAndFlush(pingFrame);
}
void secondGoAwayAndClose(ChannelHandlerContext ctx) {
if (pingAckedOrTimeout) {
return;
}
pingAckedOrTimeout = true;
pingFuture.cancel(false);
try {
Http2GoAwayFrame goAwayFrame = new DefaultHttp2GoAwayFrame(
Http2Error.NO_ERROR, ByteBufUtil.writeAscii(this.ctx.alloc(), this.goAwayMessage));
ChannelFuture future = ctx.writeAndFlush(goAwayFrame, ctx.newPromise());
if (future.isDone()) {
ctx.close(originPromise);
} else {
future.addListener((ChannelFutureListener) f -> ctx.close(originPromise));
}
} catch (Exception e) {
ctx.fireExceptionCaught(e);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/H2TransportListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/H2TransportListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.transport;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http2.Http2Headers;
/**
* An observer used for transport messaging which provides full streaming support. A
* TransportObserver receives raw data or control messages from local/remote.
*/
public interface H2TransportListener {
/**
* Transport metadata
*
* @param headers metadata KV paris
* @param endStream whether this data should terminate the stream
*/
void onHeader(Http2Headers headers, boolean endStream);
/**
* Transport data
*
* @param data raw byte array
* @param endStream whether this data should terminate the stream
*/
void onData(ByteBuf data, boolean endStream);
void cancelByRemote(long errorCode);
void onClose();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/WriteQueue.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/WriteQueue.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.transport;
import org.apache.dubbo.rpc.protocol.tri.command.QueuedCommand;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelPromise;
@Deprecated
public class WriteQueue {
static final int DEQUE_CHUNK_SIZE = 128;
private final Queue<QueuedCommand> queue;
private final AtomicBoolean scheduled;
public WriteQueue() {
queue = new ConcurrentLinkedQueue<>();
scheduled = new AtomicBoolean(false);
}
public ChannelFuture enqueue(QueuedCommand command, boolean rst) {
return enqueue(command);
}
public ChannelFuture enqueue(QueuedCommand command) {
ChannelPromise promise = command.promise();
if (promise == null) {
Channel ch = command.channel();
promise = ch.newPromise();
command.promise(promise);
}
queue.add(command);
scheduleFlush(command.channel());
return promise;
}
public void scheduleFlush(Channel ch) {
if (scheduled.compareAndSet(false, true)) {
ch.parent().eventLoop().execute(this::flush);
}
}
private void flush() {
Channel ch = null;
try {
QueuedCommand cmd;
int i = 0;
boolean flushedOnce = false;
while ((cmd = queue.poll()) != null) {
ch = cmd.channel();
cmd.run(ch);
i++;
if (i == DEQUE_CHUNK_SIZE) {
i = 0;
ch.parent().flush();
flushedOnce = true;
}
}
if (ch != null && (i != 0 || !flushedOnce)) {
ch.parent().flush();
}
} finally {
scheduled.set(false);
if (!queue.isEmpty()) {
scheduleFlush(ch);
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleGoAwayHandler.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleGoAwayHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.transport;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.api.connection.ConnectionHandler;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
import io.netty.util.ReferenceCountUtil;
public class TripleGoAwayHandler extends ChannelDuplexHandler {
private static final Logger logger = LoggerFactory.getLogger(TripleGoAwayHandler.class);
public TripleGoAwayHandler() {}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof Http2GoAwayFrame) {
final ConnectionHandler connectionHandler =
(ConnectionHandler) ctx.pipeline().get(Constants.CONNECTION_HANDLER_NAME);
if (logger.isInfoEnabled()) {
logger.info("Receive go away frame of " + ctx.channel().localAddress() + " -> "
+ ctx.channel().remoteAddress() + " and will reconnect later.");
}
connectionHandler.onGoAway(ctx.channel());
ReferenceCountUtil.release(msg);
return;
}
super.channelRead(ctx, msg);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleIsolationExecutorSupport.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleIsolationExecutorSupport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.transport;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.remoting.http12.HttpHeaders;
import org.apache.dubbo.remoting.http12.RequestMetadata;
import org.apache.dubbo.rpc.executor.AbstractIsolationExecutorSupport;
import org.apache.dubbo.rpc.protocol.tri.RequestPath;
import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants;
public class TripleIsolationExecutorSupport extends AbstractIsolationExecutorSupport {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(TripleIsolationExecutorSupport.class);
public TripleIsolationExecutorSupport(URL url) {
super(url);
}
@Override
protected String getServiceKey(Object data) {
if (data instanceof RequestMetadata) {
RequestMetadata httpMetadata = (RequestMetadata) data;
RequestPath path = RequestPath.parse(httpMetadata.path());
if (path == null) {
return null;
}
HttpHeaders headers = httpMetadata.headers();
return URL.buildKey(
path.getServiceInterface(),
getHeader(headers, TripleHeaderEnum.SERVICE_GROUP, RestConstants.HEADER_SERVICE_GROUP),
getHeader(headers, TripleHeaderEnum.SERVICE_VERSION, RestConstants.HEADER_SERVICE_VERSION));
}
if (data instanceof URL) {
return ((URL) data).getServiceKey();
}
return null;
}
private static String getHeader(HttpHeaders headers, TripleHeaderEnum en, String key) {
String value = headers.getFirst(en.getKey());
if (value == null) {
value = headers.getFirst(key);
}
return value;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleTailHandler.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleTailHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.transport;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ReferenceCounted;
/**
* Process unhandled message to avoid mem leak and netty's unhandled exception
*/
public class TripleTailHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof ReferenceCounted) {
ReferenceCountUtil.release(msg);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/WebSocketServerChannelObserver.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/WebSocketServerChannelObserver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.websocket;
import org.apache.dubbo.remoting.http12.HttpOutputMessage;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.h12.http2.Http2StreamServerChannelObserver;
public class WebSocketServerChannelObserver extends Http2StreamServerChannelObserver {
protected WebSocketServerChannelObserver(FrameworkModel frameworkModel, H2StreamChannel h2StreamChannel) {
super(frameworkModel, h2StreamChannel);
}
@Override
protected void doOnNext(Object data) throws Throwable {
int statusCode = resolveStatusCode(data);
HttpOutputMessage httpOutputMessage = buildMessage(statusCode, data);
sendMessage(httpOutputMessage);
}
@Override
protected void doOnError(Throwable throwable) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/DefaultWebSocketServerTransportListener.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/DefaultWebSocketServerTransportListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.websocket;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.http12.HttpHeaders;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http12.h2.Http2Header;
import org.apache.dubbo.remoting.http12.h2.Http2InputMessage;
import org.apache.dubbo.remoting.http12.h2.Http2ServerChannelObserver;
import org.apache.dubbo.remoting.http12.message.StreamingDecoder;
import org.apache.dubbo.remoting.websocket.FinalFragmentStreamingDecoder;
import org.apache.dubbo.remoting.websocket.WebSocketHeaderNames;
import org.apache.dubbo.remoting.websocket.WebSocketTransportListener;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.MethodDescriptor.RpcType;
import org.apache.dubbo.rpc.protocol.tri.h12.http2.GenericHttp2ServerTransportListener;
import java.util.concurrent.Executor;
public class DefaultWebSocketServerTransportListener extends GenericHttp2ServerTransportListener
implements WebSocketTransportListener {
private boolean autoClose = false;
public DefaultWebSocketServerTransportListener(
H2StreamChannel h2StreamChannel, URL url, FrameworkModel frameworkModel) {
super(h2StreamChannel, url, frameworkModel);
}
@Override
protected void onBeforeMetadata(Http2Header metadata) {}
@Override
protected Executor initializeExecutor(URL url, Http2Header metadata) {
return getExecutor(url, metadata);
}
@Override
protected void onPrepareMetadata(Http2Header metadata) {
doRoute(metadata);
}
@Override
protected StreamingDecoder newStreamingDecoder() {
return new FinalFragmentStreamingDecoder();
}
@Override
protected Http2ServerChannelObserver newResponseObserver(H2StreamChannel h2StreamChannel) {
return new WebSocketServerChannelObserver(getFrameworkModel(), h2StreamChannel);
}
@Override
protected Http2ServerChannelObserver newStreamResponseObserver(H2StreamChannel h2StreamChannel) {
return new WebSocketServerChannelObserver(getFrameworkModel(), h2StreamChannel);
}
@Override
protected Http2ServerChannelObserver prepareResponseObserver(Http2ServerChannelObserver responseObserver) {
responseObserver.addTrailersCustomizer(this::customizeWebSocketStatus);
return super.prepareResponseObserver(responseObserver);
}
@Override
protected void prepareUnaryServerCall() {
autoClose = true;
super.prepareUnaryServerCall();
}
@Override
protected void prepareStreamServerCall() {
if (getContext().getMethodDescriptor().getRpcType().equals(RpcType.SERVER_STREAM)) {
autoClose = true;
}
super.prepareStreamServerCall();
}
@Override
protected void onDataCompletion(Http2InputMessage message) {
if (autoClose) {
getStreamingDecoder().close();
return;
}
super.onDataCompletion(message);
}
private void customizeWebSocketStatus(HttpHeaders httpHeaders, Throwable throwable) {
if (throwable != null) {
httpHeaders.set(WebSocketHeaderNames.WEBSOCKET_MESSAGE.getName(), throwable.getMessage());
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/DefaultWebSocketServerTransportListenerFactory.java | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/websocket/DefaultWebSocketServerTransportListenerFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.websocket;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.websocket.WebSocketServerTransportListenerFactory;
import org.apache.dubbo.remoting.websocket.WebSocketTransportListener;
import org.apache.dubbo.rpc.model.FrameworkModel;
public class DefaultWebSocketServerTransportListenerFactory implements WebSocketServerTransportListenerFactory {
public static final WebSocketServerTransportListenerFactory INSTANCE =
new DefaultWebSocketServerTransportListenerFactory();
@Override
public WebSocketTransportListener newInstance(
H2StreamChannel streamChannel, URL url, FrameworkModel frameworkModel) {
return new DefaultWebSocketServerTransportListener(streamChannel, url, frameworkModel);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/RetryTest.java | dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/RetryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store.nacos;
import org.apache.dubbo.common.URL;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static com.alibaba.nacos.client.constant.Constants.HealthCheck.DOWN;
import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP;
import static org.mockito.ArgumentMatchers.any;
class RetryTest {
@Test
void testRetryCreate() {
try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) {
AtomicInteger atomicInteger = new AtomicInteger(0);
ConfigService mock = new MockConfigService() {
@Override
public String getServerStatus() {
return atomicInteger.incrementAndGet() > 10 ? UP : DOWN;
}
};
nacosFactoryMockedStatic
.when(() -> NacosFactory.createConfigService((Properties) any()))
.thenReturn(mock);
URL url = URL.valueOf("nacos://127.0.0.1:8848")
.addParameter("nacos.retry", 5)
.addParameter("nacos.retry-wait", 10);
Assertions.assertThrows(IllegalStateException.class, () -> new NacosMetadataReport(url));
try {
new NacosMetadataReport(url);
} catch (Throwable t) {
Assertions.fail(t);
}
}
}
@Test
void testDisable() {
try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) {
ConfigService mock = new MockConfigService() {
@Override
public String getServerStatus() {
return DOWN;
}
};
nacosFactoryMockedStatic
.when(() -> NacosFactory.createConfigService((Properties) any()))
.thenReturn(mock);
URL url = URL.valueOf("nacos://127.0.0.1:8848")
.addParameter("nacos.retry", 5)
.addParameter("nacos.retry-wait", 10)
.addParameter("nacos.check", "false");
try {
new NacosMetadataReport(url);
} catch (Throwable t) {
Assertions.fail(t);
}
}
}
@Test
void testRequest() {
try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) {
AtomicInteger atomicInteger = new AtomicInteger(0);
ConfigService mock = new MockConfigService() {
@Override
public String getConfig(String dataId, String group, long timeoutMs) throws NacosException {
if (atomicInteger.incrementAndGet() > 10) {
return "";
} else {
throw new NacosException();
}
}
@Override
public String getServerStatus() {
return UP;
}
};
nacosFactoryMockedStatic
.when(() -> NacosFactory.createConfigService((Properties) any()))
.thenReturn(mock);
URL url = URL.valueOf("nacos://127.0.0.1:8848")
.addParameter("nacos.retry", 5)
.addParameter("nacos.retry-wait", 10);
Assertions.assertThrows(IllegalStateException.class, () -> new NacosMetadataReport(url));
try {
new NacosMetadataReport(url);
} catch (Throwable t) {
Assertions.fail(t);
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/MockConfigService.java | dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/MockConfigService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store.nacos;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.filter.IConfigFilter;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
public class MockConfigService implements ConfigService {
@Override
public String getConfig(String dataId, String group, long timeoutMs) throws NacosException {
return null;
}
@Override
public String getConfigAndSignListener(String dataId, String group, long timeoutMs, Listener listener) {
return null;
}
@Override
public void addListener(String dataId, String group, Listener listener) {}
@Override
public boolean publishConfig(String dataId, String group, String content) {
return false;
}
@Override
public boolean publishConfig(String dataId, String group, String content, String type) {
return false;
}
@Override
public boolean publishConfigCas(String dataId, String group, String content, String casMd5) {
return false;
}
@Override
public boolean publishConfigCas(String dataId, String group, String content, String casMd5, String type) {
return false;
}
@Override
public boolean removeConfig(String dataId, String group) {
return false;
}
@Override
public void removeListener(String dataId, String group, Listener listener) {}
@Override
public String getServerStatus() {
return null;
}
@Override
public void shutDown() {}
@Override
public void addConfigFilter(IConfigFilter iConfigFilter) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java | dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store.nacos;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.MD5Utils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MappingChangedEvent;
import org.apache.dubbo.metadata.MappingListener;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.ServiceNameMapping;
import org.apache.dubbo.metadata.report.identifier.BaseMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import org.apache.dubbo.metadata.report.support.AbstractMetadataReport;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executor;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.AbstractSharedListener;
import com.alibaba.nacos.api.exception.NacosException;
import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR;
import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_ERROR_NACOS;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_INTERRUPTED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION;
import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY;
import static org.apache.dubbo.common.utils.StringConstantFieldValuePredicate.of;
import static org.apache.dubbo.common.utils.StringUtils.HYPHEN_CHAR;
import static org.apache.dubbo.metadata.MetadataConstants.REPORT_CONSUMER_URL_KEY;
import static org.apache.dubbo.metadata.ServiceNameMapping.DEFAULT_MAPPING_GROUP;
import static org.apache.dubbo.metadata.ServiceNameMapping.getAppNames;
/**
* metadata report impl for nacos
*/
public class NacosMetadataReport extends AbstractMetadataReport {
private NacosConfigServiceWrapper configService;
/**
* The group used to store metadata in Nacos
*/
private String group;
private ConcurrentHashMap<String, NacosConfigListener> watchListenerMap = new ConcurrentHashMap<>();
private ConcurrentHashMap<String, MappingDataListener> casListenerMap = new ConcurrentHashMap<>();
private MD5Utils md5Utils = new MD5Utils();
private static final String NACOS_RETRY_KEY = "nacos.retry";
private static final String NACOS_RETRY_WAIT_KEY = "nacos.retry-wait";
private static final String NACOS_CHECK_KEY = "nacos.check";
public NacosMetadataReport(URL url) {
super(url);
this.configService = buildConfigService(url);
group = url.getParameter(GROUP_KEY, DEFAULT_ROOT);
}
private NacosConfigServiceWrapper buildConfigService(URL url) {
Properties nacosProperties = buildNacosProperties(url);
int retryTimes = url.getPositiveParameter(NACOS_RETRY_KEY, 10);
int sleepMsBetweenRetries = url.getPositiveParameter(NACOS_RETRY_WAIT_KEY, 1000);
boolean check = url.getParameter(NACOS_CHECK_KEY, true);
ConfigService tmpConfigServices = null;
try {
for (int i = 0; i < retryTimes + 1; i++) {
tmpConfigServices = NacosFactory.createConfigService(nacosProperties);
if (!check
|| (UP.equals(tmpConfigServices.getServerStatus()) && testConfigService(tmpConfigServices))) {
break;
} else {
logger.warn(
LoggerCodeConstants.CONFIG_ERROR_NACOS,
"",
"",
"Failed to connect to nacos config server. "
+ (i < retryTimes
? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". "
: "Exceed retry max times.")
+ "Try times: "
+ (i + 1));
}
tmpConfigServices.shutDown();
tmpConfigServices = null;
Thread.sleep(sleepMsBetweenRetries);
}
} catch (NacosException e) {
logger.error(CONFIG_ERROR_NACOS, "", "", e.getErrMsg(), e);
throw new IllegalStateException(e);
} catch (InterruptedException e) {
logger.error(INTERNAL_INTERRUPTED, "", "", "Interrupted when creating nacos config service client.", e);
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
if (tmpConfigServices == null) {
logger.error(
CONFIG_ERROR_NACOS,
"",
"",
"Failed to create nacos config service client. Reason: server status check failed.");
throw new IllegalStateException(
"Failed to create nacos config service client. Reason: server status check failed.");
}
return new NacosConfigServiceWrapper(tmpConfigServices);
}
private boolean testConfigService(ConfigService configService) {
try {
configService.getConfig("Dubbo-Nacos-Test", "Dubbo-Nacos-Test", 3000L);
return true;
} catch (NacosException e) {
return false;
}
}
private Properties buildNacosProperties(URL url) {
Properties properties = new Properties();
setServerAddr(url, properties);
setProperties(url, properties);
return properties;
}
private void setServerAddr(URL url, Properties properties) {
StringBuilder serverAddrBuilder = new StringBuilder(url.getHost()) // Host
.append(':')
.append(url.getPort()); // Port
// Append backup parameter as other servers
String backup = url.getParameter(BACKUP_KEY);
if (backup != null) {
serverAddrBuilder.append(',').append(backup);
}
String serverAddr = serverAddrBuilder.toString();
properties.put(SERVER_ADDR, serverAddr);
}
private static void setProperties(URL url, Properties properties) {
// Get the parameters from constants
Map<String, String> parameters = url.getParameters(of(PropertyKeyConst.class));
// Put all parameters
properties.putAll(parameters);
}
private static void putPropertyIfAbsent(URL url, Properties properties, String propertyName) {
String propertyValue = url.getParameter(propertyName);
if (StringUtils.isNotEmpty(propertyValue)) {
properties.setProperty(propertyName, propertyValue);
}
}
private static void putPropertyIfAbsent(URL url, Properties properties, String propertyName, String defaultValue) {
String propertyValue = url.getParameter(propertyName);
if (StringUtils.isNotEmpty(propertyValue)) {
properties.setProperty(propertyName, propertyValue);
} else {
properties.setProperty(propertyName, defaultValue);
}
}
@Override
public void publishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) {
try {
if (metadataInfo.getContent() != null) {
configService.publishConfig(
identifier.getApplication(), identifier.getRevision(), metadataInfo.getContent());
}
} catch (NacosException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
public void unPublishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) {
try {
configService.removeConfig(identifier.getApplication(), identifier.getRevision());
} catch (NacosException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
public MetadataInfo getAppMetadata(SubscriberMetadataIdentifier identifier, Map<String, String> instanceMetadata) {
try {
String content = configService.getConfig(identifier.getApplication(), identifier.getRevision(), 3000L);
return JsonUtils.toJavaObject(content, MetadataInfo.class);
} catch (NacosException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) {
this.storeMetadata(providerMetadataIdentifier, serviceDefinitions);
}
@Override
protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String value) {
if (getUrl().getParameter(REPORT_CONSUMER_URL_KEY, false)) {
this.storeMetadata(consumerMetadataIdentifier, value);
}
}
@Override
protected void doSaveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier, URL url) {
storeMetadata(serviceMetadataIdentifier, URL.encode(url.toFullString()));
}
@Override
protected void doRemoveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier) {
deleteMetadata(serviceMetadataIdentifier);
}
@Override
protected List<String> doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) {
String content = getConfig(metadataIdentifier);
if (StringUtils.isEmpty(content)) {
return Collections.emptyList();
}
return new ArrayList<>(Arrays.asList(URL.decode(content)));
}
@Override
protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urlListStr) {
storeMetadata(subscriberMetadataIdentifier, urlListStr);
}
@Override
protected String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) {
return getConfig(subscriberMetadataIdentifier);
}
@Override
public String getServiceDefinition(MetadataIdentifier metadataIdentifier) {
return getConfig(metadataIdentifier);
}
@Override
public boolean registerServiceAppMapping(String key, String group, String content, Object ticket) {
try {
if (!(ticket instanceof String)) {
throw new IllegalArgumentException("nacos publishConfigCas requires string type ticket");
}
return configService.publishConfigCas(key, group, content, (String) ticket);
} catch (NacosException e) {
logger.warn(REGISTRY_NACOS_EXCEPTION, "", "", "nacos publishConfigCas failed.", e);
return false;
}
}
@Override
public ConfigItem getConfigItem(String key, String group) {
String content = getConfig(key, group);
String casMd5 = "0";
if (StringUtils.isNotEmpty(content)) {
casMd5 = md5Utils.getMd5(content);
}
return new ConfigItem(content, casMd5);
}
/**
* allow adding listener without checking if the serviceKey is existed in the map.
* there are multiple references which have the same serviceKey but might have multiple listeners,
* because the extra parameters of their subscribed URLs might be different.
*/
@Override
public Set<String> getServiceAppMapping(String serviceKey, MappingListener listener, URL url) {
String group = DEFAULT_MAPPING_GROUP;
addCasServiceMappingListener(serviceKey, group, listener);
String content = getConfig(serviceKey, group);
return ServiceNameMapping.getAppNames(content);
}
@Override
public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) {
String group = DEFAULT_MAPPING_GROUP;
MappingDataListener mappingDataListener = casListenerMap.get(buildListenerKey(serviceKey, group));
if (null != mappingDataListener) {
removeCasServiceMappingListener(serviceKey, group, listener);
}
}
@Override
public Set<String> getServiceAppMapping(String serviceKey, URL url) {
String content = getConfig(serviceKey, DEFAULT_MAPPING_GROUP);
return ServiceNameMapping.getAppNames(content);
}
private String getConfig(String dataId, String group) {
try {
return configService.getConfig(dataId, group);
} catch (NacosException e) {
logger.error(REGISTRY_NACOS_EXCEPTION, "", "", e.getMessage());
}
return null;
}
private void addCasServiceMappingListener(String serviceKey, String group, MappingListener listener) {
MappingDataListener mappingDataListener = ConcurrentHashMapUtils.computeIfAbsent(
casListenerMap, buildListenerKey(serviceKey, group), k -> new MappingDataListener(serviceKey, group));
mappingDataListener.addListeners(listener);
addListener(serviceKey, DEFAULT_MAPPING_GROUP, mappingDataListener);
}
private void removeCasServiceMappingListener(String serviceKey, String group, MappingListener listener) {
MappingDataListener mappingDataListener = casListenerMap.get(buildListenerKey(serviceKey, group));
if (mappingDataListener != null) {
mappingDataListener.removeListeners(listener);
if (mappingDataListener.isEmpty()) {
removeListener(serviceKey, DEFAULT_MAPPING_GROUP, mappingDataListener);
casListenerMap.remove(buildListenerKey(serviceKey, group), mappingDataListener);
}
}
}
public void addListener(String key, String group, ConfigurationListener listener) {
String listenerKey = buildListenerKey(key, group);
NacosConfigListener nacosConfigListener = ConcurrentHashMapUtils.computeIfAbsent(
watchListenerMap, listenerKey, k -> createTargetListener(key, group));
nacosConfigListener.addListener(listener);
try {
configService.addListener(key, group, nacosConfigListener);
} catch (NacosException e) {
logger.error(REGISTRY_NACOS_EXCEPTION, "", "", e.getMessage());
}
}
public void removeListener(String key, String group, ConfigurationListener listener) {
String listenerKey = buildListenerKey(key, group);
NacosConfigListener nacosConfigListener = watchListenerMap.get(listenerKey);
try {
if (nacosConfigListener != null) {
nacosConfigListener.removeListener(listener);
if (nacosConfigListener.isEmpty()) {
configService.removeListener(key, group, nacosConfigListener);
watchListenerMap.remove(listenerKey);
}
}
} catch (NacosException e) {
logger.error(REGISTRY_NACOS_EXCEPTION, "", "", e.getMessage());
}
}
private NacosConfigListener createTargetListener(String key, String group) {
NacosConfigListener configListener = new NacosConfigListener();
configListener.fillContext(key, group);
return configListener;
}
private String buildListenerKey(String key, String group) {
return key + HYPHEN_CHAR + group;
}
private void storeMetadata(BaseMetadataIdentifier identifier, String value) {
try {
boolean publishResult =
configService.publishConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group, value);
if (!publishResult) {
throw new RuntimeException("publish nacos metadata failed");
}
} catch (Throwable t) {
logger.error(
REGISTRY_NACOS_EXCEPTION,
"",
"",
"Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(),
t);
throw new RuntimeException(
"Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(), t);
}
}
private void deleteMetadata(BaseMetadataIdentifier identifier) {
try {
boolean publishResult = configService.removeConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group);
if (!publishResult) {
throw new RuntimeException("remove nacos metadata failed");
}
} catch (Throwable t) {
logger.error(
REGISTRY_NACOS_EXCEPTION,
"",
"",
"Failed to remove " + identifier + " from nacos , cause: " + t.getMessage(),
t);
throw new RuntimeException("Failed to remove " + identifier + " from nacos , cause: " + t.getMessage(), t);
}
}
private String getConfig(BaseMetadataIdentifier identifier) {
try {
return configService.getConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group, 3000L);
} catch (Throwable t) {
logger.error(
REGISTRY_NACOS_EXCEPTION,
"",
"",
"Failed to get " + identifier + " from nacos , cause: " + t.getMessage(),
t);
throw new RuntimeException("Failed to get " + identifier + " from nacos , cause: " + t.getMessage(), t);
}
}
public class NacosConfigListener extends AbstractSharedListener {
private Set<ConfigurationListener> listeners = new CopyOnWriteArraySet<>();
/**
* cache data to store old value
*/
private Map<String, String> cacheData = new ConcurrentHashMap<>();
@Override
public Executor getExecutor() {
return null;
}
/**
* receive
*
* @param dataId data ID
* @param group group
* @param configInfo content
*/
@Override
public void innerReceive(String dataId, String group, String configInfo) {
String oldValue = cacheData.get(dataId);
ConfigChangedEvent event =
new ConfigChangedEvent(dataId, group, configInfo, getChangeType(configInfo, oldValue));
if (configInfo == null) {
cacheData.remove(dataId);
} else {
cacheData.put(dataId, configInfo);
}
listeners.forEach(listener -> listener.process(event));
}
void addListener(ConfigurationListener configurationListener) {
this.listeners.add(configurationListener);
}
void removeListener(ConfigurationListener configurationListener) {
this.listeners.remove(configurationListener);
}
boolean isEmpty() {
return this.listeners.isEmpty();
}
private ConfigChangeType getChangeType(String configInfo, String oldValue) {
if (StringUtils.isBlank(configInfo)) {
return ConfigChangeType.DELETED;
}
if (StringUtils.isBlank(oldValue)) {
return ConfigChangeType.ADDED;
}
return ConfigChangeType.MODIFIED;
}
}
static class MappingDataListener implements ConfigurationListener {
private String dataId;
private String groupId;
private String serviceKey;
private Set<MappingListener> listeners;
public MappingDataListener(String dataId, String groupId) {
this.serviceKey = dataId;
this.dataId = dataId;
this.groupId = groupId;
this.listeners = new HashSet<>();
}
public void addListeners(MappingListener mappingListener) {
listeners.add(mappingListener);
}
public void removeListeners(MappingListener mappingListener) {
listeners.remove(mappingListener);
}
public boolean isEmpty() {
return listeners.isEmpty();
}
@Override
public void process(ConfigChangedEvent event) {
if (ConfigChangeType.DELETED == event.getChangeType()) {
return;
}
if (!dataId.equals(event.getKey()) || !groupId.equals(event.getGroup())) {
return;
}
Set<String> apps = getAppNames(event.getContent());
MappingChangedEvent mappingChangedEvent = new MappingChangedEvent(serviceKey, apps);
listeners.forEach(listener -> listener.onEvent(mappingChangedEvent));
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosConfigServiceWrapper.java | dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosConfigServiceWrapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store.nacos;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import static org.apache.dubbo.common.utils.StringUtils.HYPHEN_CHAR;
import static org.apache.dubbo.common.utils.StringUtils.SLASH_CHAR;
public class NacosConfigServiceWrapper {
private static final String INNERCLASS_SYMBOL = "$";
private static final String INNERCLASS_COMPATIBLE_SYMBOL = "___";
private static final long DEFAULT_TIMEOUT = 3000L;
private ConfigService configService;
public NacosConfigServiceWrapper(ConfigService configService) {
this.configService = configService;
}
public ConfigService getConfigService() {
return configService;
}
public void addListener(String dataId, String group, Listener listener) throws NacosException {
configService.addListener(handleInnerSymbol(dataId), handleInnerSymbol(group), listener);
}
public void removeListener(String dataId, String group, Listener listener) throws NacosException {
configService.removeListener(handleInnerSymbol(dataId), handleInnerSymbol(group), listener);
}
public String getConfig(String dataId, String group) throws NacosException {
return configService.getConfig(handleInnerSymbol(dataId), handleInnerSymbol(group), DEFAULT_TIMEOUT);
}
public String getConfig(String dataId, String group, long timeout) throws NacosException {
return configService.getConfig(handleInnerSymbol(dataId), handleInnerSymbol(group), timeout);
}
public boolean publishConfig(String dataId, String group, String content) throws NacosException {
return configService.publishConfig(handleInnerSymbol(dataId), handleInnerSymbol(group), content);
}
public boolean publishConfigCas(String dataId, String group, String content, String casMd5) throws NacosException {
return configService.publishConfigCas(handleInnerSymbol(dataId), handleInnerSymbol(group), content, casMd5);
}
public boolean removeConfig(String dataId, String group) throws NacosException {
return configService.removeConfig(handleInnerSymbol(dataId), handleInnerSymbol(group));
}
/**
* see {@link com.alibaba.nacos.client.config.utils.ParamUtils#isValid(java.lang.String)}
*/
private String handleInnerSymbol(String data) {
if (data == null) {
return null;
}
return data.replace(INNERCLASS_SYMBOL, INNERCLASS_COMPATIBLE_SYMBOL).replace(SLASH_CHAR, HYPHEN_CHAR);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java | dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store.nacos;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory;
/**
* metadata report factory impl for nacos
*/
public class NacosMetadataReportFactory extends AbstractMetadataReportFactory {
@Override
protected MetadataReport createMetadataReport(URL url) {
return new NacosMetadataReport(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.tools;
import org.apache.dubbo.config.annotation.Service;
import java.io.Serializable;
/**
* {@link TestService} Implementation
*
* @since 2.7.6
*/
@Service(
interfaceName = "org.apache.dubbo.metadata.tools.TestService",
interfaceClass = TestService.class,
version = "3.0.0",
group = "test")
public class TestServiceImpl extends GenericTestService implements TestService, AutoCloseable, Serializable {
@Override
public String echo(String message) {
return "[ECHO] " + message;
}
@Override
public void close() throws Exception {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.tools;
import org.apache.dubbo.config.annotation.Service;
import java.util.EventListener;
/**
* {@link TestService} Implementation
*
* @since 2.7.6
*/
@Service(version = "2.0.0", group = "generic")
public class GenericTestService extends DefaultTestService implements TestService, EventListener {
@Override
public String echo(String message) {
return "[ECHO] " + message;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/Ancestor.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/Ancestor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.tools;
import java.io.Serializable;
public class Ancestor implements Serializable {
private boolean z;
public boolean isZ() {
return z;
}
public void setZ(boolean z) {
this.z = z;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestService.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.tools;
import org.apache.dubbo.metadata.annotation.processing.model.Model;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import java.util.concurrent.TimeUnit;
/**
* Test Service
*
* @since 2.7.6
*/
@Path("/echo")
public interface TestService {
@GET
<T> String echo(@PathParam("message") @DefaultValue("mercyblitz") String message);
@POST
Model model(@PathParam("model") Model model);
// Test primitive
@PUT
String testPrimitive(boolean z, int i);
// Test enumeration
@PUT
Model testEnum(TimeUnit timeUnit);
// Test Array
@GET
String testArray(String[] strArray, int[] intArray, Model[] modelArray);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.tools;
import java.io.IOException;
import org.junit.jupiter.api.Test;
/**
* The Compiler test case
*/
class CompilerTest {
@Test
void testCompile() throws IOException {
Compiler compiler = new Compiler();
compiler.compile(TestServiceImpl.class, DefaultTestService.class, GenericTestService.class);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/Compiler.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/Compiler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.tools;
import javax.annotation.processing.Processor;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import static java.util.Arrays.asList;
/**
* The Java Compiler
*/
public class Compiler {
private final File sourceDirectory;
private final JavaCompiler javaCompiler;
private final StandardJavaFileManager javaFileManager;
private final Set<Processor> processors = new LinkedHashSet<>();
public Compiler() throws IOException {
this(defaultTargetDirectory());
}
public Compiler(File targetDirectory) throws IOException {
this(defaultSourceDirectory(), targetDirectory);
}
public Compiler(File sourceDirectory, File targetDirectory) throws IOException {
this.sourceDirectory = sourceDirectory;
this.javaCompiler = ToolProvider.getSystemJavaCompiler();
this.javaFileManager = javaCompiler.getStandardFileManager(null, null, null);
this.javaFileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(targetDirectory));
this.javaFileManager.setLocation(StandardLocation.SOURCE_OUTPUT, Collections.singleton(targetDirectory));
}
private static File defaultSourceDirectory() {
return new File(defaultRootDirectory(), "src/test/java");
}
private static File defaultRootDirectory() {
return detectClassPath(Compiler.class).getParentFile().getParentFile();
}
private static File defaultTargetDirectory() {
File dir = new File(defaultRootDirectory(), "target/generated-classes");
dir.mkdirs();
return dir;
}
private static File detectClassPath(Class<?> targetClass) {
URL classFileURL = targetClass.getProtectionDomain().getCodeSource().getLocation();
if ("file".equals(classFileURL.getProtocol())) {
return new File(classFileURL.getPath());
} else {
throw new RuntimeException("No support");
}
}
public Compiler processors(Processor... processors) {
this.processors.addAll(asList(processors));
return this;
}
private Iterable<? extends JavaFileObject> getJavaFileObjects(Class<?>... sourceClasses) {
int size = sourceClasses == null ? 0 : sourceClasses.length;
File[] javaSourceFiles = new File[size];
for (int i = 0; i < size; i++) {
File javaSourceFile = javaSourceFile(sourceClasses[i].getName());
javaSourceFiles[i] = javaSourceFile;
}
return javaFileManager.getJavaFileObjects(javaSourceFiles);
}
private File javaSourceFile(String sourceClassName) {
String javaSourceFilePath = sourceClassName.replace('.', '/').concat(".java");
return new File(sourceDirectory, javaSourceFilePath);
}
public boolean compile(Class<?>... sourceClasses) {
JavaCompiler.CompilationTask task = javaCompiler.getTask(
null,
this.javaFileManager,
null,
asList("-parameters", "-Xlint:unchecked", "-nowarn", "-Xlint:deprecation"),
// null,
null,
getJavaFileObjects(sourceClasses));
if (!processors.isEmpty()) {
task.setProcessors(processors);
}
return task.call();
}
public JavaCompiler getJavaCompiler() {
return javaCompiler;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.tools;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.metadata.annotation.processing.model.Model;
import java.util.concurrent.TimeUnit;
/**
* {@link TestService} Implementation
*
* @since 2.7.6
*/
@Service(interfaceName = "org.apache.dubbo.metadata.tools.TestService", version = "1.0.0", group = "default")
public class DefaultTestService implements TestService {
private String name;
@Override
public String echo(String message) {
return "[ECHO] " + message;
}
@Override
public Model model(Model model) {
return model;
}
@Override
public String testPrimitive(boolean z, int i) {
return null;
}
@Override
public Model testEnum(TimeUnit timeUnit) {
return null;
}
@Override
public String testArray(String[] strArray, int[] intArray, Model[] modelArray) {
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/Parent.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/Parent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.tools;
public class Parent extends Ancestor {
private byte b;
private short s;
private int i;
private long l;
public byte getB() {
return b;
}
public void setB(byte b) {
this.b = b;
}
public short getS() {
return s;
}
public void setS(short s) {
this.s = s;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public long getL() {
return l;
}
public void setL(long l) {
this.l = l;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.tools;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;
import java.util.Set;
import static javax.lang.model.SourceVersion.latestSupported;
/**
* {@link Processor} for test
*
* @since 2.7.6
*/
@SupportedAnnotationTypes("*")
public class TestProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
return false;
}
public ProcessingEnvironment getProcessingEnvironment() {
return super.processingEnv;
}
public SourceVersion getSupportedSourceVersion() {
return latestSupported();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing;
import org.apache.dubbo.metadata.tools.Compiler;
import java.lang.reflect.Method;
import java.util.LinkedHashSet;
import java.util.Set;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.InvocationInterceptor;
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;
import static org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest.testInstanceHolder;
public class CompilerInvocationInterceptor implements InvocationInterceptor {
@Override
public void interceptTestMethod(
Invocation<Void> invocation,
ReflectiveInvocationContext<Method> invocationContext,
ExtensionContext extensionContext)
throws Throwable {
Set<Class<?>> classesToBeCompiled = new LinkedHashSet<>();
AbstractAnnotationProcessingTest abstractAnnotationProcessingTest = testInstanceHolder.get();
classesToBeCompiled.add(getClass());
abstractAnnotationProcessingTest.addCompiledClasses(classesToBeCompiled);
Compiler compiler = new Compiler();
compiler.processors(new AnnotationProcessingTestProcessor(
abstractAnnotationProcessingTest, invocation, invocationContext, extensionContext));
compiler.compile(classesToBeCompiled.toArray(new Class[0]));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;
import java.lang.reflect.Method;
import java.util.Set;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.InvocationInterceptor;
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;
import static javax.lang.model.SourceVersion.latestSupported;
@SupportedAnnotationTypes("*")
public class AnnotationProcessingTestProcessor extends AbstractProcessor {
private final AbstractAnnotationProcessingTest abstractAnnotationProcessingTest;
private final InvocationInterceptor.Invocation<Void> invocation;
private final ReflectiveInvocationContext<Method> invocationContext;
private final ExtensionContext extensionContext;
public AnnotationProcessingTestProcessor(
AbstractAnnotationProcessingTest abstractAnnotationProcessingTest,
InvocationInterceptor.Invocation<Void> invocation,
ReflectiveInvocationContext<Method> invocationContext,
ExtensionContext extensionContext) {
this.abstractAnnotationProcessingTest = abstractAnnotationProcessingTest;
this.invocation = invocation;
this.invocationContext = invocationContext;
this.extensionContext = extensionContext;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (!roundEnv.processingOver()) {
prepare();
abstractAnnotationProcessingTest.beforeEach();
try {
invocation.proceed();
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
return false;
}
private void prepare() {
abstractAnnotationProcessingTest.processingEnv = super.processingEnv;
abstractAnnotationProcessingTest.elements = super.processingEnv.getElementUtils();
abstractAnnotationProcessingTest.types = super.processingEnv.getTypeUtils();
}
@Override
public SourceVersion getSupportedSourceVersion() {
return latestSupported();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing;
import org.apache.dubbo.metadata.annotation.processing.util.TypeUtils;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import java.lang.annotation.Annotation;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* Abstract {@link Annotation} Processing Test case
*
* @since 2.7.6
*/
@ExtendWith(CompilerInvocationInterceptor.class)
public abstract class AbstractAnnotationProcessingTest {
static ThreadLocal<AbstractAnnotationProcessingTest> testInstanceHolder = new ThreadLocal<>();
protected ProcessingEnvironment processingEnv;
protected Elements elements;
protected Types types;
@BeforeEach
public final void init() {
testInstanceHolder.set(this);
}
@AfterEach
public final void destroy() {
testInstanceHolder.remove();
}
protected abstract void addCompiledClasses(Set<Class<?>> classesToBeCompiled);
protected abstract void beforeEach();
protected TypeElement getType(Class<?> type) {
return TypeUtils.getType(processingEnv, type);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtilsTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.util;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.metadata.annotation.processing.util.LoggerUtils.info;
import static org.apache.dubbo.metadata.annotation.processing.util.LoggerUtils.warn;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* {@link LoggerUtils} Test
*
* @since 2.7.6
*/
class LoggerUtilsTest {
@Test
void testLogger() {
assertNotNull(LoggerUtils.LOGGER);
}
@Test
void testInfo() {
info("Hello,World");
info("Hello,%s", "World");
info("%s,%s", "Hello", "World");
}
@Test
void testWarn() {
warn("Hello,World");
warn("Hello,%s", "World");
warn("%s,%s", "Hello", "World");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.util;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest;
import org.apache.dubbo.metadata.tools.TestService;
import org.apache.dubbo.metadata.tools.TestServiceImpl;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import javax.ws.rs.Path;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findAnnotation;
import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findMetaAnnotation;
import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAllAnnotations;
import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAnnotation;
import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAnnotations;
import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAttribute;
import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getValue;
import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.isAnnotationPresent;
import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getAllDeclaredMethods;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The {@link AnnotationUtils} Test
*
* @since 2.7.6
*/
class AnnotationUtilsTest extends AbstractAnnotationProcessingTest {
private TypeElement testType;
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {}
@Override
protected void beforeEach() {
testType = getType(TestServiceImpl.class);
}
@Test
void testGetAnnotation() {
AnnotationMirror serviceAnnotation = getAnnotation(testType, Service.class);
assertEquals("3.0.0", getAttribute(serviceAnnotation, "version"));
assertEquals("test", getAttribute(serviceAnnotation, "group"));
assertEquals("org.apache.dubbo.metadata.tools.TestService", getAttribute(serviceAnnotation, "interfaceName"));
assertNull(getAnnotation(testType, (Class) null));
assertNull(getAnnotation(testType, (String) null));
assertNull(getAnnotation(testType.asType(), (Class) null));
assertNull(getAnnotation(testType.asType(), (String) null));
assertNull(getAnnotation((Element) null, (Class) null));
assertNull(getAnnotation((Element) null, (String) null));
assertNull(getAnnotation((TypeElement) null, (Class) null));
assertNull(getAnnotation((TypeElement) null, (String) null));
}
@Test
void testGetAnnotations() {
List<AnnotationMirror> annotations = getAnnotations(testType);
Iterator<AnnotationMirror> iterator = annotations.iterator();
assertEquals(1, annotations.size());
// assertEquals("com.alibaba.dubbo.config.annotation.Service",
// iterator.next().getAnnotationType().toString());
assertEquals(
"org.apache.dubbo.config.annotation.Service",
iterator.next().getAnnotationType().toString());
annotations = getAnnotations(testType, Service.class);
iterator = annotations.iterator();
assertEquals(1, annotations.size());
assertEquals(
"org.apache.dubbo.config.annotation.Service",
iterator.next().getAnnotationType().toString());
annotations = getAnnotations(testType.asType(), Service.class);
iterator = annotations.iterator();
assertEquals(1, annotations.size());
assertEquals(
"org.apache.dubbo.config.annotation.Service",
iterator.next().getAnnotationType().toString());
annotations = getAnnotations(testType.asType(), Service.class.getTypeName());
iterator = annotations.iterator();
assertEquals(1, annotations.size());
assertEquals(
"org.apache.dubbo.config.annotation.Service",
iterator.next().getAnnotationType().toString());
annotations = getAnnotations(testType, Override.class);
assertEquals(0, annotations.size());
// annotations = getAnnotations(testType, com.alibaba.dubbo.config.annotation.Service.class);
// assertEquals(1, annotations.size());
assertTrue(getAnnotations(null, (Class) null).isEmpty());
assertTrue(getAnnotations(null, (String) null).isEmpty());
assertTrue(getAnnotations(testType, (Class) null).isEmpty());
assertTrue(getAnnotations(testType, (String) null).isEmpty());
assertTrue(getAnnotations(null, Service.class).isEmpty());
assertTrue(getAnnotations(null, Service.class.getTypeName()).isEmpty());
}
@Test
void testGetAllAnnotations() {
List<AnnotationMirror> annotations = getAllAnnotations(testType);
assertEquals(4, annotations.size());
annotations = getAllAnnotations(testType.asType(), annotation -> true);
assertEquals(4, annotations.size());
annotations = getAllAnnotations(processingEnv, TestServiceImpl.class);
assertEquals(4, annotations.size());
annotations = getAllAnnotations(testType.asType(), Service.class);
assertEquals(3, annotations.size());
annotations = getAllAnnotations(testType, Override.class);
assertEquals(0, annotations.size());
// annotations = getAllAnnotations(testType.asType(), com.alibaba.dubbo.config.annotation.Service.class);
// assertEquals(2, annotations.size());
assertTrue(getAllAnnotations((Element) null, (Class) null).isEmpty());
assertTrue(getAllAnnotations((TypeMirror) null, (String) null).isEmpty());
assertTrue(getAllAnnotations((ProcessingEnvironment) null, (Class) null).isEmpty());
assertTrue(
getAllAnnotations((ProcessingEnvironment) null, (String) null).isEmpty());
assertTrue(getAllAnnotations((Element) null).isEmpty());
assertTrue(getAllAnnotations((TypeMirror) null).isEmpty());
assertTrue(getAllAnnotations(processingEnv, (Class) null).isEmpty());
assertTrue(getAllAnnotations(processingEnv, (String) null).isEmpty());
assertTrue(getAllAnnotations(testType, (Class) null).isEmpty());
assertTrue(getAllAnnotations(testType.asType(), (Class) null).isEmpty());
assertTrue(getAllAnnotations(testType, (String) null).isEmpty());
assertTrue(getAllAnnotations(testType.asType(), (String) null).isEmpty());
assertTrue(getAllAnnotations((Element) null, Service.class).isEmpty());
assertTrue(getAllAnnotations((TypeMirror) null, Service.class.getTypeName())
.isEmpty());
}
@Test
void testFindAnnotation() {
assertEquals(
"org.apache.dubbo.config.annotation.Service",
findAnnotation(testType, Service.class).getAnnotationType().toString());
// assertEquals("com.alibaba.dubbo.config.annotation.Service", findAnnotation(testType,
// com.alibaba.dubbo.config.annotation.Service.class).getAnnotationType().toString());
assertEquals(
"javax.ws.rs.Path",
findAnnotation(testType, Path.class).getAnnotationType().toString());
assertEquals(
"javax.ws.rs.Path",
findAnnotation(testType.asType(), Path.class)
.getAnnotationType()
.toString());
assertEquals(
"javax.ws.rs.Path",
findAnnotation(testType.asType(), Path.class.getTypeName())
.getAnnotationType()
.toString());
assertNull(findAnnotation(testType, Override.class));
assertNull(findAnnotation((Element) null, (Class) null));
assertNull(findAnnotation((Element) null, (String) null));
assertNull(findAnnotation((TypeMirror) null, (Class) null));
assertNull(findAnnotation((TypeMirror) null, (String) null));
assertNull(findAnnotation(testType, (Class) null));
assertNull(findAnnotation(testType, (String) null));
assertNull(findAnnotation(testType.asType(), (Class) null));
assertNull(findAnnotation(testType.asType(), (String) null));
}
@Test
void testFindMetaAnnotation() {
getAllDeclaredMethods(getType(TestService.class)).forEach(method -> {
assertEquals(
"javax.ws.rs.HttpMethod",
findMetaAnnotation(method, "javax.ws.rs.HttpMethod")
.getAnnotationType()
.toString());
});
}
@Test
void testGetAttribute() {
assertEquals(
"org.apache.dubbo.metadata.tools.TestService",
getAttribute(findAnnotation(testType, Service.class), "interfaceName"));
assertEquals(
"org.apache.dubbo.metadata.tools.TestService",
getAttribute(findAnnotation(testType, Service.class).getElementValues(), "interfaceName"));
assertEquals("/echo", getAttribute(findAnnotation(testType, Path.class), "value"));
assertNull(getAttribute(findAnnotation(testType, Path.class), null));
assertNull(getAttribute(findAnnotation(testType, (Class) null), null));
}
@Test
void testGetValue() {
AnnotationMirror pathAnnotation = getAnnotation(getType(TestService.class), Path.class);
assertEquals("/echo", getValue(pathAnnotation));
}
@Test
void testIsAnnotationPresent() {
assertTrue(isAnnotationPresent(testType, "org.apache.dubbo.config.annotation.Service"));
// assertTrue(isAnnotationPresent(testType, "com.alibaba.dubbo.config.annotation.Service"));
assertTrue(isAnnotationPresent(testType, "javax.ws.rs.Path"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.util;
import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest;
import org.apache.dubbo.metadata.tools.DefaultTestService;
import org.apache.dubbo.metadata.tools.GenericTestService;
import org.apache.dubbo.metadata.tools.TestService;
import org.apache.dubbo.metadata.tools.TestServiceImpl;
import javax.lang.model.element.TypeElement;
import java.util.LinkedHashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.DUBBO_SERVICE_ANNOTATION_TYPE;
import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.GROUP_ATTRIBUTE_NAME;
import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.INTERFACE_CLASS_ATTRIBUTE_NAME;
import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.INTERFACE_NAME_ATTRIBUTE_NAME;
import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.LEGACY_SERVICE_ANNOTATION_TYPE;
import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.SERVICE_ANNOTATION_TYPE;
import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.SUPPORTED_ANNOTATION_TYPES;
import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.VERSION_ATTRIBUTE_NAME;
import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.getAnnotation;
import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.getGroup;
import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.getVersion;
import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.isServiceAnnotationPresent;
import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.resolveServiceInterfaceName;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link ServiceAnnotationUtils} Test
*
* @since 2.7.6
*/
class ServiceAnnotationUtilsTest extends AbstractAnnotationProcessingTest {
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {}
@Override
protected void beforeEach() {}
@Test
void testConstants() {
assertEquals("org.apache.dubbo.config.annotation.DubboService", DUBBO_SERVICE_ANNOTATION_TYPE);
assertEquals("org.apache.dubbo.config.annotation.Service", SERVICE_ANNOTATION_TYPE);
assertEquals("com.alibaba.dubbo.config.annotation.Service", LEGACY_SERVICE_ANNOTATION_TYPE);
assertEquals("interfaceClass", INTERFACE_CLASS_ATTRIBUTE_NAME);
assertEquals("interfaceName", INTERFACE_NAME_ATTRIBUTE_NAME);
assertEquals("group", GROUP_ATTRIBUTE_NAME);
assertEquals("version", VERSION_ATTRIBUTE_NAME);
assertEquals(
new LinkedHashSet<>(asList(
"org.apache.dubbo.config.annotation.DubboService",
"org.apache.dubbo.config.annotation.Service",
"com.alibaba.dubbo.config.annotation.Service")),
SUPPORTED_ANNOTATION_TYPES);
}
@Test
void testIsServiceAnnotationPresent() {
assertTrue(isServiceAnnotationPresent(getType(TestServiceImpl.class)));
assertTrue(isServiceAnnotationPresent(getType(GenericTestService.class)));
assertTrue(isServiceAnnotationPresent(getType(DefaultTestService.class)));
assertFalse(isServiceAnnotationPresent(getType(TestService.class)));
}
@Test
void testGetAnnotation() {
TypeElement type = getType(TestServiceImpl.class);
assertEquals(
"org.apache.dubbo.config.annotation.Service",
getAnnotation(type).getAnnotationType().toString());
// type = getType(GenericTestService.class);
// assertEquals("com.alibaba.dubbo.config.annotation.Service",
// getAnnotation(type).getAnnotationType().toString());
type = getType(DefaultTestService.class);
assertEquals(
"org.apache.dubbo.config.annotation.Service",
getAnnotation(type).getAnnotationType().toString());
assertThrows(IllegalArgumentException.class, () -> getAnnotation(getType(TestService.class)));
}
@Test
void testResolveServiceInterfaceName() {
TypeElement type = getType(TestServiceImpl.class);
assertEquals(
"org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type)));
type = getType(GenericTestService.class);
assertEquals(
"org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type)));
type = getType(DefaultTestService.class);
assertEquals(
"org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type)));
}
@Test
void testGetVersion() {
TypeElement type = getType(TestServiceImpl.class);
assertEquals("3.0.0", getVersion(getAnnotation(type)));
type = getType(GenericTestService.class);
assertEquals("2.0.0", getVersion(getAnnotation(type)));
type = getType(DefaultTestService.class);
assertEquals("1.0.0", getVersion(getAnnotation(type)));
}
@Test
void testGetGroup() {
TypeElement type = getType(TestServiceImpl.class);
assertEquals("test", getGroup(getAnnotation(type)));
type = getType(GenericTestService.class);
assertEquals("generic", getGroup(getAnnotation(type)));
type = getType(DefaultTestService.class);
assertEquals("default", getGroup(getAnnotation(type)));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.util;
import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest;
import org.apache.dubbo.metadata.annotation.processing.model.Model;
import org.apache.dubbo.metadata.tools.TestService;
import org.apache.dubbo.metadata.tools.TestServiceImpl;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.findMethod;
import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getAllDeclaredMethods;
import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getDeclaredMethods;
import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getMethodName;
import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getMethodParameterTypes;
import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getOverrideMethod;
import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getPublicNonStaticMethods;
import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getReturnType;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link MethodUtils} Test
*
* @since 2.7.6
*/
class MethodUtilsTest extends AbstractAnnotationProcessingTest {
private TypeElement testType;
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {}
@Override
protected void beforeEach() {
testType = getType(TestServiceImpl.class);
}
@Test
void testDeclaredMethods() {
TypeElement type = getType(Model.class);
List<ExecutableElement> methods = getDeclaredMethods(type);
assertEquals(12, methods.size());
methods = getAllDeclaredMethods(type);
// registerNatives() no provided in JDK 17
assertTrue(methods.size() >= 33);
assertTrue(getAllDeclaredMethods((TypeElement) null).isEmpty());
assertTrue(getAllDeclaredMethods((TypeMirror) null).isEmpty());
}
private List<? extends ExecutableElement> doGetAllDeclaredMethods() {
return getAllDeclaredMethods(testType, Object.class);
}
@Test
void testGetAllDeclaredMethods() {
List<? extends ExecutableElement> methods = doGetAllDeclaredMethods();
assertEquals(14, methods.size());
}
@Test
void testGetPublicNonStaticMethods() {
List<? extends ExecutableElement> methods = getPublicNonStaticMethods(testType, Object.class);
assertEquals(14, methods.size());
methods = getPublicNonStaticMethods(testType.asType(), Object.class);
assertEquals(14, methods.size());
}
@Test
void testIsMethod() {
List<? extends ExecutableElement> methods = getPublicNonStaticMethods(testType, Object.class);
assertEquals(14, methods.stream().map(MethodUtils::isMethod).count());
}
@Test
void testIsPublicNonStaticMethod() {
List<? extends ExecutableElement> methods = getPublicNonStaticMethods(testType, Object.class);
assertEquals(
14, methods.stream().map(MethodUtils::isPublicNonStaticMethod).count());
}
@Test
void testFindMethod() {
TypeElement type = getType(Model.class);
// Test methods from java.lang.Object
// Object#toString()
String methodName = "toString";
ExecutableElement method = findMethod(type.asType(), methodName);
assertEquals(method.getSimpleName().toString(), methodName);
// Object#hashCode()
methodName = "hashCode";
method = findMethod(type.asType(), methodName);
assertEquals(method.getSimpleName().toString(), methodName);
// Object#getClass()
methodName = "getClass";
method = findMethod(type.asType(), methodName);
assertEquals(method.getSimpleName().toString(), methodName);
// Object#finalize()
methodName = "finalize";
method = findMethod(type.asType(), methodName);
assertEquals(method.getSimpleName().toString(), methodName);
// Object#clone()
methodName = "clone";
method = findMethod(type.asType(), methodName);
assertEquals(method.getSimpleName().toString(), methodName);
// Object#notify()
methodName = "notify";
method = findMethod(type.asType(), methodName);
assertEquals(method.getSimpleName().toString(), methodName);
// Object#notifyAll()
methodName = "notifyAll";
method = findMethod(type.asType(), methodName);
assertEquals(method.getSimpleName().toString(), methodName);
// Object#wait(long)
methodName = "wait";
method = findMethod(type.asType(), methodName, long.class);
assertEquals(method.getSimpleName().toString(), methodName);
// Object#wait(long,int)
methodName = "wait";
method = findMethod(type.asType(), methodName, long.class, int.class);
assertEquals(method.getSimpleName().toString(), methodName);
// Object#equals(Object)
methodName = "equals";
method = findMethod(type.asType(), methodName, Object.class);
assertEquals(method.getSimpleName().toString(), methodName);
}
@Test
void testGetOverrideMethod() {
List<? extends ExecutableElement> methods = doGetAllDeclaredMethods();
ExecutableElement overrideMethod = getOverrideMethod(processingEnv, testType, methods.get(0));
assertNull(overrideMethod);
ExecutableElement declaringMethod = findMethod(getType(TestService.class), "echo", "java.lang.String");
overrideMethod = getOverrideMethod(processingEnv, testType, declaringMethod);
assertEquals(methods.get(0), overrideMethod);
}
@Test
void testGetMethodName() {
ExecutableElement method = findMethod(testType, "echo", "java.lang.String");
assertEquals("echo", getMethodName(method));
assertNull(getMethodName(null));
}
@Test
void testReturnType() {
ExecutableElement method = findMethod(testType, "echo", "java.lang.String");
assertEquals("java.lang.String", getReturnType(method));
assertNull(getReturnType(null));
}
@Test
void testMatchParameterTypes() {
ExecutableElement method = findMethod(testType, "echo", "java.lang.String");
assertArrayEquals(new String[] {"java.lang.String"}, getMethodParameterTypes(method));
assertTrue(getMethodParameterTypes(null).length == 0);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.util;
import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest;
import org.apache.dubbo.metadata.annotation.processing.model.Model;
import org.apache.dubbo.metadata.tools.TestServiceImpl;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
import static javax.lang.model.element.Modifier.PRIVATE;
import static javax.lang.model.util.ElementFilter.fieldsIn;
import static javax.lang.model.util.ElementFilter.methodsIn;
import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.getAllDeclaredMembers;
import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.getDeclaredMembers;
import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.hasModifiers;
import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.isPublicNonStatic;
import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.matchParameterTypes;
import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.findMethod;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link MemberUtils} Test
*
* @since 2.7.6
*/
class MemberUtilsTest extends AbstractAnnotationProcessingTest {
private TypeElement testType;
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {}
@Override
protected void beforeEach() {
testType = getType(TestServiceImpl.class);
}
@Test
void testIsPublicNonStatic() {
assertFalse(isPublicNonStatic(null));
methodsIn(getDeclaredMembers(testType.asType())).forEach(method -> assertTrue(isPublicNonStatic(method)));
}
@Test
void testHasModifiers() {
assertFalse(hasModifiers(null));
List<? extends Element> members = getAllDeclaredMembers(testType.asType());
List<VariableElement> fields = fieldsIn(members);
assertTrue(hasModifiers(fields.get(0), PRIVATE));
}
@Test
void testDeclaredMembers() {
TypeElement type = getType(Model.class);
List<? extends Element> members = getDeclaredMembers(type.asType());
List<VariableElement> fields = fieldsIn(members);
assertEquals(19, members.size());
assertEquals(6, fields.size());
assertEquals("f", fields.get(0).getSimpleName().toString());
assertEquals("d", fields.get(1).getSimpleName().toString());
assertEquals("tu", fields.get(2).getSimpleName().toString());
assertEquals("str", fields.get(3).getSimpleName().toString());
assertEquals("bi", fields.get(4).getSimpleName().toString());
assertEquals("bd", fields.get(5).getSimpleName().toString());
members = getAllDeclaredMembers(type.asType());
fields = fieldsIn(members);
assertEquals(11, fields.size());
assertEquals("f", fields.get(0).getSimpleName().toString());
assertEquals("d", fields.get(1).getSimpleName().toString());
assertEquals("tu", fields.get(2).getSimpleName().toString());
assertEquals("str", fields.get(3).getSimpleName().toString());
assertEquals("bi", fields.get(4).getSimpleName().toString());
assertEquals("bd", fields.get(5).getSimpleName().toString());
assertEquals("b", fields.get(6).getSimpleName().toString());
assertEquals("s", fields.get(7).getSimpleName().toString());
assertEquals("i", fields.get(8).getSimpleName().toString());
assertEquals("l", fields.get(9).getSimpleName().toString());
assertEquals("z", fields.get(10).getSimpleName().toString());
}
@Test
void testMatchParameterTypes() {
ExecutableElement method = findMethod(testType, "echo", "java.lang.String");
assertTrue(matchParameterTypes(method.getParameters(), "java.lang.String"));
assertFalse(matchParameterTypes(method.getParameters(), "java.lang.Object"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.util;
import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest;
import org.apache.dubbo.metadata.annotation.processing.model.ArrayTypeModel;
import org.apache.dubbo.metadata.annotation.processing.model.Color;
import org.apache.dubbo.metadata.annotation.processing.model.Model;
import org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel;
import org.apache.dubbo.metadata.tools.DefaultTestService;
import org.apache.dubbo.metadata.tools.GenericTestService;
import org.apache.dubbo.metadata.tools.TestServiceImpl;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import java.io.File;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getDeclaredFields;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getAllInterfaces;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getAllSuperTypes;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getHierarchicalTypes;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getInterfaces;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getResource;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getResourceName;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getSuperType;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isAnnotationType;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isArrayType;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isClassType;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isDeclaredType;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isEnumType;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isInterfaceType;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isPrimitiveType;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isSameType;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isSimpleType;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isTypeElement;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.listDeclaredTypes;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.listTypeElements;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofDeclaredType;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofDeclaredTypes;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofTypeElement;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The {@link TypeUtils} Test
*
* @since 2.7.6
*/
class TypeUtilsTest extends AbstractAnnotationProcessingTest {
private TypeElement testType;
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {
classesToBeCompiled.add(ArrayTypeModel.class);
classesToBeCompiled.add(Color.class);
}
@Override
protected void beforeEach() {
testType = getType(TestServiceImpl.class);
}
@Test
void testIsSimpleType() {
assertTrue(isSimpleType(getType(Void.class)));
assertTrue(isSimpleType(getType(Boolean.class)));
assertTrue(isSimpleType(getType(Character.class)));
assertTrue(isSimpleType(getType(Byte.class)));
assertTrue(isSimpleType(getType(Short.class)));
assertTrue(isSimpleType(getType(Integer.class)));
assertTrue(isSimpleType(getType(Long.class)));
assertTrue(isSimpleType(getType(Float.class)));
assertTrue(isSimpleType(getType(Double.class)));
assertTrue(isSimpleType(getType(String.class)));
assertTrue(isSimpleType(getType(BigDecimal.class)));
assertTrue(isSimpleType(getType(BigInteger.class)));
assertTrue(isSimpleType(getType(Date.class)));
assertTrue(isSimpleType(getType(Object.class)));
assertFalse(isSimpleType(getType(getClass())));
assertFalse(isSimpleType((TypeElement) null));
assertFalse(isSimpleType((TypeMirror) null));
}
@Test
void testIsSameType() {
assertTrue(isSameType(getType(Void.class).asType(), "java.lang.Void"));
assertFalse(isSameType(getType(String.class).asType(), "java.lang.Void"));
assertFalse(isSameType(getType(Void.class).asType(), (Type) null));
assertFalse(isSameType(null, (Type) null));
assertFalse(isSameType(getType(Void.class).asType(), (String) null));
assertFalse(isSameType(null, (String) null));
}
@Test
void testIsArrayType() {
TypeElement type = getType(ArrayTypeModel.class);
assertTrue(isArrayType(findField(type.asType(), "integers").asType()));
assertTrue(isArrayType(findField(type.asType(), "strings").asType()));
assertTrue(isArrayType(findField(type.asType(), "primitiveTypeModels").asType()));
assertTrue(isArrayType(findField(type.asType(), "models").asType()));
assertTrue(isArrayType(findField(type.asType(), "colors").asType()));
assertFalse(isArrayType((Element) null));
assertFalse(isArrayType((TypeMirror) null));
}
@Test
void testIsEnumType() {
TypeElement type = getType(Color.class);
assertTrue(isEnumType(type.asType()));
type = getType(ArrayTypeModel.class);
assertFalse(isEnumType(type.asType()));
assertFalse(isEnumType((Element) null));
assertFalse(isEnumType((TypeMirror) null));
}
@Test
void testIsClassType() {
TypeElement type = getType(ArrayTypeModel.class);
assertTrue(isClassType(type.asType()));
type = getType(Model.class);
assertTrue(isClassType(type.asType()));
assertFalse(isClassType((Element) null));
assertFalse(isClassType((TypeMirror) null));
}
@Test
void testIsPrimitiveType() {
TypeElement type = getType(PrimitiveTypeModel.class);
getDeclaredFields(type.asType()).stream()
.map(VariableElement::asType)
.forEach(t -> assertTrue(isPrimitiveType(t)));
assertFalse(isPrimitiveType(getType(ArrayTypeModel.class)));
assertFalse(isPrimitiveType((Element) null));
assertFalse(isPrimitiveType((TypeMirror) null));
}
@Test
void testIsInterfaceType() {
TypeElement type = getType(CharSequence.class);
assertTrue(isInterfaceType(type));
assertTrue(isInterfaceType(type.asType()));
type = getType(Model.class);
assertFalse(isInterfaceType(type));
assertFalse(isInterfaceType(type.asType()));
assertFalse(isInterfaceType((Element) null));
assertFalse(isInterfaceType((TypeMirror) null));
}
@Test
void testIsAnnotationType() {
TypeElement type = getType(Override.class);
assertTrue(isAnnotationType(type));
assertTrue(isAnnotationType(type.asType()));
type = getType(Model.class);
assertFalse(isAnnotationType(type));
assertFalse(isAnnotationType(type.asType()));
assertFalse(isAnnotationType((Element) null));
assertFalse(isAnnotationType((TypeMirror) null));
}
@Test
void testGetHierarchicalTypes() {
Set hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, true, true);
Iterator iterator = hierarchicalTypes.iterator();
assertEquals(8, hierarchicalTypes.size());
assertEquals(
"org.apache.dubbo.metadata.tools.TestServiceImpl",
iterator.next().toString());
assertEquals(
"org.apache.dubbo.metadata.tools.GenericTestService",
iterator.next().toString());
assertEquals(
"org.apache.dubbo.metadata.tools.DefaultTestService",
iterator.next().toString());
assertEquals("java.lang.Object", iterator.next().toString());
assertEquals(
"org.apache.dubbo.metadata.tools.TestService", iterator.next().toString());
assertEquals("java.lang.AutoCloseable", iterator.next().toString());
assertEquals("java.io.Serializable", iterator.next().toString());
assertEquals("java.util.EventListener", iterator.next().toString());
hierarchicalTypes = getHierarchicalTypes(testType);
iterator = hierarchicalTypes.iterator();
assertEquals(8, hierarchicalTypes.size());
assertEquals(
"org.apache.dubbo.metadata.tools.TestServiceImpl",
iterator.next().toString());
assertEquals(
"org.apache.dubbo.metadata.tools.GenericTestService",
iterator.next().toString());
assertEquals(
"org.apache.dubbo.metadata.tools.DefaultTestService",
iterator.next().toString());
assertEquals("java.lang.Object", iterator.next().toString());
assertEquals(
"org.apache.dubbo.metadata.tools.TestService", iterator.next().toString());
assertEquals("java.lang.AutoCloseable", iterator.next().toString());
assertEquals("java.io.Serializable", iterator.next().toString());
assertEquals("java.util.EventListener", iterator.next().toString());
hierarchicalTypes = getHierarchicalTypes(testType.asType(), Object.class);
iterator = hierarchicalTypes.iterator();
assertEquals(7, hierarchicalTypes.size());
assertEquals(
"org.apache.dubbo.metadata.tools.TestServiceImpl",
iterator.next().toString());
assertEquals(
"org.apache.dubbo.metadata.tools.GenericTestService",
iterator.next().toString());
assertEquals(
"org.apache.dubbo.metadata.tools.DefaultTestService",
iterator.next().toString());
assertEquals(
"org.apache.dubbo.metadata.tools.TestService", iterator.next().toString());
assertEquals("java.lang.AutoCloseable", iterator.next().toString());
assertEquals("java.io.Serializable", iterator.next().toString());
assertEquals("java.util.EventListener", iterator.next().toString());
hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, true, false);
iterator = hierarchicalTypes.iterator();
assertEquals(4, hierarchicalTypes.size());
assertEquals(
"org.apache.dubbo.metadata.tools.TestServiceImpl",
iterator.next().toString());
assertEquals(
"org.apache.dubbo.metadata.tools.GenericTestService",
iterator.next().toString());
assertEquals(
"org.apache.dubbo.metadata.tools.DefaultTestService",
iterator.next().toString());
assertEquals("java.lang.Object", iterator.next().toString());
hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, false, true);
iterator = hierarchicalTypes.iterator();
assertEquals(5, hierarchicalTypes.size());
assertEquals(
"org.apache.dubbo.metadata.tools.TestServiceImpl",
iterator.next().toString());
assertEquals(
"org.apache.dubbo.metadata.tools.TestService", iterator.next().toString());
assertEquals("java.lang.AutoCloseable", iterator.next().toString());
assertEquals("java.io.Serializable", iterator.next().toString());
assertEquals("java.util.EventListener", iterator.next().toString());
hierarchicalTypes = getHierarchicalTypes(testType.asType(), false, false, true);
iterator = hierarchicalTypes.iterator();
assertEquals(4, hierarchicalTypes.size());
assertEquals(
"org.apache.dubbo.metadata.tools.TestService", iterator.next().toString());
assertEquals("java.lang.AutoCloseable", iterator.next().toString());
assertEquals("java.io.Serializable", iterator.next().toString());
assertEquals("java.util.EventListener", iterator.next().toString());
hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, false, false);
iterator = hierarchicalTypes.iterator();
assertEquals(1, hierarchicalTypes.size());
assertEquals(
"org.apache.dubbo.metadata.tools.TestServiceImpl",
iterator.next().toString());
hierarchicalTypes = getHierarchicalTypes(testType.asType(), false, false, false);
assertEquals(0, hierarchicalTypes.size());
assertTrue(getHierarchicalTypes((TypeElement) null).isEmpty());
assertTrue(getHierarchicalTypes((TypeMirror) null).isEmpty());
}
@Test
void testGetInterfaces() {
TypeElement type = getType(Model.class);
List<TypeMirror> interfaces = getInterfaces(type);
assertTrue(interfaces.isEmpty());
interfaces = getInterfaces(testType.asType());
assertEquals(3, interfaces.size());
assertEquals(
"org.apache.dubbo.metadata.tools.TestService", interfaces.get(0).toString());
assertEquals("java.lang.AutoCloseable", interfaces.get(1).toString());
assertEquals("java.io.Serializable", interfaces.get(2).toString());
assertTrue(getInterfaces((TypeElement) null).isEmpty());
assertTrue(getInterfaces((TypeMirror) null).isEmpty());
}
@Test
void testGetAllInterfaces() {
Set<? extends TypeMirror> interfaces = getAllInterfaces(testType.asType());
assertEquals(4, interfaces.size());
Iterator<? extends TypeMirror> iterator = interfaces.iterator();
assertEquals(
"org.apache.dubbo.metadata.tools.TestService", iterator.next().toString());
assertEquals("java.lang.AutoCloseable", iterator.next().toString());
assertEquals("java.io.Serializable", iterator.next().toString());
assertEquals("java.util.EventListener", iterator.next().toString());
Set<TypeElement> allInterfaces = getAllInterfaces(testType);
assertEquals(4, interfaces.size());
Iterator<TypeElement> allIterator = allInterfaces.iterator();
assertEquals(
"org.apache.dubbo.metadata.tools.TestService",
allIterator.next().toString());
assertEquals("java.lang.AutoCloseable", allIterator.next().toString());
assertEquals("java.io.Serializable", allIterator.next().toString());
assertEquals("java.util.EventListener", allIterator.next().toString());
assertTrue(getAllInterfaces((TypeElement) null).isEmpty());
assertTrue(getAllInterfaces((TypeMirror) null).isEmpty());
}
@Test
void testGetType() {
TypeElement element = TypeUtils.getType(processingEnv, String.class);
assertEquals(element, TypeUtils.getType(processingEnv, element.asType()));
assertEquals(element, TypeUtils.getType(processingEnv, "java.lang.String"));
assertNull(TypeUtils.getType(processingEnv, (Type) null));
assertNull(TypeUtils.getType(processingEnv, (TypeMirror) null));
assertNull(TypeUtils.getType(processingEnv, (CharSequence) null));
assertNull(TypeUtils.getType(null, (CharSequence) null));
}
@Test
void testGetSuperType() {
TypeElement gtsTypeElement = getSuperType(testType);
assertEquals(gtsTypeElement, getType(GenericTestService.class));
TypeElement dtsTypeElement = getSuperType(gtsTypeElement);
assertEquals(dtsTypeElement, getType(DefaultTestService.class));
TypeMirror gtsType = getSuperType(testType.asType());
assertEquals(gtsType, getType(GenericTestService.class).asType());
TypeMirror dtsType = getSuperType(gtsType);
assertEquals(dtsType, getType(DefaultTestService.class).asType());
assertNull(getSuperType((TypeElement) null));
assertNull(getSuperType((TypeMirror) null));
}
@Test
void testGetAllSuperTypes() {
Set<?> allSuperTypes = getAllSuperTypes(testType);
Iterator<?> iterator = allSuperTypes.iterator();
assertEquals(3, allSuperTypes.size());
assertEquals(iterator.next(), getType(GenericTestService.class));
assertEquals(iterator.next(), getType(DefaultTestService.class));
assertEquals(iterator.next(), getType(Object.class));
allSuperTypes = getAllSuperTypes(testType);
iterator = allSuperTypes.iterator();
assertEquals(3, allSuperTypes.size());
assertEquals(iterator.next(), getType(GenericTestService.class));
assertEquals(iterator.next(), getType(DefaultTestService.class));
assertEquals(iterator.next(), getType(Object.class));
assertTrue(getAllSuperTypes((TypeElement) null).isEmpty());
assertTrue(getAllSuperTypes((TypeMirror) null).isEmpty());
}
@Test
void testIsDeclaredType() {
assertTrue(isDeclaredType(testType));
assertTrue(isDeclaredType(testType.asType()));
assertFalse(isDeclaredType((Element) null));
assertFalse(isDeclaredType((TypeMirror) null));
assertFalse(isDeclaredType(types.getNullType()));
assertFalse(isDeclaredType(types.getPrimitiveType(TypeKind.BYTE)));
assertFalse(isDeclaredType(types.getArrayType(types.getPrimitiveType(TypeKind.BYTE))));
}
@Test
void testOfDeclaredType() {
assertEquals(testType.asType(), ofDeclaredType(testType));
assertEquals(testType.asType(), ofDeclaredType(testType.asType()));
assertEquals(ofDeclaredType(testType), ofDeclaredType(testType.asType()));
assertNull(ofDeclaredType((Element) null));
assertNull(ofDeclaredType((TypeMirror) null));
}
@Test
void testIsTypeElement() {
assertTrue(isTypeElement(testType));
assertTrue(isTypeElement(testType.asType()));
assertFalse(isTypeElement((Element) null));
assertFalse(isTypeElement((TypeMirror) null));
}
@Test
void testOfTypeElement() {
assertEquals(testType, ofTypeElement(testType));
assertEquals(testType, ofTypeElement(testType.asType()));
assertNull(ofTypeElement((Element) null));
assertNull(ofTypeElement((TypeMirror) null));
}
@Test
void testOfDeclaredTypes() {
Set<DeclaredType> declaredTypes =
ofDeclaredTypes(asList(getType(String.class), getType(TestServiceImpl.class), getType(Color.class)));
assertTrue(declaredTypes.contains(getType(String.class).asType()));
assertTrue(declaredTypes.contains(getType(TestServiceImpl.class).asType()));
assertTrue(declaredTypes.contains(getType(Color.class).asType()));
assertTrue(ofDeclaredTypes(null).isEmpty());
}
@Test
void testListDeclaredTypes() {
List<DeclaredType> types = listDeclaredTypes(asList(testType, testType, testType));
assertEquals(1, types.size());
assertEquals(ofDeclaredType(testType), types.get(0));
types = listDeclaredTypes(asList(new Element[] {null}));
assertTrue(types.isEmpty());
}
@Test
void testListTypeElements() {
List<TypeElement> typeElements = listTypeElements(asList(testType.asType(), ofDeclaredType(testType)));
assertEquals(1, typeElements.size());
assertEquals(testType, typeElements.get(0));
typeElements = listTypeElements(
asList(types.getPrimitiveType(TypeKind.BYTE), types.getNullType(), types.getNoType(TypeKind.NONE)));
assertTrue(typeElements.isEmpty());
typeElements = listTypeElements(asList(new TypeMirror[] {null}));
assertTrue(typeElements.isEmpty());
typeElements = listTypeElements(null);
assertTrue(typeElements.isEmpty());
}
@Test
@Disabled
public void testGetResource() throws URISyntaxException {
URL resource = getResource(processingEnv, testType);
assertNotNull(resource);
assertTrue(new File(resource.toURI()).exists());
assertEquals(resource, getResource(processingEnv, testType.asType()));
assertEquals(resource, getResource(processingEnv, "org.apache.dubbo.metadata.tools.TestServiceImpl"));
assertThrows(RuntimeException.class, () -> getResource(processingEnv, "NotFound"));
}
@Test
void testGetResourceName() {
assertEquals("java/lang/String.class", getResourceName("java.lang.String"));
assertNull(getResourceName(null));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.util;
import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest;
import org.apache.dubbo.metadata.annotation.processing.model.Color;
import org.apache.dubbo.metadata.annotation.processing.model.Model;
import org.apache.dubbo.metadata.tools.TestServiceImpl;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import static javax.lang.model.element.Modifier.FINAL;
import static javax.lang.model.element.Modifier.PRIVATE;
import static javax.lang.model.element.Modifier.PUBLIC;
import static javax.lang.model.element.Modifier.STATIC;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getAllDeclaredFields;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getAllNonStaticFields;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getDeclaredField;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getDeclaredFields;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getNonStaticFields;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.isEnumMemberField;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.isField;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.isNonStaticField;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link FieldUtils} Test
*
* @since 2.7.6
*/
class FieldUtilsTest extends AbstractAnnotationProcessingTest {
private TypeElement testType;
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {}
@Override
protected void beforeEach() {
testType = getType(TestServiceImpl.class);
}
@Test
void testGetDeclaredFields() {
TypeElement type = getType(Model.class);
List<VariableElement> fields = getDeclaredFields(type);
assertModelFields(fields);
fields = getDeclaredFields(type.asType());
assertModelFields(fields);
assertTrue(getDeclaredFields((Element) null).isEmpty());
assertTrue(getDeclaredFields((TypeMirror) null).isEmpty());
fields = getDeclaredFields(type, f -> "f".equals(f.getSimpleName().toString()));
assertEquals(1, fields.size());
assertEquals("f", fields.get(0).getSimpleName().toString());
}
@Test
void testGetAllDeclaredFields() {
TypeElement type = getType(Model.class);
List<VariableElement> fields = getAllDeclaredFields(type);
assertModelAllFields(fields);
assertTrue(getAllDeclaredFields((Element) null).isEmpty());
assertTrue(getAllDeclaredFields((TypeMirror) null).isEmpty());
fields = getAllDeclaredFields(type, f -> "f".equals(f.getSimpleName().toString()));
assertEquals(1, fields.size());
assertEquals("f", fields.get(0).getSimpleName().toString());
}
@Test
void testGetDeclaredField() {
TypeElement type = getType(Model.class);
testGetDeclaredField(type, "f", float.class);
testGetDeclaredField(type, "d", double.class);
testGetDeclaredField(type, "tu", TimeUnit.class);
testGetDeclaredField(type, "str", String.class);
testGetDeclaredField(type, "bi", BigInteger.class);
testGetDeclaredField(type, "bd", BigDecimal.class);
assertNull(getDeclaredField(type, "b"));
assertNull(getDeclaredField(type, "s"));
assertNull(getDeclaredField(type, "i"));
assertNull(getDeclaredField(type, "l"));
assertNull(getDeclaredField(type, "z"));
assertNull(getDeclaredField((Element) null, "z"));
assertNull(getDeclaredField((TypeMirror) null, "z"));
}
@Test
void testFindField() {
TypeElement type = getType(Model.class);
testFindField(type, "f", float.class);
testFindField(type, "d", double.class);
testFindField(type, "tu", TimeUnit.class);
testFindField(type, "str", String.class);
testFindField(type, "bi", BigInteger.class);
testFindField(type, "bd", BigDecimal.class);
testFindField(type, "b", byte.class);
testFindField(type, "s", short.class);
testFindField(type, "i", int.class);
testFindField(type, "l", long.class);
testFindField(type, "z", boolean.class);
assertNull(findField((Element) null, "f"));
assertNull(findField((Element) null, null));
assertNull(findField((TypeMirror) null, "f"));
assertNull(findField((TypeMirror) null, null));
assertNull(findField(type, null));
assertNull(findField(type.asType(), null));
}
@Test
void testIsEnumField() {
TypeElement type = getType(Color.class);
VariableElement field = findField(type, "RED");
assertTrue(isEnumMemberField(field));
field = findField(type, "YELLOW");
assertTrue(isEnumMemberField(field));
field = findField(type, "BLUE");
assertTrue(isEnumMemberField(field));
type = getType(Model.class);
field = findField(type, "f");
assertFalse(isEnumMemberField(field));
assertFalse(isEnumMemberField(null));
}
@Test
void testIsNonStaticField() {
TypeElement type = getType(Model.class);
assertTrue(isNonStaticField(findField(type, "f")));
type = getType(Color.class);
assertFalse(isNonStaticField(findField(type, "BLUE")));
}
@Test
void testIsField() {
TypeElement type = getType(Model.class);
assertTrue(isField(findField(type, "f")));
assertTrue(isField(findField(type, "f"), PRIVATE));
type = getType(Color.class);
assertTrue(isField(findField(type, "BLUE"), PUBLIC, STATIC, FINAL));
assertFalse(isField(null));
assertFalse(isField(null, PUBLIC, STATIC, FINAL));
}
@Test
void testGetNonStaticFields() {
TypeElement type = getType(Model.class);
List<VariableElement> fields = getNonStaticFields(type);
assertModelFields(fields);
fields = getNonStaticFields(type.asType());
assertModelFields(fields);
assertTrue(getAllNonStaticFields((Element) null).isEmpty());
assertTrue(getAllNonStaticFields((TypeMirror) null).isEmpty());
}
@Test
void testGetAllNonStaticFields() {
TypeElement type = getType(Model.class);
List<VariableElement> fields = getAllNonStaticFields(type);
assertModelAllFields(fields);
fields = getAllNonStaticFields(type.asType());
assertModelAllFields(fields);
assertTrue(getAllNonStaticFields((Element) null).isEmpty());
assertTrue(getAllNonStaticFields((TypeMirror) null).isEmpty());
}
private void assertModelFields(List<VariableElement> fields) {
assertEquals(6, fields.size());
assertEquals("d", fields.get(1).getSimpleName().toString());
assertEquals("tu", fields.get(2).getSimpleName().toString());
assertEquals("str", fields.get(3).getSimpleName().toString());
assertEquals("bi", fields.get(4).getSimpleName().toString());
assertEquals("bd", fields.get(5).getSimpleName().toString());
}
private void assertModelAllFields(List<VariableElement> fields) {
assertEquals(11, fields.size());
assertEquals("f", fields.get(0).getSimpleName().toString());
assertEquals("d", fields.get(1).getSimpleName().toString());
assertEquals("tu", fields.get(2).getSimpleName().toString());
assertEquals("str", fields.get(3).getSimpleName().toString());
assertEquals("bi", fields.get(4).getSimpleName().toString());
assertEquals("bd", fields.get(5).getSimpleName().toString());
assertEquals("b", fields.get(6).getSimpleName().toString());
assertEquals("s", fields.get(7).getSimpleName().toString());
assertEquals("i", fields.get(8).getSimpleName().toString());
assertEquals("l", fields.get(9).getSimpleName().toString());
assertEquals("z", fields.get(10).getSimpleName().toString());
}
private void testGetDeclaredField(TypeElement type, String fieldName, Type fieldType) {
VariableElement field = getDeclaredField(type, fieldName);
assertField(field, fieldName, fieldType);
}
private void testFindField(TypeElement type, String fieldName, Type fieldType) {
VariableElement field = findField(type, fieldName);
assertField(field, fieldName, fieldType);
}
private void assertField(VariableElement field, String fieldName, Type fieldType) {
assertEquals(fieldName, field.getSimpleName().toString());
assertEquals(fieldType.getTypeName(), field.asType().toString());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.builder;
import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest;
import org.apache.dubbo.metadata.annotation.processing.model.Color;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import javax.lang.model.element.TypeElement;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link EnumTypeDefinitionBuilder} Test
*
* @since 2.7.6
*/
class EnumTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest {
private EnumTypeDefinitionBuilder builder;
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {
classesToBeCompiled.add(Color.class);
}
@Override
protected void beforeEach() {
builder = new EnumTypeDefinitionBuilder();
}
@Test
void testAccept() {
TypeElement typeElement = getType(Color.class);
assertTrue(builder.accept(processingEnv, typeElement.asType()));
}
@Test
void testBuild() {
TypeElement typeElement = getType(Color.class);
Map<String, TypeDefinition> typeCache = new HashMap<>();
TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, typeElement, typeCache);
assertEquals(Color.class.getName(), typeDefinition.getType());
assertEquals(asList("RED", "YELLOW", "BLUE"), typeDefinition.getEnums());
// assertEquals(typeDefinition.getTypeBuilderName(), builder.getClass().getName());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.builder;
import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest;
import org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link PrimitiveTypeDefinitionBuilder} Test
*
* @since 2.7.6
*/
class PrimitiveTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest {
private PrimitiveTypeDefinitionBuilder builder;
private VariableElement zField;
private VariableElement bField;
private VariableElement cField;
private VariableElement sField;
private VariableElement iField;
private VariableElement lField;
private VariableElement fField;
private VariableElement dField;
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {
classesToBeCompiled.add(PrimitiveTypeModel.class);
}
@Override
protected void beforeEach() {
builder = new PrimitiveTypeDefinitionBuilder();
TypeElement testType = getType(PrimitiveTypeModel.class);
zField = findField(testType, "z");
bField = findField(testType, "b");
cField = findField(testType, "c");
sField = findField(testType, "s");
iField = findField(testType, "i");
lField = findField(testType, "l");
fField = findField(testType, "f");
dField = findField(testType, "d");
assertEquals("boolean", zField.asType().toString());
assertEquals("byte", bField.asType().toString());
assertEquals("char", cField.asType().toString());
assertEquals("short", sField.asType().toString());
assertEquals("int", iField.asType().toString());
assertEquals("long", lField.asType().toString());
assertEquals("float", fField.asType().toString());
assertEquals("double", dField.asType().toString());
}
@Test
void testAccept() {
assertTrue(builder.accept(processingEnv, zField.asType()));
assertTrue(builder.accept(processingEnv, bField.asType()));
assertTrue(builder.accept(processingEnv, cField.asType()));
assertTrue(builder.accept(processingEnv, sField.asType()));
assertTrue(builder.accept(processingEnv, iField.asType()));
assertTrue(builder.accept(processingEnv, lField.asType()));
assertTrue(builder.accept(processingEnv, fField.asType()));
assertTrue(builder.accept(processingEnv, dField.asType()));
}
@Test
void testBuild() {
buildAndAssertTypeDefinition(processingEnv, zField, builder);
buildAndAssertTypeDefinition(processingEnv, bField, builder);
buildAndAssertTypeDefinition(processingEnv, cField, builder);
buildAndAssertTypeDefinition(processingEnv, sField, builder);
buildAndAssertTypeDefinition(processingEnv, iField, builder);
buildAndAssertTypeDefinition(processingEnv, lField, builder);
buildAndAssertTypeDefinition(processingEnv, zField, builder);
buildAndAssertTypeDefinition(processingEnv, fField, builder);
buildAndAssertTypeDefinition(processingEnv, dField, builder);
}
static void buildAndAssertTypeDefinition(
ProcessingEnvironment processingEnv, VariableElement field, TypeBuilder builder) {
Map<String, TypeDefinition> typeCache = new HashMap<>();
TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, field, typeCache);
assertBasicTypeDefinition(typeDefinition, field.asType().toString(), builder);
// assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref());
}
static void assertBasicTypeDefinition(TypeDefinition typeDefinition, String type, TypeBuilder builder) {
assertEquals(type, typeDefinition.getType());
// assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName());
assertTrue(typeDefinition.getProperties().isEmpty());
assertTrue(typeDefinition.getItems().isEmpty());
assertTrue(typeDefinition.getEnums().isEmpty());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.builder;
import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest;
import org.apache.dubbo.metadata.annotation.processing.model.ArrayTypeModel;
import org.apache.dubbo.metadata.annotation.processing.model.CollectionTypeModel;
import org.apache.dubbo.metadata.annotation.processing.model.Color;
import org.apache.dubbo.metadata.annotation.processing.model.Model;
import org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel;
import org.apache.dubbo.metadata.annotation.processing.model.SimpleTypeModel;
import java.util.Set;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link GeneralTypeDefinitionBuilder} Test
*
* @since 2.7.6
*/
class GeneralTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest {
private GeneralTypeDefinitionBuilder builder;
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {
classesToBeCompiled.add(Model.class);
}
@Override
protected void beforeEach() {
builder = new GeneralTypeDefinitionBuilder();
}
@Test
void testAccept() {
assertTrue(builder.accept(processingEnv, getType(Model.class).asType()));
assertTrue(
builder.accept(processingEnv, getType(PrimitiveTypeModel.class).asType()));
assertTrue(builder.accept(processingEnv, getType(SimpleTypeModel.class).asType()));
assertTrue(builder.accept(processingEnv, getType(ArrayTypeModel.class).asType()));
assertTrue(
builder.accept(processingEnv, getType(CollectionTypeModel.class).asType()));
assertFalse(builder.accept(processingEnv, getType(Color.class).asType()));
}
@Test
void testBuild() {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.builder;
import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest;
import org.apache.dubbo.metadata.annotation.processing.model.SimpleTypeModel;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import java.util.Set;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.metadata.annotation.processing.builder.PrimitiveTypeDefinitionBuilderTest.buildAndAssertTypeDefinition;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link SimpleTypeDefinitionBuilder} Test
*
* @since 2.7.6
*/
class SimpleTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest {
private SimpleTypeDefinitionBuilder builder;
private VariableElement vField;
private VariableElement zField;
private VariableElement cField;
private VariableElement bField;
private VariableElement sField;
private VariableElement iField;
private VariableElement lField;
private VariableElement fField;
private VariableElement dField;
private VariableElement strField;
private VariableElement bdField;
private VariableElement biField;
private VariableElement dtField;
private VariableElement invalidField;
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {
classesToBeCompiled.add(SimpleTypeModel.class);
}
@Override
protected void beforeEach() {
builder = new SimpleTypeDefinitionBuilder();
TypeElement testType = getType(SimpleTypeModel.class);
vField = findField(testType, "v");
zField = findField(testType, "z");
cField = findField(testType, "c");
bField = findField(testType, "b");
sField = findField(testType, "s");
iField = findField(testType, "i");
lField = findField(testType, "l");
fField = findField(testType, "f");
dField = findField(testType, "d");
strField = findField(testType, "str");
bdField = findField(testType, "bd");
biField = findField(testType, "bi");
dtField = findField(testType, "dt");
invalidField = findField(testType, "invalid");
assertEquals("java.lang.Void", vField.asType().toString());
assertEquals("java.lang.Boolean", zField.asType().toString());
assertEquals("java.lang.Character", cField.asType().toString());
assertEquals("java.lang.Byte", bField.asType().toString());
assertEquals("java.lang.Short", sField.asType().toString());
assertEquals("java.lang.Integer", iField.asType().toString());
assertEquals("java.lang.Long", lField.asType().toString());
assertEquals("java.lang.Float", fField.asType().toString());
assertEquals("java.lang.Double", dField.asType().toString());
assertEquals("java.lang.String", strField.asType().toString());
assertEquals("java.math.BigDecimal", bdField.asType().toString());
assertEquals("java.math.BigInteger", biField.asType().toString());
assertEquals("java.util.Date", dtField.asType().toString());
assertEquals("int", invalidField.asType().toString());
}
@Test
void testAccept() {
assertTrue(builder.accept(processingEnv, vField.asType()));
assertTrue(builder.accept(processingEnv, zField.asType()));
assertTrue(builder.accept(processingEnv, cField.asType()));
assertTrue(builder.accept(processingEnv, bField.asType()));
assertTrue(builder.accept(processingEnv, sField.asType()));
assertTrue(builder.accept(processingEnv, iField.asType()));
assertTrue(builder.accept(processingEnv, lField.asType()));
assertTrue(builder.accept(processingEnv, fField.asType()));
assertTrue(builder.accept(processingEnv, dField.asType()));
assertTrue(builder.accept(processingEnv, strField.asType()));
assertTrue(builder.accept(processingEnv, bdField.asType()));
assertTrue(builder.accept(processingEnv, biField.asType()));
assertTrue(builder.accept(processingEnv, dtField.asType()));
// false condition
assertFalse(builder.accept(processingEnv, invalidField.asType()));
}
@Test
void testBuild() {
buildAndAssertTypeDefinition(processingEnv, vField, builder);
buildAndAssertTypeDefinition(processingEnv, zField, builder);
buildAndAssertTypeDefinition(processingEnv, cField, builder);
buildAndAssertTypeDefinition(processingEnv, sField, builder);
buildAndAssertTypeDefinition(processingEnv, iField, builder);
buildAndAssertTypeDefinition(processingEnv, lField, builder);
buildAndAssertTypeDefinition(processingEnv, fField, builder);
buildAndAssertTypeDefinition(processingEnv, dField, builder);
buildAndAssertTypeDefinition(processingEnv, strField, builder);
buildAndAssertTypeDefinition(processingEnv, bdField, builder);
buildAndAssertTypeDefinition(processingEnv, biField, builder);
buildAndAssertTypeDefinition(processingEnv, dtField, builder);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.builder;
import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest;
import org.apache.dubbo.metadata.annotation.processing.model.CollectionTypeModel;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import java.util.Set;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.metadata.annotation.processing.builder.ArrayTypeDefinitionBuilderTest.buildAndAssertTypeDefinition;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link CollectionTypeDefinitionBuilder} Test
*
* @since 2.7.6
*/
class CollectionTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest {
private CollectionTypeDefinitionBuilder builder;
private VariableElement stringsField;
private VariableElement colorsField;
private VariableElement primitiveTypeModelsField;
private VariableElement modelsField;
private VariableElement modelArraysField;
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {
classesToBeCompiled.add(CollectionTypeModel.class);
}
@Override
protected void beforeEach() {
builder = new CollectionTypeDefinitionBuilder();
TypeElement testType = getType(CollectionTypeModel.class);
stringsField = findField(testType, "strings");
colorsField = findField(testType, "colors");
primitiveTypeModelsField = findField(testType, "primitiveTypeModels");
modelsField = findField(testType, "models");
modelArraysField = findField(testType, "modelArrays");
assertEquals("strings", stringsField.getSimpleName().toString());
assertEquals("colors", colorsField.getSimpleName().toString());
assertEquals(
"primitiveTypeModels", primitiveTypeModelsField.getSimpleName().toString());
assertEquals("models", modelsField.getSimpleName().toString());
assertEquals("modelArrays", modelArraysField.getSimpleName().toString());
}
@Test
void testAccept() {
assertTrue(builder.accept(processingEnv, stringsField.asType()));
assertTrue(builder.accept(processingEnv, colorsField.asType()));
assertTrue(builder.accept(processingEnv, primitiveTypeModelsField.asType()));
assertTrue(builder.accept(processingEnv, modelsField.asType()));
assertTrue(builder.accept(processingEnv, modelArraysField.asType()));
}
@Test
void testBuild() {
buildAndAssertTypeDefinition(
processingEnv, stringsField, "java.util.Collection<java.lang.String>", "java.lang.String", builder);
buildAndAssertTypeDefinition(
processingEnv,
colorsField,
"java.util.List<org.apache.dubbo.metadata.annotation.processing.model.Color>",
"org.apache.dubbo.metadata.annotation.processing.model.Color",
builder);
buildAndAssertTypeDefinition(
processingEnv,
primitiveTypeModelsField,
"java.util.Queue<org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel>",
"org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel",
builder);
buildAndAssertTypeDefinition(
processingEnv,
modelsField,
"java.util.Deque<org.apache.dubbo.metadata.annotation.processing.model.Model>",
"org.apache.dubbo.metadata.annotation.processing.model.Model",
builder);
buildAndAssertTypeDefinition(
processingEnv,
modelArraysField,
"java.util.Set<org.apache.dubbo.metadata.annotation.processing.model.Model[]>",
"org.apache.dubbo.metadata.annotation.processing.model.Model[]",
builder);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.builder;
import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest;
import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import org.apache.dubbo.metadata.tools.TestServiceImpl;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.metadata.annotation.processing.builder.ServiceDefinitionBuilder.build;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link ServiceDefinitionBuilder} Test
*
* @since 2.7.6
*/
class ServiceDefinitionBuilderTest extends AbstractAnnotationProcessingTest {
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {
classesToBeCompiled.add(TestServiceImpl.class);
}
@Override
protected void beforeEach() {}
@Test
void testBuild() {
ServiceDefinition serviceDefinition = build(processingEnv, getType(TestServiceImpl.class));
assertEquals(TestServiceImpl.class.getTypeName(), serviceDefinition.getCanonicalName());
assertEquals("org/apache/dubbo/metadata/tools/TestServiceImpl.class", serviceDefinition.getCodeSource());
// types
List<String> typeNames = Arrays.asList(
"org.apache.dubbo.metadata.tools.TestServiceImpl",
"org.apache.dubbo.metadata.tools.GenericTestService",
"org.apache.dubbo.metadata.tools.DefaultTestService",
"org.apache.dubbo.metadata.tools.TestService",
"java.lang.AutoCloseable",
"java.io.Serializable",
"java.util.EventListener");
for (String typeName : typeNames) {
String gotTypeName = getTypeName(typeName, serviceDefinition.getTypes());
assertEquals(typeName, gotTypeName);
}
// methods
assertEquals(14, serviceDefinition.getMethods().size());
}
private static String getTypeName(String type, List<TypeDefinition> types) {
for (TypeDefinition typeDefinition : types) {
if (type.equals(typeDefinition.getType())) {
return typeDefinition.getType();
}
}
return type;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.builder;
import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest;
import org.apache.dubbo.metadata.annotation.processing.model.ArrayTypeModel;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link ArrayTypeDefinitionBuilder} Test
*
* @since 2.7.6
*/
class ArrayTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest {
private ArrayTypeDefinitionBuilder builder;
private TypeElement testType;
private VariableElement integersField;
private VariableElement stringsField;
private VariableElement primitiveTypeModelsField;
private VariableElement modelsField;
private VariableElement colorsField;
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {
classesToBeCompiled.add(ArrayTypeModel.class);
}
@Override
protected void beforeEach() {
builder = new ArrayTypeDefinitionBuilder();
testType = getType(ArrayTypeModel.class);
integersField = findField(testType, "integers");
stringsField = findField(testType, "strings");
primitiveTypeModelsField = findField(testType, "primitiveTypeModels");
modelsField = findField(testType, "models");
colorsField = findField(testType, "colors");
}
@Test
void testAccept() {
assertTrue(builder.accept(processingEnv, integersField.asType()));
assertTrue(builder.accept(processingEnv, stringsField.asType()));
assertTrue(builder.accept(processingEnv, primitiveTypeModelsField.asType()));
assertTrue(builder.accept(processingEnv, modelsField.asType()));
assertTrue(builder.accept(processingEnv, colorsField.asType()));
}
@Test
void testBuild() {
buildAndAssertTypeDefinition(processingEnv, integersField, "int[]", "int", builder);
buildAndAssertTypeDefinition(processingEnv, stringsField, "java.lang.String[]", "java.lang.String", builder);
buildAndAssertTypeDefinition(
processingEnv,
primitiveTypeModelsField,
"org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel[]",
"org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel",
builder);
buildAndAssertTypeDefinition(
processingEnv,
modelsField,
"org.apache.dubbo.metadata.annotation.processing.model.Model[]",
"org.apache.dubbo.metadata.annotation.processing.model.Model",
builder,
(def, subDef) -> {
TypeElement subType = elements.getTypeElement(subDef.getType());
assertEquals(ElementKind.CLASS, subType.getKind());
});
buildAndAssertTypeDefinition(
processingEnv,
colorsField,
"org.apache.dubbo.metadata.annotation.processing.model.Color[]",
"org.apache.dubbo.metadata.annotation.processing.model.Color",
builder,
(def, subDef) -> {
TypeElement subType = elements.getTypeElement(subDef.getType());
assertEquals(ElementKind.ENUM, subType.getKind());
});
}
static void buildAndAssertTypeDefinition(
ProcessingEnvironment processingEnv,
VariableElement field,
String expectedType,
String compositeType,
TypeBuilder builder,
BiConsumer<TypeDefinition, TypeDefinition>... assertions) {
Map<String, TypeDefinition> typeCache = new HashMap<>();
TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, field, typeCache);
String subTypeName = typeDefinition.getItems().get(0);
TypeDefinition subTypeDefinition = typeCache.get(subTypeName);
assertEquals(expectedType, typeDefinition.getType());
// assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref());
assertEquals(compositeType, subTypeDefinition.getType());
// assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName());
Stream.of(assertions).forEach(assertion -> assertion.accept(typeDefinition, subTypeDefinition));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.builder;
import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest;
import org.apache.dubbo.metadata.annotation.processing.model.MapTypeModel;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link MapTypeDefinitionBuilder} Test
*
* @since 2.7.6
*/
class MapTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest {
private MapTypeDefinitionBuilder builder;
private VariableElement stringsField;
private VariableElement colorsField;
private VariableElement primitiveTypeModelsField;
private VariableElement modelsField;
private VariableElement modelArraysField;
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {
classesToBeCompiled.add(MapTypeModel.class);
}
@Override
protected void beforeEach() {
builder = new MapTypeDefinitionBuilder();
TypeElement testType = getType(MapTypeModel.class);
stringsField = findField(testType, "strings");
colorsField = findField(testType, "colors");
primitiveTypeModelsField = findField(testType, "primitiveTypeModels");
modelsField = findField(testType, "models");
modelArraysField = findField(testType, "modelArrays");
assertEquals("strings", stringsField.getSimpleName().toString());
assertEquals("colors", colorsField.getSimpleName().toString());
assertEquals(
"primitiveTypeModels", primitiveTypeModelsField.getSimpleName().toString());
assertEquals("models", modelsField.getSimpleName().toString());
assertEquals("modelArrays", modelArraysField.getSimpleName().toString());
}
@Test
void testAccept() {
assertTrue(builder.accept(processingEnv, stringsField.asType()));
assertTrue(builder.accept(processingEnv, colorsField.asType()));
assertTrue(builder.accept(processingEnv, primitiveTypeModelsField.asType()));
assertTrue(builder.accept(processingEnv, modelsField.asType()));
assertTrue(builder.accept(processingEnv, modelArraysField.asType()));
}
@Test
void testBuild() {
buildAndAssertTypeDefinition(
processingEnv,
stringsField,
"java.util.Map<java.lang.String,java.lang.String>",
"java.lang.String",
"java.lang.String",
builder);
buildAndAssertTypeDefinition(
processingEnv,
colorsField,
"java.util.SortedMap<java.lang.String,org.apache.dubbo.metadata.annotation.processing.model.Color>",
"java.lang.String",
"org.apache.dubbo.metadata.annotation.processing.model.Color",
builder);
buildAndAssertTypeDefinition(
processingEnv,
primitiveTypeModelsField,
"java.util.NavigableMap<org.apache.dubbo.metadata.annotation.processing.model.Color,org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel>",
"org.apache.dubbo.metadata.annotation.processing.model.Color",
"org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel",
builder);
buildAndAssertTypeDefinition(
processingEnv,
modelsField,
"java.util.HashMap<java.lang.String,org.apache.dubbo.metadata.annotation.processing.model.Model>",
"java.lang.String",
"org.apache.dubbo.metadata.annotation.processing.model.Model",
builder);
buildAndAssertTypeDefinition(
processingEnv,
modelArraysField,
"java.util.TreeMap<org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel,org.apache.dubbo.metadata.annotation.processing.model.Model[]>",
"org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel",
"org.apache.dubbo.metadata.annotation.processing.model.Model[]",
builder);
}
static void buildAndAssertTypeDefinition(
ProcessingEnvironment processingEnv,
VariableElement field,
String expectedType,
String keyType,
String valueType,
TypeBuilder builder,
BiConsumer<TypeDefinition, TypeDefinition>... assertions) {
Map<String, TypeDefinition> typeCache = new HashMap<>();
TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, field, typeCache);
String keyTypeName = typeDefinition.getItems().get(0);
TypeDefinition keyTypeDefinition = typeCache.get(keyTypeName);
String valueTypeName = typeDefinition.getItems().get(1);
TypeDefinition valueTypeDefinition = typeCache.get(valueTypeName);
assertEquals(expectedType, typeDefinition.getType());
// assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref());
assertEquals(keyType, keyTypeDefinition.getType());
assertEquals(valueType, valueTypeDefinition.getType());
// assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName());
Stream.of(assertions).forEach(assertion -> assertion.accept(typeDefinition, keyTypeDefinition));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.model;
import java.util.HashMap;
import java.util.Map;
import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* {@link Map} Type model
*
* @since 2.7.6
*/
public class MapTypeModel {
private Map<String, String> strings; // The composite element is simple type
private SortedMap<String, Color> colors; // The composite element is Enum type
private NavigableMap<Color, PrimitiveTypeModel> primitiveTypeModels; // The composite element is POJO type
private HashMap<String, Model> models; // The composite element is hierarchical POJO type
private TreeMap<PrimitiveTypeModel, Model[]> modelArrays; // The composite element is hierarchical POJO type
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Model.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Model.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.model;
import org.apache.dubbo.metadata.tools.Parent;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.concurrent.TimeUnit;
/**
* Model Object
*/
public class Model extends Parent {
private float f;
private double d;
private TimeUnit tu;
private String str;
private BigInteger bi;
private BigDecimal bd;
public float getF() {
return f;
}
public void setF(float f) {
this.f = f;
}
public double getD() {
return d;
}
public void setD(double d) {
this.d = d;
}
public TimeUnit getTu() {
return tu;
}
public void setTu(TimeUnit tu) {
this.tu = tu;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public BigInteger getBi() {
return bi;
}
public void setBi(BigInteger bi) {
this.bi = bi;
}
public BigDecimal getBd() {
return bd;
}
public void setBd(BigDecimal bd) {
this.bd = bd;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/PrimitiveTypeModel.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/PrimitiveTypeModel.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.model;
/**
* Primitive Type model
*
* @since 2.7.6
*/
public class PrimitiveTypeModel {
private boolean z;
private byte b;
private char c;
private short s;
private int i;
private long l;
private float f;
private double d;
public boolean isZ() {
return z;
}
public byte getB() {
return b;
}
public char getC() {
return c;
}
public short getS() {
return s;
}
public int getI() {
return i;
}
public long getL() {
return l;
}
public float getF() {
return f;
}
public double getD() {
return d;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.model;
/**
* Array Type Model
*
* @since 2.7.6
*/
public class ArrayTypeModel {
private int[] integers; // Primitive type array
private String[] strings; // Simple type array
private PrimitiveTypeModel[] primitiveTypeModels; // Complex type array
private Model[] models; // Hierarchical Complex type array
private Color[] colors; // Enum type array
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.model;
/**
* Color enumeration
*
* @since 2.7.6
*/
public enum Color {
RED(1),
YELLOW(2),
BLUE(3);
private final int value;
Color(int value) {
this.value = value;
}
@Override
public String toString() {
return "Color{" + "value=" + value + "} " + super.toString();
}
public int getValue() {
return value;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/SimpleTypeModel.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/SimpleTypeModel.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.model;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
/**
* Simple Type model
*
* @since 2.7.6
*/
public class SimpleTypeModel {
private Void v;
private Boolean z;
private Character c;
private Byte b;
private Short s;
private Integer i;
private Long l;
private Float f;
private Double d;
private String str;
private BigDecimal bd;
private BigInteger bi;
private Date dt;
private int invalid;
public Void getV() {
return v;
}
public void setV(Void v) {
this.v = v;
}
public Boolean getZ() {
return z;
}
public void setZ(Boolean z) {
this.z = z;
}
public Character getC() {
return c;
}
public void setC(Character c) {
this.c = c;
}
public Byte getB() {
return b;
}
public void setB(Byte b) {
this.b = b;
}
public Short getS() {
return s;
}
public void setS(Short s) {
this.s = s;
}
public Integer getI() {
return i;
}
public void setI(Integer i) {
this.i = i;
}
public Long getL() {
return l;
}
public void setL(Long l) {
this.l = l;
}
public Float getF() {
return f;
}
public void setF(Float f) {
this.f = f;
}
public Double getD() {
return d;
}
public void setD(Double d) {
this.d = d;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public BigDecimal getBd() {
return bd;
}
public void setBd(BigDecimal bd) {
this.bd = bd;
}
public BigInteger getBi() {
return bi;
}
public void setBi(BigInteger bi) {
this.bi = bi;
}
public Date getDt() {
return dt;
}
public void setDt(Date dt) {
this.dt = dt;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.java | dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.model;
import java.util.Collection;
import java.util.Deque;
import java.util.List;
import java.util.Queue;
import java.util.Set;
/**
* {@link Collection} Type Model
*
* @since 2.7.6
*/
public class CollectionTypeModel {
private Collection<String> strings; // The composite element is simple type
private List<Color> colors; // The composite element is Enum type
private Queue<PrimitiveTypeModel> primitiveTypeModels; // The composite element is POJO type
private Deque<Model> models; // The composite element is hierarchical POJO type
private Set<Model[]> modelArrays; // The composite element is hierarchical POJO type
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/AbstractServiceAnnotationProcessor.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/AbstractServiceAnnotationProcessor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static javax.lang.model.util.ElementFilter.methodsIn;
import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.SUPPORTED_ANNOTATION_TYPES;
/**
* Abstract {@link Processor} for the classes that were annotated by Dubbo's @Service
*
* @since 2.7.6
*/
public abstract class AbstractServiceAnnotationProcessor extends AbstractProcessor {
protected Elements elements;
private List<? extends Element> objectMembers;
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
this.elements = processingEnv.getElementUtils();
this.objectMembers = elements.getAllMembers(elements.getTypeElement(Object.class.getName()));
}
protected List<? extends Element> getActualMembers(TypeElement type) {
List<? extends Element> members = new LinkedList<>(elements.getAllMembers(type));
members.removeAll(objectMembers);
return members;
}
protected List<? extends ExecutableElement> getActualMethods(TypeElement type) {
return methodsIn(getActualMembers(type));
}
protected Map<String, ExecutableElement> getActualMethodsMap(TypeElement type) {
Map<String, ExecutableElement> methodsMap = new HashMap<>();
getActualMethods(type).forEach(method -> {
methodsMap.put(method.toString(), method);
});
return methodsMap;
}
public static String getMethodSignature(ExecutableElement method) {
if (!ElementKind.METHOD.equals(method.getKind())) {
throw new IllegalArgumentException("The argument must be Method Kind");
}
StringBuilder methodSignatureBuilder = new StringBuilder();
method.getModifiers().forEach(member -> {
methodSignatureBuilder.append(member).append(' ');
});
methodSignatureBuilder.append(method.getReturnType()).append(' ').append(method.toString());
return methodSignatureBuilder.toString();
}
protected TypeElement getTypeElement(CharSequence className) {
return elements.getTypeElement(className);
}
protected PackageElement getPackageElement(Element type) {
return this.elements.getPackageOf(type);
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
@Override
public final Set<String> getSupportedAnnotationTypes() {
return SUPPORTED_ANNOTATION_TYPES;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/ServiceDefinitionMetadataAnnotationProcessor.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/ServiceDefinitionMetadataAnnotationProcessor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.TypeElement;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import static javax.lang.model.util.ElementFilter.typesIn;
import static org.apache.dubbo.metadata.annotation.processing.builder.ServiceDefinitionBuilder.build;
/**
* The {@link Processor} class to generate the metadata of {@link ServiceDefinition} whose classes are annotated by Dubbo's @Service
*
* @see Processor
* @since 2.7.6
*/
public class ServiceDefinitionMetadataAnnotationProcessor extends AbstractServiceAnnotationProcessor {
private List<ServiceDefinition> serviceDefinitions = new LinkedList<>();
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
typesIn(roundEnv.getRootElements()).forEach(serviceType -> process(processingEnv, serviceType, annotations));
if (roundEnv.processingOver()) {
ClassPathMetadataStorage writer = new ClassPathMetadataStorage(processingEnv);
writer.write(() -> JsonUtils.toJson(serviceDefinitions), "META-INF/dubbo/service-definitions.json");
}
return false;
}
private void process(
ProcessingEnvironment processingEnv, TypeElement serviceType, Set<? extends TypeElement> annotations) {
serviceDefinitions.add(build(processingEnv, serviceType));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/ClassPathMetadataStorage.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/ClassPathMetadataStorage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.tools.FileObject;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import static java.util.Optional.empty;
import static java.util.Optional.ofNullable;
import static javax.tools.StandardLocation.CLASS_OUTPUT;
import static org.apache.dubbo.metadata.annotation.processing.util.LoggerUtils.info;
import static org.apache.dubbo.metadata.annotation.processing.util.LoggerUtils.warn;
/**
* A storage class for metadata under class path
*/
public class ClassPathMetadataStorage {
private final Filer filer;
public ClassPathMetadataStorage(ProcessingEnvironment processingEnv) {
this.filer = processingEnv.getFiler();
}
public void write(Supplier<String> contentSupplier, String resourceName) {
try (Writer writer = getWriter(resourceName)) {
writer.write(contentSupplier.get());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public <T> Optional<T> read(String resourceName, Function<Reader, T> consumer) {
if (exists(resourceName)) {
try (Reader reader = getReader(resourceName)) {
return ofNullable(consumer.apply(reader));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return empty();
}
private boolean exists(String resourceName) {
return getResource(resourceName)
.map(FileObject::toUri)
.map(File::new)
.map(File::exists)
.orElse(false);
}
private Reader getReader(String resourceName) {
return getResource(resourceName)
.map(fileObject -> {
try {
return fileObject.openReader(false);
} catch (IOException e) {
}
return null;
})
.orElse(null);
}
private FileObject createResource(String resourceName) throws IOException {
return filer.createResource(CLASS_OUTPUT, "", resourceName);
}
private Optional<FileObject> getResource(String resourceName) {
try {
FileObject fileObject = filer.getResource(CLASS_OUTPUT, "", resourceName);
return ofNullable(fileObject);
} catch (IOException e) {
warn(e.getMessage());
}
return empty();
}
private Writer getWriter(String resourceName) throws IOException {
FileObject fileObject = createResource(resourceName);
info(
"The resource[path : %s , deleted : %s] will be written",
fileObject.toUri().getPath(), fileObject.delete());
return fileObject.openWriter();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtils.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.util;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static java.util.Collections.emptyList;
import static javax.lang.model.element.ElementKind.ENUM_CONSTANT;
import static javax.lang.model.element.ElementKind.FIELD;
import static javax.lang.model.element.Modifier.STATIC;
import static javax.lang.model.util.ElementFilter.fieldsIn;
import static org.apache.dubbo.common.function.Predicates.EMPTY_ARRAY;
import static org.apache.dubbo.common.function.Streams.filterAll;
import static org.apache.dubbo.common.function.Streams.filterFirst;
import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.getDeclaredMembers;
import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.hasModifiers;
import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.matches;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getHierarchicalTypes;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isEnumType;
/**
* The utilities class for the field in the package "javax.lang.model."
*
* @since 2.7.6
*/
public interface FieldUtils {
static List<VariableElement> getDeclaredFields(Element element, Predicate<VariableElement>... fieldFilters) {
return element == null ? emptyList() : getDeclaredFields(element.asType(), fieldFilters);
}
static List<VariableElement> getDeclaredFields(Element element) {
return getDeclaredFields(element, EMPTY_ARRAY);
}
static List<VariableElement> getDeclaredFields(TypeMirror type, Predicate<VariableElement>... fieldFilters) {
return filterAll(fieldsIn(getDeclaredMembers(type)), fieldFilters);
}
static List<VariableElement> getDeclaredFields(TypeMirror type) {
return getDeclaredFields(type, EMPTY_ARRAY);
}
static List<VariableElement> getAllDeclaredFields(Element element, Predicate<VariableElement>... fieldFilters) {
return element == null ? emptyList() : getAllDeclaredFields(element.asType(), fieldFilters);
}
static List<VariableElement> getAllDeclaredFields(Element element) {
return getAllDeclaredFields(element, EMPTY_ARRAY);
}
static List<VariableElement> getAllDeclaredFields(TypeMirror type, Predicate<VariableElement>... fieldFilters) {
return getHierarchicalTypes(type).stream()
.map(t -> getDeclaredFields(t, fieldFilters))
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
static List<VariableElement> getAllDeclaredFields(TypeMirror type) {
return getAllDeclaredFields(type, EMPTY_ARRAY);
}
static VariableElement getDeclaredField(Element element, String fieldName) {
return element == null ? null : getDeclaredField(element.asType(), fieldName);
}
static VariableElement getDeclaredField(TypeMirror type, String fieldName) {
return filterFirst(getDeclaredFields(
type, field -> fieldName.equals(field.getSimpleName().toString())));
}
static VariableElement findField(Element element, String fieldName) {
return element == null ? null : findField(element.asType(), fieldName);
}
static VariableElement findField(TypeMirror type, String fieldName) {
return filterFirst(getAllDeclaredFields(type, field -> equals(field, fieldName)));
}
/**
* is Enum's member field or not
*
* @param field {@link VariableElement} must be public static final fields
* @return if field is public static final, return <code>true</code>, or <code>false</code>
*/
static boolean isEnumMemberField(VariableElement field) {
if (field == null || !isEnumType(field.getEnclosingElement())) {
return false;
}
return ENUM_CONSTANT.equals(field.getKind());
}
static boolean isNonStaticField(VariableElement field) {
return isField(field) && !hasModifiers(field, STATIC);
}
static boolean isField(VariableElement field) {
return matches(field, FIELD) || isEnumMemberField(field);
}
static boolean isField(VariableElement field, Modifier... modifiers) {
return isField(field) && hasModifiers(field, modifiers);
}
static List<VariableElement> getNonStaticFields(TypeMirror type) {
return getDeclaredFields(type, FieldUtils::isNonStaticField);
}
static List<VariableElement> getNonStaticFields(Element element) {
return element == null ? emptyList() : getNonStaticFields(element.asType());
}
static List<VariableElement> getAllNonStaticFields(TypeMirror type) {
return getAllDeclaredFields(type, FieldUtils::isNonStaticField);
}
static List<VariableElement> getAllNonStaticFields(Element element) {
return element == null ? emptyList() : getAllNonStaticFields(element.asType());
}
static boolean equals(VariableElement field, CharSequence fieldName) {
return field != null
&& fieldName != null
&& field.getSimpleName().toString().equals(fieldName.toString());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtils.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.util;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static java.util.Collections.emptyList;
import static javax.lang.model.element.Modifier.PUBLIC;
import static javax.lang.model.element.Modifier.STATIC;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getHierarchicalTypes;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofTypeElement;
/**
* The utilities class for the members in the package "javax.lang.model.", such as "field", "method", "constructor"
*
* @since 2.7.6
*/
public interface MemberUtils {
static boolean matches(Element member, ElementKind kind) {
return member == null || kind == null ? false : kind.equals(member.getKind());
}
static boolean isPublicNonStatic(Element member) {
return hasModifiers(member, PUBLIC) && !hasModifiers(member, STATIC);
}
static boolean hasModifiers(Element member, Modifier... modifiers) {
if (member == null || modifiers == null) {
return false;
}
Set<Modifier> actualModifiers = member.getModifiers();
for (Modifier modifier : modifiers) {
if (!actualModifiers.contains(modifier)) {
return false;
}
}
return true;
}
static List<? extends Element> getDeclaredMembers(TypeMirror type) {
TypeElement element = ofTypeElement(type);
return element == null ? emptyList() : element.getEnclosedElements();
}
static List<? extends Element> getAllDeclaredMembers(TypeMirror type) {
return getHierarchicalTypes(type).stream()
.map(MemberUtils::getDeclaredMembers)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
static boolean matchParameterTypes(List<? extends VariableElement> parameters, CharSequence... parameterTypes) {
int size = parameters.size();
if (size != parameterTypes.length) {
return false;
}
for (int i = 0; i < size; i++) {
VariableElement parameter = parameters.get(i);
if (!Objects.equals(parameter.asType().toString(), parameterTypes[i])) {
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-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/ExecutableElementComparator.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/ExecutableElementComparator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.util;
import org.apache.dubbo.common.utils.CharSequenceComparator;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.VariableElement;
import java.util.Comparator;
import java.util.List;
/**
* The Comparator class for {@link ExecutableElement}, the comparison rule :
* <ol>
* <li>Comparing to two {@link ExecutableElement#getSimpleName() element names} {@link String#compareTo(String) lexicographically}.
* If equals, go to step 2</li>
* <li>Comparing to the count of two parameters. If equals, go to step 3</li>
* <li>Comparing to the type names of parameters {@link String#compareTo(String) lexicographically}</li>
* </ol>
*
* @since 2.7.6
*/
public class ExecutableElementComparator implements Comparator<ExecutableElement> {
public static final ExecutableElementComparator INSTANCE = new ExecutableElementComparator();
private ExecutableElementComparator() {}
@Override
public int compare(ExecutableElement e1, ExecutableElement e2) {
if (e1.equals(e2)) {
return 0;
}
// Step 1
int value = CharSequenceComparator.INSTANCE.compare(e1.getSimpleName(), e2.getSimpleName());
if (value == 0) { // Step 2
List<? extends VariableElement> ps1 = e1.getParameters();
List<? extends VariableElement> ps2 = e1.getParameters();
value = ps1.size() - ps2.size();
if (value == 0) { // Step 3
for (int i = 0; i < ps1.size(); i++) {
value = CharSequenceComparator.INSTANCE.compare(
ps1.get(i).getSimpleName(), ps2.get(i).getSimpleName());
if (value != 0) {
break;
}
}
}
}
return Integer.compare(value, 0);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtils.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.util;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.TypeElement;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
import static java.lang.String.valueOf;
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableSet;
import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAttribute;
import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.isAnnotationPresent;
/**
* The utilities class for @Service annotation
*
* @since 2.7.6
*/
public interface ServiceAnnotationUtils {
/**
* The class name of @Service
*
* @deprecated Recommend {@link #DUBBO_SERVICE_ANNOTATION_TYPE}
*/
@Deprecated
String SERVICE_ANNOTATION_TYPE = "org.apache.dubbo.config.annotation.Service";
/**
* The class name of the legacy @Service
*
* @deprecated Recommend {@link #DUBBO_SERVICE_ANNOTATION_TYPE}
*/
@Deprecated
String LEGACY_SERVICE_ANNOTATION_TYPE = "com.alibaba.dubbo.config.annotation.Service";
/**
* The class name of @DubboService
*
* @since 2.7.9
*/
String DUBBO_SERVICE_ANNOTATION_TYPE = "org.apache.dubbo.config.annotation.DubboService";
/**
* the attribute name of @Service.interfaceClass()
*/
String INTERFACE_CLASS_ATTRIBUTE_NAME = "interfaceClass";
/**
* the attribute name of @Service.interfaceName()
*/
String INTERFACE_NAME_ATTRIBUTE_NAME = "interfaceName";
/**
* the attribute name of @Service.group()
*/
String GROUP_ATTRIBUTE_NAME = "group";
/**
* the attribute name of @Service.version()
*/
String VERSION_ATTRIBUTE_NAME = "version";
Set<String> SUPPORTED_ANNOTATION_TYPES = unmodifiableSet(new LinkedHashSet<>(
asList(DUBBO_SERVICE_ANNOTATION_TYPE, SERVICE_ANNOTATION_TYPE, LEGACY_SERVICE_ANNOTATION_TYPE)));
static boolean isServiceAnnotationPresent(TypeElement annotatedType) {
return SUPPORTED_ANNOTATION_TYPES.stream()
.filter(type -> isAnnotationPresent(annotatedType, type))
.findFirst()
.isPresent();
}
static AnnotationMirror getAnnotation(TypeElement annotatedClass) {
return getAnnotation(annotatedClass.getAnnotationMirrors());
}
static AnnotationMirror getAnnotation(Iterable<? extends AnnotationMirror> annotationMirrors) {
AnnotationMirror matchedAnnotationMirror = null;
MAIN:
for (String supportedAnnotationType : SUPPORTED_ANNOTATION_TYPES) { // Prioritized
for (AnnotationMirror annotationMirror : annotationMirrors) {
String annotationType = annotationMirror.getAnnotationType().toString();
if (Objects.equals(supportedAnnotationType, annotationType)) {
matchedAnnotationMirror = annotationMirror;
break MAIN;
}
}
}
if (matchedAnnotationMirror == null) {
throw new IllegalArgumentException(
"The annotated element must be annotated any of " + SUPPORTED_ANNOTATION_TYPES);
}
return matchedAnnotationMirror;
}
static String resolveServiceInterfaceName(TypeElement annotatedClass, AnnotationMirror serviceAnnotation) {
Object interfaceClass = getAttribute(serviceAnnotation, INTERFACE_CLASS_ATTRIBUTE_NAME);
if (interfaceClass == null) { // try to find the "interfaceName" attribute
interfaceClass = getAttribute(serviceAnnotation, INTERFACE_NAME_ATTRIBUTE_NAME);
}
if (interfaceClass == null) {
// last, get the interface class from first one
interfaceClass = ((TypeElement) annotatedClass).getInterfaces().get(0);
}
return valueOf(interfaceClass);
}
static String getGroup(AnnotationMirror serviceAnnotation) {
return getAttribute(serviceAnnotation, GROUP_ATTRIBUTE_NAME);
}
static String getVersion(AnnotationMirror serviceAnnotation) {
return getAttribute(serviceAnnotation, VERSION_ATTRIBUTE_NAME);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtils.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.util;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static javax.lang.model.element.ElementKind.METHOD;
import static javax.lang.model.util.ElementFilter.methodsIn;
import static org.apache.dubbo.common.function.Predicates.EMPTY_ARRAY;
import static org.apache.dubbo.common.function.Streams.filter;
import static org.apache.dubbo.common.function.Streams.filterAll;
import static org.apache.dubbo.common.function.Streams.filterFirst;
import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.getDeclaredMembers;
import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.isPublicNonStatic;
import static org.apache.dubbo.metadata.annotation.processing.util.MemberUtils.matchParameterTypes;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getHierarchicalTypes;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofDeclaredType;
/**
* The utilities class for method in the package "javax.lang.model."
*
* @since 2.7.6
*/
public interface MethodUtils {
static List<ExecutableElement> getDeclaredMethods(TypeElement type, Predicate<ExecutableElement>... methodFilters) {
return type == null ? emptyList() : getDeclaredMethods(type.asType(), methodFilters);
}
static List<ExecutableElement> getDeclaredMethods(TypeMirror type, Predicate<ExecutableElement>... methodFilters) {
return filterAll(methodsIn(getDeclaredMembers(type)), methodFilters);
}
static List<ExecutableElement> getAllDeclaredMethods(
TypeElement type, Predicate<ExecutableElement>... methodFilters) {
return type == null ? emptyList() : getAllDeclaredMethods(type.asType(), methodFilters);
}
static List<ExecutableElement> getAllDeclaredMethods(TypeElement type) {
return getAllDeclaredMethods(type, EMPTY_ARRAY);
}
static List<ExecutableElement> getAllDeclaredMethods(
TypeMirror type, Predicate<ExecutableElement>... methodFilters) {
return getHierarchicalTypes(type).stream()
.map(t -> getDeclaredMethods(t, methodFilters))
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
static List<ExecutableElement> getAllDeclaredMethods(TypeMirror type) {
return getAllDeclaredMethods(type, EMPTY_ARRAY);
}
static List<ExecutableElement> getAllDeclaredMethods(TypeElement type, Type... excludedTypes) {
return type == null ? emptyList() : getAllDeclaredMethods(type.asType(), excludedTypes);
}
static List<ExecutableElement> getAllDeclaredMethods(TypeMirror type, Type... excludedTypes) {
return getHierarchicalTypes(type, excludedTypes).stream()
.map(t -> getDeclaredMethods(t))
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
static List<ExecutableElement> getPublicNonStaticMethods(TypeElement type, Type... excludedTypes) {
return getPublicNonStaticMethods(ofDeclaredType(type), excludedTypes);
}
static List<ExecutableElement> getPublicNonStaticMethods(TypeMirror type, Type... excludedTypes) {
return filter(getAllDeclaredMethods(type, excludedTypes), MethodUtils::isPublicNonStaticMethod);
}
static boolean isMethod(ExecutableElement method) {
return method != null && METHOD.equals(method.getKind());
}
static boolean isPublicNonStaticMethod(ExecutableElement method) {
return isMethod(method) && isPublicNonStatic(method);
}
static ExecutableElement findMethod(
TypeElement type, String methodName, Type oneParameterType, Type... otherParameterTypes) {
return type == null ? null : findMethod(type.asType(), methodName, oneParameterType, otherParameterTypes);
}
static ExecutableElement findMethod(
TypeMirror type, String methodName, Type oneParameterType, Type... otherParameterTypes) {
List<Type> parameterTypes = new LinkedList<>();
parameterTypes.add(oneParameterType);
parameterTypes.addAll(asList(otherParameterTypes));
return findMethod(
type, methodName, parameterTypes.stream().map(Type::getTypeName).toArray(String[]::new));
}
static ExecutableElement findMethod(TypeElement type, String methodName, CharSequence... parameterTypes) {
return type == null ? null : findMethod(type.asType(), methodName, parameterTypes);
}
static ExecutableElement findMethod(TypeMirror type, String methodName, CharSequence... parameterTypes) {
return filterFirst(
getAllDeclaredMethods(type),
method -> methodName.equals(method.getSimpleName().toString()),
method -> matchParameterTypes(method.getParameters(), parameterTypes));
}
static ExecutableElement getOverrideMethod(
ProcessingEnvironment processingEnv, TypeElement type, ExecutableElement declaringMethod) {
Elements elements = processingEnv.getElementUtils();
return filterFirst(getAllDeclaredMethods(type), method -> elements.overrides(method, declaringMethod, type));
}
static String getMethodName(ExecutableElement method) {
return method == null ? null : method.getSimpleName().toString();
}
static String getReturnType(ExecutableElement method) {
return method == null ? null : TypeUtils.toString(method.getReturnType());
}
static String[] getMethodParameterTypes(ExecutableElement method) {
return method == null
? new String[0]
: method.getParameters().stream()
.map(VariableElement::asType)
.map(TypeUtils::toString)
.toArray(String[]::new);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtils.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.util;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.AnnotatedConstruct;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.TypeMirror;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static java.lang.Enum.valueOf;
import static java.util.Collections.emptyList;
import static org.apache.dubbo.common.function.Predicates.EMPTY_ARRAY;
import static org.apache.dubbo.common.function.Streams.filterAll;
import static org.apache.dubbo.common.function.Streams.filterFirst;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getHierarchicalTypes;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getType;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isSameType;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isTypeElement;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofTypeElement;
/**
* The utilities class for annotation in the package "javax.lang.model.*"
*
* @since 2.7.6
*/
public interface AnnotationUtils {
static AnnotationMirror getAnnotation(
AnnotatedConstruct annotatedConstruct, Class<? extends Annotation> annotationClass) {
return annotationClass == null ? null : getAnnotation(annotatedConstruct, annotationClass.getTypeName());
}
static AnnotationMirror getAnnotation(AnnotatedConstruct annotatedConstruct, CharSequence annotationClassName) {
List<AnnotationMirror> annotations = getAnnotations(annotatedConstruct, annotationClassName);
return annotations.isEmpty() ? null : annotations.get(0);
}
static List<AnnotationMirror> getAnnotations(
AnnotatedConstruct annotatedConstruct, Class<? extends Annotation> annotationClass) {
return annotationClass == null
? emptyList()
: getAnnotations(annotatedConstruct, annotationClass.getTypeName());
}
static List<AnnotationMirror> getAnnotations(
AnnotatedConstruct annotatedConstruct, CharSequence annotationClassName) {
return getAnnotations(
annotatedConstruct, annotation -> isSameType(annotation.getAnnotationType(), annotationClassName));
}
static List<AnnotationMirror> getAnnotations(AnnotatedConstruct annotatedConstruct) {
return getAnnotations(annotatedConstruct, EMPTY_ARRAY);
}
static List<AnnotationMirror> getAnnotations(
AnnotatedConstruct annotatedConstruct, Predicate<AnnotationMirror>... annotationFilters) {
AnnotatedConstruct actualAnnotatedConstruct = annotatedConstruct;
if (annotatedConstruct instanceof TypeMirror) {
actualAnnotatedConstruct = ofTypeElement((TypeMirror) actualAnnotatedConstruct);
}
return actualAnnotatedConstruct == null
? emptyList()
: filterAll(
(List<AnnotationMirror>) actualAnnotatedConstruct.getAnnotationMirrors(), annotationFilters);
}
static List<AnnotationMirror> getAllAnnotations(TypeMirror type) {
return getAllAnnotations(ofTypeElement(type));
}
static List<AnnotationMirror> getAllAnnotations(Element element) {
return getAllAnnotations(element, EMPTY_ARRAY);
}
static List<AnnotationMirror> getAllAnnotations(TypeMirror type, Class<? extends Annotation> annotationClass) {
return getAllAnnotations(ofTypeElement(type), annotationClass);
}
static List<AnnotationMirror> getAllAnnotations(Element element, Class<? extends Annotation> annotationClass) {
return element == null || annotationClass == null
? emptyList()
: getAllAnnotations(element, annotationClass.getTypeName());
}
static List<AnnotationMirror> getAllAnnotations(TypeMirror type, CharSequence annotationClassName) {
return getAllAnnotations(ofTypeElement(type), annotationClassName);
}
static List<AnnotationMirror> getAllAnnotations(Element element, CharSequence annotationClassName) {
return getAllAnnotations(
element, annotation -> isSameType(annotation.getAnnotationType(), annotationClassName));
}
static List<AnnotationMirror> getAllAnnotations(TypeMirror type, Predicate<AnnotationMirror>... annotationFilters) {
return getAllAnnotations(ofTypeElement(type), annotationFilters);
}
static List<AnnotationMirror> getAllAnnotations(Element element, Predicate<AnnotationMirror>... annotationFilters) {
List<AnnotationMirror> allAnnotations = isTypeElement(element)
? getHierarchicalTypes(ofTypeElement(element)).stream()
.map(AnnotationUtils::getAnnotations)
.flatMap(Collection::stream)
.collect(Collectors.toList())
: element == null ? emptyList() : (List<AnnotationMirror>) element.getAnnotationMirrors();
return filterAll(allAnnotations, annotationFilters);
}
static List<AnnotationMirror> getAllAnnotations(ProcessingEnvironment processingEnv, Type annotatedType) {
return getAllAnnotations(processingEnv, annotatedType, EMPTY_ARRAY);
}
static List<AnnotationMirror> getAllAnnotations(
ProcessingEnvironment processingEnv, Type annotatedType, Predicate<AnnotationMirror>... annotationFilters) {
return annotatedType == null
? emptyList()
: getAllAnnotations(processingEnv, annotatedType.getTypeName(), annotationFilters);
}
static List<AnnotationMirror> getAllAnnotations(
ProcessingEnvironment processingEnv,
CharSequence annotatedTypeName,
Predicate<AnnotationMirror>... annotationFilters) {
return getAllAnnotations(getType(processingEnv, annotatedTypeName), annotationFilters);
}
static AnnotationMirror findAnnotation(TypeMirror type, Class<? extends Annotation> annotationClass) {
return annotationClass == null ? null : findAnnotation(type, annotationClass.getTypeName());
}
static AnnotationMirror findAnnotation(TypeMirror type, CharSequence annotationClassName) {
return findAnnotation(ofTypeElement(type), annotationClassName);
}
static AnnotationMirror findAnnotation(Element element, Class<? extends Annotation> annotationClass) {
return annotationClass == null ? null : findAnnotation(element, annotationClass.getTypeName());
}
static AnnotationMirror findAnnotation(Element element, CharSequence annotationClassName) {
return filterFirst(getAllAnnotations(
element, annotation -> isSameType(annotation.getAnnotationType(), annotationClassName)));
}
static AnnotationMirror findMetaAnnotation(Element annotatedConstruct, CharSequence metaAnnotationClassName) {
return annotatedConstruct == null
? null
: getAnnotations(annotatedConstruct).stream()
.map(annotation -> findAnnotation(annotation.getAnnotationType(), metaAnnotationClassName))
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
}
static boolean isAnnotationPresent(Element element, CharSequence annotationClassName) {
return findAnnotation(element, annotationClassName) != null
|| findMetaAnnotation(element, annotationClassName) != null;
}
static <T> T getAttribute(AnnotationMirror annotation, String attributeName) {
return annotation == null ? null : getAttribute(annotation.getElementValues(), attributeName);
}
static <T> T getAttribute(
Map<? extends ExecutableElement, ? extends AnnotationValue> attributesMap, String attributeName) {
T annotationValue = null;
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : attributesMap.entrySet()) {
ExecutableElement attributeMethod = entry.getKey();
if (Objects.equals(attributeName, attributeMethod.getSimpleName().toString())) {
TypeMirror attributeType = attributeMethod.getReturnType();
AnnotationValue value = entry.getValue();
if (attributeType instanceof ArrayType) { // array-typed attribute values
ArrayType arrayType = (ArrayType) attributeType;
String componentType = arrayType.getComponentType().toString();
ClassLoader classLoader = AnnotationUtils.class.getClassLoader();
List<AnnotationValue> values = (List<AnnotationValue>) value.getValue();
int size = values.size();
try {
Class componentClass = classLoader.loadClass(componentType);
boolean isEnum = componentClass.isEnum();
Object array = Array.newInstance(componentClass, values.size());
for (int i = 0; i < size; i++) {
Object element = values.get(i).getValue();
if (isEnum) {
element = valueOf(componentClass, element.toString());
}
Array.set(array, i, element);
}
annotationValue = (T) array;
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
} else {
annotationValue = (T) value.getValue();
}
break;
}
}
return annotationValue;
}
static <T> T getValue(AnnotationMirror annotation) {
return (T) getAttribute(annotation, "value");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtils.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.util;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import static java.lang.String.format;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METADATA_PROCESSOR;
/**
* Logger Utils
*
* @since 2.7.6
*/
public interface LoggerUtils {
ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger("dubbo-metadata-processor");
static void info(String format, Object... args) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info(format(format, args));
}
}
static void warn(String format, Object... args) {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn(COMMON_METADATA_PROCESSOR, "", "", format(format, args));
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtils.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.util;
import org.apache.dubbo.common.utils.ClassUtils;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
import static java.lang.String.valueOf;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toSet;
import static java.util.stream.Stream.of;
import static java.util.stream.StreamSupport.stream;
import static javax.lang.model.element.ElementKind.ANNOTATION_TYPE;
import static javax.lang.model.element.ElementKind.CLASS;
import static javax.lang.model.element.ElementKind.ENUM;
import static javax.lang.model.element.ElementKind.INTERFACE;
import static org.apache.dubbo.common.function.Predicates.EMPTY_ARRAY;
import static org.apache.dubbo.common.function.Streams.filterAll;
import static org.apache.dubbo.common.function.Streams.filterFirst;
import static org.apache.dubbo.common.utils.MethodUtils.invokeMethod;
/**
* The utilities class for type in the package "javax.lang.model.*"
*
* @since 2.7.6
*/
public interface TypeUtils {
List<String> SIMPLE_TYPES =
asList(ClassUtils.SIMPLE_TYPES.stream().map(Class::getName).toArray(String[]::new));
static boolean isSimpleType(Element element) {
return element != null && isSimpleType(element.asType());
}
static boolean isSimpleType(TypeMirror type) {
return type != null && SIMPLE_TYPES.contains(type.toString());
}
static boolean isSameType(TypeMirror type, CharSequence typeName) {
if (type == null || typeName == null) {
return false;
}
return Objects.equals(valueOf(type), valueOf(typeName));
}
static boolean isSameType(TypeMirror typeMirror, Type type) {
return type != null && isSameType(typeMirror, type.getTypeName());
}
static boolean isArrayType(TypeMirror type) {
return type != null && TypeKind.ARRAY.equals(type.getKind());
}
static boolean isArrayType(Element element) {
return element != null && isArrayType(element.asType());
}
static boolean isEnumType(TypeMirror type) {
DeclaredType declaredType = ofDeclaredType(type);
return declaredType != null && ENUM.equals(declaredType.asElement().getKind());
}
static boolean isEnumType(Element element) {
return element != null && isEnumType(element.asType());
}
static boolean isClassType(TypeMirror type) {
DeclaredType declaredType = ofDeclaredType(type);
return declaredType != null && isClassType(declaredType.asElement());
}
static boolean isClassType(Element element) {
return element != null && CLASS.equals(element.getKind());
}
static boolean isPrimitiveType(TypeMirror type) {
return type != null && type.getKind().isPrimitive();
}
static boolean isPrimitiveType(Element element) {
return element != null && isPrimitiveType(element.asType());
}
static boolean isInterfaceType(TypeMirror type) {
DeclaredType declaredType = ofDeclaredType(type);
return declaredType != null && isInterfaceType(declaredType.asElement());
}
static boolean isInterfaceType(Element element) {
return element != null && INTERFACE.equals(element.getKind());
}
static boolean isAnnotationType(TypeMirror type) {
DeclaredType declaredType = ofDeclaredType(type);
return declaredType != null && isAnnotationType(declaredType.asElement());
}
static boolean isAnnotationType(Element element) {
return element != null && ANNOTATION_TYPE.equals(element.getKind());
}
static Set<TypeElement> getHierarchicalTypes(TypeElement type) {
return getHierarchicalTypes(type, true, true, true);
}
static Set<DeclaredType> getHierarchicalTypes(TypeMirror type) {
return getHierarchicalTypes(type, EMPTY_ARRAY);
}
static Set<DeclaredType> getHierarchicalTypes(TypeMirror type, Predicate<DeclaredType>... typeFilters) {
return filterAll(ofDeclaredTypes(getHierarchicalTypes(ofTypeElement(type))), typeFilters);
}
static Set<DeclaredType> getHierarchicalTypes(TypeMirror type, Type... excludedTypes) {
return getHierarchicalTypes(
type, of(excludedTypes).map(Type::getTypeName).toArray(String[]::new));
}
static Set<DeclaredType> getHierarchicalTypes(TypeMirror type, CharSequence... excludedTypeNames) {
Set<String> typeNames =
of(excludedTypeNames).map(CharSequence::toString).collect(toSet());
return getHierarchicalTypes(type, t -> !typeNames.contains(t.toString()));
}
static Set<TypeElement> getHierarchicalTypes(
TypeElement type,
boolean includeSelf,
boolean includeSuperTypes,
boolean includeSuperInterfaces,
Predicate<TypeElement>... typeFilters) {
if (type == null) {
return emptySet();
}
Set<TypeElement> hierarchicalTypes = new LinkedHashSet<>();
if (includeSelf) {
hierarchicalTypes.add(type);
}
if (includeSuperTypes) {
hierarchicalTypes.addAll(getAllSuperTypes(type));
}
if (includeSuperInterfaces) {
hierarchicalTypes.addAll(getAllInterfaces(type));
}
return filterAll(hierarchicalTypes, typeFilters);
}
static Set<DeclaredType> getHierarchicalTypes(
TypeMirror type, boolean includeSelf, boolean includeSuperTypes, boolean includeSuperInterfaces) {
return ofDeclaredTypes(
getHierarchicalTypes(ofTypeElement(type), includeSelf, includeSuperTypes, includeSuperInterfaces));
}
static List<TypeMirror> getInterfaces(TypeElement type, Predicate<TypeMirror>... interfaceFilters) {
return type == null
? emptyList()
: filterAll((List<TypeMirror>) ofTypeElement(type).getInterfaces(), interfaceFilters);
}
static List<TypeMirror> getInterfaces(TypeMirror type, Predicate<TypeMirror>... interfaceFilters) {
return getInterfaces(ofTypeElement(type), interfaceFilters);
}
static Set<TypeElement> getAllInterfaces(TypeElement type, Predicate<TypeElement>... interfaceFilters) {
return type == null ? emptySet() : filterAll(ofTypeElements(getAllInterfaces(type.asType())), interfaceFilters);
}
static Set<? extends TypeMirror> getAllInterfaces(TypeMirror type, Predicate<TypeMirror>... interfaceFilters) {
if (type == null) {
return emptySet();
}
Set<TypeMirror> allInterfaces = new LinkedHashSet<>();
getInterfaces(type).forEach(i -> {
// Add current type's interfaces
allInterfaces.add(i);
// Add
allInterfaces.addAll(getAllInterfaces(i));
});
// Add all super types' interfaces
getAllSuperTypes(type).forEach(superType -> allInterfaces.addAll(getAllInterfaces(superType)));
return filterAll(allInterfaces, interfaceFilters);
}
static TypeMirror findInterface(TypeMirror type, CharSequence interfaceClassName) {
return filterFirst(getAllInterfaces(type), t -> isSameType(t, interfaceClassName));
}
static TypeElement getType(ProcessingEnvironment processingEnv, Type type) {
return type == null ? null : getType(processingEnv, type.getTypeName());
}
static TypeElement getType(ProcessingEnvironment processingEnv, TypeMirror type) {
return type == null ? null : getType(processingEnv, type.toString());
}
static TypeElement getType(ProcessingEnvironment processingEnv, CharSequence typeName) {
if (processingEnv == null || typeName == null) {
return null;
}
Elements elements = processingEnv.getElementUtils();
return elements.getTypeElement(typeName);
}
static TypeElement getSuperType(TypeElement type) {
return type == null ? null : ofTypeElement(type.getSuperclass());
}
static DeclaredType getSuperType(TypeMirror type) {
TypeElement superType = getSuperType(ofTypeElement(type));
return superType == null ? null : ofDeclaredType(superType.asType());
}
static Set<TypeElement> getAllSuperTypes(TypeElement type) {
return getAllSuperTypes(type, EMPTY_ARRAY);
}
static Set<TypeElement> getAllSuperTypes(TypeElement type, Predicate<TypeElement>... typeFilters) {
if (type == null) {
return emptySet();
}
Set<TypeElement> allSuperTypes = new LinkedHashSet<>();
TypeElement superType = getSuperType(type);
if (superType != null) {
// add super type
allSuperTypes.add(superType);
// add ancestors' types
allSuperTypes.addAll(getAllSuperTypes(superType));
}
return filterAll(allSuperTypes, typeFilters);
}
static Set<DeclaredType> getAllSuperTypes(TypeMirror type) {
return getAllSuperTypes(type, EMPTY_ARRAY);
}
static Set<DeclaredType> getAllSuperTypes(TypeMirror type, Predicate<DeclaredType>... typeFilters) {
return filterAll(ofDeclaredTypes(getAllSuperTypes(ofTypeElement(type))), typeFilters);
}
static boolean isDeclaredType(Element element) {
return element != null && isDeclaredType(element.asType());
}
static boolean isDeclaredType(TypeMirror type) {
return type instanceof DeclaredType;
}
static DeclaredType ofDeclaredType(Element element) {
return element == null ? null : ofDeclaredType(element.asType());
}
static DeclaredType ofDeclaredType(TypeMirror type) {
return isDeclaredType(type) ? (DeclaredType) type : null;
}
static boolean isTypeElement(Element element) {
return element instanceof TypeElement;
}
static boolean isTypeElement(TypeMirror type) {
DeclaredType declaredType = ofDeclaredType(type);
return declaredType != null && isTypeElement(declaredType.asElement());
}
static TypeElement ofTypeElement(Element element) {
return isTypeElement(element) ? (TypeElement) element : null;
}
static TypeElement ofTypeElement(TypeMirror type) {
DeclaredType declaredType = ofDeclaredType(type);
if (declaredType != null) {
return ofTypeElement(declaredType.asElement());
}
return null;
}
static Set<DeclaredType> ofDeclaredTypes(Iterable<? extends Element> elements) {
return elements == null
? emptySet()
: stream(elements.spliterator(), false)
.map(TypeUtils::ofTypeElement)
.filter(Objects::nonNull)
.map(Element::asType)
.map(TypeUtils::ofDeclaredType)
.filter(Objects::nonNull)
.collect(LinkedHashSet::new, Set::add, Set::addAll);
}
static Set<TypeElement> ofTypeElements(Iterable<? extends TypeMirror> types) {
return types == null
? emptySet()
: stream(types.spliterator(), false)
.map(TypeUtils::ofTypeElement)
.filter(Objects::nonNull)
.collect(LinkedHashSet::new, Set::add, Set::addAll);
}
static List<DeclaredType> listDeclaredTypes(Iterable<? extends Element> elements) {
return new ArrayList<>(ofDeclaredTypes(elements));
}
static List<TypeElement> listTypeElements(Iterable<? extends TypeMirror> types) {
return new ArrayList<>(ofTypeElements(types));
}
static URL getResource(ProcessingEnvironment processingEnv, Element type) {
return getResource(processingEnv, ofDeclaredType(type));
}
static URL getResource(ProcessingEnvironment processingEnv, TypeMirror type) {
return type == null ? null : getResource(processingEnv, type.toString());
}
static URL getResource(ProcessingEnvironment processingEnv, CharSequence type) {
String relativeName = getResourceName(type);
URL resource = null;
try {
if (relativeName != null) {
FileObject fileObject =
processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", relativeName);
resource = fileObject.toUri().toURL();
// try to open it
resource.getContent();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return resource;
}
static String getResourceName(CharSequence type) {
return type == null ? null : type.toString().replace('.', '/').concat(".class");
}
static String toString(TypeMirror type) {
TypeElement element = ofTypeElement(type);
if (element != null) {
List<? extends TypeParameterElement> typeParameterElements = element.getTypeParameters();
if (!typeParameterElements.isEmpty()) {
List<? extends TypeMirror> typeMirrors;
if (type instanceof DeclaredType) {
typeMirrors = ((DeclaredType) type).getTypeArguments();
} else {
typeMirrors = invokeMethod(type, "getTypeArguments");
}
StringBuilder typeBuilder = new StringBuilder(element.toString());
typeBuilder.append('<');
for (int i = 0; i < typeMirrors.size(); i++) {
if (i > 0) {
typeBuilder.append(", ");
}
typeBuilder.append(typeMirrors.get(i).toString());
}
typeBuilder.append('>');
return typeBuilder.toString();
}
}
return type.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilder.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.builder;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.TypeMirror;
import java.lang.reflect.Array;
import java.util.Map;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isArrayType;
/**
* {@link TypeBuilder} for Java {@link Array}
*
* @since 2.7.6
*/
public class ArrayTypeDefinitionBuilder implements TypeBuilder<ArrayType> {
@Override
public boolean accept(ProcessingEnvironment processingEnv, TypeMirror type) {
return isArrayType(type);
}
@Override
public TypeDefinition build(
ProcessingEnvironment processingEnv, ArrayType type, Map<String, TypeDefinition> typeCache) {
TypeDefinition typeDefinition = new TypeDefinition(type.toString());
TypeMirror componentType = type.getComponentType();
TypeDefinition subTypeDefinition = TypeDefinitionBuilder.build(processingEnv, componentType, typeCache);
typeDefinition.getItems().add(subTypeDefinition.getType());
return typeDefinition;
}
@Override
public int getPriority() {
return MIN_PRIORITY - 4;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilder.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.annotation.processing.builder;
import org.apache.dubbo.metadata.annotation.processing.util.TypeUtils;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.type.DeclaredType;
import java.util.Map;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isSimpleType;
/**
* {@link TypeBuilder} for {@link TypeUtils#SIMPLE_TYPES Java Simple Type}
*
* @since 2.7.6
*/
public class SimpleTypeDefinitionBuilder implements DeclaredTypeDefinitionBuilder {
@Override
public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) {
return isSimpleType(type);
}
@Override
public TypeDefinition build(
ProcessingEnvironment processingEnv, DeclaredType type, Map<String, TypeDefinition> typeCache) {
TypeDefinition td = new TypeDefinition(type.toString());
return td;
}
@Override
public int getPriority() {
return MIN_PRIORITY - 1;
}
}
| 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.