repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/JdkProxyDescriber.java | dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/JdkProxyDescriber.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.aot.api;
import java.util.List;
import java.util.Objects;
/**
* A describer that describes the need for a JDK interface-based {@link java.lang.reflect.Proxy}.
*/
public class JdkProxyDescriber implements ConditionalDescriber {
private final List<String> proxiedInterfaces;
private final String reachableType;
public JdkProxyDescriber(List<String> proxiedInterfaces, String reachableType) {
this.proxiedInterfaces = proxiedInterfaces;
this.reachableType = reachableType;
}
public List<String> getProxiedInterfaces() {
return proxiedInterfaces;
}
@Override
public String getReachableType() {
return reachableType;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
JdkProxyDescriber that = (JdkProxyDescriber) o;
return Objects.equals(proxiedInterfaces, that.proxiedInterfaces)
&& Objects.equals(reachableType, that.reachableType);
}
@Override
public int hashCode() {
return Objects.hash(proxiedInterfaces, reachableType);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ProxyDescriberRegistrar.java | dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ProxyDescriberRegistrar.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.aot.api;
import org.apache.dubbo.common.extension.SPI;
import java.util.List;
@SPI
public interface ProxyDescriberRegistrar {
List<JdkProxyDescriber> getJdkProxyDescribers();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ExecutableDescriber.java | dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ExecutableDescriber.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.aot.api;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* A describer that describes the need for reflection on a {@link Executable}.
*/
public class ExecutableDescriber extends MemberDescriber {
private final List<String> parameterTypes;
private final ExecutableMode mode;
public ExecutableDescriber(Constructor<?> constructor, ExecutableMode mode) {
this(
"<init>",
Arrays.stream(constructor.getParameterTypes())
.map(Class::getName)
.collect(Collectors.toList()),
mode);
}
public ExecutableDescriber(String name, List<String> parameterTypes, ExecutableMode mode) {
super(name);
this.parameterTypes = parameterTypes;
this.mode = mode;
}
public List<String> getParameterTypes() {
return parameterTypes;
}
public ExecutableMode getMode() {
return mode;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ExecutableDescriber that = (ExecutableDescriber) o;
return Objects.equals(parameterTypes, that.parameterTypes) && mode == that.mode;
}
@Override
public int hashCode() {
return Objects.hash(parameterTypes, mode);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/MemberCategory.java | dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/MemberCategory.java | /*
* Copyright 2002-2023 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.aot.api;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
/**
* Represent predefined {@linkplain Member members} groups.
*/
public enum MemberCategory {
/**
* A category that represents public {@linkplain Field fields}.
* @see Class#getFields()
*/
PUBLIC_FIELDS,
/**
* A category that represents {@linkplain Class#getDeclaredFields() declared
* fields}, that is all fields defined by the class, but not inherited ones.
* @see Class#getDeclaredFields()
*/
DECLARED_FIELDS,
/**
* A category that defines public {@linkplain Constructor constructors} can
* be introspected, but not invoked.
* @see Class#getConstructors()
* @see ExecutableMode#INTROSPECT
*/
INTROSPECT_PUBLIC_CONSTRUCTORS,
/**
* A category that defines {@linkplain Class#getDeclaredConstructors() all
* constructors} can be introspected, but not invoked.
* @see Class#getDeclaredConstructors()
* @see ExecutableMode#INTROSPECT
*/
INTROSPECT_DECLARED_CONSTRUCTORS,
/**
* A category that defines public {@linkplain Constructor constructors} can
* be invoked.
* @see Class#getConstructors()
* @see ExecutableMode#INVOKE
*/
INVOKE_PUBLIC_CONSTRUCTORS,
/**
* A category that defines {@linkplain Class#getDeclaredConstructors() all
* constructors} can be invoked.
* @see Class#getDeclaredConstructors()
* @see ExecutableMode#INVOKE
*/
INVOKE_DECLARED_CONSTRUCTORS,
/**
* A category that defines public {@linkplain Method methods}, including
* inherited ones can be introspect, but not invoked.
* @see Class#getMethods()
* @see ExecutableMode#INTROSPECT
*/
INTROSPECT_PUBLIC_METHODS,
/**
* A category that defines {@linkplain Class#getDeclaredMethods() all
* methods}, excluding inherited ones can be introspected, but not invoked.
* @see Class#getDeclaredMethods()
* @see ExecutableMode#INTROSPECT
*/
INTROSPECT_DECLARED_METHODS,
/**
* A category that defines public {@linkplain Method methods}, including
* inherited ones can be invoked.
* @see Class#getMethods()
* @see ExecutableMode#INVOKE
*/
INVOKE_PUBLIC_METHODS,
/**
* A category that defines {@linkplain Class#getDeclaredMethods() all
* methods}, excluding inherited ones can be invoked.
* @see Class#getDeclaredMethods()
* @see ExecutableMode#INVOKE
*/
INVOKE_DECLARED_METHODS,
/**
* A category that represents public {@linkplain Class#getClasses() inner
* classes}. Contrary to other categories, this does not register any
* particular reflection for them but rather make sure they are available
* via a call to {@link Class#getClasses}.
*/
PUBLIC_CLASSES,
/**
* A category that represents all {@linkplain Class#getDeclaredClasses()
* inner classes}. Contrary to other categories, this does not register any
* particular reflection for them but rather make sure they are available
* via a call to {@link Class#getDeclaredClasses}.
*/
DECLARED_CLASSES;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidatorTest.java | dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget;
import org.apache.dubbo.validation.support.jvalidation.mock.ValidationParameter;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
class JValidatorTest {
@Test
void testItWithNonExistMethod() {
Assertions.assertThrows(NoSuchMethodException.class, () -> {
URL url = URL.valueOf(
"test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate("nonExistingMethod", new Class<?>[] {String.class}, new Object[] {"arg1"});
});
}
@Test
void testItWithExistMethod() throws Exception {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate("someMethod1", new Class<?>[] {String.class}, new Object[] {"anything"});
}
@Test
void testItWhenItViolatedConstraint() {
Assertions.assertThrows(ValidationException.class, () -> {
URL url = URL.valueOf(
"test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate(
"someMethod2", new Class<?>[] {ValidationParameter.class}, new Object[] {new ValidationParameter()
});
});
}
@Test
void testItWhenItMeetsConstraint() throws Exception {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate("someMethod2", new Class<?>[] {ValidationParameter.class}, new Object[] {
new ValidationParameter("NotBeNull")
});
}
@Test
void testItWithArrayArg() throws Exception {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate("someMethod3", new Class<?>[] {ValidationParameter[].class}, new Object[] {
new ValidationParameter[] {new ValidationParameter("parameter")}
});
}
@Test
void testItWithCollectionArg() throws Exception {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate(
"someMethod4", new Class<?>[] {List.class}, new Object[] {Collections.singletonList("parameter")});
}
@Test
void testItWithMapArg() throws Exception {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
Map<String, String> map = new HashMap<>();
map.put("key", "value");
jValidator.validate("someMethod5", new Class<?>[] {Map.class}, new Object[] {map});
}
@Test
void testItWithPrimitiveArg() {
Assertions.assertThrows(ValidationException.class, () -> {
URL url = URL.valueOf(
"test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate("someMethod6", new Class<?>[] {Integer.class, String.class, Long.class}, new Object[] {
null, null, null
});
});
}
@Test
void testItWithPrimitiveArgWithProvidedMessage() {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
try {
jValidator.validate("someMethod6", new Class<?>[] {Integer.class, String.class, Long.class}, new Object[] {
null, "", null
});
Assertions.fail();
} catch (Exception e) {
assertThat(e.getMessage(), containsString("string must not be blank"));
assertThat(e.getMessage(), containsString("longValue must not be null"));
}
}
@Test
void testItWithPartialParameterValidation() {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
try {
jValidator.validate("someMethod6", new Class<?>[] {Integer.class, String.class, Long.class}, new Object[] {
null, "", null
});
Assertions.fail();
} catch (Exception e) {
assertThat(e, instanceOf(ConstraintViolationException.class));
ConstraintViolationException e1 = (ConstraintViolationException) e;
assertThat(e1.getConstraintViolations().size(), is(2));
}
}
@Test
void testItWithNestedParameterValidationWithNullParam() {
Assertions.assertThrows(ValidationException.class, () -> {
URL url = URL.valueOf(
"test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate(
"someMethod7", new Class<?>[] {JValidatorTestTarget.BaseParam.class}, new Object[] {null});
});
}
@Test
void testItWithNestedParameterValidationWithNullNestedParam() {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
try {
JValidatorTestTarget.BaseParam<JValidatorTestTarget.Param> param = new JValidatorTestTarget.BaseParam<>();
jValidator.validate(
"someMethod7", new Class<?>[] {JValidatorTestTarget.BaseParam.class}, new Object[] {param});
Assertions.fail();
} catch (Exception e) {
assertThat(e, instanceOf(ConstraintViolationException.class));
ConstraintViolationException e1 = (ConstraintViolationException) e;
assertThat(e1.getConstraintViolations().size(), is(1));
assertThat(e1.getMessage(), containsString("body must not be null"));
}
}
@Test
void testItWithNestedParameterValidationWithNullNestedParams() {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
try {
JValidatorTestTarget.BaseParam<JValidatorTestTarget.Param> param = new JValidatorTestTarget.BaseParam<>();
param.setBody(new JValidatorTestTarget.Param());
jValidator.validate(
"someMethod7", new Class<?>[] {JValidatorTestTarget.BaseParam.class}, new Object[] {param});
Assertions.fail();
} catch (Exception e) {
assertThat(e, instanceOf(ConstraintViolationException.class));
ConstraintViolationException e1 = (ConstraintViolationException) e;
assertThat(e1.getConstraintViolations().size(), is(1));
assertThat(e1.getMessage(), containsString("name must not be null"));
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidationTest.java | dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.validation.Validation;
import org.apache.dubbo.validation.Validator;
import javax.validation.ValidationException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
class JValidationTest {
@Test
void testReturnTypeWithInvalidValidationProvider() {
Assertions.assertThrows(ValidationException.class, () -> {
Validation jValidation = new JValidation();
URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.JValidation?"
+ "jvalidation=org.apache.dubbo.validation.Validation");
jValidation.getValidator(url);
});
}
@Test
void testReturnTypeWithDefaultValidatorProvider() {
Validation jValidation = new JValidation();
URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.JValidation");
Validator validator = jValidation.getValidator(url);
assertThat(validator instanceof JValidator, is(true));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/ValidationParameter.java | dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/ValidationParameter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation.mock;
import javax.validation.constraints.NotNull;
public class ValidationParameter {
@NotNull
private String parameter;
public ValidationParameter() {}
public ValidationParameter(String parameter) {
this.parameter = parameter;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/JValidatorTestTarget.java | dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/JValidatorTestTarget.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation.mock;
import org.apache.dubbo.validation.MethodValidated;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import org.hibernate.validator.constraints.NotBlank;
public interface JValidatorTestTarget {
@MethodValidated
void someMethod1(String anything);
@MethodValidated(Test2.class)
void someMethod2(@NotNull ValidationParameter validationParameter);
void someMethod3(ValidationParameter[] parameters);
void someMethod4(List<String> strings);
void someMethod5(Map<String, String> map);
void someMethod6(
Integer intValue,
@NotBlank(message = "string must not be blank") String string,
@NotNull(message = "longValue must not be null") Long longValue);
void someMethod7(@NotNull BaseParam<Param> baseParam);
@interface Test2 {}
class BaseParam<T> {
@Valid
@NotNull(message = "body must not be null")
private T body;
public T getBody() {
return body;
}
public void setBody(T body) {
this.body = body;
}
}
class Param {
@NotNull(message = "name must not be null")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java | dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.validation.Validation;
import org.apache.dubbo.validation.Validator;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
class ValidationFilterTest {
private Invoker<?> invoker = mock(Invoker.class);
private Validation validation = mock(Validation.class);
private Validator validator = mock(Validator.class);
private RpcInvocation invocation = mock(RpcInvocation.class);
private ValidationFilter validationFilter;
@BeforeEach
public void setUp() {
this.validationFilter = new ValidationFilter();
}
@Test
void testItWithNotExistClass() {
URL url = URL.valueOf("test://test:11/test?validation=true");
given(validation.getValidator(url)).willThrow(new IllegalStateException("Not found class test, cause: test"));
given(invoker.invoke(invocation)).willReturn(new AppResponse("success"));
given(invoker.getUrl()).willReturn(url);
given(invocation.getMethodName()).willReturn("echo1");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class});
given(invocation.getArguments()).willReturn(new Object[] {"arg1"});
validationFilter.setValidation(validation);
Result result = validationFilter.invoke(invoker, invocation);
assertThat(result.getException().getMessage(), is("Not found class test, cause: test"));
}
@Test
void testItWithExistClass() {
URL url = URL.valueOf("test://test:11/test?validation=true");
given(validation.getValidator(url)).willReturn(validator);
given(invoker.invoke(invocation)).willReturn(new AppResponse("success"));
given(invoker.getUrl()).willReturn(url);
given(invocation.getMethodName()).willReturn("echo1");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class});
given(invocation.getArguments()).willReturn(new Object[] {"arg1"});
validationFilter.setValidation(validation);
Result result = validationFilter.invoke(invoker, invocation);
assertThat(String.valueOf(result.getValue()), is("success"));
}
@Test
void testItWithoutUrlParameters() {
URL url = URL.valueOf("test://test:11/test");
given(validation.getValidator(url)).willReturn(validator);
given(invoker.invoke(invocation)).willReturn(new AppResponse("success"));
given(invoker.getUrl()).willReturn(url);
given(invocation.getMethodName()).willReturn("echo1");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class});
given(invocation.getArguments()).willReturn(new Object[] {"arg1"});
validationFilter.setValidation(validation);
Result result = validationFilter.invoke(invoker, invocation);
assertThat(String.valueOf(result.getValue()), is("success"));
}
@Test
void testItWhileMethodNameStartWithDollar() {
URL url = URL.valueOf("test://test:11/test");
given(validation.getValidator(url)).willReturn(validator);
given(invoker.invoke(invocation)).willReturn(new AppResponse("success"));
given(invoker.getUrl()).willReturn(url);
given(invocation.getMethodName()).willReturn("$echo1");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class});
given(invocation.getArguments()).willReturn(new Object[] {"arg1"});
validationFilter.setValidation(validation);
Result result = validationFilter.invoke(invoker, invocation);
assertThat(String.valueOf(result.getValue()), is("success"));
}
@Test
void testItWhileThrowoutRpcException() {
Assertions.assertThrows(RpcException.class, () -> {
URL url = URL.valueOf("test://test:11/test?validation=true");
given(validation.getValidator(url)).willThrow(new RpcException("rpc exception"));
given(invoker.invoke(invocation)).willReturn(new AppResponse("success"));
given(invoker.getUrl()).willReturn(url);
given(invocation.getMethodName()).willReturn("echo1");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class});
given(invocation.getArguments()).willReturn(new Object[] {"arg1"});
validationFilter.setValidation(validation);
validationFilter.invoke(invoker, invocation);
});
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/MethodValidated.java | dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/MethodValidated.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Method grouping validation.
* <p>
* Scenario: this annotation can be used on interface's method when need to check against group before invoke the method
* For example: <pre> @MethodValidated({Save.class, Update.class})
* void relatedQuery(ValidationParameter parameter);
* </pre>
* It means both Save group and Update group are needed to check when method relatedQuery is invoked.
* </p>
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MethodValidated {
Class<?>[] value() default {};
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java | dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation;
/**
* Instance of validator class is an extension to perform validation on method input parameter before the actual method invocation.
*
*/
public interface Validator {
void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception;
boolean isSupport();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java | dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY;
/**
* Instance of Validation interface provide instance of {@link Validator} based on the value of <b>validation</b> attribute.
*/
@SPI("jvalidation")
public interface Validation {
/**
* Return the instance of {@link Validator} for a given url.
* @param url Invocation url
* @return Instance of {@link Validator}
*/
@Adaptive(VALIDATION_KEY)
Validator getValidator(URL url);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java | dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.validation.Validation;
import org.apache.dubbo.validation.Validator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* AbstractValidation is abstract class for Validation interface. It helps low level Validation implementation classes
* by performing common task e.g. key formation, storing instance of validation class to avoid creation of unnecessary
* copy of validation instance and faster execution.
*
* @see Validation
* @see Validator
*/
public abstract class AbstractValidation implements Validation {
private final ConcurrentMap<String, Validator> validators = new ConcurrentHashMap<>();
@Override
public Validator getValidator(URL url) {
String key = url.toFullString();
Validator validator = validators.get(key);
if (validator == null) {
validators.put(key, createValidator(url));
validator = validators.get(key);
}
return validator;
}
protected abstract Validator createValidator(URL url);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/AdapterValidation.java | dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/AdapterValidation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.validation.Validator;
import org.apache.dubbo.validation.support.AbstractValidation;
import java.util.Arrays;
import java.util.List;
public class AdapterValidation extends AbstractValidation {
@Override
protected Validator createValidator(URL url) {
List<Class<? extends Validator>> validatorList = Arrays.asList(JValidator.class, JValidatorNew.class);
for (Class<? extends Validator> instance : validatorList) {
try {
Validator validator = instance.getConstructor(URL.class).newInstance(url);
if (validator.isSupport()) {
return validator;
}
} catch (Throwable ignore) {
}
}
throw new IllegalArgumentException(
"Failed to load jakarta.validation.Validation or javax.validation.Validation from env. "
+ "Please import at least one validator");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidationNew.java | dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidationNew.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.validation.Validator;
import org.apache.dubbo.validation.support.AbstractValidation;
/**
* Creates a new instance of {@link Validator} using input argument url.
* @see AbstractValidation
* @see Validator
*/
@Activate(onClass = "jakarta.validation.Validation")
public class JValidationNew extends AbstractValidation {
/**
* Return new instance of {@link JValidator}
* @param url Valid URL instance
* @return Instance of JValidator
*/
@Override
protected Validator createValidator(URL url) {
return new JValidatorNew(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java | dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.bytecode.ClassGenerator;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.validation.MethodValidated;
import org.apache.dubbo.validation.Validator;
import javax.validation.Constraint;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.MessageInterpolator;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import javax.validation.groups.Default;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.CtNewConstructor;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile;
import javassist.bytecode.ConstPool;
import javassist.bytecode.annotation.ArrayMemberValue;
import javassist.bytecode.annotation.BooleanMemberValue;
import javassist.bytecode.annotation.ByteMemberValue;
import javassist.bytecode.annotation.CharMemberValue;
import javassist.bytecode.annotation.ClassMemberValue;
import javassist.bytecode.annotation.DoubleMemberValue;
import javassist.bytecode.annotation.EnumMemberValue;
import javassist.bytecode.annotation.FloatMemberValue;
import javassist.bytecode.annotation.IntegerMemberValue;
import javassist.bytecode.annotation.LongMemberValue;
import javassist.bytecode.annotation.MemberValue;
import javassist.bytecode.annotation.ShortMemberValue;
import javassist.bytecode.annotation.StringMemberValue;
import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION;
/**
* Implementation of JValidation. JValidation is invoked if configuration validation attribute value is 'jvalidation'.
* <pre>
* e.g. <dubbo:method name="save" validation="jvalidation" />
* </pre>
*/
public class JValidator implements Validator {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(JValidator.class);
private final Class<?> clazz;
private final Map<String, Class<?>> methodClassMap;
private final javax.validation.Validator validator;
@SuppressWarnings({"unchecked", "rawtypes"})
public JValidator(URL url) {
this.clazz = ReflectUtils.forName(url.getServiceInterface());
String jvalidation = url.getParameter("jvalidation");
ValidatorFactory factory;
if (StringUtils.isNotEmpty(jvalidation)) {
factory = Validation.byProvider((Class) ReflectUtils.forName(jvalidation))
.configure()
.buildValidatorFactory();
} else {
MessageInterpolator messageInterpolator = new ParameterMessageInterpolator();
factory = Validation.byDefaultProvider()
.configure()
.messageInterpolator(messageInterpolator)
.buildValidatorFactory();
}
this.validator = factory.getValidator();
this.methodClassMap = new ConcurrentHashMap<>();
}
private static Object getMethodParameterBean(Class<?> clazz, Method method, Object[] args) {
if (!hasConstraintParameter(method)) {
return null;
}
try {
String parameterClassName = generateMethodParameterClassName(clazz, method);
Class<?> parameterClass;
try {
parameterClass = Class.forName(parameterClassName, true, clazz.getClassLoader());
} catch (ClassNotFoundException e) {
parameterClass = generateMethodParameterClass(clazz, method, parameterClassName);
}
Object parameterBean = parameterClass.getDeclaredConstructor().newInstance();
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
Field field = parameterClass.getField(parameters[i].getName());
field.set(parameterBean, args[i]);
}
return parameterBean;
} catch (Throwable e) {
logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", e.getMessage(), e);
return null;
}
}
/**
* try to generate methodParameterClass.
*
* @param clazz interface class
* @param method invoke method
* @param parameterClassName generated parameterClassName
* @return Class<?> generated methodParameterClass
*/
private static Class<?> generateMethodParameterClass(Class<?> clazz, Method method, String parameterClassName)
throws Exception {
ClassPool pool = ClassGenerator.getClassPool(clazz.getClassLoader());
synchronized (parameterClassName.intern()) {
CtClass ctClass = null;
try {
ctClass = pool.getCtClass(parameterClassName);
} catch (NotFoundException ignore) {
}
if (null == ctClass) {
ctClass = pool.makeClass(parameterClassName);
ClassFile classFile = ctClass.getClassFile();
ctClass.addConstructor(CtNewConstructor.defaultConstructor(pool.getCtClass(parameterClassName)));
// parameter fields
Parameter[] parameters = method.getParameters();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int i = 0; i < parameters.length; i++) {
Annotation[] annotations = parameterAnnotations[i];
AnnotationsAttribute attribute =
new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag);
for (Annotation annotation : annotations) {
if (annotation.annotationType().isAnnotationPresent(Constraint.class)) {
javassist.bytecode.annotation.Annotation ja = new javassist.bytecode.annotation.Annotation(
classFile.getConstPool(),
pool.getCtClass(annotation.annotationType().getName()));
Method[] members = annotation.annotationType().getMethods();
for (Method member : members) {
if (Modifier.isPublic(member.getModifiers())
&& member.getParameterTypes().length == 0
&& member.getDeclaringClass() == annotation.annotationType()) {
Object value = member.invoke(annotation);
if (null != value) {
MemberValue memberValue = createMemberValue(
classFile.getConstPool(),
pool.get(member.getReturnType().getName()),
value);
ja.addMemberValue(member.getName(), memberValue);
}
}
}
attribute.addAnnotation(ja);
}
}
Parameter parameter = parameters[i];
Class<?> type = parameter.getType();
String fieldName = parameter.getName();
CtField ctField = CtField.make(
"public " + type.getCanonicalName() + " " + fieldName + ";",
pool.getCtClass(parameterClassName));
ctField.getFieldInfo().addAttribute(attribute);
ctClass.addField(ctField);
}
return pool.toClass(ctClass, clazz, clazz.getClassLoader(), clazz.getProtectionDomain());
} else {
return Class.forName(parameterClassName, true, clazz.getClassLoader());
}
}
}
private static String generateMethodParameterClassName(Class<?> clazz, Method method) {
StringBuilder builder = new StringBuilder()
.append(clazz.getName())
.append('_')
.append(toUpperMethodName(method.getName()))
.append("Parameter");
Class<?>[] parameterTypes = method.getParameterTypes();
for (Class<?> parameterType : parameterTypes) {
// In order to ensure that the parameter class can be generated correctly,
// replace "." with "_" to make the package name of the generated parameter class
// consistent with the package name of the actual parameter class.
builder.append('_').append(parameterType.getName().replace(".", "_"));
}
return builder.toString();
}
private static boolean hasConstraintParameter(Method method) {
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (Annotation[] annotations : parameterAnnotations) {
for (Annotation annotation : annotations) {
if (annotation.annotationType().isAnnotationPresent(Constraint.class)) {
return true;
}
}
}
return false;
}
private static String toUpperMethodName(String methodName) {
return methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
}
// Copy from javassist.bytecode.annotation.Annotation.createMemberValue(ConstPool, CtClass);
private static MemberValue createMemberValue(ConstPool cp, CtClass type, Object value) throws NotFoundException {
MemberValue memberValue = javassist.bytecode.annotation.Annotation.createMemberValue(cp, type);
if (memberValue instanceof BooleanMemberValue) {
((BooleanMemberValue) memberValue).setValue((Boolean) value);
} else if (memberValue instanceof ByteMemberValue) {
((ByteMemberValue) memberValue).setValue((Byte) value);
} else if (memberValue instanceof CharMemberValue) {
((CharMemberValue) memberValue).setValue((Character) value);
} else if (memberValue instanceof ShortMemberValue) {
((ShortMemberValue) memberValue).setValue((Short) value);
} else if (memberValue instanceof IntegerMemberValue) {
((IntegerMemberValue) memberValue).setValue((Integer) value);
} else if (memberValue instanceof LongMemberValue) {
((LongMemberValue) memberValue).setValue((Long) value);
} else if (memberValue instanceof FloatMemberValue) {
((FloatMemberValue) memberValue).setValue((Float) value);
} else if (memberValue instanceof DoubleMemberValue) {
((DoubleMemberValue) memberValue).setValue((Double) value);
} else if (memberValue instanceof ClassMemberValue) {
((ClassMemberValue) memberValue).setValue(((Class<?>) value).getName());
} else if (memberValue instanceof StringMemberValue) {
((StringMemberValue) memberValue).setValue((String) value);
} else if (memberValue instanceof EnumMemberValue) {
((EnumMemberValue) memberValue).setValue(((Enum<?>) value).name());
}
/* else if (memberValue instanceof AnnotationMemberValue) */
else if (memberValue instanceof ArrayMemberValue) {
CtClass arrayType = type.getComponentType();
int len = Array.getLength(value);
MemberValue[] members = new MemberValue[len];
for (int i = 0; i < len; i++) {
members[i] = createMemberValue(cp, arrayType, Array.get(value, i));
}
((ArrayMemberValue) memberValue).setValue(members);
}
return memberValue;
}
@Override
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
List<Class<?>> groups = new ArrayList<>();
Class<?> methodClass = methodClass(methodName);
if (methodClass != null) {
groups.add(methodClass);
}
Method method = clazz.getMethod(methodName, parameterTypes);
Class<?>[] methodClasses;
if (method.isAnnotationPresent(MethodValidated.class)) {
methodClasses = method.getAnnotation(MethodValidated.class).value();
groups.addAll(Arrays.asList(methodClasses));
}
// add into default group
groups.add(0, Default.class);
groups.add(1, clazz);
// convert list to array
Class<?>[] classGroups = groups.toArray(new Class[0]);
Set<ConstraintViolation<?>> violations = new HashSet<>();
Object parameterBean = getMethodParameterBean(clazz, method, arguments);
if (parameterBean != null) {
violations.addAll(validator.validate(parameterBean, classGroups));
}
for (Object arg : arguments) {
validate(violations, arg, classGroups);
}
if (!violations.isEmpty()) {
logger.info("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: "
+ violations);
throw new ConstraintViolationException(
"Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: "
+ violations,
violations);
}
}
@Override
public boolean isSupport() {
Class<?> cls = null;
try {
cls = javax.validation.Validation.class;
} catch (Throwable ignore) {
}
return cls != null;
}
private Class<?> methodClass(String methodName) {
Class<?> methodClass = null;
String methodClassName = clazz.getName() + "$" + toUpperMethodName(methodName);
Class<?> cached = methodClassMap.get(methodClassName);
if (cached != null) {
return cached == clazz ? null : cached;
}
try {
methodClass =
Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
methodClassMap.put(methodClassName, methodClass);
} catch (ClassNotFoundException e) {
methodClassMap.put(methodClassName, clazz);
}
return methodClass;
}
private void validate(Set<ConstraintViolation<?>> violations, Object arg, Class<?>... groups) {
if (arg != null && !ReflectUtils.isPrimitives(arg.getClass())) {
if (arg instanceof Object[]) {
for (Object item : (Object[]) arg) {
validate(violations, item, groups);
}
} else if (arg instanceof Collection) {
for (Object item : (Collection<?>) arg) {
validate(violations, item, groups);
}
} else if (arg instanceof Map) {
for (Map.Entry<?, ?> entry : ((Map<?, ?>) arg).entrySet()) {
validate(violations, entry.getKey(), groups);
validate(violations, entry.getValue(), groups);
}
} else {
violations.addAll(validator.validate(arg, groups));
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java | dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.validation.Validator;
import org.apache.dubbo.validation.support.AbstractValidation;
/**
* Creates a new instance of {@link Validator} using input argument url.
* @see AbstractValidation
* @see Validator
*/
@Activate(onClass = "javax.validation.Validation")
public class JValidation extends AbstractValidation {
/**
* Return new instance of {@link JValidator}
* @param url Valid URL instance
* @return Instance of JValidator
*/
@Override
protected Validator createValidator(URL url) {
return new JValidator(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java | dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.bytecode.ClassGenerator;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.validation.MethodValidated;
import org.apache.dubbo.validation.Validator;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.CtNewConstructor;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile;
import javassist.bytecode.ConstPool;
import javassist.bytecode.annotation.ArrayMemberValue;
import javassist.bytecode.annotation.BooleanMemberValue;
import javassist.bytecode.annotation.ByteMemberValue;
import javassist.bytecode.annotation.CharMemberValue;
import javassist.bytecode.annotation.ClassMemberValue;
import javassist.bytecode.annotation.DoubleMemberValue;
import javassist.bytecode.annotation.EnumMemberValue;
import javassist.bytecode.annotation.FloatMemberValue;
import javassist.bytecode.annotation.IntegerMemberValue;
import javassist.bytecode.annotation.LongMemberValue;
import javassist.bytecode.annotation.MemberValue;
import javassist.bytecode.annotation.ShortMemberValue;
import javassist.bytecode.annotation.StringMemberValue;
import jakarta.validation.Constraint;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validation;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.groups.Default;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION;
/**
* Implementation of JValidationNew. JValidationNew is invoked if configuration validation attribute value is 'jvalidationNew'.
* <pre>
* e.g. <dubbo:method name="save" validation="jvalidationNew" />
* </pre>
*/
public class JValidatorNew implements Validator {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(JValidatorNew.class);
private final Class<?> clazz;
private final Map<String, Class<?>> methodClassMap;
private final jakarta.validation.Validator validator;
@SuppressWarnings({"unchecked", "rawtypes"})
public JValidatorNew(URL url) {
this.clazz = ReflectUtils.forName(url.getServiceInterface());
String jvalidation = url.getParameter("jvalidationNew");
ValidatorFactory factory;
if (StringUtils.isNotEmpty(jvalidation)) {
factory = Validation.byProvider((Class) ReflectUtils.forName(jvalidation))
.configure()
.buildValidatorFactory();
} else {
factory = Validation.buildDefaultValidatorFactory();
}
this.validator = factory.getValidator();
this.methodClassMap = new ConcurrentHashMap<>();
}
private static Object getMethodParameterBean(Class<?> clazz, Method method, Object[] args) {
if (!hasConstraintParameter(method)) {
return null;
}
try {
String parameterClassName = generateMethodParameterClassName(clazz, method);
Class<?> parameterClass;
try {
parameterClass = Class.forName(parameterClassName, true, clazz.getClassLoader());
} catch (ClassNotFoundException e) {
parameterClass = generateMethodParameterClass(clazz, method, parameterClassName);
}
Object parameterBean = parameterClass.getDeclaredConstructor().newInstance();
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
Field field = parameterClass.getField(parameters[i].getName());
field.set(parameterBean, args[i]);
}
return parameterBean;
} catch (Throwable e) {
logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", e.getMessage(), e);
return null;
}
}
/**
* try to generate methodParameterClass.
*
* @param clazz interface class
* @param method invoke method
* @param parameterClassName generated parameterClassName
* @return Class<?> generated methodParameterClass
*/
private static Class<?> generateMethodParameterClass(Class<?> clazz, Method method, String parameterClassName)
throws Exception {
ClassPool pool = ClassGenerator.getClassPool(clazz.getClassLoader());
synchronized (parameterClassName.intern()) {
CtClass ctClass = null;
try {
ctClass = pool.getCtClass(parameterClassName);
} catch (NotFoundException ignore) {
}
if (null == ctClass) {
ctClass = pool.makeClass(parameterClassName);
ClassFile classFile = ctClass.getClassFile();
ctClass.addConstructor(CtNewConstructor.defaultConstructor(pool.getCtClass(parameterClassName)));
// parameter fields
Parameter[] parameters = method.getParameters();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int i = 0; i < parameters.length; i++) {
Annotation[] annotations = parameterAnnotations[i];
AnnotationsAttribute attribute =
new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag);
for (Annotation annotation : annotations) {
if (annotation.annotationType().isAnnotationPresent(Constraint.class)) {
javassist.bytecode.annotation.Annotation ja = new javassist.bytecode.annotation.Annotation(
classFile.getConstPool(),
pool.getCtClass(annotation.annotationType().getName()));
Method[] members = annotation.annotationType().getMethods();
for (Method member : members) {
if (Modifier.isPublic(member.getModifiers())
&& member.getParameterTypes().length == 0
&& member.getDeclaringClass() == annotation.annotationType()) {
Object value = member.invoke(annotation);
if (null != value) {
MemberValue memberValue = createMemberValue(
classFile.getConstPool(),
pool.get(member.getReturnType().getName()),
value);
ja.addMemberValue(member.getName(), memberValue);
}
}
}
attribute.addAnnotation(ja);
}
}
Parameter parameter = parameters[i];
Class<?> type = parameter.getType();
String fieldName = parameter.getName();
CtField ctField = CtField.make(
"public " + type.getCanonicalName() + " " + fieldName + ";",
pool.getCtClass(parameterClassName));
ctField.getFieldInfo().addAttribute(attribute);
ctClass.addField(ctField);
}
return pool.toClass(ctClass, clazz, clazz.getClassLoader(), clazz.getProtectionDomain());
} else {
return Class.forName(parameterClassName, true, clazz.getClassLoader());
}
}
}
private static String generateMethodParameterClassName(Class<?> clazz, Method method) {
StringBuilder builder = new StringBuilder()
.append(clazz.getName())
.append('_')
.append(toUpperMethodName(method.getName()))
.append("Parameter");
Class<?>[] parameterTypes = method.getParameterTypes();
for (Class<?> parameterType : parameterTypes) {
// In order to ensure that the parameter class can be generated correctly,
// replace "." with "_" to make the package name of the generated parameter class
// consistent with the package name of the actual parameter class.
builder.append('_').append(parameterType.getName().replace(".", "_"));
}
return builder.toString();
}
private static boolean hasConstraintParameter(Method method) {
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (Annotation[] annotations : parameterAnnotations) {
for (Annotation annotation : annotations) {
if (annotation.annotationType().isAnnotationPresent(Constraint.class)) {
return true;
}
}
}
return false;
}
private static String toUpperMethodName(String methodName) {
return methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
}
// Copy from javassist.bytecode.annotation.Annotation.createMemberValue(ConstPool, CtClass);
private static MemberValue createMemberValue(ConstPool cp, CtClass type, Object value) throws NotFoundException {
MemberValue memberValue = javassist.bytecode.annotation.Annotation.createMemberValue(cp, type);
if (memberValue instanceof BooleanMemberValue) {
((BooleanMemberValue) memberValue).setValue((Boolean) value);
} else if (memberValue instanceof ByteMemberValue) {
((ByteMemberValue) memberValue).setValue((Byte) value);
} else if (memberValue instanceof CharMemberValue) {
((CharMemberValue) memberValue).setValue((Character) value);
} else if (memberValue instanceof ShortMemberValue) {
((ShortMemberValue) memberValue).setValue((Short) value);
} else if (memberValue instanceof IntegerMemberValue) {
((IntegerMemberValue) memberValue).setValue((Integer) value);
} else if (memberValue instanceof LongMemberValue) {
((LongMemberValue) memberValue).setValue((Long) value);
} else if (memberValue instanceof FloatMemberValue) {
((FloatMemberValue) memberValue).setValue((Float) value);
} else if (memberValue instanceof DoubleMemberValue) {
((DoubleMemberValue) memberValue).setValue((Double) value);
} else if (memberValue instanceof ClassMemberValue) {
((ClassMemberValue) memberValue).setValue(((Class<?>) value).getName());
} else if (memberValue instanceof StringMemberValue) {
((StringMemberValue) memberValue).setValue((String) value);
} else if (memberValue instanceof EnumMemberValue) {
((EnumMemberValue) memberValue).setValue(((Enum<?>) value).name());
}
/* else if (memberValue instanceof AnnotationMemberValue) */
else if (memberValue instanceof ArrayMemberValue) {
CtClass arrayType = type.getComponentType();
int len = Array.getLength(value);
MemberValue[] members = new MemberValue[len];
for (int i = 0; i < len; i++) {
members[i] = createMemberValue(cp, arrayType, Array.get(value, i));
}
((ArrayMemberValue) memberValue).setValue(members);
}
return memberValue;
}
@Override
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
List<Class<?>> groups = new ArrayList<>();
Class<?> methodClass = methodClass(methodName);
if (methodClass != null) {
groups.add(methodClass);
}
Method method = clazz.getMethod(methodName, parameterTypes);
Class<?>[] methodClasses;
if (method.isAnnotationPresent(MethodValidated.class)) {
methodClasses = method.getAnnotation(MethodValidated.class).value();
groups.addAll(Arrays.asList(methodClasses));
}
// add into default group
groups.add(0, Default.class);
groups.add(1, clazz);
// convert list to array
Class<?>[] classGroups = groups.toArray(new Class[0]);
Set<ConstraintViolation<?>> violations = new HashSet<>();
Object parameterBean = getMethodParameterBean(clazz, method, arguments);
if (parameterBean != null) {
violations.addAll(validator.validate(parameterBean, classGroups));
}
for (Object arg : arguments) {
validate(violations, arg, classGroups);
}
if (!violations.isEmpty()) {
logger.info("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: "
+ violations);
throw new ConstraintViolationException(
"Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: "
+ violations,
violations);
}
}
@Override
public boolean isSupport() {
Class<?> cls = null;
try {
cls = jakarta.validation.Validation.class;
} catch (Throwable ignore) {
}
return cls != null;
}
private Class<?> methodClass(String methodName) {
Class<?> methodClass = null;
String methodClassName = clazz.getName() + "$" + toUpperMethodName(methodName);
Class<?> cached = methodClassMap.get(methodClassName);
if (cached != null) {
return cached == clazz ? null : cached;
}
try {
methodClass =
Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
methodClassMap.put(methodClassName, methodClass);
} catch (ClassNotFoundException e) {
methodClassMap.put(methodClassName, clazz);
}
return methodClass;
}
private void validate(Set<ConstraintViolation<?>> violations, Object arg, Class<?>... groups) {
if (arg != null && !ReflectUtils.isPrimitives(arg.getClass())) {
if (arg instanceof Object[]) {
for (Object item : (Object[]) arg) {
validate(violations, item, groups);
}
} else if (arg instanceof Collection) {
for (Object item : (Collection<?>) arg) {
validate(violations, item, groups);
}
} else if (arg instanceof Map) {
for (Map.Entry<?, ?> entry : ((Map<?, ?>) arg).entrySet()) {
validate(violations, entry.getKey(), groups);
validate(violations, entry.getValue(), groups);
}
} else {
violations.addAll(validator.validate(arg, groups));
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java | dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.validation.Validation;
import org.apache.dubbo.validation.Validator;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY;
/**
* ValidationFilter invoke the validation by finding the right {@link Validator} instance based on the
* configured <b>validation</b> attribute value of invoker url before the actual method invocation.
*
* <pre>
* e.g. <dubbo:method name="save" validation="jvalidation" />
* In the above configuration a validation has been configured of type jvalidation. On invocation of method <b>save</b>
* dubbo will invoke {@link org.apache.dubbo.validation.support.jvalidation.JValidator}
* </pre>
* <p>
* To add a new type of validation
* <pre>
* e.g. <dubbo:method name="save" validation="special" />
* where "special" is representing a validator for special character.
* </pre>
* <p>
* developer needs to do
* <br/>
* 1)Implement a SpecialValidation.java class (package name xxx.yyy.zzz) either by implementing {@link Validation} or extending {@link org.apache.dubbo.validation.support.AbstractValidation} <br/>
* 2)Implement a SpecialValidator.java class (package name xxx.yyy.zzz) <br/>
* 3)Add an entry <b>special</b>=<b>xxx.yyy.zzz.SpecialValidation</b> under <b>META-INF folders org.apache.dubbo.validation.Validation file</b>.
*
* @see Validation
* @see Validator
* @see Filter
* @see org.apache.dubbo.validation.support.AbstractValidation
*/
@Activate(
group = {CONSUMER, PROVIDER},
value = VALIDATION_KEY,
order = 10000)
public class ValidationFilter implements Filter {
private Validation validation;
/**
* Sets the validation instance for ValidationFilter
*
* @param validation Validation instance injected by dubbo framework based on "validation" attribute value.
*/
public void setValidation(Validation validation) {
this.validation = validation;
}
/**
* Perform the validation of before invoking the actual method based on <b>validation</b> attribute value.
*
* @param invoker service
* @param invocation invocation.
* @return Method invocation result
* @throws RpcException Throws RpcException if validation failed or any other runtime exception occurred.
*/
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
if (needValidate(invoker.getUrl(), invocation.getMethodName())) {
try {
Validator validator = validation.getValidator(invoker.getUrl());
if (validator != null) {
validator.validate(
invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments());
}
} catch (RpcException e) {
throw e;
} catch (Throwable t) {
return AsyncRpcResult.newDefaultAsyncResult(t, invocation);
}
}
return invoker.invoke(invocation);
}
private boolean needValidate(URL url, String methodName) {
return validation != null
&& !methodName.startsWith("$")
&& ConfigUtils.isNotEmpty(url.getMethodParameter(methodName, VALIDATION_KEY))
&& !"false".equalsIgnoreCase(url.getParameter(VALIDATION_KEY));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/OneToOneMethodHandlerTest.java | dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/OneToOneMethodHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive;
import org.apache.dubbo.reactive.handler.OneToOneMethodHandler;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Unit test for OneToOneMethodHandler
*/
public final class OneToOneMethodHandlerTest {
@Test
void testInvoke() throws ExecutionException, InterruptedException {
String request = "request";
OneToOneMethodHandler<String, String> handler =
new OneToOneMethodHandler<>(requestMono -> requestMono.map(r -> r + "Test"));
CompletableFuture<?> future = handler.invoke(new Object[] {request});
assertEquals("requestTest", future.get());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/OneToManyMethodHandlerTest.java | dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/OneToManyMethodHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive;
import org.apache.dubbo.reactive.handler.OneToManyMethodHandler;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
/**
* Unit test for OneToManyMethodHandler
*/
public final class OneToManyMethodHandlerTest {
private CreateObserverAdapter creator;
@BeforeEach
void init() {
creator = new CreateObserverAdapter();
}
@Test
void testInvoke() {
String request = "1,2,3,4,5,6,7";
OneToManyMethodHandler<String, String> handler =
new OneToManyMethodHandler<>(requestMono -> requestMono.flatMapMany(r -> Flux.fromArray(r.split(","))));
CompletableFuture<?> future = handler.invoke(new Object[] {request, creator.getResponseObserver()});
Assertions.assertTrue(future.isDone());
Assertions.assertEquals(7, creator.getNextCounter().get());
Assertions.assertEquals(0, creator.getErrorCounter().get());
Assertions.assertEquals(1, creator.getCompleteCounter().get());
}
@Test
void testError() {
String request = "1,2,3,4,5,6,7";
OneToManyMethodHandler<String, String> handler =
new OneToManyMethodHandler<>(requestMono -> Flux.create(emitter -> {
for (int i = 0; i < 10; i++) {
if (i == 6) {
emitter.error(new Throwable());
} else {
emitter.next(String.valueOf(i));
}
}
}));
CompletableFuture<?> future = handler.invoke(new Object[] {request, creator.getResponseObserver()});
Assertions.assertTrue(future.isDone());
Assertions.assertEquals(6, creator.getNextCounter().get());
Assertions.assertEquals(1, creator.getErrorCounter().get());
Assertions.assertEquals(0, creator.getCompleteCounter().get());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/ManyToManyMethodHandlerTest.java | dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/ManyToManyMethodHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.reactive.handler.ManyToManyMethodHandler;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Unit test for ManyToManyMethodHandler
*/
public final class ManyToManyMethodHandlerTest {
@Test
void testInvoke() throws ExecutionException, InterruptedException {
CreateObserverAdapter creator = new CreateObserverAdapter();
ManyToManyMethodHandler<String, String> handler =
new ManyToManyMethodHandler<>(requestFlux -> requestFlux.map(r -> r + "0"));
CompletableFuture<StreamObserver<String>> future = handler.invoke(new Object[] {creator.getResponseObserver()});
StreamObserver<String> requestObserver = future.get();
for (int i = 0; i < 10; i++) {
requestObserver.onNext(String.valueOf(i));
}
requestObserver.onCompleted();
Assertions.assertEquals(10, creator.getNextCounter().get());
Assertions.assertEquals(0, creator.getErrorCounter().get());
Assertions.assertEquals(1, creator.getCompleteCounter().get());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/CreateObserverAdapter.java | dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/CreateObserverAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive;
import org.apache.dubbo.rpc.protocol.tri.ServerStreamObserver;
import java.util.concurrent.atomic.AtomicInteger;
import org.mockito.Mockito;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
public class CreateObserverAdapter {
private ServerStreamObserver<String> responseObserver;
private AtomicInteger nextCounter;
private AtomicInteger completeCounter;
private AtomicInteger errorCounter;
CreateObserverAdapter() {
nextCounter = new AtomicInteger();
completeCounter = new AtomicInteger();
errorCounter = new AtomicInteger();
responseObserver = Mockito.mock(ServerStreamObserver.class);
doAnswer(o -> nextCounter.incrementAndGet()).when(responseObserver).onNext(anyString());
doAnswer(o -> completeCounter.incrementAndGet()).when(responseObserver).onCompleted();
doAnswer(o -> errorCounter.incrementAndGet()).when(responseObserver).onError(any(Throwable.class));
}
public AtomicInteger getCompleteCounter() {
return completeCounter;
}
public AtomicInteger getNextCounter() {
return nextCounter;
}
public AtomicInteger getErrorCounter() {
return errorCounter;
}
public ServerStreamObserver<String> getResponseObserver() {
return this.responseObserver;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/ManyToOneMethodHandlerTest.java | dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/ManyToOneMethodHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.reactive.handler.ManyToOneMethodHandler;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Unit test for ManyToOneMethodHandler
*/
public final class ManyToOneMethodHandlerTest {
private StreamObserver<String> requestObserver;
private CreateObserverAdapter creator;
@BeforeEach
void init() throws ExecutionException, InterruptedException {
creator = new CreateObserverAdapter();
ManyToOneMethodHandler<String, String> handler = new ManyToOneMethodHandler<>(requestFlux ->
requestFlux.map(Integer::valueOf).reduce(Integer::sum).map(String::valueOf));
CompletableFuture<StreamObserver<String>> future = handler.invoke(new Object[] {creator.getResponseObserver()});
requestObserver = future.get();
}
@Test
void testInvoker() {
for (int i = 0; i < 10; i++) {
requestObserver.onNext(String.valueOf(i));
}
requestObserver.onCompleted();
Assertions.assertEquals(1, creator.getNextCounter().get());
Assertions.assertEquals(0, creator.getErrorCounter().get());
Assertions.assertEquals(1, creator.getCompleteCounter().get());
}
@Test
void testError() {
for (int i = 0; i < 10; i++) {
if (i == 6) {
requestObserver.onError(new Throwable());
}
requestObserver.onNext(String.valueOf(i));
}
requestObserver.onCompleted();
Assertions.assertEquals(0, creator.getNextCounter().get());
Assertions.assertEquals(1, creator.getErrorCounter().get());
Assertions.assertEquals(0, creator.getCompleteCounter().get());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ClientTripleReactorPublisher.java | dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ClientTripleReactorPublisher.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive;
import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver;
import org.apache.dubbo.rpc.protocol.tri.observer.ClientCallToObserverAdapter;
import java.util.function.Consumer;
/**
* Used in OneToMany & ManyToOne & ManyToMany in client. <br>
* It is a Publisher for user subscriber to subscribe. <br>
* It is a StreamObserver for responseStream. <br>
* It is a Subscription for user subscriber to request and pass request to requestStream.
*/
public class ClientTripleReactorPublisher<T> extends AbstractTripleReactorPublisher<T> {
public ClientTripleReactorPublisher() {}
public ClientTripleReactorPublisher(Consumer<CallStreamObserver<?>> onSubscribe, Runnable shutdownHook) {
super(onSubscribe, shutdownHook);
}
@Override
public void beforeStart(ClientCallToObserverAdapter<T> clientCallToObserverAdapter) {
super.onSubscribe(clientCallToObserverAdapter);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorPublisher.java | dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorPublisher.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive;
import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver;
/**
* Used in ManyToOne and ManyToMany in server. <br>
* It is a Publisher for user subscriber to subscribe. <br>
* It is a StreamObserver for requestStream. <br>
* It is a Subscription for user subscriber to request and pass request to responseStream.
*/
public class ServerTripleReactorPublisher<T> extends AbstractTripleReactorPublisher<T> {
public ServerTripleReactorPublisher(CallStreamObserver<?> callStreamObserver) {
super.onSubscribe(callStreamObserver);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorSubscriber.java | dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorSubscriber.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive;
import org.apache.dubbo.rpc.CancellationContext;
import org.apache.dubbo.rpc.protocol.tri.CancelableStreamObserver;
import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* The Subscriber in server to passing the data produced by user publisher to responseStream.
*/
public class ServerTripleReactorSubscriber<T> extends AbstractTripleReactorSubscriber<T> {
/**
* The execution future of the current task, in order to be returned to stubInvoker
*/
private final CompletableFuture<List<T>> executionFuture = new CompletableFuture<>();
/**
* The result elements collected by the current task.
* This class is a flux subscriber, which usually means there will be multiple elements, so it is declared as a list type.
*/
private final List<T> collectedData = new ArrayList<>();
public ServerTripleReactorSubscriber() {}
public ServerTripleReactorSubscriber(CallStreamObserver<T> streamObserver) {
this.downstream = streamObserver;
}
@Override
public void subscribe(CallStreamObserver<T> downstream) {
super.subscribe(downstream);
if (downstream instanceof CancelableStreamObserver) {
CancelableStreamObserver<?> observer = (CancelableStreamObserver<?>) downstream;
final CancellationContext context;
if (observer.getCancellationContext() == null) {
context = new CancellationContext();
observer.setCancellationContext(context);
} else {
context = observer.getCancellationContext();
}
context.addListener(ctx -> super.cancel());
}
}
@Override
public void onNext(T t) {
super.onNext(t);
collectedData.add(t);
}
@Override
public void onError(Throwable throwable) {
super.onError(throwable);
executionFuture.completeExceptionally(throwable);
}
@Override
public void onComplete() {
super.onComplete();
executionFuture.complete(this.collectedData);
}
public CompletableFuture<List<T>> getExecutionFuture() {
return executionFuture;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorPublisher.java | dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorPublisher.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive;
import org.apache.dubbo.rpc.protocol.tri.CancelableStreamObserver;
import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
/**
* The middle layer between {@link org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver} and Reactive API. <p>
* 1. passing the data received by CallStreamObserver to Reactive consumer <br>
* 2. passing the request of Reactive API to CallStreamObserver
*/
public abstract class AbstractTripleReactorPublisher<T> extends CancelableStreamObserver<T>
implements Publisher<T>, Subscription {
private boolean canRequest;
private long requested;
// weather publisher has been subscribed
private final AtomicBoolean SUBSCRIBED = new AtomicBoolean();
private volatile Subscriber<? super T> downstream;
protected volatile CallStreamObserver<?> subscription;
private final AtomicBoolean HAS_SUBSCRIPTION = new AtomicBoolean();
// cancel status
private volatile boolean isCancelled;
// complete status
private volatile boolean isDone;
// to help bind TripleSubscriber
private volatile Consumer<CallStreamObserver<?>> onSubscribe;
private volatile Runnable shutdownHook;
private final AtomicBoolean CALLED_SHUT_DOWN_HOOK = new AtomicBoolean();
public AbstractTripleReactorPublisher() {}
public AbstractTripleReactorPublisher(Consumer<CallStreamObserver<?>> onSubscribe, Runnable shutdownHook) {
this.onSubscribe = onSubscribe;
this.shutdownHook = shutdownHook;
}
protected void onSubscribe(final CallStreamObserver<?> subscription) {
if (subscription != null && this.subscription == null && HAS_SUBSCRIPTION.compareAndSet(false, true)) {
this.subscription = subscription;
subscription.disableAutoFlowControl();
if (onSubscribe != null) {
onSubscribe.accept(subscription);
}
return;
}
throw new IllegalStateException(getClass().getSimpleName() + " supports only a single subscription");
}
@Override
public void onNext(T data) {
if (isDone || isCancelled) {
return;
}
downstream.onNext(data);
}
@Override
public void onError(Throwable throwable) {
if (isDone || isCancelled) {
return;
}
isDone = true;
downstream.onError(throwable);
doPostShutdown();
}
@Override
public void onCompleted() {
if (isDone || isCancelled) {
return;
}
isDone = true;
downstream.onComplete();
doPostShutdown();
}
private void doPostShutdown() {
Runnable r = shutdownHook;
// CAS to confirm shutdownHook will be run only once.
if (r != null && CALLED_SHUT_DOWN_HOOK.compareAndSet(false, true)) {
shutdownHook = null;
r.run();
}
}
@Override
public void subscribe(Subscriber<? super T> subscriber) {
if (subscriber == null) {
throw new NullPointerException();
}
if (SUBSCRIBED.compareAndSet(false, true)) {
subscriber.onSubscribe(this);
this.downstream = subscriber;
if (isCancelled) {
this.downstream = null;
}
}
}
@Override
public void request(long l) {
synchronized (this) {
if (SUBSCRIBED.get() && canRequest) {
subscription.request(l >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) l);
} else {
requested += l;
}
}
}
@Override
public void startRequest() {
synchronized (this) {
if (!canRequest) {
canRequest = true;
long count = requested;
subscription.request(count >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) count);
}
}
}
@Override
public void cancel() {
if (isCancelled) {
return;
}
isCancelled = true;
doPostShutdown();
}
public boolean isCancelled() {
return isCancelled;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorSubscriber.java | dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorSubscriber.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive;
import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver;
import java.util.concurrent.atomic.AtomicBoolean;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.util.annotation.NonNull;
/**
* The middle layer between {@link org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver} and Reactive API. <br>
* Passing the data from Reactive producer to CallStreamObserver.
*/
public abstract class AbstractTripleReactorSubscriber<T> implements Subscriber<T>, CoreSubscriber<T> {
private volatile boolean isCancelled;
protected volatile CallStreamObserver<T> downstream;
private final AtomicBoolean SUBSCRIBED = new AtomicBoolean();
private volatile Subscription subscription;
private final AtomicBoolean HAS_SUBSCRIBED = new AtomicBoolean();
// complete status
private volatile boolean isDone;
/**
* Binding the downstream, and call subscription#request(1).
*
* @param downstream downstream
*/
public void subscribe(final CallStreamObserver<T> downstream) {
if (downstream == null) {
throw new NullPointerException();
}
if (SUBSCRIBED.compareAndSet(false, true)) {
this.downstream = downstream;
subscription.request(1);
}
}
@Override
public void onSubscribe(@NonNull final Subscription subscription) {
if (this.subscription == null && HAS_SUBSCRIBED.compareAndSet(false, true)) {
this.subscription = subscription;
return;
}
// onSubscribe cannot be called repeatedly
subscription.cancel();
}
@Override
public void onNext(T t) {
if (!isDone && !isCanceled()) {
downstream.onNext(t);
subscription.request(1);
}
}
@Override
public void onError(Throwable throwable) {
if (!isCanceled()) {
isDone = true;
downstream.onError(throwable);
}
}
@Override
public void onComplete() {
if (!isCanceled()) {
isDone = true;
downstream.onCompleted();
}
}
public void cancel() {
if (!isCancelled && subscription != null) {
isCancelled = true;
subscription.cancel();
}
}
public boolean isCanceled() {
return isCancelled;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ClientTripleReactorSubscriber.java | dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ClientTripleReactorSubscriber.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive;
import org.apache.dubbo.rpc.protocol.tri.observer.ClientCallToObserverAdapter;
/**
* The subscriber in client to subscribe user publisher and is subscribed by ClientStreamObserver.
*/
public class ClientTripleReactorSubscriber<T> extends AbstractTripleReactorSubscriber<T> {
@Override
public void cancel() {
if (!isCanceled()) {
super.cancel();
((ClientCallToObserverAdapter<T>) downstream).cancel(new Exception("Cancelled"));
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorClientCalls.java | dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorClientCalls.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive.calls;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.reactive.ClientTripleReactorPublisher;
import org.apache.dubbo.reactive.ClientTripleReactorSubscriber;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.model.StubMethodDescriptor;
import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver;
import org.apache.dubbo.rpc.stub.StubInvocationUtil;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* A collection of methods to convert client-side Reactor calls to stream calls.
*/
public final class ReactorClientCalls {
private ReactorClientCalls() {}
/**
* Implements a unary -> unary call as Mono -> Mono
*
* @param invoker invoker
* @param monoRequest the mono with request
* @param methodDescriptor the method descriptor
* @return the mono with response
*/
public static <TRequest, TResponse, TInvoker> Mono<TResponse> oneToOne(
Invoker<TInvoker> invoker, Mono<TRequest> monoRequest, StubMethodDescriptor methodDescriptor) {
try {
return Mono.create(emitter -> monoRequest.subscribe(
request -> StubInvocationUtil.unaryCall(
invoker, methodDescriptor, request, new StreamObserver<TResponse>() {
@Override
public void onNext(TResponse tResponse) {
emitter.success(tResponse);
}
@Override
public void onError(Throwable throwable) {
emitter.error(throwable);
}
@Override
public void onCompleted() {
// Do nothing
}
}),
emitter::error));
} catch (Throwable throwable) {
return Mono.error(throwable);
}
}
/**
* Implements a unary -> stream call as Mono -> Flux
*
* @param invoker invoker
* @param monoRequest the mono with request
* @param methodDescriptor the method descriptor
* @return the flux with response
*/
public static <TRequest, TResponse, TInvoker> Flux<TResponse> oneToMany(
Invoker<TInvoker> invoker, Mono<TRequest> monoRequest, StubMethodDescriptor methodDescriptor) {
try {
return monoRequest.flatMapMany(request -> {
ClientTripleReactorPublisher<TResponse> clientPublisher = new ClientTripleReactorPublisher<>();
StubInvocationUtil.serverStreamCall(invoker, methodDescriptor, request, clientPublisher);
return clientPublisher;
});
} catch (Throwable throwable) {
return Flux.error(throwable);
}
}
/**
* Implements a stream -> unary call as Flux -> Mono
*
* @param invoker invoker
* @param requestFlux the flux with request
* @param methodDescriptor the method descriptor
* @return the mono with response
*/
public static <TRequest, TResponse, TInvoker> Mono<TResponse> manyToOne(
Invoker<TInvoker> invoker, Flux<TRequest> requestFlux, StubMethodDescriptor methodDescriptor) {
try {
ClientTripleReactorSubscriber<TRequest> clientSubscriber =
requestFlux.subscribeWith(new ClientTripleReactorSubscriber<>());
ClientTripleReactorPublisher<TResponse> clientPublisher = new ClientTripleReactorPublisher<>(
s -> clientSubscriber.subscribe((CallStreamObserver<TRequest>) s), clientSubscriber::cancel);
return Mono.from(clientPublisher)
.doOnSubscribe(dummy ->
StubInvocationUtil.biOrClientStreamCall(invoker, methodDescriptor, clientPublisher));
} catch (Throwable throwable) {
return Mono.error(throwable);
}
}
/**
* Implements a stream -> stream call as Flux -> Flux
*
* @param invoker invoker
* @param requestFlux the flux with request
* @param methodDescriptor the method descriptor
* @return the flux with response
*/
public static <TRequest, TResponse, TInvoker> Flux<TResponse> manyToMany(
Invoker<TInvoker> invoker, Flux<TRequest> requestFlux, StubMethodDescriptor methodDescriptor) {
try {
ClientTripleReactorSubscriber<TRequest> clientSubscriber =
requestFlux.subscribeWith(new ClientTripleReactorSubscriber<>());
ClientTripleReactorPublisher<TResponse> clientPublisher = new ClientTripleReactorPublisher<>(
s -> clientSubscriber.subscribe((CallStreamObserver<TRequest>) s), clientSubscriber::cancel);
return Flux.from(clientPublisher)
.doOnSubscribe(dummy ->
StubInvocationUtil.biOrClientStreamCall(invoker, methodDescriptor, clientPublisher));
} catch (Throwable throwable) {
return Flux.error(throwable);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorServerCalls.java | dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorServerCalls.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive.calls;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.reactive.ServerTripleReactorPublisher;
import org.apache.dubbo.reactive.ServerTripleReactorSubscriber;
import org.apache.dubbo.rpc.StatusRpcException;
import org.apache.dubbo.rpc.TriRpcStatus;
import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* A collection of methods to convert server-side stream calls to Reactor calls.
*/
public final class ReactorServerCalls {
private ReactorServerCalls() {}
/**
* Implements a unary -> unary call as Mono -> Mono
*
* @param request request
* @param responseObserver response StreamObserver
* @param func service implementation
*/
public static <T, R> void oneToOne(T request, StreamObserver<R> responseObserver, Function<Mono<T>, Mono<R>> func) {
try {
func.apply(Mono.just(request))
.switchIfEmpty(Mono.error(TriRpcStatus.NOT_FOUND.asException()))
.subscribe(
responseObserver::onNext,
throwable -> doOnResponseHasException(throwable, responseObserver),
responseObserver::onCompleted);
} catch (Throwable throwable) {
doOnResponseHasException(throwable, responseObserver);
}
}
/**
* Implements a unary -> stream call as Mono -> Flux
*
* @param request request
* @param responseObserver response StreamObserver
* @param func service implementation
*/
public static <T, R> CompletableFuture<List<R>> oneToMany(
T request, StreamObserver<R> responseObserver, Function<Mono<T>, Flux<R>> func) {
try {
CallStreamObserver<R> callStreamObserver = (CallStreamObserver<R>) responseObserver;
Flux<R> response = func.apply(Mono.just(request));
ServerTripleReactorSubscriber<R> reactorSubscriber =
new ServerTripleReactorSubscriber<>(callStreamObserver);
response.subscribeWith(reactorSubscriber).subscribe(callStreamObserver);
return reactorSubscriber.getExecutionFuture();
} catch (Throwable throwable) {
doOnResponseHasException(throwable, responseObserver);
CompletableFuture<List<R>> future = new CompletableFuture<>();
future.completeExceptionally(throwable);
return future;
}
}
/**
* Implements a stream -> unary call as Flux -> Mono
*
* @param responseObserver response StreamObserver
* @param func service implementation
* @return request StreamObserver
*/
public static <T, R> StreamObserver<T> manyToOne(
StreamObserver<R> responseObserver, Function<Flux<T>, Mono<R>> func) {
ServerTripleReactorPublisher<T> serverPublisher =
new ServerTripleReactorPublisher<>((CallStreamObserver<R>) responseObserver);
try {
Mono<R> responseMono = func.apply(Flux.from(serverPublisher));
responseMono.subscribe(
value -> {
// Don't try to respond if the server has already canceled the request
if (!serverPublisher.isCancelled()) {
responseObserver.onNext(value);
}
},
throwable -> {
// Don't try to respond if the server has already canceled the request
if (!serverPublisher.isCancelled()) {
responseObserver.onError(throwable);
}
},
responseObserver::onCompleted);
serverPublisher.startRequest();
} catch (Throwable throwable) {
responseObserver.onError(throwable);
}
return serverPublisher;
}
/**
* Implements a stream -> stream call as Flux -> Flux
*
* @param responseObserver response StreamObserver
* @param func service implementation
* @return request StreamObserver
*/
public static <T, R> StreamObserver<T> manyToMany(
StreamObserver<R> responseObserver, Function<Flux<T>, Flux<R>> func) {
// responseObserver is also a subscription of publisher, we can use it to request more data
ServerTripleReactorPublisher<T> serverPublisher =
new ServerTripleReactorPublisher<>((CallStreamObserver<R>) responseObserver);
try {
Flux<R> responseFlux = func.apply(Flux.from(serverPublisher));
ServerTripleReactorSubscriber<R> serverSubscriber =
responseFlux.subscribeWith(new ServerTripleReactorSubscriber<>());
serverSubscriber.subscribe((CallStreamObserver<R>) responseObserver);
serverPublisher.startRequest();
} catch (Throwable throwable) {
responseObserver.onError(throwable);
}
return serverPublisher;
}
private static void doOnResponseHasException(Throwable throwable, StreamObserver<?> responseObserver) {
StatusRpcException statusRpcException =
TriRpcStatus.getStatus(throwable).asException();
responseObserver.onError(statusRpcException);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/ManyToManyMethodHandler.java | dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/ManyToManyMethodHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive.handler;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.reactive.calls.ReactorServerCalls;
import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver;
import org.apache.dubbo.rpc.stub.StubMethodHandler;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import reactor.core.publisher.Flux;
/**
* The handler of ManyToMany() method for stub invocation.
*/
public class ManyToManyMethodHandler<T, R> implements StubMethodHandler<T, R> {
private final Function<Flux<T>, Flux<R>> func;
public ManyToManyMethodHandler(Function<Flux<T>, Flux<R>> func) {
this.func = func;
}
@SuppressWarnings("unchecked")
@Override
public CompletableFuture<StreamObserver<T>> invoke(Object[] arguments) {
CallStreamObserver<R> responseObserver = (CallStreamObserver<R>) arguments[0];
StreamObserver<T> requestObserver = ReactorServerCalls.manyToMany(responseObserver, func);
return CompletableFuture.completedFuture(requestObserver);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToOneMethodHandler.java | dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToOneMethodHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive.handler;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.reactive.calls.ReactorServerCalls;
import org.apache.dubbo.rpc.stub.FutureToObserverAdaptor;
import org.apache.dubbo.rpc.stub.StubMethodHandler;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import reactor.core.publisher.Mono;
/**
* The handler of OneToOne() method for stub invocation.
*/
public class OneToOneMethodHandler<T, R> implements StubMethodHandler<T, R> {
private final Function<Mono<T>, Mono<R>> func;
public OneToOneMethodHandler(Function<Mono<T>, Mono<R>> func) {
this.func = func;
}
@SuppressWarnings("unchecked")
@Override
public CompletableFuture<R> invoke(Object[] arguments) {
T request = (T) arguments[0];
CompletableFuture<R> future = new CompletableFuture<>();
StreamObserver<R> responseObserver = new FutureToObserverAdaptor<>(future);
ReactorServerCalls.oneToOne(request, responseObserver, func);
return future;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/ManyToOneMethodHandler.java | dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/ManyToOneMethodHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive.handler;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.reactive.calls.ReactorServerCalls;
import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver;
import org.apache.dubbo.rpc.stub.StubMethodHandler;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* The handler of ManyToOne() method for stub invocation.
*/
public class ManyToOneMethodHandler<T, R> implements StubMethodHandler<T, R> {
private final Function<Flux<T>, Mono<R>> func;
public ManyToOneMethodHandler(Function<Flux<T>, Mono<R>> func) {
this.func = func;
}
@SuppressWarnings("unchecked")
@Override
public CompletableFuture<StreamObserver<T>> invoke(Object[] arguments) {
CallStreamObserver<R> responseObserver = (CallStreamObserver<R>) arguments[0];
StreamObserver<T> requestObserver = ReactorServerCalls.manyToOne(responseObserver, func);
return CompletableFuture.completedFuture(requestObserver);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToManyMethodHandler.java | dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToManyMethodHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.reactive.handler;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.reactive.calls.ReactorServerCalls;
import org.apache.dubbo.rpc.stub.StubMethodHandler;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* The handler of OneToMany() method for stub invocation.
*/
public class OneToManyMethodHandler<T, R> implements StubMethodHandler<T, R> {
private final Function<Mono<T>, Flux<R>> func;
public OneToManyMethodHandler(Function<Mono<T>, Flux<R>> func) {
this.func = func;
}
@SuppressWarnings("unchecked")
@Override
public CompletableFuture<?> invoke(Object[] arguments) {
T request = (T) arguments[0];
StreamObserver<R> responseObserver = (StreamObserver<R>) arguments[1];
return ReactorServerCalls.oneToMany(request, responseObserver, func);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/basic/BasicOpenAPIDefinitionResolver.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/basic/BasicOpenAPIDefinitionResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.support.basic;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta.PropertyMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ServiceMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Helper;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.OpenAPIDefinitionResolver;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.OpenAPISchemaPredicate;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.OpenAPISchemaResolver;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.ExternalDocs;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Info;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Operation;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.PathItem;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Schema;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Schema.Type;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Tag;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Map;
import static org.apache.dubbo.rpc.protocol.tri.rest.openapi.Helper.setBoolValue;
import static org.apache.dubbo.rpc.protocol.tri.rest.openapi.Helper.setValue;
import static org.apache.dubbo.rpc.protocol.tri.rest.openapi.Helper.trim;
@Activate(order = 100)
public final class BasicOpenAPIDefinitionResolver
implements OpenAPIDefinitionResolver, OpenAPISchemaResolver, OpenAPISchemaPredicate {
private static final String HIDDEN = "hidden";
@Override
public OpenAPI resolve(OpenAPI openAPI, ServiceMeta serviceMeta, OpenAPIChain chain) {
AnnotationMeta<?> annoMeta = serviceMeta.findAnnotation(Annotations.OpenAPI);
if (annoMeta == null) {
return chain.resolve(openAPI, serviceMeta);
}
if (annoMeta.getBoolean(HIDDEN)) {
return null;
}
Info info = openAPI.getInfo();
if (info == null) {
openAPI.setInfo(info = new Info());
}
Map<String, String> tags = Helper.toProperties(annoMeta.getStringArray("tags"));
for (Map.Entry<String, String> entry : tags.entrySet()) {
openAPI.addTag(new Tag().setName(entry.getKey()).setDescription(entry.getValue()));
}
String group = trim(annoMeta.getString("group"));
if (group != null) {
openAPI.setGroup(group);
}
String title = trim(annoMeta.getString("infoTitle"));
if (title != null) {
info.setTitle(title);
}
String description = trim(annoMeta.getString("infoDescription"));
if (description != null) {
info.setDescription(description);
}
String version = trim(annoMeta.getString("infoVersion"));
if (version != null) {
info.setVersion(version);
}
String docDescription = trim(annoMeta.getString("docDescription"));
String docUrl = trim(annoMeta.getString("docUrl"));
if (docDescription != null || docUrl != null) {
openAPI.setExternalDocs(
new ExternalDocs().setDescription(docDescription).setUrl(docUrl));
}
openAPI.setPriority(annoMeta.getNumber("order"));
openAPI.setExtensions(Helper.toProperties(annoMeta.getStringArray("extensions")));
return chain.resolve(openAPI, serviceMeta);
}
@Override
public Collection<HttpMethods> resolve(PathItem pathItem, MethodMeta methodMeta, OperationContext context) {
AnnotationMeta<?> annoMeta = methodMeta.findAnnotation(Annotations.Operation);
if (annoMeta == null) {
return null;
}
String method = trim(annoMeta.getString("method"));
if (method == null) {
return null;
}
return Collections.singletonList(HttpMethods.of(method.toUpperCase()));
}
@Override
public Operation resolve(Operation operation, MethodMeta methodMeta, OperationContext ctx, OperationChain chain) {
AnnotationMeta<?> annoMeta = methodMeta.findAnnotation(Annotations.Operation);
if (annoMeta == null) {
return chain.resolve(operation, methodMeta, ctx);
}
if (annoMeta.getBoolean(HIDDEN)) {
return null;
}
String[] tags = trim(annoMeta.getStringArray("tags"));
if (tags != null) {
operation.setTags(new LinkedHashSet<>(Arrays.asList(tags)));
}
String summary = trim(annoMeta.getValue());
if (summary == null) {
summary = trim(annoMeta.getString("summary"));
}
operation
.setGroup(trim(annoMeta.getString("group")))
.setVersion(trim(annoMeta.getString("version")))
.setOperationId(trim(annoMeta.getString("id")))
.setSummary(summary)
.setDescription(trim(annoMeta.getString("description")))
.setDeprecated(annoMeta.getBoolean("deprecated"))
.setExtensions(Helper.toProperties(annoMeta.getStringArray("extensions")));
return chain.resolve(operation, methodMeta, ctx);
}
@Override
public Schema resolve(ParameterMeta parameter, SchemaContext context, SchemaChain chain) {
AnnotationMeta<?> annoMeta = parameter.getAnnotation(Annotations.Schema);
if (annoMeta == null) {
return chain.resolve(parameter, context);
}
if (annoMeta.getBoolean(HIDDEN)) {
return null;
}
Class<?> impl = annoMeta.getClass("implementation");
Schema schema = impl == Void.class ? chain.resolve(parameter, context) : context.resolve(impl);
setValue(annoMeta, "group", schema::setGroup);
setValue(annoMeta, "version", schema::setVersion);
setValue(annoMeta, "type", v -> schema.setType(Type.valueOf(v)));
setValue(annoMeta, "format", schema::setFormat);
setValue(annoMeta, "name", schema::setName);
String title = trim(annoMeta.getValue());
schema.setTitle(title == null ? trim(annoMeta.getString("title")) : title);
setValue(annoMeta, "description", schema::setDescription);
setValue(annoMeta, "defaultValue", schema::setDefaultValue);
setValue(annoMeta, "max", v -> schema.setMaxLength(Integer.parseInt(v)));
setValue(annoMeta, "min", v -> schema.setMinLength(Integer.parseInt(v)));
setValue(annoMeta, "pattern", schema::setPattern);
setValue(annoMeta, "example", schema::setExample);
String[] enumItems = trim(annoMeta.getStringArray("enumeration"));
if (enumItems != null) {
schema.setEnumeration(Arrays.asList(enumItems));
}
setBoolValue(annoMeta, "required", schema::setRequired);
setBoolValue(annoMeta, "readOnly", schema::setReadOnly);
setBoolValue(annoMeta, "writeOnly", schema::setWriteOnly);
setBoolValue(annoMeta, "nullable", schema::setNullable);
setBoolValue(annoMeta, "deprecated", schema::setDeprecated);
schema.setExtensions(Helper.toProperties(annoMeta.getStringArray("extensions")));
return chain.resolve(parameter, context);
}
@Override
public Boolean acceptProperty(BeanMeta bean, PropertyMeta property) {
AnnotationMeta<?> annoMeta = property.getAnnotation(Annotations.Schema);
return annoMeta == null ? null : annoMeta.getBoolean(HIDDEN);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/swagger/RedocRequestHandler.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/swagger/RedocRequestHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.swagger;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.io.StreamUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.nested.OpenAPIConfig;
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.HttpStatusException;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.ConfigFactory;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Constants;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Helper;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.OpenAPIRequestHandler;
import org.apache.dubbo.rpc.protocol.tri.rest.util.PathUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static java.nio.charset.StandardCharsets.UTF_8;
@Activate
public class RedocRequestHandler implements OpenAPIRequestHandler {
private static final String DEFAULT_CDN = "https://cdn.redoc.ly/redoc/latest/bundles";
private static final String INDEX_PATH = "/META-INF/resources/redoc/index.html";
private final ConfigFactory configFactory;
private OpenAPIConfig config;
public RedocRequestHandler(FrameworkModel frameworkModel) {
configFactory = frameworkModel.getOrRegisterBean(ConfigFactory.class);
}
private OpenAPIConfig getConfig() {
if (config == null) {
config = configFactory.getGlobalConfig();
}
return config;
}
@Override
public String[] getPaths() {
return new String[] {"/redoc/{*path}"};
}
@Override
public HttpResult<?> handle(String path, HttpRequest request, HttpResponse response) {
String resPath = RequestUtils.getPathVariable(request, "path");
if (StringUtils.isEmpty(resPath)) {
throw HttpResult.found(PathUtils.join(request.path(), "index.html")).toPayload();
}
String requestPath = StringUtils.substringBeforeLast(resPath, '.');
if (requestPath.equals("index")) {
return handleIndex(request.parameter("group", Constants.DEFAULT_GROUP));
} else if (WebjarHelper.ENABLED && requestPath.startsWith("assets/")) {
return WebjarHelper.getInstance().handleAssets("redoc", resPath.substring(7));
}
throw new HttpStatusException(HttpStatus.NOT_FOUND.getCode());
}
private HttpResult<?> handleIndex(String group) {
Map<String, String> variables = new HashMap<>(4);
OpenAPIConfig config = getConfig();
String cdn = config.getSetting("redoc.cdn");
if (cdn == null) {
if (WebjarHelper.ENABLED && WebjarHelper.getInstance().hasWebjar("redoc")) {
cdn = "./assets";
} else {
cdn = DEFAULT_CDN;
}
}
variables.put("redoc.cdn", cdn);
variables.put("group", group);
try {
String content = StreamUtils.toString(getClass().getResourceAsStream(INDEX_PATH));
return HttpResult.of(Helper.render(content, variables::get).getBytes(UTF_8));
} catch (IOException e) {
throw new HttpStatusException(HttpStatus.INTERNAL_SERVER_ERROR.getCode(), e);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/swagger/JavadocOpenAPIDefinitionResolver.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/swagger/JavadocOpenAPIDefinitionResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.swagger;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.LRUCache;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta.ReturnParameterMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodParameterMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ServiceMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.OpenAPIDefinitionResolver;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.OpenAPISchemaResolver;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Info;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Operation;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Parameter;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.PathItem;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Schema;
import java.lang.ref.WeakReference;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import com.github.therapi.runtimejavadoc.ClassJavadoc;
import com.github.therapi.runtimejavadoc.Comment;
import com.github.therapi.runtimejavadoc.CommentFormatter;
import com.github.therapi.runtimejavadoc.FieldJavadoc;
import com.github.therapi.runtimejavadoc.MethodJavadoc;
import com.github.therapi.runtimejavadoc.ParamJavadoc;
import com.github.therapi.runtimejavadoc.RuntimeJavadoc;
import com.github.therapi.runtimejavadoc.internal.MethodSignature;
import com.github.therapi.runtimejavadoc.internal.RuntimeJavadocHelper;
@Activate(order = -10000, onClass = "com.github.therapi.runtimejavadoc.RuntimeJavadoc")
public class JavadocOpenAPIDefinitionResolver implements OpenAPIDefinitionResolver, OpenAPISchemaResolver {
private final LRUCache<Class<?>, WeakReference<ClassJavadocWrapper>> cache = new LRUCache<>(128);
private final CommentFormatter formatter = new CommentFormatter();
@Override
public OpenAPI resolve(OpenAPI openAPI, ServiceMeta serviceMeta, OpenAPIChain chain) {
openAPI = chain.resolve(openAPI, serviceMeta);
if (openAPI == null) {
return null;
}
Info info = openAPI.getInfo();
if (info == null) {
openAPI.setInfo(info = new Info());
}
if (info.getSummary() != null || info.getDescription() != null) {
return openAPI;
}
ClassJavadoc javadoc = getClassJavadoc(serviceMeta.getType()).javadoc;
if (javadoc.isEmpty()) {
return openAPI;
}
populateComment(javadoc.getComment(), info::setSummary, info::setDescription);
return openAPI;
}
@Override
public Collection<HttpMethods> resolve(PathItem pathItem, MethodMeta methodMeta, OperationContext context) {
return null;
}
@Override
public Operation resolve(Operation operation, MethodMeta methodMeta, OperationContext ctx, OperationChain chain) {
operation = chain.resolve(operation, methodMeta, ctx);
if (operation == null) {
return null;
}
Method method = methodMeta.getMethod();
ClassJavadocWrapper javadoc = getClassJavadoc(method.getDeclaringClass());
if (javadoc.isEmpty()) {
return operation;
}
if (operation.getSummary() == null && operation.getDescription() == null) {
MethodJavadoc methodJavadoc = javadoc.getMethod(method);
if (methodJavadoc != null) {
populateComment(methodJavadoc.getComment(), operation::setSummary, operation::setDescription);
}
}
List<Parameter> parameters = operation.getParameters();
if (parameters != null) {
for (Parameter parameter : parameters) {
if (parameter.getDescription() != null) {
continue;
}
ParameterMeta meta = parameter.getMeta();
if (!(meta instanceof MethodParameterMeta)) {
continue;
}
populateComment(javadoc.getParameter(method, parameter.getName()), null, parameter::setDescription);
}
}
return operation;
}
@Override
public Schema resolve(ParameterMeta parameter, SchemaContext context, SchemaChain chain) {
Schema schema = chain.resolve(parameter, context);
if (schema == null) {
return null;
}
if (schema.getTitle() != null || schema.getDescription() != null) {
return schema;
}
Comment comment = null;
if (parameter instanceof MethodParameterMeta) {
MethodParameterMeta meta = (MethodParameterMeta) parameter;
Method method = meta.getMethod();
comment = getClassJavadoc(method.getDeclaringClass()).getParameter(method, parameter.getName());
} else if (parameter instanceof ReturnParameterMeta) {
ReturnParameterMeta meta = (ReturnParameterMeta) parameter;
Method method = meta.getMethod();
MethodJavadoc methodJavadoc =
getClassJavadoc(method.getDeclaringClass()).getMethod(method);
if (methodJavadoc != null) {
comment = methodJavadoc.getReturns();
}
} else {
for (AnnotatedElement element : parameter.getAnnotatedElements()) {
if (element instanceof Class) {
comment = getClassJavadoc((Class<?>) element).getClassComment();
} else if (element instanceof Field) {
Field field = (Field) element;
ClassJavadocWrapper javadoc = getClassJavadoc(field.getDeclaringClass());
FieldJavadoc fieldJavadoc = javadoc.getField(field);
if (fieldJavadoc != null) {
comment = fieldJavadoc.getComment();
break;
}
ParamJavadoc paramJavadoc = javadoc.getRecordComponent(field.getName());
if (paramJavadoc != null) {
comment = paramJavadoc.getComment();
break;
}
} else if (element instanceof Method) {
Method method = (Method) element;
ClassJavadocWrapper javadoc = getClassJavadoc(method.getDeclaringClass());
MethodJavadoc methodJavadoc = javadoc.getMethod(method);
if (methodJavadoc != null) {
comment = methodJavadoc.getReturns();
break;
}
}
}
}
populateComment(comment, schema::setTitle, schema::setDescription);
return schema;
}
private ClassJavadocWrapper getClassJavadoc(Class<?> clazz) {
WeakReference<ClassJavadocWrapper> ref = cache.get(clazz);
ClassJavadocWrapper javadoc = ref == null ? null : ref.get();
if (javadoc == null) {
javadoc = new ClassJavadocWrapper(RuntimeJavadoc.getJavadoc(clazz));
cache.put(clazz, new WeakReference<>(javadoc));
}
return javadoc;
}
private void populateComment(Comment comment, Consumer<String> sConsumer, Consumer<String> dConsumer) {
if (comment == null) {
return;
}
String description = formatter.format(comment);
if (sConsumer == null) {
dConsumer.accept(description);
return;
}
String summary = getFirstSentence(description);
sConsumer.accept(summary);
if (description.equals(summary)) {
return;
}
dConsumer.accept(description);
}
private static String getFirstSentence(String text) {
if (StringUtils.isEmpty(text)) {
return text;
}
int pOpenIndex = text.indexOf("<p>");
int pCloseIndex = text.indexOf("</p>");
int dotIndex = text.indexOf(".");
if (pOpenIndex != -1) {
if (pOpenIndex == 0 && pCloseIndex != -1) {
if (dotIndex != -1) {
return text.substring(3, Math.min(pCloseIndex, dotIndex));
}
return text.substring(3, pCloseIndex);
}
if (dotIndex != -1) {
return text.substring(0, Math.min(pOpenIndex, dotIndex));
}
return text.substring(0, pOpenIndex);
}
if (dotIndex != -1 && text.length() != dotIndex + 1 && Character.isWhitespace(text.charAt(dotIndex + 1))) {
return text.substring(0, dotIndex + 1);
}
return text;
}
private static final class ClassJavadocWrapper {
private static final Map<Field, Field> MAPPING = new LinkedHashMap<>();
private static Field PARAMS;
public final ClassJavadoc javadoc;
public Map<String, FieldJavadoc> fields;
public Map<MethodSignature, MethodJavadoc> methods;
public Map<String, ParamJavadoc> recordComponents;
static {
try {
Field[] fields = ClassJavadoc.class.getDeclaredFields();
Field[] wFields = ClassJavadocWrapper.class.getFields();
for (Field field : fields) {
field.setAccessible(true);
for (Field wField : wFields) {
if (wField.getName().equals(field.getName())) {
MAPPING.put(field, wField);
break;
}
}
}
PARAMS = MethodJavadoc.class.getDeclaredField("params");
PARAMS.setAccessible(true);
} catch (Throwable ignored) {
}
}
public ClassJavadocWrapper(ClassJavadoc javadoc) {
this.javadoc = javadoc;
try {
for (Map.Entry<Field, Field> entry : MAPPING.entrySet()) {
entry.getValue().set(this, entry.getKey().get(javadoc));
}
} catch (Throwable ignored) {
}
}
public boolean isEmpty() {
return javadoc.isEmpty();
}
public Comment getClassComment() {
return javadoc.getComment();
}
public FieldJavadoc getField(Field field) {
if (fields == null) {
return null;
}
FieldJavadoc fieldJavadoc = fields.get(field.getName());
return fieldJavadoc == null || fieldJavadoc.isEmpty() ? null : fieldJavadoc;
}
public MethodJavadoc getMethod(Method method) {
if (methods == null) {
return null;
}
MethodJavadoc methodJavadoc = methods.get(MethodSignature.from(method));
if (methodJavadoc != null && !methodJavadoc.isEmpty()) {
return methodJavadoc;
}
Method bridgeMethod = RuntimeJavadocHelper.findBridgeMethod(method);
if (bridgeMethod != null && bridgeMethod != method) {
methodJavadoc = methods.get(MethodSignature.from(bridgeMethod));
if (methodJavadoc != null && !methodJavadoc.isEmpty()) {
return methodJavadoc;
}
}
return null;
}
@SuppressWarnings("unchecked")
public Comment getParameter(Method method, String name) {
if (methods == null) {
return null;
}
MethodJavadoc methodJavadoc = methods.get(MethodSignature.from(method));
if (methodJavadoc == null || PARAMS == null) {
return null;
}
try {
Map<String, ParamJavadoc> params = (Map<String, ParamJavadoc>) PARAMS.get(methodJavadoc);
ParamJavadoc paramJavadoc = params.get(name);
if (paramJavadoc != null) {
return paramJavadoc.getComment();
}
} catch (Throwable ignored) {
}
return null;
}
public ParamJavadoc getRecordComponent(String name) {
return recordComponents == null ? null : recordComponents.get(name);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/swagger/WebjarHelper.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/swagger/WebjarHelper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.swagger;
import org.apache.dubbo.common.io.StreamUtils;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.remoting.http12.HttpResult;
import org.apache.dubbo.remoting.http12.HttpStatus;
import org.apache.dubbo.remoting.http12.exception.HttpStatusException;
import java.io.IOException;
import java.io.InputStream;
import org.webjars.WebJarVersionLocator;
public class WebjarHelper {
public static final boolean ENABLED = ClassUtils.isPresent("org.webjars.WebJarVersionLocator");
private static volatile WebjarHelper INSTANCE;
private final WebJarVersionLocator locator = new WebJarVersionLocator();
public static WebjarHelper getInstance() {
if (INSTANCE == null) {
synchronized (WebjarHelper.class) {
if (INSTANCE == null) {
INSTANCE = new WebjarHelper();
}
}
}
return INSTANCE;
}
public HttpResult<?> handleAssets(String webjar, String path) {
try {
byte[] bytes = getWebjarResource(webjar, path);
if (bytes != null) {
return HttpResult.builder()
.header("Cache-Control", "public, max-age=604800")
.body(bytes)
.build();
}
} catch (IOException ignored) {
}
throw new HttpStatusException(HttpStatus.NOT_FOUND.getCode());
}
public boolean hasWebjar(String webjar) {
return locator.version(webjar) != null;
}
private byte[] getWebjarResource(String webjar, String exactPath) throws IOException {
String fullPath = locator.fullPath(webjar, exactPath);
if (fullPath != null) {
InputStream is = WebJarVersionLocator.class.getClassLoader().getResourceAsStream(fullPath);
if (is != null) {
return StreamUtils.readBytes(is);
}
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/swagger/SwaggerUIRequestHandler.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/swagger/SwaggerUIRequestHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.swagger;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.io.StreamUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.nested.OpenAPIConfig;
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.HttpStatusException;
import org.apache.dubbo.remoting.http12.rest.OpenAPIService;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.ConfigFactory;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Helper;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.OpenAPIRequestHandler;
import org.apache.dubbo.rpc.protocol.tri.rest.util.PathUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static java.nio.charset.StandardCharsets.UTF_8;
@Activate
public class SwaggerUIRequestHandler implements OpenAPIRequestHandler {
private static final String DEFAULT_CDN = "https://unpkg.com/swagger-ui-dist@5.18.2";
private static final String INDEX_PATH = "/META-INF/resources/swagger-ui/index.html";
private final FrameworkModel frameworkModel;
private final ConfigFactory configFactory;
private OpenAPIConfig config;
public SwaggerUIRequestHandler(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
configFactory = frameworkModel.getOrRegisterBean(ConfigFactory.class);
}
private OpenAPIConfig getConfig() {
if (config == null) {
config = configFactory.getGlobalConfig();
}
return config;
}
@Override
public String[] getPaths() {
return new String[] {"/swagger-ui/{*path}"};
}
@Override
public HttpResult<?> handle(String path, HttpRequest request, HttpResponse response) {
String resPath = RequestUtils.getPathVariable(request, "path");
if (StringUtils.isEmpty(resPath)) {
throw HttpResult.found(PathUtils.join(request.uri(), "index.html")).toPayload();
}
String requestPath = StringUtils.substringBeforeLast(resPath, '.');
switch (requestPath) {
case "index":
return handleIndex();
case "swagger-config":
return handleSwaggerConfig();
default:
if (WebjarHelper.ENABLED && requestPath.startsWith("assets/")) {
return WebjarHelper.getInstance().handleAssets("swagger-ui", resPath.substring(7));
}
}
throw new HttpStatusException(HttpStatus.NOT_FOUND.getCode());
}
private HttpResult<?> handleIndex() {
Map<String, String> variables = new HashMap<>(4);
OpenAPIConfig config = getConfig();
String cdn = config.getSetting("swagger-ui.cdn");
if (cdn == null) {
if (WebjarHelper.ENABLED && WebjarHelper.getInstance().hasWebjar("swagger-ui")) {
cdn = "./assets";
} else {
cdn = DEFAULT_CDN;
}
}
variables.put("swagger-ui.cdn", cdn);
Map<String, String> settings = config.getSettings();
if (settings != null) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : settings.entrySet()) {
String key = entry.getKey();
if (key.startsWith("swagger-ui.settings.")) {
sb.append(",\n \"")
.append(key.substring(20))
.append("\": ")
.append(entry.getValue());
}
}
if (sb.length() > 0) {
variables.put("swagger-ui.settings", sb.toString());
}
}
try {
String content = StreamUtils.toString(getClass().getResourceAsStream(INDEX_PATH));
return HttpResult.of(Helper.render(content, variables::get).getBytes(UTF_8));
} catch (IOException e) {
throw new HttpStatusException(HttpStatus.INTERNAL_SERVER_ERROR.getCode(), e);
}
}
private HttpResult<?> handleSwaggerConfig() {
OpenAPIService openAPIService = frameworkModel.getBean(OpenAPIService.class);
if (openAPIService == null) {
return HttpResult.notFound();
}
Collection<String> groups = openAPIService.getOpenAPIGroups();
List<Map<String, String>> urls = new ArrayList<>();
for (String group : groups) {
Map<String, String> url = new LinkedHashMap<>(4);
url.put("name", group);
url.put("url", "../api-docs/" + group);
urls.add(url);
}
Map<String, Object> configMap = new LinkedHashMap<>();
configMap.put("urls", urls);
return HttpResult.of(JsonUtils.toJson(configMap).getBytes(UTF_8));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/swagger/SwaggerOpenAPIDefinitionResolver.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/swagger/SwaggerOpenAPIDefinitionResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.swagger;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta.PropertyMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ServiceMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Constants;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.OpenAPIDefinitionResolver;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.OpenAPISchemaPredicate;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.OpenAPISchemaResolver;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Contact;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.ExternalDocs;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Info;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.License;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Operation;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.PathItem;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Schema;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Schema.Type;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Tag;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import io.swagger.v3.oas.annotations.ExternalDocumentation;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.extensions.ExtensionProperty;
import io.swagger.v3.oas.annotations.media.Schema.AccessMode;
import io.swagger.v3.oas.annotations.media.Schema.RequiredMode;
import static org.apache.dubbo.rpc.protocol.tri.rest.openapi.Helper.setValue;
import static org.apache.dubbo.rpc.protocol.tri.rest.openapi.Helper.trim;
@Activate(order = 50, onClass = "io.swagger.v3.oas.annotations.OpenAPIDefinition")
public final class SwaggerOpenAPIDefinitionResolver
implements OpenAPIDefinitionResolver, OpenAPISchemaResolver, OpenAPISchemaPredicate {
@Override
public OpenAPI resolve(OpenAPI openAPI, ServiceMeta serviceMeta, OpenAPIChain chain) {
AnnotationMeta<OpenAPIDefinition> annoMeta = serviceMeta.findAnnotation(OpenAPIDefinition.class);
if (annoMeta == null) {
return chain.resolve(openAPI, serviceMeta);
}
if (serviceMeta.isHierarchyAnnotated(Hidden.class)) {
return null;
}
OpenAPIDefinition anno = annoMeta.getAnnotation();
Info info = openAPI.getInfo();
if (info == null) {
openAPI.setInfo(info = new Info());
}
io.swagger.v3.oas.annotations.info.Info infoAnn = anno.info();
info.setTitle(trim(infoAnn.title()))
.setDescription(trim(infoAnn.description()))
.setVersion(trim(infoAnn.version()))
.setExtensions(toProperties(infoAnn.extensions()));
Contact contact = new Contact();
info.setContact(contact);
io.swagger.v3.oas.annotations.info.Contact contactAnn = infoAnn.contact();
contact.setName(trim(contactAnn.name()))
.setEmail(trim(contactAnn.email()))
.setUrl(trim(contactAnn.url()))
.setExtensions(toProperties(contactAnn.extensions()));
License license = new License();
info.setLicense(license);
io.swagger.v3.oas.annotations.info.License licenseAnn = infoAnn.license();
license.setName(trim(licenseAnn.name()))
.setUrl(trim(licenseAnn.url()))
.setExtensions(toProperties(licenseAnn.extensions()));
for (io.swagger.v3.oas.annotations.tags.Tag tagAnn : anno.tags()) {
openAPI.addTag(new Tag()
.setName(trim(tagAnn.name()))
.setDescription(trim(tagAnn.description()))
.setExternalDocs(toExternalDocs(tagAnn.externalDocs()))
.setExtensions(toProperties(tagAnn.extensions())));
}
openAPI.setExternalDocs(toExternalDocs(anno.externalDocs()));
Map<String, String> properties = toProperties(anno.extensions());
if (properties != null) {
String group = properties.remove(Constants.X_API_GROUP);
if (group != null) {
openAPI.setGroup(group);
}
openAPI.setExtensions(properties);
}
return chain.resolve(openAPI, serviceMeta);
}
private static Map<String, String> toProperties(io.swagger.v3.oas.annotations.extensions.Extension[] extensions) {
int len = extensions.length;
if (len == 0) {
return null;
}
Map<String, String> properties = CollectionUtils.newLinkedHashMap(extensions.length);
for (io.swagger.v3.oas.annotations.extensions.Extension extension : extensions) {
for (ExtensionProperty property : extension.properties()) {
properties.put(property.name(), property.value());
}
}
return properties;
}
private static ExternalDocs toExternalDocs(ExternalDocumentation anno) {
return new ExternalDocs()
.setDescription(trim(anno.description()))
.setUrl(trim(anno.url()))
.setExtensions(toProperties(anno.extensions()));
}
@Override
public Collection<HttpMethods> resolve(PathItem pathItem, MethodMeta methodMeta, OperationContext context) {
AnnotationMeta<io.swagger.v3.oas.annotations.Operation> annoMeta =
methodMeta.findAnnotation(io.swagger.v3.oas.annotations.Operation.class);
if (annoMeta == null) {
return null;
}
String method = trim(annoMeta.getAnnotation().method());
if (method == null) {
return null;
}
return Collections.singletonList(HttpMethods.of(method.toUpperCase()));
}
@Override
public Operation resolve(Operation operation, MethodMeta methodMeta, OperationContext ctx, OperationChain chain) {
AnnotationMeta<io.swagger.v3.oas.annotations.Operation> annoMeta =
methodMeta.findAnnotation(io.swagger.v3.oas.annotations.Operation.class);
if (annoMeta == null) {
return chain.resolve(operation, methodMeta, ctx);
}
io.swagger.v3.oas.annotations.Operation anno = annoMeta.getAnnotation();
if (anno.hidden() || methodMeta.isHierarchyAnnotated(Hidden.class)) {
return null;
}
String method = trim(anno.method());
if (method != null) {
operation.setHttpMethod(HttpMethods.of(method.toUpperCase()));
}
for (String tag : anno.tags()) {
operation.addTag(tag);
}
Map<String, String> properties = toProperties(anno.extensions());
if (properties != null) {
String group = properties.remove(Constants.X_API_GROUP);
if (group != null) {
operation.setGroup(group);
}
String version = properties.remove(Constants.X_API_VERSION);
if (version != null) {
operation.setVersion(version);
}
operation.setExtensions(properties);
}
operation
.setSummary(trim(anno.summary()))
.setDescription(trim(anno.description()))
.setExternalDocs(toExternalDocs(anno.externalDocs()))
.setOperationId(trim(anno.operationId()))
.setDeprecated(anno.deprecated() ? Boolean.TRUE : null);
return chain.resolve(operation, methodMeta, ctx);
}
@Override
public Schema resolve(ParameterMeta parameter, SchemaContext context, SchemaChain chain) {
AnnotationMeta<io.swagger.v3.oas.annotations.media.Schema> annoMeta =
parameter.getAnnotation(io.swagger.v3.oas.annotations.media.Schema.class);
if (annoMeta == null) {
return chain.resolve(parameter, context);
}
io.swagger.v3.oas.annotations.media.Schema anno = annoMeta.getAnnotation();
if (anno.hidden() || parameter.isHierarchyAnnotated(Hidden.class)) {
return null;
}
Schema schema = chain.resolve(parameter, context);
if (schema == null) {
return null;
}
Map<String, String> properties = toProperties(anno.extensions());
if (properties != null) {
String group = properties.remove(Constants.X_API_GROUP);
if (group != null) {
schema.setGroup(group);
}
String version = properties.remove(Constants.X_API_VERSION);
if (version != null) {
schema.setVersion(version);
}
schema.setExtensions(properties);
}
setValue(anno::type, v -> schema.setType(Type.valueOf(v)));
setValue(anno::format, schema::setFormat);
setValue(anno::name, schema::setName);
setValue(anno::title, schema::setTitle);
setValue(anno::description, schema::setDescription);
setValue(anno::defaultValue, schema::setDefaultValue);
setValue(anno::pattern, schema::setPattern);
setValue(anno::example, schema::setExample);
String[] enumItems = trim(anno.allowableValues());
if (enumItems != null) {
schema.setEnumeration(Arrays.asList(enumItems));
}
schema.setRequired(anno.requiredMode() == RequiredMode.REQUIRED ? Boolean.TRUE : null);
schema.setReadOnly(anno.accessMode() == AccessMode.READ_ONLY ? Boolean.TRUE : null);
schema.setWriteOnly(anno.accessMode() == AccessMode.WRITE_ONLY ? Boolean.TRUE : null);
schema.setNullable(anno.nullable() ? Boolean.TRUE : null);
schema.setDeprecated(anno.deprecated() ? Boolean.TRUE : null);
return chain.resolve(parameter, context);
}
@Override
public Boolean acceptProperty(BeanMeta bean, PropertyMeta property) {
AnnotationMeta<io.swagger.v3.oas.annotations.media.Schema> meta =
bean.getAnnotation(io.swagger.v3.oas.annotations.media.Schema.class);
if (meta == null) {
return null;
}
io.swagger.v3.oas.annotations.media.Schema schema = meta.getAnnotation();
return schema.hidden() || bean.isHierarchyAnnotated(Hidden.class) ? false : null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/DefinitionMerger.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/DefinitionMerger.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.common.logger.FluentLogger;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.config.nested.OpenAPIConfig;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.remoting.http12.rest.OpenAPIRequest;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.ApiResponse;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Components;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Contact;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.ExternalDocs;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Header;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Info;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.License;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.MediaType;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Node;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Operation;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Parameter;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.PathItem;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.RequestBody;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Schema;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.SecurityRequirement;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.SecurityScheme;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Server;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Tag;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import static org.apache.dubbo.rpc.protocol.tri.rest.openapi.Helper.setValue;
final class DefinitionMerger {
private static final FluentLogger LOG = FluentLogger.of(DefinitionMerger.class);
private static final String NAMING_STRATEGY_PREFIX = "naming-strategy-";
private static final String NAMING_STRATEGY_DEFAULT = "default";
private static Type SECURITY_SCHEMES_TYPE;
private static Type SECURITY_TYPE;
private final ExtensionFactory extensionFactory;
private final ConfigFactory configFactory;
private OpenAPINamingStrategy openAPINamingStrategy;
DefinitionMerger(FrameworkModel frameworkModel) {
extensionFactory = frameworkModel.getOrRegisterBean(ExtensionFactory.class);
configFactory = frameworkModel.getOrRegisterBean(ConfigFactory.class);
}
private OpenAPINamingStrategy getNamingStrategy() {
if (openAPINamingStrategy == null) {
String strategy = configFactory.getGlobalConfig().getNameStrategy();
String name = NAMING_STRATEGY_PREFIX + (strategy == null ? NAMING_STRATEGY_DEFAULT : strategy);
openAPINamingStrategy = extensionFactory.getExtension(OpenAPINamingStrategy.class, name);
Objects.requireNonNull(openAPINamingStrategy, "Can't find OpenAPINamingStrategy with name: " + name);
}
return openAPINamingStrategy;
}
public OpenAPI merge(List<OpenAPI> openAPIs, OpenAPIRequest request) {
Info info = new Info();
OpenAPI target = new OpenAPI().setInfo(info);
OpenAPIConfig globalConfig = configFactory.getGlobalConfig();
target.setGlobalConfig(globalConfig);
applyConfig(target, globalConfig);
if (openAPIs.isEmpty()) {
return target;
}
String group = request.getGroup();
if (group == null) {
group = Constants.DEFAULT_GROUP;
}
target.setGroup(group);
String version = request.getVersion();
if (version != null) {
info.setVersion(version);
}
target.setOpenapi(Helper.formatSpecVersion(request.getOpenapi()));
OpenAPIConfig config = configFactory.getConfig(group);
target.setConfig(config);
String[] tags = request.getTag();
String[] services = request.getService();
for (int i = openAPIs.size() - 1; i >= 0; i--) {
OpenAPI source = openAPIs.get(i);
if (isServiceNotMatch(source.getMeta().getServiceInterface(), services)) {
continue;
}
if (group.equals(source.getGroup())) {
mergeBasic(target, source);
}
mergePaths(target, source, group, version, tags);
mergeSecuritySchemes(target, source);
mergeTags(target, source);
}
applyConfig(target, config);
addSchemas(target, version, group);
completeOperations(target);
completeModel(target);
return target;
}
private void applyConfig(OpenAPI target, OpenAPIConfig config) {
if (config == null) {
return;
}
Info info = target.getInfo();
setValue(config::getInfoTitle, info::setTitle);
setValue(config::getInfoDescription, info::setDescription);
setValue(config::getInfoVersion, info::setVersion);
Contact contact = info.getContact();
if (contact == null) {
info.setContact(contact = new Contact());
}
setValue(config::getInfoContactName, contact::setName);
setValue(config::getInfoContactUrl, contact::setUrl);
setValue(config::getInfoContactEmail, contact::setEmail);
ExternalDocs externalDocs = target.getExternalDocs();
if (externalDocs == null) {
target.setExternalDocs(externalDocs = new ExternalDocs());
}
setValue(config::getExternalDocsDescription, externalDocs::setDescription);
setValue(config::getExternalDocsUrl, externalDocs::setUrl);
String[] servers = config.getServers();
if (servers != null) {
target.setServers(Arrays.stream(servers).map(Helper::parseServer).collect(Collectors.toList()));
}
Components components = target.getComponents();
if (target.getComponents() == null) {
target.setComponents(components = new Components());
}
String securityScheme = config.getSecurityScheme();
if (securityScheme != null) {
try {
if (SECURITY_SCHEMES_TYPE == null) {
SECURITY_SCHEMES_TYPE =
Components.class.getDeclaredField("securitySchemes").getGenericType();
}
components.setSecuritySchemes(JsonUtils.toJavaObject(securityScheme, SECURITY_SCHEMES_TYPE));
} catch (NoSuchFieldException ignored) {
}
}
String security = config.getSecurity();
if (security != null) {
try {
if (SECURITY_TYPE == null) {
SECURITY_TYPE = OpenAPI.class.getDeclaredField("security").getGenericType();
}
target.setSecurity(JsonUtils.toJavaObject(securityScheme, SECURITY_TYPE));
} catch (NoSuchFieldException ignored) {
}
}
}
private void mergeBasic(OpenAPI target, OpenAPI source) {
mergeInfo(target, source);
if (target.getServers() == null) {
target.setServers(Node.clone(source.getServers()));
}
List<SecurityRequirement> sourceSecurity = source.getSecurity();
if (target.getSecurity() == null) {
target.setSecurity(Node.clone(sourceSecurity));
}
ExternalDocs sourceExternalDocs = source.getExternalDocs();
if (sourceExternalDocs != null) {
ExternalDocs targetExternalDocs = target.getExternalDocs();
setValue(sourceExternalDocs::getDescription, targetExternalDocs::setDescription);
setValue(sourceExternalDocs::getUrl, targetExternalDocs::setUrl);
targetExternalDocs.addExtensions(sourceExternalDocs.getExtensions());
}
target.addExtensions(source.getExtensions());
}
private void mergeInfo(OpenAPI target, OpenAPI source) {
Info sourceInfo = source.getInfo();
if (sourceInfo == null) {
return;
}
Info info = target.getInfo();
setValue(sourceInfo::getTitle, info::setTitle);
setValue(sourceInfo::getSummary, info::setSummary);
setValue(sourceInfo::getDescription, info::setDescription);
setValue(sourceInfo::getTermsOfService, info::setTermsOfService);
setValue(sourceInfo::getVersion, info::setVersion);
Contact sourceContact = sourceInfo.getContact();
if (sourceContact != null) {
Contact contact = info.getContact();
setValue(sourceContact::getName, contact::setName);
setValue(sourceContact::getUrl, contact::setUrl);
setValue(sourceContact::getEmail, contact::setEmail);
contact.addExtensions(sourceContact.getExtensions());
}
License sourceLicense = sourceInfo.getLicense();
if (sourceLicense != null) {
License license = info.getLicense();
if (license == null) {
info.setLicense(license = new License());
}
setValue(sourceLicense::getName, license::setName);
setValue(sourceLicense::getUrl, license::setUrl);
license.addExtensions(sourceLicense.getExtensions());
}
info.addExtensions(sourceInfo.getExtensions());
}
private void mergePaths(OpenAPI target, OpenAPI source, String group, String version, String[] tags) {
Map<String, PathItem> sourcePaths = source.getPaths();
if (sourcePaths == null) {
return;
}
Map<String, PathItem> paths = target.getPaths();
if (paths == null) {
target.setPaths(paths = new TreeMap<>());
}
for (Entry<String, PathItem> entry : sourcePaths.entrySet()) {
String path = entry.getKey();
PathItem sourcePathItem = entry.getValue();
PathItem pathItem = paths.get(path);
if (pathItem != null) {
String ref = sourcePathItem.getRef();
if (ref != null) {
pathItem = paths.get(ref);
}
}
if (pathItem == null) {
paths.put(path, pathItem = new PathItem());
}
mergePath(path, pathItem, sourcePathItem, group, version, tags);
}
}
private void mergePath(String path, PathItem target, PathItem source, String group, String version, String[] tags) {
if (target.getRef() == null) {
target.setRef(source.getRef());
}
if (target.getSummary() == null) {
target.setSummary(source.getSummary());
}
if (target.getDescription() == null) {
target.setDescription(source.getDescription());
}
Map<HttpMethods, Operation> sourceOperations = source.getOperations();
if (sourceOperations != null) {
for (Entry<HttpMethods, Operation> entry : sourceOperations.entrySet()) {
HttpMethods httpMethod = entry.getKey();
Operation sourceOperation = entry.getValue();
if (isGroupNotMatch(group, sourceOperation.getGroup())
|| isVersionNotMatch(version, sourceOperation.getVersion())
|| isTagNotMatch(tags, sourceOperation.getTags())) {
continue;
}
Operation operation = target.getOperation(httpMethod);
if (operation == null) {
target.addOperation(httpMethod, sourceOperation.clone());
} else if (operation.getMeta() != null) {
LOG.internalWarn(
"Operation already exists, path='{}', httpMethod='{}', method={}",
path,
httpMethod,
sourceOperation.getMeta());
}
}
}
if (target.getServers() == null) {
List<Server> sourceServers = source.getServers();
if (sourceServers != null) {
target.setServers(Node.clone(sourceServers));
}
}
List<Parameter> sourceParameters = source.getParameters();
if (sourceParameters != null) {
if (target.getParameters() == null) {
target.setParameters(Node.clone(sourceParameters));
} else {
for (Parameter parameter : sourceParameters) {
target.addParameter(parameter.clone());
}
}
}
target.addExtensions(source.getExtensions());
}
private static boolean isServiceNotMatch(String apiService, String[] services) {
if (apiService == null || services == null) {
return false;
}
for (String service : services) {
if (apiService.regionMatches(true, 0, service, 0, service.length())) {
return false;
}
}
return true;
}
private static boolean isGroupNotMatch(String group, String sourceGroup) {
return !(sourceGroup == null && Constants.DEFAULT_GROUP.equals(group)
|| Constants.ALL_GROUP.equals(group)
|| group.equals(sourceGroup));
}
private static boolean isVersionNotMatch(String version, String sourceVersion) {
return !(version == null || sourceVersion == null || Helper.isVersionGreaterOrEqual(sourceVersion, version));
}
private static boolean isTagNotMatch(String[] tags, Set<String> operationTags) {
if (tags == null || operationTags == null) {
return false;
}
for (String tag : tags) {
if (operationTags.contains(tag)) {
return false;
}
}
return true;
}
private void mergeSecuritySchemes(OpenAPI target, OpenAPI source) {
Components sourceComponents = source.getComponents();
if (sourceComponents == null) {
return;
}
Map<String, SecurityScheme> sourceSecuritySchemes = sourceComponents.getSecuritySchemes();
if (sourceSecuritySchemes == null) {
return;
}
Components components = target.getComponents();
Map<String, SecurityScheme> securitySchemes = components.getSecuritySchemes();
if (securitySchemes == null) {
components.setSecuritySchemes(Node.clone(sourceSecuritySchemes));
} else {
for (Entry<String, SecurityScheme> entry : sourceSecuritySchemes.entrySet()) {
securitySchemes.computeIfAbsent(
entry.getKey(), k -> entry.getValue().clone());
}
}
}
private void mergeTags(OpenAPI target, OpenAPI source) {
List<Tag> sourceTags = source.getTags();
if (sourceTags == null) {
return;
}
if (target.getTags() == null) {
target.setTags(Node.clone(sourceTags));
} else {
for (Tag tag : sourceTags) {
target.addTag(tag.clone());
}
}
}
private void addSchemas(OpenAPI target, String version, String group) {
Map<String, PathItem> paths = target.getPaths();
if (paths == null) {
return;
}
Map<Schema, Schema> schemas = new IdentityHashMap<>();
for (PathItem pathItem : paths.values()) {
Map<HttpMethods, Operation> operations = pathItem.getOperations();
if (operations == null) {
continue;
}
for (Operation operation : operations.values()) {
List<Parameter> parameters = operation.getParameters();
if (parameters != null) {
for (Parameter parameter : parameters) {
addSchema(parameter.getSchema(), schemas, group, version);
Map<String, MediaType> contents = parameter.getContents();
if (contents == null) {
continue;
}
for (MediaType content : contents.values()) {
addSchema(content.getSchema(), schemas, group, version);
}
}
}
RequestBody requestBody = operation.getRequestBody();
if (requestBody != null) {
Map<String, MediaType> contents = requestBody.getContents();
if (contents == null) {
continue;
}
for (MediaType content : contents.values()) {
addSchema(content.getSchema(), schemas, group, version);
}
}
Map<String, ApiResponse> responses = operation.getResponses();
if (responses != null) {
for (ApiResponse response : responses.values()) {
Map<String, Header> headers = response.getHeaders();
if (headers != null) {
for (Header header : headers.values()) {
addSchema(header.getSchema(), schemas, group, version);
}
}
Map<String, MediaType> contents = response.getContents();
if (contents == null) {
continue;
}
for (MediaType content : contents.values()) {
addSchema(content.getSchema(), schemas, group, version);
}
}
}
}
}
Components components = target.getComponents();
if (components == null) {
target.setComponents(components = new Components());
}
Set<String> names = CollectionUtils.newHashSet(schemas.size());
for (Schema schema : schemas.keySet()) {
String name = schema.getName();
if (name != null) {
names.add(name);
}
}
OpenAPINamingStrategy strategy = getNamingStrategy();
for (Schema schema : schemas.values()) {
String name = schema.getName();
if (name == null) {
Class<?> clazz = schema.getJavaType();
name = strategy.generateSchemaName(clazz, target);
for (int i = 1; i < 100; i++) {
if (names.contains(name)) {
name = strategy.resolveSchemaNameConflict(i, name, clazz, target);
} else {
names.add(name);
break;
}
}
schema.setName(name);
}
for (Schema sourceSchema : schema.getSourceSchemas()) {
sourceSchema.setTargetSchema(schema);
sourceSchema.setRef("#/components/schemas/" + name);
}
schema.setSourceSchemas(null);
components.addSchema(name, schema);
}
}
private void addSchema(Schema schema, Map<Schema, Schema> schemas, String group, String version) {
if (schema == null) {
return;
}
addSchema(schema.getItems(), schemas, group, version);
Map<String, Schema> properties = schema.getProperties();
if (properties != null) {
Iterator<Entry<String, Schema>> it = properties.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Schema> entry = it.next();
Schema property = entry.getValue();
if (isGroupNotMatch(group, property.getGroup()) || isVersionNotMatch(version, property.getVersion())) {
it.remove();
continue;
}
addSchema(property, schemas, group, version);
}
}
addSchema(schema.getAdditionalPropertiesSchema(), schemas, group, version);
List<Schema> allOf = schema.getAllOf();
if (allOf != null) {
for (Schema item : allOf) {
addSchema(item, schemas, group, version);
}
}
List<Schema> oneOf = schema.getOneOf();
if (oneOf != null) {
for (Schema item : oneOf) {
addSchema(item, schemas, group, version);
}
}
List<Schema> anyOf = schema.getAnyOf();
if (anyOf != null) {
for (Schema item : anyOf) {
addSchema(item, schemas, group, version);
}
}
addSchema(schema.getNot(), schemas, group, version);
Schema targetSchema = schema.getTargetSchema();
if (targetSchema == null) {
return;
}
targetSchema.addSourceSchema(schema);
Schema newSchema = schemas.get(targetSchema);
if (newSchema == null) {
newSchema = targetSchema.clone();
schemas.put(targetSchema, newSchema);
addSchema(newSchema, schemas, group, version);
}
}
private void completeOperations(OpenAPI target) {
Map<String, PathItem> paths = target.getPaths();
if (paths == null) {
return;
}
Set<String> allOperationIds = new HashSet<>(32);
Set<String> allTags = new HashSet<>(32);
target.walkOperations(operation -> {
String operationId = operation.getOperationId();
if (operationId != null) {
allOperationIds.add(operationId);
}
Set<String> tags = operation.getTags();
if (tags != null) {
allTags.addAll(tags);
}
});
OpenAPINamingStrategy strategy = getNamingStrategy();
target.walkOperations(operation -> {
String id = operation.getOperationId();
if (id != null) {
return;
}
id = strategy.generateOperationId(operation.getMeta(), target);
for (int i = 1; i < 100; i++) {
if (allOperationIds.contains(id)) {
id = strategy.resolveOperationIdConflict(i, id, operation.getMeta(), target);
} else {
allOperationIds.add(id);
break;
}
}
operation.setOperationId(id);
});
List<Tag> tags = target.getTags();
if (tags != null) {
ListIterator<Tag> it = tags.listIterator();
while (it.hasNext()) {
if (allTags.contains(it.next().getName())) {
continue;
}
it.remove();
}
}
}
private void completeModel(OpenAPI target) {
Info info = target.getInfo();
if (info.getTitle() == null) {
info.setTitle("Dubbo OpenAPI");
}
if (info.getVersion() == null) {
info.setVersion("v1");
}
if (CollectionUtils.isEmptyMap(target.getPaths())) {
return;
}
ExternalDocs docs = target.getExternalDocs();
if (docs.getUrl() == null && docs.getDescription() == null) {
docs.setUrl("../redoc/index.html?group=" + target.getGroup()).setDescription("ReDoc");
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPISchemaPredicate.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPISchemaPredicate.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta.PropertyMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
public interface OpenAPISchemaPredicate extends OpenAPIExtension {
default Boolean acceptClass(Class<?> clazz, ParameterMeta parameter) {
return null;
}
default Boolean acceptProperty(BeanMeta bean, PropertyMeta property) {
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/Context.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/Context.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.remoting.http12.rest.OpenAPIRequest;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI;
public interface Context {
OpenAPIRequest getRequest();
HttpRequest getHttpRequest();
HttpResponse getHttpResponse();
String getGroup();
OpenAPI getOpenAPI();
boolean isOpenAPI31();
SchemaResolver getSchemaResolver();
ExtensionFactory getExtensionFactory();
<T> T getAttribute(String name);
<T> T removeAttribute(String name);
void setAttribute(String name, Object value);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPIScopeModelInitializer.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPIScopeModelInitializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
@Activate
public class OpenAPIScopeModelInitializer implements ScopeModelInitializer {
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {
frameworkModel.getBeanFactory().registerBeanDefinition(DefaultOpenAPIService.class);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/ExtensionFactory.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/ExtensionFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Pair;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
@SuppressWarnings("unchecked")
public final class ExtensionFactory {
private final ExtensionLoader<OpenAPIExtension> extensionLoader;
private final List<OpenAPIExtension> extensions;
private final Map<Object, Object> cache;
public ExtensionFactory(FrameworkModel frameworkModel) {
extensionLoader = frameworkModel.getExtensionLoader(OpenAPIExtension.class);
extensions = extensionLoader.getActivateExtensions();
cache = CollectionUtils.newConcurrentHashMap();
}
public <T extends OpenAPIExtension> boolean hasExtensions(Class<T> type) {
return getExtensions(type).length > 0;
}
public <T extends OpenAPIExtension> T[] getExtensions(Class<T> type) {
return (T[]) cache.computeIfAbsent(type, k -> {
List<OpenAPIExtension> list = new ArrayList<>();
for (OpenAPIExtension extension : extensions) {
if (extension instanceof Supplier) {
extension = ((Supplier<T>) extension).get();
}
if (type.isInstance(extension)) {
list.add(extension);
}
}
return list.toArray((T[]) Array.newInstance(type, list.size()));
});
}
public <T extends OpenAPIExtension> T[] getExtensions(Class<T> type, String group) {
if (group == null) {
return getExtensions(type);
}
return (T[]) cache.computeIfAbsent(Pair.of(type, group), k -> {
List<OpenAPIExtension> list = new ArrayList<>();
for (OpenAPIExtension extension : extensions) {
if (extension instanceof Supplier) {
extension = ((Supplier<T>) extension).get();
}
if (type.isInstance(extension) && accept(extension, group)) {
list.add(extension);
}
}
return list.toArray((T[]) Array.newInstance(type, list.size()));
});
}
public <T extends OpenAPIExtension> T getExtension(Class<T> type, String name) {
OpenAPIExtension extension = extensionLoader.getExtension(name, true);
if (extension instanceof Supplier) {
extension = ((Supplier<T>) extension).get();
}
return type.isInstance(extension) ? (T) extension : null;
}
private static boolean accept(OpenAPIExtension extension, String group) {
String[] groups = extension.getGroups();
return groups == null || groups.length == 0 || Arrays.asList(groups).contains(group);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/DefaultOpenAPINamingStrategy.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/DefaultOpenAPINamingStrategy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.common.io.Bytes;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI;
import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils;
import java.lang.reflect.Method;
import java.util.concurrent.ThreadLocalRandom;
public class DefaultOpenAPINamingStrategy implements OpenAPINamingStrategy {
@Override
public String generateOperationId(MethodMeta methodMeta, OpenAPI openAPI) {
return methodMeta.getMethod().getName();
}
@Override
public String resolveOperationIdConflict(int attempt, String operationId, MethodMeta methodMeta, OpenAPI openAPI) {
Method method = methodMeta.getMethod();
if (attempt == 1) {
String sig = TypeUtils.buildSig(method);
if (sig != null) {
return method.getName() + '_' + sig;
}
}
return method.getName() + '_' + buildPostfix(attempt, method.toString());
}
@Override
public String generateSchemaName(Class<?> clazz, OpenAPI openAPI) {
return clazz.getSimpleName();
}
@Override
public String resolveSchemaNameConflict(int attempt, String schemaName, Class<?> clazz, OpenAPI openAPI) {
return clazz.getSimpleName() + '_' + buildPostfix(attempt, clazz.getName());
}
private static String buildPostfix(int attempt, String str) {
if (attempt > 4) {
str += ThreadLocalRandom.current().nextInt(10000);
}
return Bytes.bytes2hex(Bytes.getMD5(str), 0, Math.min(4, attempt));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPIExtension.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPIExtension.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface OpenAPIExtension {
default String[] getGroups() {
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/DefinitionResolver.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/DefinitionResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.FluentLogger;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.nested.OpenAPIConfig;
import org.apache.dubbo.remoting.http12.ErrorResponse;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.remoting.http12.HttpUtils;
import org.apache.dubbo.remoting.http12.message.MediaType;
import org.apache.dubbo.remoting.http12.rest.ParamType;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.Registration;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMapping;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.MethodsCondition;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.PathCondition;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.condition.PathExpression;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta.PropertyMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta;
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.mapping.meta.ServiceMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.OpenAPIDefinitionResolver.OpenAPIChain;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.OpenAPIDefinitionResolver.OperationChain;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.OpenAPIDefinitionResolver.OperationContext;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.ApiResponse;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Operation;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Parameter;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Parameter.In;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.PathItem;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.RequestBody;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Schema;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Server;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Tag;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
final class DefinitionResolver {
private static final FluentLogger LOG = FluentLogger.of(DefinitionResolver.class);
private final ExtensionFactory extensionFactory;
private final ConfigFactory configFactory;
private final SchemaResolver schemaResolver;
private final OpenAPIDefinitionResolver[] resolvers;
DefinitionResolver(FrameworkModel frameworkModel) {
extensionFactory = frameworkModel.getOrRegisterBean(ExtensionFactory.class);
configFactory = frameworkModel.getOrRegisterBean(ConfigFactory.class);
schemaResolver = frameworkModel.getOrRegisterBean(SchemaResolver.class);
resolvers = extensionFactory.getExtensions(OpenAPIDefinitionResolver.class);
}
public OpenAPI resolve(ServiceMeta serviceMeta, Collection<List<Registration>> registrationsByMethod) {
OpenAPI definition = new OpenAPIChainImpl(resolvers, openAPI -> {
if (StringUtils.isEmpty(openAPI.getGroup())) {
openAPI.setGroup(Constants.DEFAULT_GROUP);
}
openAPI.setConfig(configFactory.getConfig(openAPI.getGroup()));
String service = serviceMeta.getServiceInterface();
int index = service.lastIndexOf('.');
String tagName = index == -1 ? service : service.substring(index + 1);
openAPI.addTag(new Tag().setName(tagName).setDescription(service));
return openAPI;
})
.resolve(
new OpenAPI().setMeta(serviceMeta).setGlobalConfig(configFactory.getGlobalConfig()),
serviceMeta);
if (definition == null) {
return null;
}
if (definition.getConfig() == null) {
definition.setConfig(configFactory.getConfig(definition.getGroup()));
}
if (CollectionUtils.isEmpty(definition.getServers())) {
URL url = serviceMeta.getUrl();
definition.addServer(new Server()
.setUrl("http://" + url.getHost() + ':' + url.getPort())
.setDescription(Constants.DUBBO_DEFAULT_SERVER));
}
OperationContext context = new OperationContextImpl(definition, schemaResolver, extensionFactory);
for (List<Registration> registrations : registrationsByMethod) {
String mainPath = null;
for (Registration registration : registrations) {
RequestMapping mapping = registration.getMapping();
PathCondition pathCondition = mapping.getPathCondition();
if (pathCondition == null) {
continue;
}
for (PathExpression expression : pathCondition.getExpressions()) {
String path = expression.toString();
PathItem pathItem = definition.getOrAddPath(path);
String ref = pathItem.getRef();
if (ref != null) {
path = ref;
pathItem = definition.getOrAddPath(path);
}
if (mainPath != null && expression.isDirect()) {
pathItem.setRef(mainPath);
continue;
}
MethodMeta methodMeta = registration.getMeta().getMethod();
if (resolvePath(path, pathItem, definition, methodMeta, mapping, context)) {
mainPath = path;
}
}
}
}
return definition;
}
private boolean resolvePath(
String path,
PathItem pathItem,
OpenAPI openAPI,
MethodMeta methodMeta,
RequestMapping mapping,
OperationContext context) {
Collection<HttpMethods> httpMethods = null;
for (OpenAPIDefinitionResolver resolver : resolvers) {
httpMethods = resolver.resolve(pathItem, methodMeta, context);
if (httpMethods != null) {
break;
}
}
if (httpMethods == null) {
httpMethods = new LinkedList<>();
for (String method : determineHttpMethods(openAPI, methodMeta, mapping)) {
httpMethods.add(HttpMethods.of(method.toUpperCase()));
}
}
boolean added = false;
for (HttpMethods httpMethod : httpMethods) {
Operation operation = new Operation().setMeta(methodMeta);
Operation existingOperation = pathItem.getOperation(httpMethod);
if (existingOperation != null && existingOperation.getMeta() != null) {
LOG.internalWarn(
"Operation already exists, path='{}', httpMethod='{}', method={}",
path,
httpMethod,
methodMeta);
continue;
}
operation = new OperationChainImpl(
resolvers, op -> resolveOperation(path, httpMethod, op, openAPI, methodMeta, mapping))
.resolve(operation, methodMeta, context);
if (operation != null) {
pathItem.addOperation(httpMethod, operation);
added = true;
}
}
return added;
}
private Collection<String> determineHttpMethods(OpenAPI openAPI, MethodMeta meta, RequestMapping mapping) {
Collection<String> httpMethods = null;
MethodsCondition condition = mapping.getMethodsCondition();
if (condition != null) {
httpMethods = condition.getMethods();
}
if (httpMethods == null) {
String[] defaultHttpMethods = openAPI.getConfigValue(OpenAPIConfig::getDefaultHttpMethods);
if (defaultHttpMethods == null) {
httpMethods = Helper.guessHttpMethod(meta);
} else {
httpMethods = Arrays.asList(defaultHttpMethods);
}
}
return httpMethods;
}
private Operation resolveOperation(
String path,
HttpMethods httpMethod,
Operation operation,
OpenAPI openAPI,
MethodMeta meta,
RequestMapping mapping) {
if (operation.getGroup() == null) {
operation.setGroup(openAPI.getGroup());
}
for (Tag tag : openAPI.getTags()) {
operation.addTag(tag.getName());
}
if (operation.getDeprecated() == null && meta.isHierarchyAnnotated(Deprecated.class)) {
operation.setDeprecated(true);
}
ServiceMeta serviceMeta = meta.getServiceMeta();
if (serviceMeta.getServiceVersion() != null) {
operation.addParameter(new Parameter(TripleHeaderEnum.SERVICE_GROUP.getName(), In.HEADER)
.setSchema(PrimitiveSchema.STRING.newSchema()));
}
if (serviceMeta.getServiceGroup() != null) {
operation.addParameter(new Parameter(TripleHeaderEnum.SERVICE_VERSION.getName(), In.HEADER)
.setSchema(PrimitiveSchema.STRING.newSchema()));
}
List<String> variables = Helper.extractVariables(path);
if (variables != null) {
for (String variable : variables) {
Parameter parameter = operation.getParameter(variable, In.PATH);
if (parameter == null) {
parameter = new Parameter(variable, In.PATH);
operation.addParameter(parameter);
}
parameter.setRequired(true);
if (parameter.getSchema() == null) {
parameter.setSchema(PrimitiveSchema.STRING.newSchema());
}
}
}
for (ParameterMeta paramMeta : meta.getParameters()) {
resolveParameter(httpMethod, operation, paramMeta, true);
}
if (httpMethod.supportBody()) {
RequestBody body = operation.getRequestBody();
if (body == null) {
body = new RequestBody();
operation.setRequestBody(body);
}
if (CollectionUtils.isEmptyMap(body.getContents())) {
resolveRequestBody(body, openAPI, meta, mapping);
}
}
if (CollectionUtils.isEmptyMap(operation.getResponses())) {
String[] httpStatusCodes = openAPI.getConfigValue(OpenAPIConfig::getDefaultHttpStatusCodes);
if (httpStatusCodes == null) {
httpStatusCodes = new String[] {"200", "400", "500"};
}
for (String httpStatusCode : httpStatusCodes) {
ApiResponse response = operation.getOrAddResponse(httpStatusCode);
resolveResponse(httpStatusCode, response, openAPI, meta, mapping);
}
}
return operation;
}
private void resolveParameter(HttpMethods httpMethod, Operation operation, ParameterMeta meta, boolean traverse) {
String name = meta.getName();
if (name == null) {
return;
}
NamedValueMeta valueMeta = meta.getNamedValueMeta();
ParamType paramType = valueMeta.paramType();
if (paramType == null) {
if (httpMethod.supportBody()) {
return;
}
paramType = ParamType.Param;
}
In in = Helper.toIn(paramType);
if (in == null) {
return;
}
boolean simple = meta.isSimple();
if (in != In.QUERY && !simple) {
return;
}
if (simple) {
Parameter parameter = operation.getParameter(name, in);
if (parameter == null) {
parameter = new Parameter(name, in);
operation.addParameter(parameter);
}
if (parameter.getRequired() == null) {
parameter.setRequired(valueMeta.required());
}
Schema schema = parameter.getSchema();
if (schema == null) {
parameter.setSchema(schema = schemaResolver.resolve(meta));
}
if (schema.getDefaultValue() == null) {
schema.setDefaultValue(valueMeta.defaultValue());
}
parameter.setMeta(meta);
return;
}
if (!traverse) {
return;
}
BeanMeta beanMeta = meta.getBeanMeta();
try {
for (ParameterMeta ctorParam : beanMeta.getConstructor().getParameters()) {
resolveParameter(httpMethod, operation, ctorParam, false);
}
} catch (Throwable ignored) {
}
for (PropertyMeta property : beanMeta.getProperties()) {
if ((property.getVisibility() & 0b001) == 0) {
continue;
}
resolveParameter(httpMethod, operation, property, false);
}
}
private void resolveRequestBody(RequestBody body, OpenAPI openAPI, MethodMeta meta, RequestMapping mapping) {
Collection<MediaType> mediaTypes = null;
if (mapping.getConsumesCondition() != null) {
mediaTypes = mapping.getConsumesCondition().getMediaTypes();
}
if (mediaTypes == null) {
String[] defaultMediaTypes = openAPI.getConfigValue(OpenAPIConfig::getDefaultConsumesMediaTypes);
if (defaultMediaTypes == null) {
mediaTypes = Collections.singletonList(MediaType.APPLICATION_JSON);
} else {
mediaTypes = Arrays.stream(defaultMediaTypes).map(MediaType::of).collect(Collectors.toList());
}
}
out:
for (MediaType mediaType : mediaTypes) {
org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.MediaType content =
body.getOrAddContent(mediaType.getName());
if (content.getSchema() == null) {
for (ParameterMeta paramMeta : meta.getParameters()) {
ParamType paramType = paramMeta.getNamedValueMeta().paramType();
if (paramType == ParamType.Body) {
content.setSchema(schemaResolver.resolve(paramMeta));
continue out;
}
}
List<ParameterMeta> paramMetas = new ArrayList<>();
for (ParameterMeta paramMeta : meta.getParameters()) {
if (paramMeta.getNamedValueMeta().paramType() == null) {
paramMetas.add(paramMeta);
}
}
int size = paramMetas.size();
if (size == 0) {
continue;
}
if (size == 1) {
content.setSchema(schemaResolver.resolve(paramMetas.get(0)));
} else {
content.setSchema(schemaResolver.resolve(paramMetas));
}
}
}
}
private void resolveResponse(
String httpStatusCode, ApiResponse response, OpenAPI openAPI, MethodMeta meta, RequestMapping mapping) {
int httpStatus = Integer.parseInt(httpStatusCode);
if (response.getDescription() == null) {
response.setDescription(HttpUtils.getStatusMessage(httpStatus));
}
if (httpStatus > 201 && httpStatus < 400) {
return;
}
if (meta.getActualReturnType() == void.class) {
return;
}
Collection<MediaType> mediaTypes = null;
if (mapping.getProducesCondition() != null) {
mediaTypes = mapping.getProducesCondition().getMediaTypes();
}
if (mediaTypes == null) {
String[] defaultMediaTypes = openAPI.getConfigValue(OpenAPIConfig::getDefaultProducesMediaTypes);
if (defaultMediaTypes == null) {
mediaTypes = Collections.singletonList(MediaType.APPLICATION_JSON);
} else {
mediaTypes = Arrays.stream(defaultMediaTypes).map(MediaType::of).collect(Collectors.toList());
}
}
for (MediaType mediaType : mediaTypes) {
org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.MediaType content =
response.getOrAddContent(mediaType.getName());
if (content.getSchema() == null) {
if (httpStatus >= 400) {
content.setSchema(schemaResolver.resolve(ErrorResponse.class));
} else {
content.setSchema(schemaResolver.resolve(meta.getReturnParameter()));
}
}
}
}
private static final class OperationContextImpl extends AbstractContext implements OperationContext {
OperationContextImpl(OpenAPI openAPI, SchemaResolver schemaResolver, ExtensionFactory extensionFactory) {
super(openAPI, schemaResolver, extensionFactory);
}
}
private static final class OpenAPIChainImpl implements OpenAPIChain {
private final OpenAPIDefinitionResolver[] resolvers;
private final Function<OpenAPI, OpenAPI> fallback;
private int cursor;
OpenAPIChainImpl(OpenAPIDefinitionResolver[] resolvers, Function<OpenAPI, OpenAPI> fallback) {
this.resolvers = resolvers;
this.fallback = fallback;
}
@Override
public OpenAPI resolve(OpenAPI openAPI, ServiceMeta serviceMeta) {
if (cursor < resolvers.length) {
return resolvers[cursor++].resolve(openAPI, serviceMeta, this);
}
return fallback.apply(openAPI);
}
}
private static final class OperationChainImpl implements OperationChain {
private final OpenAPIDefinitionResolver[] resolvers;
private final Function<Operation, Operation> fallback;
private int cursor;
OperationChainImpl(OpenAPIDefinitionResolver[] resolvers, Function<Operation, Operation> fallback) {
this.resolvers = resolvers;
this.fallback = fallback;
}
@Override
public Operation resolve(Operation operation, MethodMeta methodMeta, OperationContext chain) {
if (cursor < resolvers.length) {
return resolvers[cursor++].resolve(operation, methodMeta, chain, this);
}
return fallback.apply(operation);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPINamingStrategy.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPINamingStrategy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI;
public interface OpenAPINamingStrategy extends OpenAPIExtension {
String generateOperationId(MethodMeta methodMeta, OpenAPI openAPI);
String resolveOperationIdConflict(int attempt, String operationId, MethodMeta methodMeta, OpenAPI openAPI);
String generateSchemaName(Class<?> clazz, OpenAPI openAPI);
String resolveSchemaNameConflict(int attempt, String schemaName, Class<?> clazz, OpenAPI openAPI);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/PrimitiveSchema.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/PrimitiveSchema.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Schema;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Schema.Type;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Primitive Schema
* Format: <a href="https://spec.openapis.org/registry/format/">Formats Registry</a>
*/
public enum PrimitiveSchema {
STRING(String.class, Type.STRING),
BOOLEAN(Boolean.class, Type.BOOLEAN),
BYTE(Byte.class, Type.STRING, "byte"),
BINARY(Byte.class, Type.STRING, "binary"),
URI(java.net.URI.class, Type.STRING, "uri"),
URL(java.net.URL.class, Type.STRING, "url"),
EMAIL(String.class, Type.STRING, "email"),
PASSWORD(String.class, Type.STRING, "password"),
UUID(java.util.UUID.class, Type.STRING, "uuid"),
INT(Integer.class, Type.INTEGER, "int32"),
LONG(Long.class, Type.INTEGER, "int64"),
FLOAT(Float.class, Type.NUMBER, "float"),
DOUBLE(Double.class, Type.NUMBER, "double"),
INTEGER(java.math.BigInteger.class, Type.INTEGER),
DECIMAL(java.math.BigDecimal.class, Type.NUMBER, "number"),
NUMBER(Number.class, Type.NUMBER),
IP_V4(java.net.Inet4Address.class, Type.STRING, "ipv4"),
IP_V6(java.net.Inet6Address.class, Type.STRING, "ipv6"),
DATE_TIME(java.util.Date.class, Type.STRING, "date-time"),
DATE(java.time.LocalDate.class, Type.STRING, "date"),
TIME(java.time.LocalTime.class, Type.STRING, "time"),
DURATION(java.time.Duration.class, Type.STRING, "duration"),
FILE(java.io.File.class, Type.STRING, "binary"),
OBJECT(Object.class, Type.OBJECT),
ARRAY(Object[].class, Type.ARRAY);
private static final Map<Object, PrimitiveSchema> TYPE_MAPPING = new ConcurrentHashMap<>();
static {
for (PrimitiveSchema schema : values()) {
TYPE_MAPPING.putIfAbsent(schema.keyClass, schema);
}
TYPE_MAPPING.put(boolean.class, BOOLEAN);
TYPE_MAPPING.put(byte.class, BYTE);
TYPE_MAPPING.put(char.class, STRING);
TYPE_MAPPING.put(Character.class, STRING);
TYPE_MAPPING.put(short.class, INT);
TYPE_MAPPING.put(Short.class, INT);
TYPE_MAPPING.put(int.class, INT);
TYPE_MAPPING.put(long.class, LONG);
TYPE_MAPPING.put(float.class, FLOAT);
TYPE_MAPPING.put(double.class, DOUBLE);
TYPE_MAPPING.put(byte[].class, BYTE);
TYPE_MAPPING.put(java.util.Calendar.class, DATE_TIME);
TYPE_MAPPING.put(java.sql.Date.class, DATE_TIME);
TYPE_MAPPING.put(java.time.Instant.class, DATE_TIME);
TYPE_MAPPING.put(java.time.LocalDateTime.class, DATE_TIME);
TYPE_MAPPING.put(java.time.ZonedDateTime.class, DATE_TIME);
TYPE_MAPPING.put(java.time.OffsetDateTime.class, DATE_TIME);
TYPE_MAPPING.put(java.time.OffsetTime.class, TIME);
TYPE_MAPPING.put(java.time.Period.class, DURATION);
TYPE_MAPPING.put("javax.xml.datatype.XMLGregorianCalendar", DATE_TIME);
TYPE_MAPPING.put("org.joda.time.LocalDateTime", DATE_TIME);
TYPE_MAPPING.put("org.joda.time.ReadableDateTime", DATE_TIME);
TYPE_MAPPING.put("org.joda.time.DateTime", DATE_TIME);
TYPE_MAPPING.put("org.joda.time.LocalTime", TIME);
TYPE_MAPPING.put(CharSequence.class, STRING);
TYPE_MAPPING.put(StringBuffer.class, STRING);
TYPE_MAPPING.put(StringBuilder.class, STRING);
TYPE_MAPPING.put(java.nio.charset.Charset.class, STRING);
TYPE_MAPPING.put(java.time.ZoneId.class, STRING);
TYPE_MAPPING.put(java.util.Currency.class, STRING);
TYPE_MAPPING.put(java.util.Locale.class, STRING);
TYPE_MAPPING.put(java.util.TimeZone.class, STRING);
TYPE_MAPPING.put(java.util.regex.Pattern.class, STRING);
TYPE_MAPPING.put(java.io.InputStream.class, BYTE);
TYPE_MAPPING.put(java.net.InetAddress.class, IP_V4);
TYPE_MAPPING.put("object", OBJECT);
}
private final Class<?> keyClass;
private final Type type;
private final String format;
PrimitiveSchema(Class<?> keyClass, Type type, String format) {
this.keyClass = keyClass;
this.type = type;
this.format = format;
}
PrimitiveSchema(Class<?> keyClass, Type type) {
this.keyClass = keyClass;
this.type = type;
format = null;
}
public Schema newSchema() {
return new Schema().setType(type).setFormat(format);
}
public static Schema newSchemaOf(Class<?> type) {
PrimitiveSchema schema = TYPE_MAPPING.get(type);
if (schema == null) {
schema = TYPE_MAPPING.get(type.getName());
}
return schema == null ? null : schema.newSchema();
}
public static boolean isPrimitive(Class<?> type) {
return TYPE_MAPPING.containsKey(type);
}
public static void addTypeMapping(Object key, PrimitiveSchema schema) {
TYPE_MAPPING.put(key, schema);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/DefinitionFilter.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/DefinitionFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.rest.OpenAPIRequest;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.ApiResponse;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Components;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Header;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.MediaType;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Node;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Operation;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Parameter;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.PathItem;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.RequestBody;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Schema;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.SecurityScheme;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Server;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Consumer;
import java.util.function.Supplier;
final class DefinitionFilter {
private final ExtensionFactory extensionFactory;
private final SchemaResolver schemaResolver;
public DefinitionFilter(FrameworkModel frameworkModel) {
extensionFactory = frameworkModel.getOrRegisterBean(ExtensionFactory.class);
schemaResolver = frameworkModel.getOrRegisterBean(SchemaResolver.class);
}
public OpenAPI filter(OpenAPI openAPI, OpenAPIRequest request) {
OpenAPIFilter[] filters = extensionFactory.getExtensions(OpenAPIFilter.class, request.getGroup());
Context context = new ContextImpl(openAPI, schemaResolver, extensionFactory, request);
if (filters.length > 0) {
for (OpenAPIFilter filter : filters) {
openAPI = filter.filterOpenAPI(openAPI, context);
if (openAPI == null) {
return null;
}
}
filterPaths(openAPI, filters, context);
filterComponents(openAPI, filters, context);
for (OpenAPIFilter filter : filters) {
openAPI = filter.filterOpenAPICompletion(openAPI, context);
if (openAPI == null) {
return null;
}
}
}
filterServer(openAPI, context);
return openAPI;
}
private static void filterServer(OpenAPI openAPI, Context context) {
List<Server> servers = openAPI.getServers();
if (servers == null || servers.size() != 1) {
return;
}
Server server = servers.get(0);
if (!Constants.DUBBO_DEFAULT_SERVER.equals(server.getDescription())) {
return;
}
HttpRequest httpRequest = context.getHttpRequest();
if (httpRequest == null) {
return;
}
String host = httpRequest.serverHost();
if (host == null) {
return;
}
String referer = httpRequest.header(Constants.REFERER);
if (referer != null && referer.contains(host)) {
servers.clear();
} else {
server.setUrl(httpRequest.scheme() + "://" + host);
}
}
private void filterPaths(OpenAPI openAPI, OpenAPIFilter[] filters, Context context) {
Map<String, PathItem> paths = openAPI.getPaths();
if (paths == null) {
return;
}
Iterator<Entry<String, PathItem>> it = paths.entrySet().iterator();
out:
while (it.hasNext()) {
Entry<String, PathItem> entry = it.next();
PathItem pathItem = entry.getValue();
PathItem initialPathItem = pathItem;
for (OpenAPIFilter filter : filters) {
pathItem = filter.filterPathItem(entry.getKey(), pathItem, context);
if (pathItem == null) {
it.remove();
continue out;
}
}
if (pathItem != initialPathItem) {
entry.setValue(pathItem);
}
filterOperation(pathItem, filters, context);
}
}
private void filterOperation(PathItem pathItem, OpenAPIFilter[] filters, Context context) {
Map<HttpMethods, Operation> operations = pathItem.getOperations();
if (operations == null) {
return;
}
Iterator<Entry<HttpMethods, Operation>> it = operations.entrySet().iterator();
out:
while (it.hasNext()) {
Entry<HttpMethods, Operation> entry = it.next();
HttpMethods httpMethod = entry.getKey();
Operation operation = entry.getValue();
Operation initialOperation = operation;
for (OpenAPIFilter filter : filters) {
operation = filter.filterOperation(httpMethod, operation, pathItem, context);
if (operation == null) {
it.remove();
continue out;
}
}
if (operation != initialOperation) {
entry.setValue(operation);
}
filterParameter(operation, filters, context);
filterRequestBody(operation, filters, context);
filterResponse(operation, filters, context);
}
}
private void filterParameter(Operation operation, OpenAPIFilter[] filters, Context context) {
List<Parameter> parameters = operation.getParameters();
if (parameters == null) {
return;
}
ListIterator<Parameter> it = parameters.listIterator();
out:
while (it.hasNext()) {
Parameter parameter = it.next();
Parameter initialParameter = parameter;
for (OpenAPIFilter filter : filters) {
parameter = filter.filterParameter(parameter, operation, context);
if (parameter == null) {
it.remove();
continue out;
}
}
if (parameter != initialParameter) {
it.set(parameter);
}
filterContext(parameter.getContents(), filters, context);
}
}
private void filterRequestBody(Operation operation, OpenAPIFilter[] filters, Context context) {
RequestBody body = operation.getRequestBody();
if (body == null) {
return;
}
RequestBody initialRequestBody = body;
for (OpenAPIFilter filter : filters) {
body = filter.filterRequestBody(body, operation, context);
if (body == null) {
operation.setRequestBody(null);
return;
}
}
if (body != initialRequestBody) {
operation.setRequestBody(body);
}
filterContext(body.getContents(), filters, context);
}
private void filterResponse(Operation operation, OpenAPIFilter[] filters, Context context) {
Map<String, ApiResponse> responses = operation.getResponses();
if (responses == null) {
return;
}
Iterator<Entry<String, ApiResponse>> it = responses.entrySet().iterator();
out:
while (it.hasNext()) {
Entry<String, ApiResponse> entry = it.next();
ApiResponse response = entry.getValue();
ApiResponse initialApiResponse = response;
for (OpenAPIFilter filter : filters) {
response = filter.filterResponse(response, operation, context);
if (response == null) {
it.remove();
continue out;
}
}
if (response != initialApiResponse) {
entry.setValue(response);
}
filterHeader(response, operation, filters, context);
filterContext(response.getContents(), filters, context);
}
}
private void filterHeader(ApiResponse response, Operation operation, OpenAPIFilter[] filters, Context context) {
Map<String, Header> headers = response.getHeaders();
if (headers == null) {
return;
}
Iterator<Entry<String, Header>> it = headers.entrySet().iterator();
out:
while (it.hasNext()) {
Entry<String, Header> entry = it.next();
Header header = entry.getValue();
Header initialHeader = header;
for (OpenAPIFilter filter : filters) {
header = filter.filterHeader(header, response, operation, context);
if (header == null) {
it.remove();
continue out;
}
}
if (header != initialHeader) {
entry.setValue(header);
}
filterSchema(header::getSchema, header::setSchema, header, filters, context);
Map<String, MediaType> contents = header.getContents();
if (contents == null) {
continue;
}
for (MediaType content : contents.values()) {
filterSchema(content::getSchema, content::setSchema, content, filters, context);
}
}
}
private boolean filterContext(Map<String, MediaType> contents, OpenAPIFilter[] filters, Context context) {
if (contents == null) {
return true;
}
for (MediaType content : contents.values()) {
filterSchema(content::getSchema, content::setSchema, content, filters, context);
}
return false;
}
private void filterComponents(OpenAPI openAPI, OpenAPIFilter[] filters, Context context) {
Components components = openAPI.getComponents();
if (components == null) {
return;
}
filterSchemas(components, filters, context);
filterSecuritySchemes(components, filters, context);
}
private void filterSchemas(Components components, OpenAPIFilter[] filters, Context context) {
if (components == null) {
return;
}
Map<String, Schema> schemas = components.getSchemas();
if (schemas == null) {
return;
}
for (Entry<String, Schema> entry : schemas.entrySet()) {
filterSchema(entry::getValue, entry::setValue, components, filters, context);
}
}
private void filterSchema(
Supplier<Schema> getter, Consumer<Schema> setter, Node<?> owner, OpenAPIFilter[] filters, Context context) {
Schema schema = getter.get();
if (schema == null) {
return;
}
Schema initialSchema = schema;
for (OpenAPIFilter filter : filters) {
schema = filter.filterSchema(schema, owner, context);
if (schema == null) {
setter.accept(null);
return;
}
}
if (schema != initialSchema) {
setter.accept(schema);
}
filterSchema(schema::getItems, schema::setItems, schema, filters, context);
Map<String, Schema> properties = schema.getProperties();
if (properties != null) {
out:
for (Entry<String, Schema> entry : properties.entrySet()) {
String name = entry.getKey();
Schema valueSchema = entry.getValue();
for (OpenAPIFilter filter : filters) {
valueSchema = filter.filterSchemaProperty(name, valueSchema, schema, context);
if (valueSchema == null) {
entry.setValue(null);
continue out;
}
}
filterSchema(entry::getValue, entry::setValue, schema, filters, context);
}
}
filterSchema(
schema::getAdditionalPropertiesSchema, schema::setAdditionalPropertiesSchema, schema, filters, context);
List<Schema> allOf = schema.getAllOf();
if (allOf != null) {
ListIterator<Schema> it = allOf.listIterator();
while (it.hasNext()) {
filterSchema(it::next, it::set, schema, filters, context);
}
}
List<Schema> oneOf = schema.getOneOf();
if (oneOf != null) {
ListIterator<Schema> it = oneOf.listIterator();
while (it.hasNext()) {
filterSchema(it::next, it::set, schema, filters, context);
}
}
List<Schema> anyOf = schema.getAnyOf();
if (anyOf != null) {
ListIterator<Schema> it = anyOf.listIterator();
while (it.hasNext()) {
filterSchema(it::next, it::set, schema, filters, context);
}
}
filterSchema(schema::getNot, schema::setNot, schema, filters, context);
}
private void filterSecuritySchemes(Components components, OpenAPIFilter[] filters, Context context) {
if (components == null) {
return;
}
Map<String, SecurityScheme> securitySchemes = components.getSecuritySchemes();
if (securitySchemes == null) {
return;
}
Iterator<Entry<String, SecurityScheme>> it = securitySchemes.entrySet().iterator();
out:
while (it.hasNext()) {
Entry<String, SecurityScheme> entry = it.next();
SecurityScheme securityScheme = entry.getValue();
SecurityScheme initialSecurityScheme = securityScheme;
for (OpenAPIFilter filter : filters) {
securityScheme = filter.filterSecurityScheme(securityScheme, context);
if (securityScheme == null) {
it.remove();
continue out;
}
}
if (securityScheme != initialSecurityScheme) {
entry.setValue(securityScheme);
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/DefaultOpenAPIService.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/DefaultOpenAPIService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.common.logger.FluentLogger;
import org.apache.dubbo.common.logger.Level;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.LRUCache;
import org.apache.dubbo.common.utils.Pair;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.remoting.http12.HttpResult;
import org.apache.dubbo.remoting.http12.exception.HttpResultPayloadException;
import org.apache.dubbo.remoting.http12.message.MediaType;
import org.apache.dubbo.remoting.http12.rest.OpenAPIRequest;
import org.apache.dubbo.remoting.http12.rest.OpenAPIService;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.ExceptionUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants;
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.mapping.Registration;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMappingRegistry;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.HandlerMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ServiceMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI;
import org.apache.dubbo.rpc.protocol.tri.rest.util.PathUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils;
import java.lang.ref.SoftReference;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class DefaultOpenAPIService implements OpenAPIRequestHandler, OpenAPIService {
private static final FluentLogger LOG = FluentLogger.of(DefaultOpenAPIService.class);
private static final String API_DOCS = "/api-docs";
private final LRUCache<String, SoftReference<String>> cache = new LRUCache<>(64);
private final FrameworkModel frameworkModel;
private final ConfigFactory configFactory;
private final ExtensionFactory extensionFactory;
private final DefinitionResolver definitionResolver;
private final DefinitionMerger definitionMerger;
private final DefinitionFilter definitionFilter;
private final DefinitionEncoder definitionEncoder;
private final RadixTree<OpenAPIRequestHandler> tree;
private volatile List<OpenAPI> openAPIs;
private boolean exported;
private ScheduledFuture<?> exportFuture;
public DefaultOpenAPIService(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
configFactory = frameworkModel.getOrRegisterBean(ConfigFactory.class);
extensionFactory = frameworkModel.getOrRegisterBean(ExtensionFactory.class);
definitionResolver = new DefinitionResolver(frameworkModel);
definitionMerger = new DefinitionMerger(frameworkModel);
definitionFilter = new DefinitionFilter(frameworkModel);
definitionEncoder = new DefinitionEncoder(frameworkModel);
tree = initRequestHandlers();
}
private RadixTree<OpenAPIRequestHandler> initRequestHandlers() {
RadixTree<OpenAPIRequestHandler> tree = new RadixTree<>(false);
for (OpenAPIRequestHandler handler : extensionFactory.getExtensions(OpenAPIRequestHandler.class)) {
for (String path : handler.getPaths()) {
tree.addPath(path, handler);
}
}
tree.addPath(this, API_DOCS, API_DOCS + "/{group}");
return tree;
}
@Override
public HttpResult<?> handle(String path, HttpRequest httpRequest, HttpResponse httpResponse) {
OpenAPIRequest request = httpRequest.attribute(OpenAPIRequest.class.getName());
String group = RequestUtils.getPathVariable(httpRequest, "group");
if (group != null) {
request.setGroup(StringUtils.substringBeforeLast(group, '.'));
}
return HttpResult.builder()
.contentType(MediaType.APPLICATION + '/' + request.getFormat())
.body(handleDocument(request, httpRequest).getBytes(StandardCharsets.UTF_8))
.build();
}
@Override
public Collection<String> getOpenAPIGroups() {
Set<String> groups = new LinkedHashSet<>();
groups.add(Constants.DEFAULT_GROUP);
for (OpenAPI openAPI : getOpenAPIs()) {
groups.add(openAPI.getGroup());
openAPI.walkOperations(operation -> {
String group = operation.getGroup();
if (StringUtils.isNotEmpty(group)) {
groups.add(group);
}
});
}
return groups;
}
public OpenAPI getOpenAPI(OpenAPIRequest request) {
return definitionFilter.filter(definitionMerger.merge(getOpenAPIs(), request), request);
}
private List<OpenAPI> getOpenAPIs() {
if (openAPIs == null) {
synchronized (this) {
if (openAPIs == null) {
openAPIs = resolveOpenAPIs();
}
}
}
return openAPIs;
}
private List<OpenAPI> resolveOpenAPIs() {
RequestMappingRegistry registry = frameworkModel.getBean(RequestMappingRegistry.class);
if (registry == null) {
return Collections.emptyList();
}
Map<Key, Map<Method, List<Registration>>> byClassMap = new HashMap<>();
for (Registration registration : registry.getRegistrations()) {
HandlerMeta meta = registration.getMeta();
byClassMap
.computeIfAbsent(new Key(meta.getService()), k -> new IdentityHashMap<>())
.computeIfAbsent(meta.getMethod().getMethod(), k -> new ArrayList<>(1))
.add(registration);
}
List<OpenAPI> openAPIs = new ArrayList<>(byClassMap.size());
for (Map.Entry<Key, Map<Method, List<Registration>>> entry : byClassMap.entrySet()) {
OpenAPI openAPI = definitionResolver.resolve(
entry.getKey().serviceMeta, entry.getValue().values());
if (openAPI != null) {
openAPIs.add(openAPI);
}
}
openAPIs.sort(Comparator.comparingInt(OpenAPI::getPriority));
return openAPIs;
}
@Override
public String getDocument(OpenAPIRequest request) {
String path = null;
try {
request = Helper.formatRequest(request);
HttpRequest httpRequest = RpcContext.getServiceContext().getRequest(HttpRequest.class);
if (!RequestUtils.isRestRequest(httpRequest)) {
return handleDocument(request, null);
}
path = RequestUtils.getPathVariable(httpRequest, "path");
if (StringUtils.isEmpty(path)) {
String url = PathUtils.join(httpRequest.path(), "swagger-ui/index.html");
throw HttpResult.found(url).toPayload();
}
path = '/' + path;
List<Match<OpenAPIRequestHandler>> matches = tree.matchRelaxed(path);
if (matches.isEmpty()) {
throw HttpResult.notFound().toPayload();
}
Collections.sort(matches);
Match<OpenAPIRequestHandler> match = matches.get(0);
HttpResponse httpResponse = RpcContext.getServiceContext().getResponse(HttpResponse.class);
if (request.getFormat() == null) {
request.setFormat(Helper.parseFormat(httpResponse.contentType()));
}
httpRequest.setAttribute(OpenAPIRequest.class.getName(), request);
httpRequest.setAttribute(RestConstants.URI_TEMPLATE_VARIABLES_ATTRIBUTE, match.getVariableMap());
throw match.getValue().handle(path, httpRequest, httpResponse).toPayload();
} catch (HttpResultPayloadException e) {
throw e;
} catch (Throwable t) {
Level level = ExceptionUtils.resolveLogLevel(ExceptionUtils.unwrap(t));
LOG.log(level, "Failed to processing OpenAPI request {} for path: '{}'", request, path, t);
throw t;
}
}
private String handleDocument(OpenAPIRequest request, HttpRequest httpRequest) {
if (Boolean.FALSE.equals(configFactory.getGlobalConfig().getCache())) {
return definitionEncoder.encode(getOpenAPI(request), request);
}
StringBuilder sb = new StringBuilder();
if (httpRequest != null) {
String host = httpRequest.serverHost();
if (host != null) {
String referer = httpRequest.header(Constants.REFERER);
sb.append(referer != null && referer.contains(host) ? '/' : host);
}
}
sb.append('|').append(request.toString());
String cacheKey = sb.toString();
SoftReference<String> ref = cache.get(cacheKey);
if (ref != null) {
String value = ref.get();
if (value != null) {
return value;
}
}
String value = definitionEncoder.encode(getOpenAPI(request), request);
cache.put(cacheKey, new SoftReference<>(value));
return value;
}
@Override
public void refresh() {
LOG.debug("Refreshing OpenAPI documents");
openAPIs = null;
cache.clear();
if (exported) {
export();
}
}
@Override
public void export() {
if (!extensionFactory.hasExtensions(OpenAPIDocumentPublisher.class)) {
return;
}
try {
if (exportFuture != null) {
exportFuture.cancel(false);
}
exportFuture = frameworkModel
.getBean(FrameworkExecutorRepository.class)
.getMetadataRetryExecutor()
.schedule(this::doExport, 30, TimeUnit.SECONDS);
exported = true;
} catch (Throwable t) {
LOG.internalWarn("Failed to export OpenAPI documents", t);
}
}
private void doExport() {
for (OpenAPIDocumentPublisher publisher : extensionFactory.getExtensions(OpenAPIDocumentPublisher.class)) {
try {
publisher.publish(request -> {
OpenAPI openAPI = getOpenAPI(request);
String document = definitionEncoder.encode(openAPI, request);
return Pair.of(openAPI, document);
});
} catch (Throwable t) {
LOG.internalWarn("Failed to publish OpenAPI document by {}", publisher, t);
}
}
exportFuture = null;
}
private static final class Key {
private final ServiceMeta serviceMeta;
public Key(ServiceMeta serviceMeta) {
this.serviceMeta = serviceMeta;
}
@SuppressWarnings({"EqualsWhichDoesntCheckParameterClass", "EqualsDoesntCheckParameterClass"})
@Override
public boolean equals(Object obj) {
return serviceMeta.getType() == ((Key) obj).serviceMeta.getType();
}
@Override
public int hashCode() {
return serviceMeta.getType().hashCode();
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPIRequestHandler.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPIRequestHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.remoting.http12.HttpResult;
public interface OpenAPIRequestHandler extends OpenAPIExtension {
default String[] getPaths() {
return StringUtils.EMPTY_STRING_ARRAY;
}
HttpResult<?> handle(String path, 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-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPIFilter.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPIFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.ApiResponse;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Header;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Node;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Operation;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Parameter;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.PathItem;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.RequestBody;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Schema;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.SecurityScheme;
public interface OpenAPIFilter extends OpenAPIExtension {
default OpenAPI filterOpenAPI(OpenAPI openAPI, Context context) {
return openAPI;
}
default PathItem filterPathItem(String key, PathItem pathItem, Context context) {
return pathItem;
}
default Operation filterOperation(HttpMethods key, Operation operation, PathItem pathItem, Context context) {
return operation;
}
default Parameter filterParameter(Parameter parameter, Operation operation, Context context) {
return parameter;
}
default RequestBody filterRequestBody(RequestBody body, Operation operation, Context context) {
return body;
}
default ApiResponse filterResponse(ApiResponse response, Operation operation, Context context) {
return response;
}
default Header filterHeader(Header header, ApiResponse response, Operation operation, Context context) {
return header;
}
default Schema filterSchema(Schema schema, Node<?> node, Context context) {
return schema;
}
default Schema filterSchemaProperty(String name, Schema schema, Schema owner, Context context) {
return schema;
}
default SecurityScheme filterSecurityScheme(SecurityScheme securityScheme, Context context) {
return securityScheme;
}
default OpenAPI filterOpenAPICompletion(OpenAPI openAPI, Context context) {
return openAPI;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPIDocumentPublisher.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPIDocumentPublisher.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.common.utils.Pair;
import org.apache.dubbo.remoting.http12.rest.OpenAPIRequest;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI;
import java.util.function.Function;
public interface OpenAPIDocumentPublisher extends OpenAPIExtension {
void publish(Function<OpenAPIRequest, Pair<OpenAPI, String>> fn);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/ConfigFactory.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/ConfigFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.common.config.Configuration;
import org.apache.dubbo.common.config.Environment;
import org.apache.dubbo.common.utils.Pair;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.nested.OpenAPIConfig;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import static org.apache.dubbo.rpc.Constants.H2_SETTINGS_OPENAPI_PREFIX;
public final class ConfigFactory {
private static Map<String, Method> CONFIG_METHODS;
private final FrameworkModel frameworkModel;
private volatile Map<String, OpenAPIConfig> configMap;
public ConfigFactory(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
private static Environment getEnvironment(FrameworkModel frameworkModel) {
return frameworkModel.defaultApplication().modelEnvironment();
}
public OpenAPIConfig getConfig(String group) {
return getConfigMap().get(group);
}
public OpenAPIConfig getGlobalConfig() {
return getConfigMap().get(Constants.GLOBAL_GROUP);
}
private Map<String, OpenAPIConfig> getConfigMap() {
if (configMap == null) {
synchronized (this) {
if (configMap == null) {
configMap = readConfigMap();
}
}
}
return configMap;
}
private Map<String, OpenAPIConfig> readConfigMap() {
Map<String, OpenAPIConfig> map = new HashMap<>();
Environment environment = getEnvironment(frameworkModel);
Configuration configuration = environment.getConfiguration();
List<Map<String, String>> configMaps = environment.getConfigurationMaps();
Set<String> allKeys = new HashSet<>();
for (Map<String, String> configMap : configMaps) {
for (String key : configMap.keySet()) {
if (key.startsWith(H2_SETTINGS_OPENAPI_PREFIX)) {
allKeys.add(key);
}
}
}
int len = H2_SETTINGS_OPENAPI_PREFIX.length();
Map<Pair<String, String>, TreeMap<Integer, String>> valuesMap = new HashMap<>();
for (String fullKey : allKeys) {
if (fullKey.length() > len) {
char c = fullKey.charAt(len);
String group, key;
if (c == '.') {
group = StringUtils.EMPTY_STRING;
key = fullKey.substring(len + 1);
} else if (c == 's') {
int end = fullKey.indexOf('.', len + 1);
group = fullKey.substring(len + 1, end);
key = fullKey.substring(end + 1);
} else {
continue;
}
int brkStart = key.lastIndexOf('[');
if (brkStart > 0) {
try {
String value = configuration.getString(fullKey);
if (StringUtils.isEmpty(value)) {
continue;
}
int index = Integer.parseInt(key.substring(brkStart + 1, key.length() - 1));
valuesMap
.computeIfAbsent(Pair.of(group, key.substring(0, brkStart)), k -> new TreeMap<>())
.put(index, value);
} catch (NumberFormatException ignored) {
}
continue;
}
applyConfigValue(map, group, key, configuration.getString(fullKey));
}
}
for (Map.Entry<Pair<String, String>, TreeMap<Integer, String>> entry : valuesMap.entrySet()) {
Pair<String, String> pair = entry.getKey();
String value = StringUtils.join(entry.getValue().values(), ",");
applyConfigValue(map, pair.getKey(), pair.getValue(), value);
}
map.computeIfAbsent(Constants.GLOBAL_GROUP, k -> new OpenAPIConfig());
return map;
}
private static void applyConfigValue(Map<String, OpenAPIConfig> map, String group, String key, String value) {
if (value == null || value.isEmpty()) {
return;
}
OpenAPIConfig config = map.computeIfAbsent(group, k -> new OpenAPIConfig());
int index = key.indexOf("settings.");
if (index == 0) {
Map<String, String> settings = config.getSettings();
if (settings == null) {
config.setSettings(settings = new HashMap<>());
}
settings.put(key.substring(9), value);
return;
}
Map<String, Method> configMethods = CONFIG_METHODS;
if (configMethods == null) {
configMethods = new HashMap<>();
for (Method method : OpenAPIConfig.class.getMethods()) {
String name = toConfigName(method);
if (name != null) {
configMethods.put(name, method);
}
}
CONFIG_METHODS = configMethods;
}
Method method = configMethods.get(key);
if (method == null) {
return;
}
Class<?> valueType = method.getParameterTypes()[0];
try {
if (valueType == String.class) {
method.invoke(config, value);
} else if (valueType == Boolean.class) {
method.invoke(config, StringUtils.toBoolean(value, false));
} else if (valueType.isArray()) {
method.invoke(config, new Object[] {StringUtils.tokenize(value)});
}
} catch (Throwable ignored) {
}
}
private static String toConfigName(Method method) {
if (method.getParameterCount() != 1) {
return null;
}
String name = method.getName();
if (!name.startsWith("set")) {
return null;
}
int len = name.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 3; i < len; i++) {
char c = name.charAt(i);
if (Character.isUpperCase(c)) {
if (i > 3) {
sb.append('-');
}
sb.append(Character.toLowerCase(c));
} else {
sb.append(c);
}
}
return sb.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPIDefinitionResolver.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPIDefinitionResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.remoting.http12.HttpMethods;
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.openapi.model.OpenAPI;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Operation;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.PathItem;
import java.util.Collection;
public interface OpenAPIDefinitionResolver extends OpenAPIExtension {
OpenAPI resolve(OpenAPI openAPI, ServiceMeta serviceMeta, OpenAPIChain chain);
Collection<HttpMethods> resolve(PathItem pathItem, MethodMeta methodMeta, OperationContext context);
Operation resolve(Operation operation, MethodMeta methodMeta, OperationContext context, OperationChain chain);
interface OpenAPIChain {
OpenAPI resolve(OpenAPI openAPI, ServiceMeta serviceMeta);
}
interface OperationChain {
Operation resolve(Operation operation, MethodMeta methodMeta, OperationContext context);
}
interface OperationContext {
String getGroup();
OpenAPI getOpenAPI();
SchemaResolver getSchemaResolver();
ExtensionFactory getExtensionFactory();
<T> T getAttribute(String name);
<T> T removeAttribute(String name);
void setAttribute(String name, Object value);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/SchemaResolver.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/SchemaResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
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.mapping.meta.AnnotationMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta.PropertyMeta;
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.openapi.OpenAPISchemaResolver.SchemaChain;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.OpenAPISchemaResolver.SchemaContext;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Schema;
import org.apache.dubbo.rpc.protocol.tri.rest.support.basic.Annotations;
import org.apache.dubbo.rpc.protocol.tri.rest.util.RestToolKit;
import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import static org.apache.dubbo.rpc.protocol.tri.rest.openapi.PrimitiveSchema.ARRAY;
import static org.apache.dubbo.rpc.protocol.tri.rest.openapi.PrimitiveSchema.OBJECT;
public final class SchemaResolver {
private final ConfigFactory configFactory;
private final OpenAPISchemaResolver[] resolvers;
private final OpenAPISchemaPredicate[] predicates;
private final Map<Class<?>, Schema> schemaMap = CollectionUtils.newConcurrentHashMap();
private volatile RadixTree<Boolean> classFilter;
public SchemaResolver(FrameworkModel frameworkModel) {
configFactory = frameworkModel.getOrRegisterBean(ConfigFactory.class);
ExtensionFactory extensionFactory = frameworkModel.getOrRegisterBean(ExtensionFactory.class);
resolvers = extensionFactory.getExtensions(OpenAPISchemaResolver.class);
predicates = extensionFactory.getExtensions(OpenAPISchemaPredicate.class);
}
public Schema resolve(Type type) {
return resolve(new TypeParameterMeta(type));
}
public Schema resolve(ParameterMeta parameter) {
return new SchemaChainImpl(resolvers, this::fallbackResolve).resolve(parameter, new SchemaContextImpl());
}
public Schema resolve(List<ParameterMeta> parameters) {
Schema schema = OBJECT.newSchema();
for (ParameterMeta parameter : parameters) {
String name = parameter.getName();
if (name == null) {
return ARRAY.newSchema();
}
schema.addProperty(name, resolve(parameter));
}
return schema;
}
private Schema fallbackResolve(ParameterMeta parameter) {
return doResolveType(parameter.getActualGenericType(), parameter);
}
private Schema doResolveNestedType(Type nestedType, ParameterMeta parameter) {
return doResolveType(nestedType, new TypeParameterMeta(parameter.getToolKit(), nestedType));
}
private Schema doResolveType(Type type, ParameterMeta parameter) {
if (type instanceof Class) {
return doResolveClass((Class<?>) type, parameter);
}
if (type instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) type;
Type rawType = pType.getRawType();
if (rawType instanceof Class) {
Class<?> clazz = (Class<?>) rawType;
Type[] argTypes = pType.getActualTypeArguments();
if (Iterable.class.isAssignableFrom(clazz)) {
Type itemType = TypeUtils.getActualGenericType(argTypes[0]);
return ARRAY.newSchema()
.addExtension(Constants.X_JAVA_CLASS, TypeUtils.toTypeString(type))
.setItems(doResolveNestedType(itemType, parameter));
}
if (Map.class.isAssignableFrom(clazz)) {
return OBJECT.newSchema()
.addExtension(Constants.X_JAVA_CLASS, TypeUtils.toTypeString(type))
.setAdditionalPropertiesSchema(doResolveNestedType(argTypes[1], parameter));
}
return doResolveClass(clazz, parameter);
}
}
if (type instanceof TypeVariable) {
return doResolveNestedType(((TypeVariable<?>) type).getBounds()[0], parameter);
}
if (type instanceof WildcardType) {
return doResolveNestedType(((WildcardType) type).getUpperBounds()[0], parameter);
}
if (type instanceof GenericArrayType) {
return ARRAY.newSchema()
.addExtension(Constants.X_JAVA_CLASS, TypeUtils.toTypeString(type))
.setItems(doResolveNestedType(((GenericArrayType) type).getGenericComponentType(), parameter));
}
return OBJECT.newSchema();
}
private Schema doResolveClass(Class<?> clazz, ParameterMeta parameter) {
Schema schema = PrimitiveSchema.newSchemaOf(clazz);
if (schema != null) {
return schema;
}
if (clazz.isArray()) {
schema = ARRAY.newSchema();
if (!PrimitiveSchema.isPrimitive(clazz.getComponentType())) {
schema.addExtension(Constants.X_JAVA_CLASS, TypeUtils.toTypeString(clazz));
}
return schema.setItems(doResolveNestedType(clazz.getComponentType(), parameter));
}
Schema existingSchema = schemaMap.get(clazz);
if (existingSchema != null) {
return new Schema().setTargetSchema(existingSchema);
}
if (isClassExcluded(clazz)) {
schema = OBJECT.newSchema().addExtension(Constants.X_JAVA_CLASS, TypeUtils.toTypeString(clazz));
schemaMap.put(clazz, schema);
return schema;
}
TypeParameterMeta typeParameter = new TypeParameterMeta(clazz);
for (OpenAPISchemaPredicate predicate : predicates) {
Boolean accepted = predicate.acceptClass(clazz, typeParameter);
if (accepted == null) {
continue;
}
if (accepted) {
break;
} else {
schema = OBJECT.newSchema().addExtension(Constants.X_JAVA_CLASS, TypeUtils.toTypeString(clazz));
schemaMap.put(clazz, schema);
return schema;
}
}
if (clazz.isEnum()) {
schema = PrimitiveSchema.STRING.newSchema().setJavaType(clazz);
for (Object value : clazz.getEnumConstants()) {
schema.addEnumeration(value);
}
schemaMap.put(clazz, schema);
return schema.clone();
}
Boolean flatten = configFactory.getGlobalConfig().getSchemaFlatten();
if (flatten == null) {
AnnotationMeta<?> anno = typeParameter.getAnnotation(Annotations.Schema);
flatten = anno != null && anno.getBoolean("flatten");
}
return new Schema().setTargetSchema(doResolveBeanClass(parameter.getToolKit(), clazz, flatten));
}
private Schema doResolveBeanClass(RestToolKit toolKit, Class<?> clazz, boolean flatten) {
Schema beanSchema = OBJECT.newSchema().setJavaType(clazz);
schemaMap.put(clazz, beanSchema);
BeanMeta beanMeta = new BeanMeta(toolKit, clazz, flatten);
out:
for (PropertyMeta property : beanMeta.getProperties()) {
boolean fallback = true;
for (OpenAPISchemaPredicate predicate : predicates) {
Boolean accepted = predicate.acceptProperty(beanMeta, property);
if (accepted == null) {
continue;
}
if (accepted) {
fallback = false;
break;
} else {
continue out;
}
}
if (fallback) {
int visibility = property.getVisibility();
if ((visibility & 0b001) == 0 || (visibility & 0b110) == 0) {
continue;
}
}
beanSchema.addProperty(property.getName(), resolve(property));
}
if (flatten) {
return beanSchema;
}
Class<?> superClass = clazz.getSuperclass();
if (superClass == null || superClass == Object.class || TypeUtils.isSystemType(superClass)) {
return beanSchema;
}
return beanSchema.addAllOf(resolve(superClass));
}
private boolean isClassExcluded(Class<?> clazz) {
RadixTree<Boolean> classFilter = this.classFilter;
if (classFilter == null) {
synchronized (this) {
classFilter = this.classFilter;
if (classFilter == null) {
classFilter = new RadixTree<>('.');
for (String prefix : TypeUtils.getSystemPrefixes()) {
addPath(classFilter, prefix);
}
String[] excludes = configFactory.getGlobalConfig().getSchemaClassExcludes();
if (excludes != null) {
for (String exclude : excludes) {
addPath(classFilter, exclude);
}
}
this.classFilter = classFilter;
}
}
}
List<Match<Boolean>> matches = classFilter.match('.' + clazz.getName());
int size = matches.size();
if (size == 0) {
return false;
} else if (size > 1) {
Collections.sort(matches);
}
return matches.get(0).getValue();
}
public static void addPath(RadixTree<Boolean> tree, String path) {
if (path == null) {
return;
}
int size = path.length();
if (size == 0) {
return;
}
boolean value = true;
if (path.charAt(0) == '!') {
path = path.substring(1);
size--;
value = false;
}
if (path.charAt(size - 1) == '.') {
path += "**";
}
tree.addPath(path, value);
}
private static final class SchemaChainImpl implements SchemaChain {
private final OpenAPISchemaResolver[] resolvers;
private final Function<ParameterMeta, Schema> fallback;
private int cursor;
SchemaChainImpl(OpenAPISchemaResolver[] resolvers, Function<ParameterMeta, Schema> fallback) {
this.resolvers = resolvers;
this.fallback = fallback;
}
@Override
public Schema resolve(ParameterMeta parameter, SchemaContext context) {
if (cursor < resolvers.length) {
return resolvers[cursor++].resolve(parameter, context, this);
}
return fallback.apply(parameter);
}
}
private final class SchemaContextImpl implements SchemaContext {
@Override
public void defineSchema(Class<?> type, Schema schema) {
schemaMap.putIfAbsent(type, schema);
}
@Override
public Schema resolve(ParameterMeta parameter) {
return SchemaResolver.this.resolve(parameter);
}
@Override
public Schema resolve(Type type) {
return SchemaResolver.this.resolve(type);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/DefinitionEncoder.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/DefinitionEncoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.remoting.http12.exception.UnsupportedMediaTypeException;
import org.apache.dubbo.remoting.http12.message.MediaType;
import org.apache.dubbo.remoting.http12.message.codec.YamlCodec;
import org.apache.dubbo.remoting.http12.rest.OpenAPIRequest;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
final class DefinitionEncoder {
private final ExtensionFactory extensionFactory;
private final SchemaResolver schemaResolver;
private ProtoEncoder protoEncoder;
DefinitionEncoder(FrameworkModel frameworkModel) {
extensionFactory = frameworkModel.getOrRegisterBean(ExtensionFactory.class);
schemaResolver = frameworkModel.getOrRegisterBean(SchemaResolver.class);
}
public String encode(OpenAPI openAPI, OpenAPIRequest request) {
if (openAPI == null) {
openAPI = new OpenAPI();
}
Map<String, Object> root = new LinkedHashMap<>();
ContextImpl context = new ContextImpl(openAPI, schemaResolver, extensionFactory, request);
openAPI.writeTo(root, context);
String format = request.getFormat();
format = format == null ? MediaType.JSON : format.toLowerCase();
switch (format) {
case MediaType.JSON:
if (Boolean.TRUE.equals(request.getPretty())) {
return JsonUtils.toPrettyJson(root);
}
return JsonUtils.toJson(root);
case "yml":
case "yaml":
ByteArrayOutputStream os = new ByteArrayOutputStream(4096);
YamlCodec.INSTANCE.encode(os, root, StandardCharsets.UTF_8);
return new String(os.toByteArray(), StandardCharsets.UTF_8);
case "proto":
if (protoEncoder == null) {
protoEncoder = new ProtoEncoder();
}
return protoEncoder.encode(openAPI);
default:
throw new UnsupportedMediaTypeException("text/" + format);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/AbstractContext.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/AbstractContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI;
import java.util.HashMap;
import java.util.Map;
public abstract class AbstractContext {
private final OpenAPI openAPI;
private final SchemaResolver schemaResolver;
private final ExtensionFactory extensionFactory;
private Map<String, Object> attributes;
AbstractContext(OpenAPI openAPI, SchemaResolver schemaResolver, ExtensionFactory extensionFactory) {
this.openAPI = openAPI;
this.schemaResolver = schemaResolver;
this.extensionFactory = extensionFactory;
}
public final String getGroup() {
return openAPI.getGroup();
}
public final OpenAPI getOpenAPI() {
return openAPI;
}
public final SchemaResolver getSchemaResolver() {
return schemaResolver;
}
public final ExtensionFactory getExtensionFactory() {
return extensionFactory;
}
@SuppressWarnings("unchecked")
public final <T> T getAttribute(String name) {
return attributes == null ? null : (T) attributes.get(name);
}
@SuppressWarnings("unchecked")
public final <T> T removeAttribute(String name) {
return attributes == null ? null : (T) attributes.remove(name);
}
public final void setAttribute(String name, Object value) {
if (attributes == null) {
attributes = new HashMap<>();
}
attributes.put(name, value);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPISchemaResolver.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPISchemaResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Schema;
import java.lang.reflect.Type;
public interface OpenAPISchemaResolver extends OpenAPIExtension {
Schema resolve(ParameterMeta parameter, SchemaContext context, SchemaChain chain);
interface SchemaChain {
Schema resolve(ParameterMeta parameter, SchemaContext context);
}
interface SchemaContext {
void defineSchema(Class<?> type, Schema schema);
Schema resolve(ParameterMeta parameter);
Schema resolve(Type type);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/Constants.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/Constants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.openapi;
public final class Constants {
public static final String VERSION_30 = "3.0.1";
public static final String VERSION_31 = "3.1.0";
public static final String ALL_GROUP = "all";
public static final String DEFAULT_GROUP = "default";
public static final String GLOBAL_GROUP = "";
public static final String X_API_GROUP = "x-api-group";
public static final String X_API_VERSION = "x-api-version";
public static final String X_JAVA_CLASS = "x-java-class";
public static final String X_JAVA_METHOD = "x-java-method";
public static final String X_JAVA_METHOD_DESCRIPTOR = "x-java-method-descriptor";
public static final String DUBBO_DEFAULT_SERVER = "Dubbo Default Server";
public static final String REFERER = "referer";
private Constants() {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/ProtoEncoder.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/ProtoEncoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI;
public final class ProtoEncoder {
public String encode(OpenAPI openAPI) {
return "";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/Helper.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/Helper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.openapi;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.http12.rest.OpenAPIRequest;
import org.apache.dubbo.remoting.http12.rest.ParamType;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Parameter.In;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Server;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.dubbo.remoting.http12.HttpMethods.DELETE;
import static org.apache.dubbo.remoting.http12.HttpMethods.GET;
import static org.apache.dubbo.remoting.http12.HttpMethods.PATCH;
import static org.apache.dubbo.remoting.http12.HttpMethods.POST;
import static org.apache.dubbo.remoting.http12.HttpMethods.PUT;
public final class Helper {
private static final String[][] VERBS_TABLE = {
{
GET.name(),
"get",
"load",
"fetch",
"read",
"retrieve",
"obtain",
"list",
"find",
"query",
"search",
"is",
"are",
"was",
"has",
"check",
"verify",
"test",
"can",
"should",
"need",
"allow",
"support",
"accept"
},
{PUT.name(), "put", "replace"},
{PATCH.name(), "patch", "update", "modify", "edit", "change", "set"},
{DELETE.name(), "delete", "remove", "erase", "destroy", "drop"}
};
private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{\\{([\\w.-]+)}}");
private Helper() {}
public static Collection<String> guessHttpMethod(MethodMeta method) {
String name = method.getMethod().getName();
for (String[] verbs : VERBS_TABLE) {
for (int i = 1, len = verbs.length; i < len; i++) {
if (name.startsWith(verbs[i])) {
String httpMethod = verbs[0];
if (GET.name().equals(httpMethod)) {
for (ParameterMeta parameter : method.getParameters()) {
ParamType paramType = parameter.getNamedValueMeta().paramType();
if (paramType == null) {
if (parameter.isSimple()) {
continue;
}
return Arrays.asList(GET.name(), POST.name());
} else {
switch (paramType) {
case Form:
case Part:
case Body:
return Collections.singletonList(POST.name());
default:
}
}
}
}
return Collections.singletonList(httpMethod);
}
}
}
return Collections.singletonList(POST.name());
}
public static List<String> extractVariables(String path) {
List<String> variables = null;
for (int i = 0, len = path.length(), start = 0; i < len; i++) {
char c = path.charAt(i);
if (c == '{') {
start = i + 1;
} else if (start > 0 && c == '}') {
if (variables == null) {
variables = new ArrayList<>();
}
variables.add(path.substring(start, i));
start = 0;
}
}
return variables;
}
public static In toIn(ParamType paramType) {
switch (paramType) {
case PathVariable:
return In.PATH;
case Param:
return In.QUERY;
case Header:
return In.HEADER;
case Cookie:
return In.COOKIE;
default:
return null;
}
}
public static String formatSpecVersion(String version) {
if (version == null) {
return null;
}
if (version.startsWith("3.1")) {
return Constants.VERSION_31;
}
return Constants.VERSION_30;
}
public static OpenAPIRequest formatRequest(OpenAPIRequest request) {
if (request == null) {
return new OpenAPIRequest();
}
request.setGroup(trim(request.getGroup()));
request.setVersion(trim(request.getVersion()));
String[] tag = trim(request.getTag());
if (tag != null) {
Arrays.sort(tag);
}
request.setTag(tag);
String[] service = trim(request.getService());
if (service != null) {
Arrays.sort(service);
}
request.setService(service);
request.setOpenapi(trim(request.getOpenapi()));
request.setFormat(trim(request.getFormat()));
return request;
}
public static String parseFormat(String contentType) {
if (contentType != null) {
int index = contentType.indexOf('/');
if (index > 0 && contentType.indexOf("htm", index) == -1) {
return contentType.substring(index + 1);
}
}
return "json";
}
public static String trim(String str) {
if (str == null || str.isEmpty()) {
return null;
}
str = str.trim();
return str.isEmpty() ? null : str;
}
public static String[] trim(String[] array) {
if (array == null) {
return null;
}
int len = array.length;
if (len == 0) {
return null;
}
int p = 0;
for (int i = 0; i < len; i++) {
String value = trim(array[i]);
if (value != null) {
array[p++] = value;
}
}
int newLen = p;
return newLen == len ? array : Arrays.copyOf(array, newLen);
}
public static Map<String, String> toProperties(String[] array) {
if (array == null) {
return Collections.emptyMap();
}
int len = array.length;
if (len == 0) {
return Collections.emptyMap();
}
Map<String, String> properties = CollectionUtils.newLinkedHashMap(len);
for (String item : array) {
int index = item.indexOf('=');
if (index > 0) {
properties.put(trim(item.substring(0, index)), trim(item.substring(index + 1)));
} else {
properties.put(trim(item), null);
}
}
return properties;
}
public static Server parseServer(String server) {
String url = null;
String description = null;
int equalIndex = server.indexOf('=');
if (equalIndex > 0) {
int index = server.indexOf("://");
if (index == -1 || index > equalIndex) {
url = trim(server.substring(equalIndex + 1));
description = trim(server.substring(0, equalIndex));
}
}
if (url == null) {
url = trim(server);
}
return new Server().setDescription(description).setUrl(url);
}
public static void setValue(Supplier<String> getter, Consumer<String> setter) {
String value = trim(getter.get());
if (value != null) {
setter.accept(value);
}
}
public static void setBoolValue(Supplier<String> getter, Consumer<Boolean> setter) {
String value = trim(getter.get());
if (value != null) {
setter.accept(StringUtils.toBoolean(value));
}
}
public static void setValue(AnnotationMeta<?> schema, String key, Consumer<String> setter) {
String value = trim(schema.getString(key));
if (value != null) {
setter.accept(value);
}
}
public static void setBoolValue(AnnotationMeta<?> schema, String key, Consumer<Boolean> setter) {
Boolean value = schema.getBoolean(key);
if (Boolean.TRUE.equals(value)) {
setter.accept(true);
}
}
public static String pathToRef(String path) {
StringBuilder sb = new StringBuilder(path.length() + 16);
sb.append("#/paths/");
for (int i = 0, len = path.length(); i < len; i++) {
char c = path.charAt(i);
if (c == '/') {
sb.append('~').append('1');
} else if (c == '~') {
sb.append('~').append('0');
} else {
sb.append(c);
}
}
return sb.toString();
}
public static boolean isVersionGreaterOrEqual(String version1, String version2) {
int i = 0, j = 0, len1 = version1.length(), len2 = version2.length();
while (i < len1 || j < len2) {
int num1 = 0;
while (i < len1) {
char c = version1.charAt(i);
if (Character.isDigit(c)) {
num1 = num1 * 10 + (c - '0');
} else if (c == '.' || c == '-' || c == '_') {
i++;
break;
}
i++;
}
int num2 = 0;
while (j < len2) {
char c = version2.charAt(j);
if (Character.isDigit(c)) {
num2 = num2 * 10 + (c - '0');
} else if (c == '.' || c == '-' || c == '_') {
j++;
break;
}
j++;
}
if (num1 < num2) {
return false;
}
}
return true;
}
public static String render(String text, Function<String, String> fn) {
if (text == null) {
return null;
}
Matcher matcher = PLACEHOLDER_PATTERN.matcher(text);
StringBuffer result = new StringBuffer(text.length());
while (matcher.find()) {
String value = fn.apply(matcher.group(1));
matcher.appendReplacement(result, value == null ? StringUtils.EMPTY_STRING : value);
}
matcher.appendTail(result);
return result.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/ContextImpl.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/ContextImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.remoting.http12.rest.OpenAPIRequest;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.OpenAPI;
final class ContextImpl extends AbstractContext implements Context {
private final OpenAPIRequest request;
private Boolean openAPI31;
private Holder<HttpRequest> httpRequest;
private Holder<HttpResponse> httpResponse;
ContextImpl(OpenAPI openAPI, SchemaResolver schemaResolver, ExtensionFactory extFactory, OpenAPIRequest request) {
super(openAPI, schemaResolver, extFactory);
this.request = request;
}
@Override
public boolean isOpenAPI31() {
if (openAPI31 == null) {
String v = request.getOpenapi();
openAPI31 = v != null && v.startsWith("3.1.");
}
return openAPI31;
}
@Override
public OpenAPIRequest getRequest() {
return request;
}
@Override
public HttpRequest getHttpRequest() {
Holder<HttpRequest> holder = httpRequest;
if (holder == null) {
holder = new Holder<>();
holder.set(RpcContext.getServiceContext().getRequest(HttpRequest.class));
httpRequest = holder;
}
return holder.get();
}
@Override
public HttpResponse getHttpResponse() {
Holder<HttpResponse> holder = httpResponse;
if (holder == null) {
holder = new Holder<>();
holder.set(RpcContext.getServiceContext().getResponse(HttpResponse.class));
httpResponse = holder;
}
return holder.get();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Info.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Info.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.Map;
public final class Info extends Node<Info> {
private String title;
private String summary;
private String description;
private String termsOfService;
private Contact contact;
private License license;
private String version;
public String getTitle() {
return title;
}
public Info setTitle(String title) {
this.title = title;
return this;
}
public String getSummary() {
return summary;
}
public Info setSummary(String summary) {
this.summary = summary;
return this;
}
public String getDescription() {
return description;
}
public Info setDescription(String description) {
this.description = description;
return this;
}
public String getTermsOfService() {
return termsOfService;
}
public Info setTermsOfService(String termsOfService) {
this.termsOfService = termsOfService;
return this;
}
public Contact getContact() {
return contact;
}
public Info setContact(Contact contact) {
this.contact = contact;
return this;
}
public License getLicense() {
return license;
}
public Info setLicense(License license) {
this.license = license;
return this;
}
public String getVersion() {
return version;
}
public Info setVersion(String version) {
this.version = version;
return this;
}
@Override
public Info clone() {
Info clone = super.clone();
clone.contact = clone(contact);
clone.license = clone(license);
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "title", title);
write(node, "summary", summary);
write(node, "description", description);
write(node, "termsOfService", termsOfService);
write(node, "contact", contact, context);
write(node, "license", license, context);
write(node, "version", version);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Parameter.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Parameter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
public final class Parameter extends Node<Parameter> {
public enum In {
PATH("path"),
QUERY("query"),
HEADER("header"),
COOKIE("cookie");
private final String value;
In(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
public enum Style {
MATRIX("matrix"),
LABEL("label"),
FORM("form"),
SIMPLE("simple"),
SPACE_DELIMITED("spaceDelimited"),
PIPE_DELIMITED("pipeDelimited"),
DEEP_OBJECT("deepObject");
private final String value;
Style(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
private final String name;
private final In in;
private String description;
private Boolean required;
private Boolean deprecated;
private Boolean allowEmptyValue;
private Style style;
private Boolean explode;
private Boolean allowReserved;
private Schema schema;
private Object example;
private Map<String, Example> examples;
private Map<String, MediaType> contents;
private transient ParameterMeta meta;
public Parameter(String name, In in) {
this.name = Objects.requireNonNull(name);
this.in = Objects.requireNonNull(in);
}
public String getName() {
return name;
}
public In getIn() {
return in;
}
public String getDescription() {
return description;
}
public Parameter setDescription(String description) {
this.description = description;
return this;
}
public Boolean getRequired() {
return required;
}
public Parameter setRequired(Boolean required) {
this.required = required;
return this;
}
public Boolean getDeprecated() {
return deprecated;
}
public Parameter setDeprecated(Boolean deprecated) {
this.deprecated = deprecated;
return this;
}
public Boolean getAllowEmptyValue() {
return allowEmptyValue;
}
public Parameter setAllowEmptyValue(Boolean allowEmptyValue) {
this.allowEmptyValue = allowEmptyValue;
return this;
}
public Style getStyle() {
return style;
}
public Parameter setStyle(Style style) {
this.style = style;
return this;
}
public Boolean getExplode() {
return explode;
}
public Parameter setExplode(Boolean explode) {
this.explode = explode;
return this;
}
public Boolean getAllowReserved() {
return allowReserved;
}
public Parameter setAllowReserved(Boolean allowReserved) {
this.allowReserved = allowReserved;
return this;
}
public Schema getSchema() {
return schema;
}
public Parameter setSchema(Schema schema) {
this.schema = schema;
return this;
}
public Object getExample() {
return example;
}
public Parameter setExample(Object example) {
this.example = example;
return this;
}
public Map<String, Example> getExamples() {
return examples;
}
public Parameter setExamples(Map<String, Example> examples) {
this.examples = examples;
return this;
}
public Parameter addExample(String name, Example example) {
if (examples == null) {
examples = new LinkedHashMap<>();
}
examples.put(name, example);
return this;
}
public Parameter removeExample(String name) {
if (examples != null) {
examples.remove(name);
}
return this;
}
public Map<String, MediaType> getContents() {
return contents;
}
public Parameter setContents(Map<String, MediaType> contents) {
this.contents = contents;
return this;
}
public Parameter addContent(String name, MediaType content) {
if (contents == null) {
contents = new LinkedHashMap<>();
}
contents.put(name, content);
return this;
}
public Parameter removeContent(String name) {
if (contents != null) {
contents.remove(name);
}
return this;
}
public ParameterMeta getMeta() {
return meta;
}
public Parameter setMeta(ParameterMeta meta) {
this.meta = meta;
return this;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != Parameter.class) {
return false;
}
Parameter other = (Parameter) obj;
return name.equals(other.name) && in == other.in;
}
@Override
public int hashCode() {
return 31 * name.hashCode() + in.hashCode();
}
@Override
public Parameter clone() {
Parameter clone = super.clone();
clone.schema = clone(schema);
clone.examples = clone(examples);
clone.contents = clone(contents);
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "name", name);
write(node, "in", in.toString());
write(node, "description", description);
write(node, "required", required);
write(node, "deprecated", deprecated);
write(node, "allowEmptyValue", allowEmptyValue);
write(node, "style", style);
write(node, "explode", explode);
write(node, "allowReserved", allowReserved);
write(node, "schema", schema, context);
write(node, "example", example);
write(node, "examples", examples, context);
write(node, "content", contents, context);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/License.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/License.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.Map;
public final class License extends Node<License> {
private String name;
private String url;
public String getName() {
return name;
}
public License setName(String name) {
this.name = name;
return this;
}
public String getUrl() {
return url;
}
public License setUrl(String url) {
this.url = url;
return this;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "name", name);
write(node, "url", url);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Node.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Node.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.common.utils.ToStringUtils;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public abstract class Node<T extends Node<T>> implements Cloneable {
private Map<String, Object> extensions;
public Map<String, Object> getExtensions() {
return extensions;
}
@SuppressWarnings("unchecked")
public T addExtension(String name, Object value) {
Map<String, Object> extensions = this.extensions;
if (extensions == null) {
this.extensions = extensions = new LinkedHashMap<>();
}
extensions.put(name, value);
return (T) this;
}
@SuppressWarnings("unchecked")
public T addExtensions(Map<String, ?> extensions) {
if (extensions == null || extensions.isEmpty()) {
return (T) this;
}
Map<String, Object> thisExtensions = this.extensions;
if (thisExtensions == null) {
this.extensions = new LinkedHashMap<>(extensions);
} else {
for (Map.Entry<String, ?> entry : extensions.entrySet()) {
thisExtensions.putIfAbsent(entry.getKey(), entry.getValue());
}
}
return (T) this;
}
public void removeExtension(String name) {
if (extensions != null) {
extensions.remove(name);
}
}
@SuppressWarnings("unchecked")
public T setExtensions(Map<String, ?> extensions) {
if (extensions != null) {
this.extensions = new LinkedHashMap<>(extensions);
}
return (T) this;
}
@Override
@SuppressWarnings("unchecked")
public T clone() {
try {
T clone = (T) super.clone();
if (extensions != null) {
clone.setExtensions(extensions);
}
return clone;
} catch (CloneNotSupportedException e) {
throw new UnsupportedOperationException(e);
}
}
@Override
public String toString() {
return ToStringUtils.printToString(this);
}
public static <T extends Node<T>> T clone(T node) {
return node == null ? null : node.clone();
}
public static <T extends Node<T>> List<T> clone(List<T> list) {
if (list == null) {
return null;
}
int size = list.size();
if (size == 0) {
return new ArrayList<>();
}
List<T> clone = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
clone.add(list.get(i).clone());
}
return clone;
}
public static <K, V extends Node<V>> Map<K, V> clone(Map<K, V> map) {
if (map == null) {
return null;
}
int size = map.size();
if (size == 0) {
return new LinkedHashMap<>();
}
Map<K, V> clone = newMap(size);
for (Map.Entry<K, V> entry : map.entrySet()) {
clone.put(entry.getKey(), entry.getValue().clone());
}
return clone;
}
protected static void write(Map<String, Object> node, String name, Object value) {
if (value == null || "".equals(value)) {
return;
}
node.put(name, value instanceof Set ? ((Set<?>) value).toArray() : value);
}
protected static void write(Map<String, Object> node, String name, Node<?> value, Context context) {
if (value == null) {
return;
}
Map<String, Object> valueMap = value.writeTo(new LinkedHashMap<>(), context);
if (valueMap == null || valueMap.isEmpty()) {
return;
}
node.put(name, valueMap);
}
protected static void write(Map<String, Object> node, String name, List<? extends Node<?>> value, Context context) {
if (value == null) {
return;
}
int size = value.size();
if (size > 0) {
List<Map<String, Object>> list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
Map<String, Object> valueMap = value.get(i).writeTo(new LinkedHashMap<>(), context);
if (valueMap == null || valueMap.isEmpty()) {
continue;
}
list.add(valueMap);
}
node.put(name, list);
}
}
protected static void write(
Map<String, Object> node, String name, Map<?, ? extends Node<?>> value, Context context) {
if (value == null) {
return;
}
int size = value.size();
if (size > 0) {
Map<Object, Map<String, Object>> map = newMap(size);
for (Map.Entry<?, ? extends Node<?>> entry : value.entrySet()) {
Map<String, Object> valueMap = entry.getValue().writeTo(new LinkedHashMap<>(), context);
if (valueMap == null || valueMap.isEmpty()) {
continue;
}
map.put(entry.getKey(), valueMap);
}
node.put(name, map);
}
}
protected static <K, V> Map<K, V> newMap(int capacity) {
return new LinkedHashMap<>(capacity < 3 ? capacity + 1 : (int) (capacity / 0.75F + 1.0F));
}
protected final void writeExtensions(Map<String, Object> node) {
if (extensions == null) {
return;
}
node.putAll(extensions);
}
public abstract Map<String, Object> writeTo(Map<String, Object> node, Context context);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/ServerVariable.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/ServerVariable.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public final class ServerVariable extends Node<ServerVariable> {
private List<String> enumeration;
private String defaultValue;
private String description;
public List<String> getEnumeration() {
return enumeration;
}
public ServerVariable setEnumeration(List<String> enumeration) {
this.enumeration = enumeration;
return this;
}
public ServerVariable addEnumeration(String value) {
if (enumeration == null) {
enumeration = new ArrayList<>();
}
enumeration.add(value);
return this;
}
public ServerVariable removeEnumeration(String value) {
if (enumeration != null) {
enumeration.remove(value);
}
return this;
}
public String getDefaultValue() {
return defaultValue;
}
public ServerVariable setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
return this;
}
public String getDescription() {
return description;
}
public ServerVariable setDescription(String description) {
this.description = description;
return this;
}
@Override
public ServerVariable clone() {
ServerVariable clone = super.clone();
if (enumeration != null) {
clone.enumeration = new ArrayList<>(enumeration);
}
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "enum", enumeration);
write(node, "default", defaultValue);
write(node, "description", description);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Server.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Server.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.LinkedHashMap;
import java.util.Map;
public final class Server extends Node<Server> {
private String url;
private String description;
private Map<String, ServerVariable> variables;
public String getUrl() {
return url;
}
public Server setUrl(String url) {
this.url = url;
return this;
}
public String getDescription() {
return description;
}
public Server setDescription(String description) {
this.description = description;
return this;
}
public Map<String, ServerVariable> getVariables() {
return variables;
}
public Server setVariables(Map<String, ServerVariable> variables) {
this.variables = variables;
return this;
}
public Server addVariable(String name, ServerVariable variable) {
if (variables == null) {
variables = new LinkedHashMap<>();
}
variables.put(name, variable);
return this;
}
public Server removeVariable(String name) {
if (variables != null) {
variables.remove(name);
}
return this;
}
@Override
public Server clone() {
Server clone = super.clone();
clone.variables = clone(variables);
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "url", url);
write(node, "description", description);
write(node, "variables", variables, context);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/XML.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/XML.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.Map;
public final class XML extends Node<XML> {
private String name;
private String namespace;
private String prefix;
private Boolean attribute;
private Boolean wrapped;
public String getName() {
return name;
}
public XML setName(String name) {
this.name = name;
return this;
}
public String getNamespace() {
return namespace;
}
public XML setNamespace(String namespace) {
this.namespace = namespace;
return this;
}
public String getPrefix() {
return prefix;
}
public XML setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
public Boolean getAttribute() {
return attribute;
}
public XML setAttribute(Boolean attribute) {
this.attribute = attribute;
return this;
}
public Boolean getWrapped() {
return wrapped;
}
public XML setWrapped(Boolean wrapped) {
this.wrapped = wrapped;
return this;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
node.put("name", name);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/SecurityRequirement.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/SecurityRequirement.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public final class SecurityRequirement extends Node<SecurityRequirement> {
private Map<String, List<String>> requirements;
public Map<String, List<String>> getRequirements() {
return requirements;
}
public void setRequirements(Map<String, List<String>> requirements) {
this.requirements = requirements;
}
public SecurityRequirement addRequirement(String name, String... scope) {
return addRequirement(name, scope == null ? Collections.emptyList() : Arrays.asList(scope));
}
public SecurityRequirement addRequirement(String name, List<String> scopes) {
if (requirements == null) {
requirements = new LinkedHashMap<>();
}
if (scopes == null) {
scopes = Collections.emptyList();
}
requirements.put(name, scopes);
return this;
}
public void removeRequirement(String name) {
if (requirements != null) {
requirements.remove(name);
}
}
@Override
public SecurityRequirement clone() {
SecurityRequirement clone = super.clone();
if (requirements != null) {
Map<String, List<String>> requirements = newMap(this.requirements.size());
for (Map.Entry<String, List<String>> entry : this.requirements.entrySet()) {
requirements.put(entry.getKey(), new ArrayList<>(entry.getValue()));
}
clone.requirements = requirements;
}
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "requirements", requirements);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Header.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Header.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.LinkedHashMap;
import java.util.Map;
public final class Header extends Node<Header> {
public enum Style {
SIMPLE("simple");
private final String value;
Style(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
private String description;
private Boolean required;
private Boolean deprecated;
private Boolean allowEmptyValue;
private final Style style = Style.SIMPLE;
private Boolean explode;
private Schema schema;
private Object example;
private Map<String, Example> examples;
private Map<String, MediaType> contents;
public String getDescription() {
return description;
}
public Header setDescription(String description) {
this.description = description;
return this;
}
public Boolean getRequired() {
return required;
}
public Header setRequired(Boolean required) {
this.required = required;
return this;
}
public Boolean getDeprecated() {
return deprecated;
}
public Header setDeprecated(Boolean deprecated) {
this.deprecated = deprecated;
return this;
}
public Boolean getAllowEmptyValue() {
return allowEmptyValue;
}
public Header setAllowEmptyValue(Boolean allowEmptyValue) {
this.allowEmptyValue = allowEmptyValue;
return this;
}
public Style getStyle() {
return style;
}
public Boolean getExplode() {
return explode;
}
public Header setExplode(Boolean explode) {
this.explode = explode;
return this;
}
public Schema getSchema() {
return schema;
}
public Header setSchema(Schema schema) {
this.schema = schema;
return this;
}
public Object getExample() {
return example;
}
public Header setExample(Object example) {
this.example = example;
return this;
}
public Map<String, Example> getExamples() {
return examples;
}
public Header setExamples(Map<String, Example> examples) {
this.examples = examples;
return this;
}
public Header addExample(String name, Example example) {
if (examples == null) {
examples = new LinkedHashMap<>();
}
examples.put(name, example);
return this;
}
public Header removeExample(String name) {
if (examples != null) {
examples.remove(name);
}
return this;
}
public Map<String, MediaType> getContents() {
return contents;
}
public MediaType getContent(String name) {
return contents == null ? null : contents.get(name);
}
public Header setContents(Map<String, MediaType> contents) {
this.contents = contents;
return this;
}
public Header addContent(String name, MediaType content) {
if (contents == null) {
contents = new LinkedHashMap<>();
}
contents.put(name, content);
return this;
}
public Header removeContent(String name) {
if (contents != null) {
contents.remove(name);
}
return this;
}
@Override
public Header clone() {
Header clone = super.clone();
clone.schema = clone(schema);
clone.examples = clone(examples);
clone.contents = clone(contents);
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "description", description);
write(node, "required", required);
write(node, "deprecated", deprecated);
write(node, "allowEmptyValue", allowEmptyValue);
write(node, "style", style);
write(node, "explode", explode);
write(node, "schema", schema, context);
write(node, "example", example);
write(node, "examples", examples, context);
write(node, "content", contents, context);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Schema.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Schema.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Constants;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public final class Schema extends Node<Schema> {
public enum Type {
STRING("string"),
INTEGER("integer"),
NUMBER("number"),
BOOLEAN("boolean"),
OBJECT("object"),
ARRAY("array");
private final String value;
Type(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
public Type of(String value) {
for (Type type : values()) {
if (type.value.equals(value)) {
return type;
}
}
return STRING;
}
}
private String ref;
private String format;
private String name;
private String title;
private String description;
private Object defaultValue;
private BigDecimal multipleOf;
private BigDecimal maximum;
private Boolean exclusiveMaximum;
private BigDecimal minimum;
private Boolean exclusiveMinimum;
private Integer maxLength;
private Integer minLength;
private String pattern;
private Integer maxItems;
private Integer minItems;
private Boolean uniqueItems;
private Integer maxProperties;
private Integer minProperties;
private Boolean required;
private List<Object> enumeration;
private Type type;
private Schema items;
private Map<String, Schema> properties;
private Schema additionalPropertiesSchema;
private Boolean additionalPropertiesBoolean;
private Boolean readOnly;
private XML xml;
private ExternalDocs externalDocs;
private Object example;
private List<Schema> allOf;
private List<Schema> oneOf;
private List<Schema> anyOf;
private Schema not;
private Discriminator discriminator;
private Boolean nullable;
private Boolean writeOnly;
private Boolean deprecated;
private String group;
private String version;
private Class<?> javaType;
private transient Schema targetSchema;
private transient List<Schema> sourceSchemas;
public String getRef() {
return ref;
}
public Schema setRef(String ref) {
this.ref = ref;
return this;
}
public String getFormat() {
return format;
}
public Schema setFormat(String format) {
this.format = format;
return this;
}
public String getName() {
return name;
}
public Schema setName(String name) {
this.name = name;
return this;
}
public String getTitle() {
return title;
}
public Schema setTitle(String title) {
this.title = title;
return this;
}
public String getDescription() {
return description;
}
public Schema setDescription(String description) {
this.description = description;
return this;
}
public Object getDefaultValue() {
return defaultValue;
}
public Schema setDefaultValue(Object defaultValue) {
this.defaultValue = defaultValue;
return this;
}
public BigDecimal getMultipleOf() {
return multipleOf;
}
public Schema setMultipleOf(BigDecimal multipleOf) {
this.multipleOf = multipleOf;
return this;
}
public BigDecimal getMaximum() {
return maximum;
}
public Schema setMaximum(BigDecimal maximum) {
this.maximum = maximum;
return this;
}
public Boolean getExclusiveMaximum() {
return exclusiveMaximum;
}
public Schema setExclusiveMaximum(Boolean exclusiveMaximum) {
this.exclusiveMaximum = exclusiveMaximum;
return this;
}
public BigDecimal getMinimum() {
return minimum;
}
public Schema setMinimum(BigDecimal minimum) {
this.minimum = minimum;
return this;
}
public Boolean getExclusiveMinimum() {
return exclusiveMinimum;
}
public Schema setExclusiveMinimum(Boolean exclusiveMinimum) {
this.exclusiveMinimum = exclusiveMinimum;
return this;
}
public Integer getMaxLength() {
return maxLength;
}
public Schema setMaxLength(Integer maxLength) {
this.maxLength = maxLength;
return this;
}
public Integer getMinLength() {
return minLength;
}
public Schema setMinLength(Integer minLength) {
this.minLength = minLength;
return this;
}
public String getPattern() {
return pattern;
}
public Schema setPattern(String pattern) {
this.pattern = pattern;
return this;
}
public Integer getMaxItems() {
return maxItems;
}
public Schema setMaxItems(Integer maxItems) {
this.maxItems = maxItems;
return this;
}
public Integer getMinItems() {
return minItems;
}
public Schema setMinItems(Integer minItems) {
this.minItems = minItems;
return this;
}
public Boolean getUniqueItems() {
return uniqueItems;
}
public Schema setUniqueItems(Boolean uniqueItems) {
this.uniqueItems = uniqueItems;
return this;
}
public Integer getMaxProperties() {
return maxProperties;
}
public Schema setMaxProperties(Integer maxProperties) {
this.maxProperties = maxProperties;
return this;
}
public Integer getMinProperties() {
return minProperties;
}
public Schema setMinProperties(Integer minProperties) {
this.minProperties = minProperties;
return this;
}
public Boolean getRequired() {
return required;
}
public Schema setRequired(Boolean required) {
this.required = required;
return this;
}
public List<Object> getEnumeration() {
return enumeration;
}
public Schema setEnumeration(List<Object> enumeration) {
this.enumeration = enumeration;
return this;
}
public Schema addEnumeration(Object enumeration) {
if (this.enumeration == null) {
this.enumeration = new ArrayList<>();
}
this.enumeration.add(enumeration);
return this;
}
public Schema removeEnumeration(Object enumeration) {
if (this.enumeration != null) {
this.enumeration.remove(enumeration);
}
return this;
}
public Type getType() {
return type;
}
public Schema setType(Type type) {
this.type = type;
return this;
}
public Schema getItems() {
return items;
}
public Schema setItems(Schema items) {
this.items = items;
return this;
}
public Map<String, Schema> getProperties() {
return properties;
}
public Schema getProperty(String name) {
return properties == null ? null : properties.get(name);
}
public Schema setProperties(Map<String, Schema> properties) {
this.properties = properties;
return this;
}
public Schema addProperty(String name, Schema schema) {
if (schema == null) {
return this;
}
if (properties == null) {
properties = new LinkedHashMap<>();
}
properties.put(name, schema);
return this;
}
public Schema removeProperty(String name) {
if (properties != null) {
properties.remove(name);
}
return this;
}
public Schema getAdditionalPropertiesSchema() {
return additionalPropertiesSchema;
}
public Schema setAdditionalPropertiesSchema(Schema additionalPropertiesSchema) {
this.additionalPropertiesSchema = additionalPropertiesSchema;
return this;
}
public Boolean getAdditionalPropertiesBoolean() {
return additionalPropertiesBoolean;
}
public Schema setAdditionalPropertiesBoolean(Boolean additionalPropertiesBoolean) {
this.additionalPropertiesBoolean = additionalPropertiesBoolean;
return this;
}
public Boolean getReadOnly() {
return readOnly;
}
public Schema setReadOnly(Boolean readOnly) {
this.readOnly = readOnly;
return this;
}
public XML getXml() {
return xml;
}
public Schema setXml(XML xml) {
this.xml = xml;
return this;
}
public ExternalDocs getExternalDocs() {
return externalDocs;
}
public Schema setExternalDocs(ExternalDocs externalDocs) {
this.externalDocs = externalDocs;
return this;
}
public Object getExample() {
return example;
}
public Schema setExample(Object example) {
this.example = example;
return this;
}
public List<Schema> getAllOf() {
return allOf;
}
public Schema setAllOf(List<Schema> allOf) {
this.allOf = allOf;
return this;
}
public Schema addAllOf(Schema schema) {
if (allOf == null) {
allOf = new ArrayList<>();
}
allOf.add(schema);
return this;
}
public List<Schema> getOneOf() {
return oneOf;
}
public Schema setOneOf(List<Schema> oneOf) {
this.oneOf = oneOf;
return this;
}
public Schema addOneOf(Schema schema) {
if (oneOf == null) {
oneOf = new ArrayList<>();
}
oneOf.add(schema);
return this;
}
public List<Schema> getAnyOf() {
return anyOf;
}
public Schema setAnyOf(List<Schema> anyOf) {
this.anyOf = anyOf;
return this;
}
public Schema addAnyOf(Schema schema) {
if (anyOf == null) {
anyOf = new ArrayList<>();
}
anyOf.add(schema);
return this;
}
public Schema getNot() {
return not;
}
public Schema setNot(Schema not) {
this.not = not;
return this;
}
public Discriminator getDiscriminator() {
return discriminator;
}
public Schema setDiscriminator(Discriminator discriminator) {
this.discriminator = discriminator;
return this;
}
public Boolean getNullable() {
return nullable;
}
public Schema setNullable(Boolean nullable) {
this.nullable = nullable;
return this;
}
public Boolean getWriteOnly() {
return writeOnly;
}
public Schema setWriteOnly(Boolean writeOnly) {
this.writeOnly = writeOnly;
return this;
}
public Boolean getDeprecated() {
return deprecated;
}
public Schema setDeprecated(Boolean deprecated) {
this.deprecated = deprecated;
return this;
}
public String getGroup() {
return group;
}
public Schema setGroup(String group) {
this.group = group;
return this;
}
public String getVersion() {
return version;
}
public Schema setVersion(String version) {
this.version = version;
return this;
}
public Class<?> getJavaType() {
return javaType;
}
public Schema setJavaType(Class<?> javaType) {
this.javaType = javaType;
return this;
}
public Schema getTargetSchema() {
return targetSchema;
}
public Schema setTargetSchema(Schema targetSchema) {
this.targetSchema = targetSchema;
return this;
}
public List<Schema> getSourceSchemas() {
return sourceSchemas;
}
public Schema setSourceSchemas(List<Schema> sourceSchemas) {
this.sourceSchemas = sourceSchemas;
return this;
}
public void addSourceSchema(Schema sourceSchema) {
if (sourceSchemas == null) {
sourceSchemas = new LinkedList<>();
}
sourceSchemas.add(sourceSchema);
}
@Override
public Schema clone() {
Schema clone = super.clone();
if (enumeration != null) {
clone.enumeration = new ArrayList<>(enumeration);
}
clone.items = clone(items);
clone.properties = clone(properties);
clone.additionalPropertiesSchema = clone(additionalPropertiesSchema);
clone.xml = clone(xml);
clone.externalDocs = clone(externalDocs);
clone.allOf = clone(allOf);
clone.oneOf = clone(oneOf);
clone.anyOf = clone(anyOf);
clone.not = clone(not);
clone.discriminator = clone(discriminator);
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> schema, Context context) {
if (ref != null) {
schema.put("$ref", ref);
}
write(schema, "format", format);
write(schema, "title", title);
write(schema, "description", description);
write(schema, "default", defaultValue);
write(schema, "multipleOf", multipleOf);
write(schema, "maximum", maximum);
write(schema, "exclusiveMaximum", exclusiveMaximum);
write(schema, "minimum", minimum);
write(schema, "exclusiveMinimum", exclusiveMinimum);
write(schema, "maxLength", maxLength);
write(schema, "minLength", minLength);
write(schema, "pattern", pattern);
write(schema, "maxItems", maxItems);
write(schema, "minItems", minItems);
write(schema, "uniqueItems", uniqueItems);
write(schema, "maxProperties", maxProperties);
write(schema, "minProperties", minProperties);
write(schema, "required", required);
write(schema, "enum", enumeration);
if (type != null) {
if (context.isOpenAPI31()) {
if (nullable == null || !nullable) {
write(schema, "type", type.toString());
} else {
write(schema, "type", new String[] {type.toString(), "null"});
}
} else {
write(schema, "type", type.toString());
write(schema, "nullable", nullable);
}
}
write(schema, "items", items, context);
write(schema, "properties", properties, context);
if (additionalPropertiesBoolean == null) {
write(schema, "additionalProperties", additionalPropertiesSchema, context);
} else {
schema.put("additionalProperties", additionalPropertiesBoolean);
}
write(schema, "readOnly", readOnly);
write(schema, "xml", xml, context);
write(schema, "externalDocs", externalDocs, context);
write(schema, "example", example);
write(schema, "allOf", allOf, context);
write(schema, "oneOf", oneOf, context);
write(schema, "anyOf", anyOf, context);
write(schema, "not", not, context);
write(schema, "discriminator", discriminator, context);
write(schema, "writeOnly", writeOnly);
write(schema, "deprecated", deprecated);
writeExtensions(schema);
if (javaType != null) {
schema.put(Constants.X_JAVA_CLASS, javaType.getName());
}
return schema;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/MediaType.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/MediaType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.LinkedHashMap;
import java.util.Map;
public final class MediaType extends Node<MediaType> {
private Schema schema;
private Object example;
private Map<String, Example> examples;
private Map<String, Encoding> encoding;
public Schema getSchema() {
return schema;
}
public MediaType setSchema(Schema schema) {
this.schema = schema;
return this;
}
public Object getExample() {
return example;
}
public MediaType setExample(Object example) {
this.example = example;
return this;
}
public Map<String, Example> getExamples() {
return examples;
}
public MediaType setExamples(Map<String, Example> examples) {
this.examples = examples;
return this;
}
public MediaType addExample(String name, Example example) {
if (examples == null) {
examples = new LinkedHashMap<>();
}
examples.put(name, example);
return this;
}
public MediaType removeExample(String name) {
if (examples != null) {
examples.remove(name);
}
return this;
}
public Map<String, Encoding> getEncoding() {
return encoding;
}
public MediaType setEncoding(Map<String, Encoding> encoding) {
this.encoding = encoding;
return this;
}
public MediaType addEncoding(String name, Encoding encoding) {
if (this.encoding == null) {
this.encoding = new LinkedHashMap<>();
}
this.encoding.put(name, encoding);
return this;
}
public MediaType removeEncoding(String name) {
if (encoding != null) {
encoding.remove(name);
}
return this;
}
@Override
public MediaType clone() {
MediaType clone = super.clone();
clone.schema = clone(schema);
clone.examples = clone(examples);
clone.encoding = clone(encoding);
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "schema", schema, context);
write(node, "example", example);
write(node, "examples", examples, context);
write(node, "encoding", encoding, context);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/RequestBody.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/RequestBody.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.LinkedHashMap;
import java.util.Map;
public final class RequestBody extends Node<RequestBody> {
private String description;
private Map<String, MediaType> contents;
private boolean required;
public String getDescription() {
return description;
}
public RequestBody setDescription(String description) {
this.description = description;
return this;
}
public Map<String, MediaType> getContents() {
return contents;
}
public MediaType getContent(String content) {
return contents == null ? null : contents.get(content);
}
public MediaType getOrAddContent(String content) {
if (contents == null) {
contents = new LinkedHashMap<>();
}
return contents.computeIfAbsent(content, k -> new MediaType());
}
public RequestBody setContents(Map<String, MediaType> contents) {
this.contents = contents;
return this;
}
public RequestBody addContent(String name, MediaType content) {
if (contents == null) {
contents = new LinkedHashMap<>();
}
contents.put(name, content);
return this;
}
public RequestBody removeContent(String name) {
if (contents != null) {
contents.remove(name);
}
return this;
}
public boolean isRequired() {
return required;
}
public RequestBody setRequired(boolean required) {
this.required = required;
return this;
}
@Override
public RequestBody clone() {
RequestBody clone = super.clone();
clone.contents = clone(contents);
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "description", description);
write(node, "required", required);
write(node, "content", contents, context);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/PathItem.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/PathItem.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Helper;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public final class PathItem extends Node<PathItem> {
private String ref;
private String summary;
private String description;
private Map<HttpMethods, Operation> operations;
private List<Server> servers;
private List<Parameter> parameters;
public String getRef() {
return ref;
}
public PathItem setRef(String ref) {
this.ref = ref;
return this;
}
public String getSummary() {
return summary;
}
public PathItem setSummary(String summary) {
this.summary = summary;
return this;
}
public String getDescription() {
return description;
}
public PathItem setDescription(String description) {
this.description = description;
return this;
}
public Map<HttpMethods, Operation> getOperations() {
return operations;
}
public Operation getOperation(HttpMethods method) {
return operations == null ? null : operations.get(method);
}
public PathItem setOperations(Map<HttpMethods, Operation> operations) {
this.operations = operations;
return this;
}
public PathItem addOperation(HttpMethods method, Operation operation) {
if (operations == null) {
operations = new LinkedHashMap<>();
}
operations.put(method, operation);
return this;
}
public PathItem removeOperation(HttpMethods method) {
if (operations != null) {
operations.remove(method);
}
return this;
}
public List<Server> getServers() {
return servers;
}
public PathItem setServers(List<Server> servers) {
this.servers = servers;
return this;
}
public PathItem addServer(Server server) {
if (servers == null) {
servers = new ArrayList<>();
}
servers.add(server);
return this;
}
public PathItem removeServer(Server server) {
if (servers != null) {
servers.remove(server);
}
return this;
}
public List<Parameter> getParameters() {
return parameters;
}
public PathItem setParameters(List<Parameter> parameters) {
this.parameters = parameters;
return this;
}
public PathItem addParameter(Parameter parameter) {
List<Parameter> thisParameters = parameters;
if (thisParameters == null) {
parameters = thisParameters = new ArrayList<>();
} else {
for (int i = 0, size = thisParameters.size(); i < size; i++) {
Parameter tParameter = thisParameters.get(i);
if (tParameter.getName().equals(parameter.getName())) {
return this;
}
}
}
thisParameters.add(parameter);
return this;
}
public PathItem removeParameter(Parameter parameter) {
if (parameters != null) {
parameters.remove(parameter);
}
return this;
}
@Override
public PathItem clone() {
PathItem clone = super.clone();
clone.operations = clone(operations);
clone.servers = clone(servers);
clone.parameters = clone(parameters);
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
if (ref != null) {
write(node, "$ref", Helper.pathToRef(ref));
} else if (operations != null) {
write(node, "summary", summary);
write(node, "description", description);
for (Map.Entry<HttpMethods, Operation> entry : operations.entrySet()) {
write(node, entry.getKey().name().toLowerCase(), entry.getValue(), context);
}
write(node, "servers", servers, context);
write(node, "parameters", parameters, context);
}
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/OAuthFlows.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/OAuthFlows.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.Map;
public final class OAuthFlows extends Node<OAuthFlows> {
private OAuthFlow implicit;
private OAuthFlow password;
private OAuthFlow clientCredentials;
private OAuthFlow authorizationCode;
public OAuthFlow getImplicit() {
return implicit;
}
public OAuthFlows setImplicit(OAuthFlow implicit) {
this.implicit = implicit;
return this;
}
public OAuthFlow getPassword() {
return password;
}
public OAuthFlows setPassword(OAuthFlow password) {
this.password = password;
return this;
}
public OAuthFlow getClientCredentials() {
return clientCredentials;
}
public OAuthFlows setClientCredentials(OAuthFlow clientCredentials) {
this.clientCredentials = clientCredentials;
return this;
}
public OAuthFlow getAuthorizationCode() {
return authorizationCode;
}
public OAuthFlows setAuthorizationCode(OAuthFlow authorizationCode) {
this.authorizationCode = authorizationCode;
return this;
}
@Override
public OAuthFlows clone() {
OAuthFlows clone = super.clone();
clone.implicit = clone(implicit);
clone.password = clone(password);
clone.clientCredentials = clone(clientCredentials);
clone.authorizationCode = clone(authorizationCode);
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "implicit", implicit);
write(node, "password", password);
write(node, "clientCredentials", clientCredentials);
write(node, "authorizationCode", authorizationCode);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Operation.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Operation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.openapi.model;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Constants;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.model.Parameter.In;
import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public final class Operation extends Node<Operation> {
private Set<String> tags;
private String summary;
private String description;
private ExternalDocs externalDocs;
private String operationId;
private List<Parameter> parameters;
private RequestBody requestBody;
private Map<String, ApiResponse> responses;
private Boolean deprecated;
private List<SecurityRequirement> security;
private List<Server> servers;
private String group;
private String version;
private HttpMethods httpMethod;
private transient MethodMeta meta;
public Set<String> getTags() {
return tags;
}
public Operation setTags(Set<String> tags) {
this.tags = tags;
return this;
}
public Operation addTag(String tag) {
if (tags == null) {
tags = new LinkedHashSet<>();
}
tags.add(tag);
return this;
}
public Operation removeTag(String tag) {
if (tags != null) {
tags.remove(tag);
}
return this;
}
public String getSummary() {
return summary;
}
public Operation setSummary(String summary) {
this.summary = summary;
return this;
}
public String getDescription() {
return description;
}
public Operation setDescription(String description) {
this.description = description;
return this;
}
public ExternalDocs getExternalDocs() {
return externalDocs;
}
public Operation setExternalDocs(ExternalDocs externalDocs) {
this.externalDocs = externalDocs;
return this;
}
public String getOperationId() {
return operationId;
}
public Operation setOperationId(String operationId) {
this.operationId = operationId;
return this;
}
public List<Parameter> getParameters() {
return parameters;
}
public Parameter getParameter(String name, In in) {
if (parameters == null || name == null || in == null) {
return null;
}
for (int i = 0, size = parameters.size(); i < size; i++) {
Parameter parameter = parameters.get(i);
if (name.equals(parameter.getName()) && in == parameter.getIn()) {
return parameter;
}
}
return null;
}
public Operation setParameters(List<Parameter> parameters) {
this.parameters = parameters;
return this;
}
public Operation addParameter(Parameter parameter) {
if (parameters == null) {
parameters = new ArrayList<>();
}
parameters.add(parameter);
return this;
}
public Operation removeParameter(Parameter parameter) {
if (parameters != null) {
parameters.remove(parameter);
}
return this;
}
public RequestBody getRequestBody() {
return requestBody;
}
public Operation setRequestBody(RequestBody requestBody) {
this.requestBody = requestBody;
return this;
}
public Map<String, ApiResponse> getResponses() {
return responses;
}
public ApiResponse getResponse(String httpStatusCode) {
return responses == null ? null : responses.get(httpStatusCode);
}
public ApiResponse getOrAddResponse(String httpStatusCode) {
if (responses == null) {
responses = new LinkedHashMap<>();
}
return responses.computeIfAbsent(httpStatusCode, k -> new ApiResponse());
}
public Operation setResponses(Map<String, ApiResponse> responses) {
this.responses = responses;
return this;
}
public Operation addResponse(String name, ApiResponse response) {
if (responses == null) {
responses = new LinkedHashMap<>();
}
responses.put(name, response);
return this;
}
public Operation removeResponse(String name) {
if (responses != null) {
responses.remove(name);
}
return this;
}
public Boolean getDeprecated() {
return deprecated;
}
public Operation setDeprecated(Boolean deprecated) {
this.deprecated = deprecated;
return this;
}
public List<SecurityRequirement> getSecurity() {
return security;
}
public Operation setSecurity(List<SecurityRequirement> security) {
this.security = security;
return this;
}
public Operation addSecurity(SecurityRequirement security) {
if (this.security == null) {
this.security = new ArrayList<>();
}
this.security.add(security);
return this;
}
public Operation removeSecurity(SecurityRequirement security) {
if (this.security != null) {
this.security.remove(security);
}
return this;
}
public List<Server> getServers() {
return servers;
}
public Operation setServers(List<Server> servers) {
this.servers = servers;
return this;
}
public Operation addServer(Server server) {
if (servers == null) {
servers = new ArrayList<>();
}
servers.add(server);
return this;
}
public Operation removeServer(Server server) {
if (servers != null) {
servers.remove(server);
}
return this;
}
public String getGroup() {
return group;
}
public Operation setGroup(String group) {
this.group = group;
return this;
}
public String getVersion() {
return version;
}
public Operation setVersion(String version) {
this.version = version;
return this;
}
public HttpMethods getHttpMethod() {
return httpMethod;
}
public Operation setHttpMethod(HttpMethods httpMethod) {
this.httpMethod = httpMethod;
return this;
}
public MethodMeta getMeta() {
return meta;
}
public Operation setMeta(MethodMeta meta) {
this.meta = meta;
return this;
}
@Override
public Operation clone() {
Operation clone = super.clone();
if (tags != null) {
clone.tags = new LinkedHashSet<>(tags);
}
clone.externalDocs = clone(externalDocs);
clone.parameters = clone(parameters);
clone.requestBody = clone(requestBody);
clone.responses = clone(responses);
clone.security = clone(security);
clone.servers = clone(servers);
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "tags", tags);
write(node, "summary", summary);
write(node, "description", description);
write(node, "externalDocs", externalDocs, context);
write(node, "operationId", operationId);
write(node, "parameters", parameters, context);
write(node, "requestBody", requestBody, context);
write(node, "responses", responses, context);
write(node, "deprecated", deprecated);
write(node, "security", security, context);
write(node, "servers", servers, context);
writeExtensions(node);
write(node, Constants.X_JAVA_CLASS, meta.getServiceMeta().getServiceInterface());
write(node, Constants.X_JAVA_METHOD, meta.getMethod().getName());
write(node, Constants.X_JAVA_METHOD_DESCRIPTOR, TypeUtils.getMethodDescriptor(meta));
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/ExternalDocs.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/ExternalDocs.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.Map;
public final class ExternalDocs extends Node<ExternalDocs> {
private String description;
private String url;
public String getDescription() {
return description;
}
public ExternalDocs setDescription(String description) {
this.description = description;
return this;
}
public String getUrl() {
return url;
}
public ExternalDocs setUrl(String url) {
this.url = url;
return this;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "description", description);
write(node, "url", url);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Example.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Example.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.Map;
public final class Example extends Node<Example> {
private String summary;
private String description;
private Object value;
private String externalValue;
public String getSummary() {
return summary;
}
public Example setSummary(String summary) {
this.summary = summary;
return this;
}
public String getDescription() {
return description;
}
public Example setDescription(String description) {
this.description = description;
return this;
}
public Object getValue() {
return value;
}
public Example setValue(Object value) {
this.value = value;
return this;
}
public String getExternalValue() {
return externalValue;
}
public Example setExternalValue(String externalValue) {
this.externalValue = externalValue;
return this;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> exampleNode, Context context) {
write(exampleNode, "summary", summary);
write(exampleNode, "description", description);
write(exampleNode, "value", value);
write(exampleNode, "externalValue", externalValue);
writeExtensions(exampleNode);
return exampleNode;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/SecurityScheme.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/SecurityScheme.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.Map;
public final class SecurityScheme extends Node<SecurityScheme> {
public enum Type {
APIKEY("apiKey"),
HTTP("http"),
OAUTH2("oauth2"),
MUTUAL_TLS("mutualTLS"),
OPEN_ID_CONNECT("openIdConnect");
private final String value;
Type(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
public enum In {
COOKIE("cookie"),
HEADER("header"),
QUERY("query");
private final String value;
In(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
private Type type;
private String description;
private String name;
private In in;
private String scheme;
private String bearerFormat;
private OAuthFlows flows;
private String openIdConnectUrl;
public Type getType() {
return type;
}
public SecurityScheme setType(Type type) {
this.type = type;
return this;
}
public String getDescription() {
return description;
}
public SecurityScheme setDescription(String description) {
this.description = description;
return this;
}
public String getName() {
return name;
}
public SecurityScheme setName(String name) {
this.name = name;
return this;
}
public In getIn() {
return in;
}
public SecurityScheme setIn(In in) {
this.in = in;
return this;
}
public String getScheme() {
return scheme;
}
public SecurityScheme setScheme(String scheme) {
this.scheme = scheme;
return this;
}
public String getBearerFormat() {
return bearerFormat;
}
public SecurityScheme setBearerFormat(String bearerFormat) {
this.bearerFormat = bearerFormat;
return this;
}
public OAuthFlows getFlows() {
return flows;
}
public SecurityScheme setFlows(OAuthFlows flows) {
this.flows = flows;
return this;
}
public String getOpenIdConnectUrl() {
return openIdConnectUrl;
}
public SecurityScheme setOpenIdConnectUrl(String openIdConnectUrl) {
this.openIdConnectUrl = openIdConnectUrl;
return this;
}
@Override
public SecurityScheme clone() {
SecurityScheme clone = super.clone();
clone.flows = clone(flows);
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
if (type == null) {
return node;
}
write(node, "type", type.toString());
write(node, "description", description);
write(node, "name", name);
if (in != null) {
write(node, "in", in.toString());
}
write(node, "scheme", scheme);
write(node, "bearerFormat", bearerFormat);
write(node, "flows", flows, context);
write(node, "openIdConnectUrl", openIdConnectUrl);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Components.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Components.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public final class Components extends Node<Components> {
private Map<String, Schema> schemas;
private Map<String, SecurityScheme> securitySchemes;
public Map<String, Schema> getSchemas() {
return schemas;
}
public Components setSchemas(Map<String, Schema> schemas) {
this.schemas = schemas;
return this;
}
public Components addSchema(String name, Schema schema) {
if (schemas == null) {
schemas = new TreeMap<>();
}
schemas.put(name, schema);
return this;
}
public Components removeSchema(String name) {
if (schemas != null) {
schemas.remove(name);
}
return this;
}
public Map<String, SecurityScheme> getSecuritySchemes() {
return securitySchemes;
}
public Components setSecuritySchemes(Map<String, SecurityScheme> securitySchemes) {
this.securitySchemes = securitySchemes;
return this;
}
public Components addSecurityScheme(String name, SecurityScheme securityScheme) {
if (securitySchemes == null) {
securitySchemes = new LinkedHashMap<>();
}
securitySchemes.put(name, securityScheme);
return this;
}
public Components removeSecurityScheme(String name) {
if (securitySchemes != null) {
securitySchemes.remove(name);
}
return this;
}
@Override
public Components clone() {
Components clone = super.clone();
clone.schemas = clone(schemas);
clone.securitySchemes = clone(securitySchemes);
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "schemas", schemas, context);
write(node, "securitySchemes", securitySchemes, context);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Encoding.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Encoding.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.LinkedHashMap;
import java.util.Map;
public final class Encoding extends Node<Encoding> {
public enum Style {
FORM("form"),
SPACE_DELIMITED("spaceDelimited"),
PIPE_DELIMITED("pipeDelimited"),
DEEP_OBJECT("deepObject");
private final String value;
Style(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
private String contentType;
private Map<String, Parameter> headers;
private Style style;
private Boolean explode;
private Boolean allowReserved;
public String getContentType() {
return contentType;
}
public Encoding setContentType(String contentType) {
this.contentType = contentType;
return this;
}
public Map<String, Parameter> getHeaders() {
return headers;
}
public Parameter getHeader(String name) {
return headers == null ? null : headers.get(name);
}
public Encoding setHeaders(Map<String, Parameter> headers) {
this.headers = headers;
return this;
}
public Encoding addHeader(String name, Parameter header) {
if (headers == null) {
headers = new LinkedHashMap<>();
}
headers.put(name, header);
return this;
}
public Encoding removeHeader(String name) {
if (headers != null) {
headers.remove(name);
}
return this;
}
public Style getStyle() {
return style;
}
public Encoding setStyle(Style style) {
this.style = style;
return this;
}
public Boolean getExplode() {
return explode;
}
public Encoding setExplode(Boolean explode) {
this.explode = explode;
return this;
}
public Boolean getAllowReserved() {
return allowReserved;
}
public Encoding setAllowReserved(Boolean allowReserved) {
this.allowReserved = allowReserved;
return this;
}
@Override
public Encoding clone() {
Encoding clone = super.clone();
clone.headers = clone(headers);
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> encoding, Context context) {
write(encoding, "contentType", contentType);
write(encoding, "headers", headers, context);
write(encoding, "style", style);
write(encoding, "explode", explode);
write(encoding, "allowReserved", allowReserved);
writeExtensions(encoding);
return encoding;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Tag.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Tag.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.Map;
public final class Tag extends Node<Tag> {
private String name;
private String description;
private ExternalDocs externalDocs;
public String getName() {
return name;
}
public Tag setName(String name) {
this.name = name;
return this;
}
public String getDescription() {
return description;
}
public Tag setDescription(String description) {
this.description = description;
return this;
}
public ExternalDocs getExternalDocs() {
return externalDocs;
}
public Tag setExternalDocs(ExternalDocs externalDocs) {
this.externalDocs = externalDocs;
return this;
}
@Override
public Tag clone() {
Tag clone = super.clone();
clone.externalDocs = clone(externalDocs);
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
node.put("name", name);
node.put("description", description);
write(node, "externalDocs", externalDocs, context);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/ApiResponse.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/ApiResponse.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.LinkedHashMap;
import java.util.Map;
public final class ApiResponse extends Node<ApiResponse> {
private String ref;
private String description;
private Map<String, Header> headers;
private Map<String, MediaType> contents;
public String getRef() {
return ref;
}
public ApiResponse setRef(String ref) {
this.ref = ref;
return this;
}
public String getDescription() {
return description;
}
public ApiResponse setDescription(String description) {
this.description = description;
return this;
}
public Map<String, Header> getHeaders() {
return headers;
}
public Header getHeader(String name) {
return headers == null ? null : headers.get(name);
}
public ApiResponse setHeaders(Map<String, Header> headers) {
this.headers = headers;
return this;
}
public ApiResponse addHeader(String name, Header header) {
if (headers == null) {
headers = new LinkedHashMap<>();
}
headers.put(name, header);
return this;
}
public ApiResponse removeHeader(String name) {
if (headers != null) {
headers.remove(name);
}
return this;
}
public Map<String, MediaType> getContents() {
return contents;
}
public MediaType getContent(String name) {
return contents == null ? null : contents.get(name);
}
public MediaType getOrAddContent(String name) {
if (contents == null) {
contents = new LinkedHashMap<>();
}
return contents.computeIfAbsent(name, k -> new MediaType());
}
public ApiResponse setContents(Map<String, MediaType> contents) {
this.contents = contents;
return this;
}
public ApiResponse addContent(String name, MediaType content) {
if (contents == null) {
contents = new LinkedHashMap<>();
}
contents.put(name, content);
return this;
}
public ApiResponse removeContent(String name) {
if (contents != null) {
contents.remove(name);
}
return this;
}
@Override
public ApiResponse clone() {
ApiResponse clone = super.clone();
clone.contents = clone(contents);
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "description", description);
write(node, "content", contents, context);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Contact.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Contact.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.Map;
public final class Contact extends Node<Contact> {
private String name;
private String url;
private String email;
public String getName() {
return name;
}
public Contact setName(String name) {
this.name = name;
return this;
}
public String getUrl() {
return url;
}
public Contact setUrl(String url) {
this.url = url;
return this;
}
public String getEmail() {
return email;
}
public Contact setEmail(String email) {
this.email = email;
return this;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "name", name);
write(node, "url", url);
write(node, "email", email);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/OpenAPI.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/OpenAPI.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.rest.openapi.model;
import org.apache.dubbo.config.nested.OpenAPIConfig;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ServiceMeta;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Constants;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
public final class OpenAPI extends Node<OpenAPI> {
private String openapi;
private Info info;
private List<Server> servers;
private Map<String, PathItem> paths;
private Components components;
private List<SecurityRequirement> security;
private List<Tag> tags;
private ExternalDocs externalDocs;
private String group;
private int priority;
private transient OpenAPIConfig globalConfig;
private transient OpenAPIConfig config;
private transient ServiceMeta meta;
public String getOpenapi() {
return openapi;
}
public OpenAPI setOpenapi(String openapi) {
this.openapi = openapi;
return this;
}
public Info getInfo() {
return info;
}
public OpenAPI setInfo(Info info) {
this.info = info;
return this;
}
public List<Server> getServers() {
return servers;
}
public OpenAPI setServers(List<Server> servers) {
this.servers = servers;
return this;
}
public OpenAPI addServer(Server server) {
List<Server> thisServers = servers;
if (thisServers == null) {
servers = thisServers = new ArrayList<>();
} else {
for (int i = 0, size = thisServers.size(); i < size; i++) {
if (thisServers.get(i).getUrl().equals(server.getUrl())) {
return this;
}
}
}
thisServers.add(server);
return this;
}
public OpenAPI removeServer(Server server) {
if (servers != null) {
servers.remove(server);
}
return this;
}
public Map<String, PathItem> getPaths() {
return paths;
}
public PathItem getPath(String path) {
return paths == null ? null : paths.get(path);
}
public PathItem getOrAddPath(String path) {
if (paths == null) {
paths = new LinkedHashMap<>();
}
return paths.computeIfAbsent(path, k -> new PathItem());
}
public OpenAPI setPaths(Map<String, PathItem> paths) {
this.paths = paths;
return this;
}
public OpenAPI addPath(String path, PathItem pathItem) {
if (paths == null) {
paths = new LinkedHashMap<>();
}
paths.put(path, pathItem);
return this;
}
public OpenAPI removePath(String path) {
if (paths != null) {
paths.remove(path);
}
return this;
}
public Components getComponents() {
return components;
}
public OpenAPI setComponents(Components components) {
this.components = components;
return this;
}
public List<SecurityRequirement> getSecurity() {
return security;
}
public OpenAPI setSecurity(List<SecurityRequirement> security) {
this.security = security;
return this;
}
public OpenAPI addSecurity(SecurityRequirement securityRequirement) {
if (security == null) {
security = new ArrayList<>();
}
security.add(securityRequirement);
return this;
}
public List<Tag> getTags() {
return tags;
}
public OpenAPI setTags(List<Tag> tags) {
this.tags = tags;
return this;
}
public OpenAPI addTag(Tag tag) {
List<Tag> thisTags = tags;
if (thisTags == null) {
tags = thisTags = new ArrayList<>();
} else {
for (int i = 0, size = thisTags.size(); i < size; i++) {
if (thisTags.get(i).getName().equals(tag.getName())) {
return this;
}
}
}
thisTags.add(tag);
return this;
}
public OpenAPI removeTag(Tag tag) {
if (tags != null) {
tags.remove(tag);
}
return this;
}
public ExternalDocs getExternalDocs() {
return externalDocs;
}
public OpenAPI setExternalDocs(ExternalDocs externalDocs) {
this.externalDocs = externalDocs;
return this;
}
public String getGroup() {
return group;
}
public OpenAPI setGroup(String group) {
this.group = group;
return this;
}
public int getPriority() {
return priority;
}
public OpenAPI setPriority(int priority) {
this.priority = priority;
return this;
}
public OpenAPIConfig getGlobalConfig() {
return globalConfig;
}
public OpenAPI setGlobalConfig(OpenAPIConfig globalConfig) {
this.globalConfig = globalConfig;
return this;
}
public OpenAPIConfig getConfig() {
return config;
}
public OpenAPI setConfig(OpenAPIConfig config) {
this.config = config;
return this;
}
public <T> T getConfigValue(Function<OpenAPIConfig, T> fn) {
if (config != null) {
T value = fn.apply(config);
if (value != null) {
return value;
}
}
return globalConfig == null ? null : fn.apply(globalConfig);
}
public String getConfigSetting(String key) {
return getConfigValue(config -> config == null ? null : config.getSetting(key));
}
public void walkOperations(Consumer<Operation> consumer) {
Map<String, PathItem> paths = this.paths;
if (paths == null) {
return;
}
for (PathItem pathItem : paths.values()) {
Map<HttpMethods, Operation> operations = pathItem.getOperations();
if (operations != null) {
for (Operation operation : operations.values()) {
consumer.accept(operation);
}
}
}
}
public ServiceMeta getMeta() {
return meta;
}
public OpenAPI setMeta(ServiceMeta meta) {
this.meta = meta;
return this;
}
@Override
public OpenAPI clone() {
OpenAPI clone = super.clone();
clone.info = clone(info);
clone.servers = clone(servers);
clone.paths = clone(paths);
clone.components = clone(components);
clone.security = clone(security);
clone.tags = clone(tags);
clone.externalDocs = clone(externalDocs);
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
node.put("openapi", openapi == null ? Constants.VERSION_30 : openapi);
write(node, "info", info, context);
write(node, "servers", servers, context);
write(node, "paths", paths, context);
write(node, "components", components, context);
write(node, "security", security, context);
write(node, "tags", tags, context);
write(node, "externalDocs", externalDocs, context);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/OAuthFlow.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/OAuthFlow.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.LinkedHashMap;
import java.util.Map;
public final class OAuthFlow extends Node<OAuthFlow> {
private String authorizationUrl;
private String tokenUrl;
private String refreshUrl;
private Map<String, String> scopes;
public String getAuthorizationUrl() {
return authorizationUrl;
}
public OAuthFlow setAuthorizationUrl(String authorizationUrl) {
this.authorizationUrl = authorizationUrl;
return this;
}
public String getTokenUrl() {
return tokenUrl;
}
public OAuthFlow setTokenUrl(String tokenUrl) {
this.tokenUrl = tokenUrl;
return this;
}
public String getRefreshUrl() {
return refreshUrl;
}
public OAuthFlow setRefreshUrl(String refreshUrl) {
this.refreshUrl = refreshUrl;
return this;
}
public Map<String, String> getScopes() {
return scopes;
}
public OAuthFlow setScopes(Map<String, String> scopes) {
this.scopes = scopes;
return this;
}
public OAuthFlow addScope(String name, String description) {
if (scopes == null) {
scopes = new LinkedHashMap<>();
}
scopes.put(name, description);
return this;
}
public void removeScope(String name) {
if (scopes != null) {
scopes.remove(name);
}
}
@Override
public OAuthFlow clone() {
OAuthFlow clone = super.clone();
if (scopes != null) {
clone.scopes = new LinkedHashMap<>(scopes);
}
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "authorizationUrl", authorizationUrl);
write(node, "tokenUrl", tokenUrl);
write(node, "refreshUrl", refreshUrl);
write(node, "scopes", scopes);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Discriminator.java | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/model/Discriminator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.openapi.model;
import org.apache.dubbo.rpc.protocol.tri.rest.openapi.Context;
import java.util.LinkedHashMap;
import java.util.Map;
public final class Discriminator extends Node<Discriminator> {
private String propertyName;
private Map<String, String> mapping;
public String getPropertyName() {
return propertyName;
}
public Discriminator setPropertyName(String propertyName) {
this.propertyName = propertyName;
return this;
}
public Map<String, String> getMapping() {
return mapping;
}
public Discriminator setMapping(Map<String, String> mapping) {
this.mapping = mapping;
return this;
}
public Discriminator addMapping(String key, String value) {
if (mapping == null) {
mapping = new LinkedHashMap<>();
}
mapping.put(key, value);
return this;
}
public Discriminator removeMapping(String key) {
if (mapping != null) {
mapping.remove(key);
}
return this;
}
@Override
public Discriminator clone() {
Discriminator clone = super.clone();
if (mapping != null) {
clone.setMapping(new LinkedHashMap<>(mapping));
}
return clone;
}
@Override
public Map<String, Object> writeTo(Map<String, Object> node, Context context) {
write(node, "propertyName", propertyName);
write(node, "mapping", mapping);
writeExtensions(node);
return node;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/JsonSchemaTypeTest.java | dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/JsonSchemaTypeTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.mcp;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class JsonSchemaTypeTest {
@Test
void testBooleanTypes() {
assertEquals("boolean", JsonSchemaType.BOOLEAN.getJsonSchemaType());
assertEquals(boolean.class, JsonSchemaType.BOOLEAN.getJavaType());
assertNull(JsonSchemaType.BOOLEAN.getJsonSchemaFormat());
assertEquals("boolean", JsonSchemaType.BOOLEAN_OBJ.getJsonSchemaType());
assertEquals(Boolean.class, JsonSchemaType.BOOLEAN_OBJ.getJavaType());
}
@Test
void testIntegerTypes() {
assertEquals("integer", JsonSchemaType.INT.getJsonSchemaType());
assertEquals(int.class, JsonSchemaType.INT.getJavaType());
assertNull(JsonSchemaType.INT.getJsonSchemaFormat());
assertEquals("integer", JsonSchemaType.LONG.getJsonSchemaType());
assertEquals(long.class, JsonSchemaType.LONG.getJavaType());
assertEquals("int64", JsonSchemaType.LONG.getJsonSchemaFormat());
assertEquals("integer", JsonSchemaType.BIG_INTEGER.getJsonSchemaType());
assertEquals(BigInteger.class, JsonSchemaType.BIG_INTEGER.getJavaType());
assertEquals("int64", JsonSchemaType.BIG_INTEGER.getJsonSchemaFormat());
}
@Test
void testNumberTypes() {
assertEquals("number", JsonSchemaType.FLOAT.getJsonSchemaType());
assertEquals(float.class, JsonSchemaType.FLOAT.getJavaType());
assertEquals("float", JsonSchemaType.FLOAT.getJsonSchemaFormat());
assertEquals("number", JsonSchemaType.DOUBLE.getJsonSchemaType());
assertEquals(double.class, JsonSchemaType.DOUBLE.getJavaType());
assertEquals("double", JsonSchemaType.DOUBLE.getJsonSchemaFormat());
assertEquals("number", JsonSchemaType.BIG_DECIMAL.getJsonSchemaType());
assertEquals(BigDecimal.class, JsonSchemaType.BIG_DECIMAL.getJavaType());
assertNull(JsonSchemaType.BIG_DECIMAL.getJsonSchemaFormat());
}
@Test
void testStringTypes() {
assertEquals("string", JsonSchemaType.STRING.getJsonSchemaType());
assertEquals(String.class, JsonSchemaType.STRING.getJavaType());
assertNull(JsonSchemaType.STRING.getJsonSchemaFormat());
assertEquals("string", JsonSchemaType.CHAR.getJsonSchemaType());
assertEquals(char.class, JsonSchemaType.CHAR.getJavaType());
assertEquals("string", JsonSchemaType.BYTE_ARRAY.getJsonSchemaType());
assertEquals(byte[].class, JsonSchemaType.BYTE_ARRAY.getJavaType());
assertEquals("byte", JsonSchemaType.BYTE_ARRAY.getJsonSchemaFormat());
}
@Test
void testGenericSchemaTypes() {
assertEquals("object", JsonSchemaType.OBJECT_SCHEMA.getJsonSchemaType());
assertNull(JsonSchemaType.OBJECT_SCHEMA.getJavaType());
assertEquals("array", JsonSchemaType.ARRAY_SCHEMA.getJsonSchemaType());
assertNull(JsonSchemaType.ARRAY_SCHEMA.getJavaType());
assertEquals("string", JsonSchemaType.STRING_SCHEMA.getJsonSchemaType());
assertNull(JsonSchemaType.STRING_SCHEMA.getJavaType());
}
@Test
void testDateTimeFormats() {
assertEquals("date", JsonSchemaType.DATE_FORMAT.getJsonSchemaFormat());
assertNull(JsonSchemaType.DATE_FORMAT.getJsonSchemaType());
assertEquals("time", JsonSchemaType.TIME_FORMAT.getJsonSchemaFormat());
assertNull(JsonSchemaType.TIME_FORMAT.getJsonSchemaType());
assertEquals("date-time", JsonSchemaType.DATE_TIME_FORMAT.getJsonSchemaFormat());
assertNull(JsonSchemaType.DATE_TIME_FORMAT.getJsonSchemaType());
}
@Test
void testFromJavaType() {
assertEquals(JsonSchemaType.STRING, JsonSchemaType.fromJavaType(String.class));
assertEquals(JsonSchemaType.INT, JsonSchemaType.fromJavaType(int.class));
assertEquals(JsonSchemaType.INTEGER_OBJ, JsonSchemaType.fromJavaType(Integer.class));
assertEquals(JsonSchemaType.BOOLEAN, JsonSchemaType.fromJavaType(boolean.class));
assertEquals(JsonSchemaType.DOUBLE, JsonSchemaType.fromJavaType(double.class));
assertEquals(JsonSchemaType.BIG_DECIMAL, JsonSchemaType.fromJavaType(BigDecimal.class));
assertNull(JsonSchemaType.fromJavaType(Object.class));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/util/TypeSchemaUtilsTest.java | dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/util/TypeSchemaUtilsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.mcp.util;
import org.apache.dubbo.mcp.JsonSchemaType;
import org.apache.dubbo.mcp.McpConstant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class TypeSchemaUtilsTest {
enum TestEnum {
VALUE1,
VALUE2,
VALUE3
}
@Test
void testResolvePrimitiveTypes() {
TypeSchemaUtils.TypeSchemaInfo intSchema = TypeSchemaUtils.resolveTypeSchema(int.class, int.class, "test int");
assertEquals(JsonSchemaType.INTEGER_SCHEMA.getJsonSchemaType(), intSchema.getType());
assertNull(intSchema.getFormat());
assertEquals("test int", intSchema.getDescription());
TypeSchemaUtils.TypeSchemaInfo longSchema =
TypeSchemaUtils.resolveTypeSchema(long.class, long.class, "test long");
assertEquals(JsonSchemaType.INTEGER_SCHEMA.getJsonSchemaType(), longSchema.getType());
assertEquals("int64", longSchema.getFormat());
TypeSchemaUtils.TypeSchemaInfo doubleSchema =
TypeSchemaUtils.resolveTypeSchema(double.class, double.class, "test double");
assertEquals(JsonSchemaType.NUMBER_SCHEMA.getJsonSchemaType(), doubleSchema.getType());
assertEquals("double", doubleSchema.getFormat());
TypeSchemaUtils.TypeSchemaInfo stringSchema =
TypeSchemaUtils.resolveTypeSchema(String.class, String.class, "test string");
assertEquals(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType(), stringSchema.getType());
assertNull(stringSchema.getFormat());
TypeSchemaUtils.TypeSchemaInfo booleanSchema =
TypeSchemaUtils.resolveTypeSchema(boolean.class, boolean.class, "test boolean");
assertEquals(JsonSchemaType.BOOLEAN_SCHEMA.getJsonSchemaType(), booleanSchema.getType());
}
@Test
void testResolveArrayTypes() {
TypeSchemaUtils.TypeSchemaInfo arraySchema =
TypeSchemaUtils.resolveTypeSchema(int[].class, int[].class, "test array");
assertEquals(JsonSchemaType.ARRAY_SCHEMA.getJsonSchemaType(), arraySchema.getType());
assertNotNull(arraySchema.getItems());
assertEquals(
JsonSchemaType.INTEGER_SCHEMA.getJsonSchemaType(),
arraySchema.getItems().getType());
}
@Test
void testResolveEnumTypes() {
TypeSchemaUtils.TypeSchemaInfo enumSchema =
TypeSchemaUtils.resolveTypeSchema(TestEnum.class, TestEnum.class, "test enum");
assertEquals(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType(), enumSchema.getType());
assertNotNull(enumSchema.getEnumValues());
assertEquals(3, enumSchema.getEnumValues().size());
assertTrue(enumSchema.getEnumValues().contains("VALUE1"));
assertTrue(enumSchema.getEnumValues().contains("VALUE2"));
assertTrue(enumSchema.getEnumValues().contains("VALUE3"));
}
@Test
void testResolveDateTimeTypes() {
TypeSchemaUtils.TypeSchemaInfo dateSchema =
TypeSchemaUtils.resolveTypeSchema(Date.class, Date.class, "test date");
assertEquals(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType(), dateSchema.getType());
assertEquals(JsonSchemaType.DATE_TIME_FORMAT.getJsonSchemaFormat(), dateSchema.getFormat());
TypeSchemaUtils.TypeSchemaInfo localDateSchema =
TypeSchemaUtils.resolveTypeSchema(LocalDate.class, LocalDate.class, "test local date");
assertEquals(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType(), localDateSchema.getType());
assertEquals(JsonSchemaType.DATE_FORMAT.getJsonSchemaFormat(), localDateSchema.getFormat());
TypeSchemaUtils.TypeSchemaInfo localTimeSchema =
TypeSchemaUtils.resolveTypeSchema(LocalTime.class, LocalTime.class, "test local time");
assertEquals(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType(), localTimeSchema.getType());
assertEquals(JsonSchemaType.TIME_FORMAT.getJsonSchemaFormat(), localTimeSchema.getFormat());
TypeSchemaUtils.TypeSchemaInfo localDateTimeSchema =
TypeSchemaUtils.resolveTypeSchema(LocalDateTime.class, LocalDateTime.class, "test local datetime");
assertEquals(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType(), localDateTimeSchema.getType());
assertEquals(JsonSchemaType.DATE_TIME_FORMAT.getJsonSchemaFormat(), localDateTimeSchema.getFormat());
}
@Test
void testResolveCollectionTypes() {
TypeSchemaUtils.TypeSchemaInfo listSchema =
TypeSchemaUtils.resolveTypeSchema(List.class, List.class, "test list");
assertEquals(JsonSchemaType.ARRAY_SCHEMA.getJsonSchemaType(), listSchema.getType());
assertNotNull(listSchema.getItems());
assertEquals(
JsonSchemaType.STRING_SCHEMA.getJsonSchemaType(),
listSchema.getItems().getType());
TypeSchemaUtils.TypeSchemaInfo mapSchema = TypeSchemaUtils.resolveTypeSchema(Map.class, Map.class, "test map");
assertEquals(JsonSchemaType.OBJECT_SCHEMA.getJsonSchemaType(), mapSchema.getType());
assertNotNull(mapSchema.getAdditionalProperties());
assertEquals(
JsonSchemaType.STRING_SCHEMA.getJsonSchemaType(),
mapSchema.getAdditionalProperties().getType());
}
@Test
void testResolveComplexObjectTypes() {
TypeSchemaUtils.TypeSchemaInfo objectSchema =
TypeSchemaUtils.resolveTypeSchema(Object.class, Object.class, "test object");
assertEquals(JsonSchemaType.OBJECT_SCHEMA.getJsonSchemaType(), objectSchema.getType());
// The description includes the provided description plus type information
assertEquals("test object (POJO type: Object)", objectSchema.getDescription());
}
@Test
void testToSchemaMap() {
TypeSchemaUtils.TypeSchemaInfo schemaInfo = TypeSchemaUtils.TypeSchemaInfo.builder()
.type(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType())
.format("email")
.description("Email address")
.build();
Map<String, Object> schemaMap = TypeSchemaUtils.toSchemaMap(schemaInfo);
assertEquals(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType(), schemaMap.get(McpConstant.SCHEMA_PROPERTY_TYPE));
assertEquals("email", schemaMap.get(McpConstant.SCHEMA_PROPERTY_FORMAT));
assertEquals("Email address", schemaMap.get(McpConstant.SCHEMA_PROPERTY_DESCRIPTION));
}
@Test
void testToSchemaMapWithEnumValues() {
List<String> enumValues = new ArrayList<>();
enumValues.add("OPTION1");
enumValues.add("OPTION2");
TypeSchemaUtils.TypeSchemaInfo schemaInfo = TypeSchemaUtils.TypeSchemaInfo.builder()
.type(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType())
.enumValues(enumValues)
.description("Enum field")
.build();
Map<String, Object> schemaMap = TypeSchemaUtils.toSchemaMap(schemaInfo);
assertEquals(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType(), schemaMap.get(McpConstant.SCHEMA_PROPERTY_TYPE));
assertEquals(enumValues, schemaMap.get(McpConstant.SCHEMA_PROPERTY_ENUM));
assertEquals("Enum field", schemaMap.get(McpConstant.SCHEMA_PROPERTY_DESCRIPTION));
}
@Test
void testToSchemaMapWithArrayItems() {
TypeSchemaUtils.TypeSchemaInfo itemSchema = TypeSchemaUtils.TypeSchemaInfo.builder()
.type(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType())
.description("Array item")
.build();
TypeSchemaUtils.TypeSchemaInfo arraySchema = TypeSchemaUtils.TypeSchemaInfo.builder()
.type(JsonSchemaType.ARRAY_SCHEMA.getJsonSchemaType())
.items(itemSchema)
.description("Array field")
.build();
Map<String, Object> schemaMap = TypeSchemaUtils.toSchemaMap(arraySchema);
assertEquals(JsonSchemaType.ARRAY_SCHEMA.getJsonSchemaType(), schemaMap.get(McpConstant.SCHEMA_PROPERTY_TYPE));
assertEquals("Array field", schemaMap.get(McpConstant.SCHEMA_PROPERTY_DESCRIPTION));
@SuppressWarnings("unchecked")
Map<String, Object> itemsMap = (Map<String, Object>) schemaMap.get(McpConstant.SCHEMA_PROPERTY_ITEMS);
assertNotNull(itemsMap);
assertEquals(JsonSchemaType.STRING_SCHEMA.getJsonSchemaType(), itemsMap.get(McpConstant.SCHEMA_PROPERTY_TYPE));
}
@Test
void testUtilityMethods() {
assertTrue(TypeSchemaUtils.isPrimitiveType(int.class));
assertTrue(TypeSchemaUtils.isPrimitiveType(String.class));
assertFalse(TypeSchemaUtils.isPrimitiveType(Object.class));
assertEquals(
JsonSchemaType.INTEGER_SCHEMA.getJsonSchemaType(),
TypeSchemaUtils.getPrimitiveJsonSchemaType(int.class));
assertEquals(
JsonSchemaType.STRING_SCHEMA.getJsonSchemaType(),
TypeSchemaUtils.getPrimitiveJsonSchemaType(String.class));
assertEquals("int64", TypeSchemaUtils.getFormatForType(long.class));
assertNull(TypeSchemaUtils.getFormatForType(int.class));
assertTrue(TypeSchemaUtils.isDateTimeType(Date.class));
assertTrue(TypeSchemaUtils.isDateTimeType(LocalDate.class));
assertFalse(TypeSchemaUtils.isDateTimeType(String.class));
assertEquals(
JsonSchemaType.DATE_FORMAT.getJsonSchemaFormat(), TypeSchemaUtils.getDateTimeFormat(LocalDate.class));
assertEquals(
JsonSchemaType.TIME_FORMAT.getJsonSchemaFormat(), TypeSchemaUtils.getDateTimeFormat(LocalTime.class));
assertEquals(
JsonSchemaType.DATE_TIME_FORMAT.getJsonSchemaFormat(),
TypeSchemaUtils.getDateTimeFormat(LocalDateTime.class));
assertEquals(String.class, TypeSchemaUtils.getClassFromType(String.class));
assertEquals(Object.class, TypeSchemaUtils.getClassFromType(Object.class));
assertTrue(TypeSchemaUtils.isPrimitiveOrWrapper(int.class));
assertTrue(TypeSchemaUtils.isPrimitiveOrWrapper(Integer.class));
assertFalse(TypeSchemaUtils.isPrimitiveOrWrapper(Object.class));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/annotations/McpToolTest.java | dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/annotations/McpToolTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.mcp.annotations;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class McpToolTest {
static class TestService {
@McpTool
public void defaultMethod() {}
@McpTool(
enabled = false,
name = "customTool",
description = "Test description",
tags = {"tag1", "tag2"},
priority = 10)
public void customMethod() {}
@McpTool(enabled = true)
public void enabledMethod() {}
public void normalMethod(
@McpToolParam String param1,
@McpToolParam(name = "customParam", description = "Custom param", required = true) String param2) {}
}
@Test
void testMcpToolDefaultValues() throws NoSuchMethodException {
Method method = TestService.class.getMethod("defaultMethod");
McpTool annotation = method.getAnnotation(McpTool.class);
assertNotNull(annotation);
assertTrue(annotation.enabled());
assertEquals("", annotation.name());
assertEquals("", annotation.description());
assertEquals(0, annotation.tags().length);
assertEquals(0, annotation.priority());
}
@Test
void testMcpToolCustomValues() throws NoSuchMethodException {
Method method = TestService.class.getMethod("customMethod");
McpTool annotation = method.getAnnotation(McpTool.class);
assertNotNull(annotation);
assertFalse(annotation.enabled());
assertEquals("customTool", annotation.name());
assertEquals("Test description", annotation.description());
assertEquals(2, annotation.tags().length);
assertEquals("tag1", annotation.tags()[0]);
assertEquals("tag2", annotation.tags()[1]);
assertEquals(10, annotation.priority());
}
@Test
void testMcpToolEnabledTrue() throws NoSuchMethodException {
Method method = TestService.class.getMethod("enabledMethod");
McpTool annotation = method.getAnnotation(McpTool.class);
assertNotNull(annotation);
assertTrue(annotation.enabled());
}
@Test
void testMcpToolParamDefaultValues() throws NoSuchMethodException {
Method method = TestService.class.getMethod("normalMethod", String.class, String.class);
McpToolParam[] paramAnnotations = method.getParameters()[0].getAnnotationsByType(McpToolParam.class);
assertEquals(1, paramAnnotations.length);
McpToolParam annotation = paramAnnotations[0];
assertEquals("", annotation.name());
assertEquals("", annotation.description());
assertFalse(annotation.required());
}
@Test
void testMcpToolParamCustomValues() throws NoSuchMethodException {
Method method = TestService.class.getMethod("normalMethod", String.class, String.class);
McpToolParam[] paramAnnotations = method.getParameters()[1].getAnnotationsByType(McpToolParam.class);
assertEquals(1, paramAnnotations.length);
McpToolParam annotation = paramAnnotations[0];
assertEquals("customParam", annotation.name());
assertEquals("Custom param", annotation.description());
assertTrue(annotation.required());
}
@Test
void testMethodWithoutAnnotation() throws NoSuchMethodException {
Method method = TestService.class.getMethod("normalMethod", String.class, String.class);
McpTool annotation = method.getAnnotation(McpTool.class);
assertNull(annotation);
}
@Test
void testAnnotationPresence() {
assertTrue(McpTool.class.isAnnotationPresent(java.lang.annotation.Documented.class));
assertTrue(McpTool.class.isAnnotationPresent(java.lang.annotation.Retention.class));
assertTrue(McpTool.class.isAnnotationPresent(java.lang.annotation.Target.class));
assertTrue(McpToolParam.class.isAnnotationPresent(java.lang.annotation.Documented.class));
assertTrue(McpToolParam.class.isAnnotationPresent(java.lang.annotation.Retention.class));
assertTrue(McpToolParam.class.isAnnotationPresent(java.lang.annotation.Target.class));
}
@Test
void testAnnotationRetentionAndTarget() {
java.lang.annotation.Retention retention = McpTool.class.getAnnotation(java.lang.annotation.Retention.class);
assertEquals(java.lang.annotation.RetentionPolicy.RUNTIME, retention.value());
java.lang.annotation.Target target = McpTool.class.getAnnotation(java.lang.annotation.Target.class);
assertEquals(1, target.value().length);
assertEquals(java.lang.annotation.ElementType.METHOD, target.value()[0]);
java.lang.annotation.Retention paramRetention =
McpToolParam.class.getAnnotation(java.lang.annotation.Retention.class);
assertEquals(java.lang.annotation.RetentionPolicy.RUNTIME, paramRetention.value());
java.lang.annotation.Target paramTarget = McpToolParam.class.getAnnotation(java.lang.annotation.Target.class);
assertEquals(2, paramTarget.value().length);
assertTrue(java.util.Arrays.asList(paramTarget.value()).contains(java.lang.annotation.ElementType.PARAMETER));
assertTrue(java.util.Arrays.asList(paramTarget.value()).contains(java.lang.annotation.ElementType.FIELD));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/core/McpApplicationDeployListenerTest.java | dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/core/McpApplicationDeployListenerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.mcp.core;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.jupiter.api.Assertions.*;
class McpApplicationDeployListenerTest {
@Mock
private ApplicationModel applicationModel;
private McpApplicationDeployListener listener;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
listener = new McpApplicationDeployListener();
}
@Test
void testOnInitialize() {
assertDoesNotThrow(() -> listener.onInitialize(applicationModel));
}
@Test
void testOnStarting() {
assertDoesNotThrow(() -> listener.onStarting(applicationModel));
}
@Test
void testOnStarted_WithNullModel() {
assertDoesNotThrow(() -> listener.onStarted(null));
}
@Test
void testOnStarted_WithMockModel() {
assertThrows(NullPointerException.class, () -> listener.onStarted(applicationModel));
}
@Test
void testOnStopping() {
assertDoesNotThrow(() -> listener.onStopping(applicationModel));
}
@Test
void testOnStopped() {
assertDoesNotThrow(() -> listener.onStopped(applicationModel));
}
@Test
void testOnFailure() {
Throwable cause = new RuntimeException("Test failure");
assertDoesNotThrow(() -> listener.onFailure(applicationModel, cause));
}
@Test
void testGetDubboMcpSseTransportProvider() {
assertDoesNotThrow(() -> McpApplicationDeployListener.getDubboMcpSseTransportProvider());
}
@Test
void testListenerCreation() {
McpApplicationDeployListener newListener = new McpApplicationDeployListener();
assertNotNull(newListener);
}
@Test
void testBasicLifecycleMethods() {
assertDoesNotThrow(() -> {
listener.onInitialize(applicationModel);
listener.onStarting(applicationModel);
listener.onStopping(applicationModel);
listener.onStopped(applicationModel);
listener.onFailure(applicationModel, new Exception("test"));
});
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/core/McpServiceExportListenerTest.java | dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/core/McpServiceExportListenerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.mcp.core;
import org.apache.dubbo.config.ServiceConfig;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class McpServiceExportListenerTest {
@Mock
private ServiceConfig serviceConfig;
private McpServiceExportListener listener;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
listener = new McpServiceExportListener();
}
@Test
void testExported_WithNullRef() {
when(serviceConfig.getRef()).thenReturn(null);
listener.exported(serviceConfig);
verify(serviceConfig).getRef();
verify(serviceConfig, never()).getUniqueServiceName();
}
@Test
void testUnexported_WithNullRef() {
when(serviceConfig.getRef()).thenReturn(null);
listener.unexported(serviceConfig);
verify(serviceConfig).getRef();
verify(serviceConfig, never()).getUniqueServiceName();
}
@Test
void testExported_WithValidRef() {
Object serviceRef = new TestService();
when(serviceConfig.getRef()).thenReturn(serviceRef);
when(serviceConfig.getUniqueServiceName()).thenReturn("test.service");
assertDoesNotThrow(() -> listener.exported(serviceConfig));
verify(serviceConfig).getRef();
verify(serviceConfig).getUniqueServiceName();
}
@Test
void testUnexported_WithValidRef() {
Object serviceRef = new TestService();
when(serviceConfig.getRef()).thenReturn(serviceRef);
when(serviceConfig.getUniqueServiceName()).thenReturn("test.service");
assertDoesNotThrow(() -> listener.unexported(serviceConfig));
verify(serviceConfig).getRef();
verify(serviceConfig).getUniqueServiceName();
}
@Test
void testExported_WithException() {
when(serviceConfig.getRef()).thenReturn(new TestService());
when(serviceConfig.getUniqueServiceName()).thenThrow(new RuntimeException("Test exception"));
assertDoesNotThrow(() -> listener.exported(serviceConfig));
verify(serviceConfig).getRef();
verify(serviceConfig).getUniqueServiceName();
}
@Test
void testUnexported_WithException() {
when(serviceConfig.getRef()).thenReturn(new TestService());
when(serviceConfig.getUniqueServiceName()).thenThrow(new RuntimeException("Test exception"));
assertDoesNotThrow(() -> listener.unexported(serviceConfig));
verify(serviceConfig).getRef();
verify(serviceConfig).getUniqueServiceName();
}
@Test
void testListenerCreation() {
McpServiceExportListener newListener = new McpServiceExportListener();
assertNotNull(newListener);
}
public static class TestService {
public void testMethod() {
// Test method
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/core/McpServiceFilterTest.java | dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/core/McpServiceFilterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.mcp.core;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.mcp.annotations.McpTool;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.lang.reflect.Method;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.jupiter.api.Assertions.*;
class McpServiceFilterTest {
@Mock
private ApplicationModel applicationModel;
private McpServiceFilter mcpServiceFilter;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
try {
mcpServiceFilter = new McpServiceFilter(ApplicationModel.defaultModel());
} catch (Exception e) {
mcpServiceFilter = null;
}
}
@Test
void testMcpToolConfig_SettersAndGetters() {
McpServiceFilter.McpToolConfig config = new McpServiceFilter.McpToolConfig();
config.setToolName("testTool");
assertEquals("testTool", config.getToolName());
config.setDescription("Test description");
assertEquals("Test description", config.getDescription());
config.setPriority(10);
assertEquals(10, config.getPriority());
}
@Test
void testMcpToolConfig_DefaultValues() {
McpServiceFilter.McpToolConfig config = new McpServiceFilter.McpToolConfig();
assertNull(config.getToolName());
assertNull(config.getDescription());
assertEquals(0, config.getPriority());
}
@Test
void testTestServiceAnnotations() throws NoSuchMethodException {
Class<?> testServiceClass = TestServiceImpl.class;
assertTrue(testServiceClass.isAnnotationPresent(DubboService.class));
Method annotatedMethod = testServiceClass.getMethod("annotatedMethod");
assertTrue(annotatedMethod.isAnnotationPresent(McpTool.class));
McpTool mcpTool = annotatedMethod.getAnnotation(McpTool.class);
assertEquals("customTool", mcpTool.name());
assertEquals("Custom tool description", mcpTool.description());
assertEquals(5, mcpTool.priority());
}
@Test
void testDisabledMethodAnnotation() throws NoSuchMethodException {
Method disabledMethod = TestServiceImpl.class.getMethod("disabledMethod");
assertTrue(disabledMethod.isAnnotationPresent(McpTool.class));
McpTool mcpTool = disabledMethod.getAnnotation(McpTool.class);
assertFalse(mcpTool.enabled());
}
@Test
void testPublicMethodExists() throws NoSuchMethodException {
Method publicMethod = TestServiceImpl.class.getMethod("publicMethod");
assertNotNull(publicMethod);
assertTrue(java.lang.reflect.Modifier.isPublic(publicMethod.getModifiers()));
}
@Test
void testServiceImplementsInterface() {
TestServiceImpl impl = new TestServiceImpl();
assertTrue(impl instanceof TestService);
}
@DubboService
public static class TestServiceImpl implements TestService {
public void publicMethod() {}
@McpTool(name = "customTool", description = "Custom tool description", priority = 5)
public void annotatedMethod() {}
@McpTool(enabled = false)
public void disabledMethod() {}
private void privateMethod() {}
}
public interface TestService {
void publicMethod();
void annotatedMethod();
void disabledMethod();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/transport/DubboMcpStreamableTransportProviderTest.java | dubbo-plugin/dubbo-mcp/src/test/java/org/apache/dubbo/mcp/transport/DubboMcpStreamableTransportProviderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.mcp.transport;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.remoting.http12.HttpRequest;
import org.apache.dubbo.remoting.http12.HttpResponse;
import org.apache.dubbo.remoting.http12.HttpStatus;
import org.apache.dubbo.remoting.http12.message.ServerSentEvent;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcServiceContext;
import java.io.ByteArrayInputStream;
import java.util.Collections;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.modelcontextprotocol.spec.McpSchema;
import io.modelcontextprotocol.spec.McpStreamableServerSession;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class DubboMcpStreamableTransportProviderTest {
@Mock
private StreamObserver<ServerSentEvent<byte[]>> responseObserver;
@Mock
private HttpRequest httpRequest;
@Mock
private HttpResponse httpResponse;
@Mock
private McpStreamableServerSession.Factory sessionFactory;
@Mock
private RpcServiceContext rpcServiceContext;
@Mock
private McpStreamableServerSession mockSession;
private MockedStatic<RpcContext> rpcContextMockedStatic;
private DubboMcpStreamableTransportProvider transportProvider;
private final ObjectMapper objectMapper = new ObjectMapper();
@BeforeEach
void setUp() {
rpcContextMockedStatic = mockStatic(RpcContext.class);
rpcContextMockedStatic.when(RpcContext::getServiceContext).thenReturn(rpcServiceContext);
when(rpcServiceContext.getRequest(HttpRequest.class)).thenReturn(httpRequest);
when(rpcServiceContext.getResponse(HttpResponse.class)).thenReturn(httpResponse);
transportProvider = new DubboMcpStreamableTransportProvider(objectMapper);
transportProvider.setSessionFactory(sessionFactory);
}
@Test
void handleRequestHandlesGetRequest() {
when(httpRequest.method()).thenReturn(HttpMethods.GET.name());
when(httpRequest.accept()).thenReturn("text/event-stream");
when(httpRequest.header(DubboMcpStreamableTransportProvider.SESSION_ID_HEADER))
.thenReturn("test-session-id");
transportProvider.handleRequest(responseObserver);
verify(httpRequest, times(1)).method();
// For GET requests, we don't verify onNext because the implementation calls
// session.sendNotification().subscribe() directly
}
@Test
void handleRequestHandlesPostRequest() {
when(httpRequest.method()).thenReturn(HttpMethods.POST.name());
when(httpRequest.accept()).thenReturn("application/json");
when(httpRequest.header(DubboMcpStreamableTransportProvider.SESSION_ID_HEADER))
.thenReturn("test-session-id");
when(httpRequest.inputStream())
.thenReturn(new ByteArrayInputStream(
"{\"jsonrpc\":\"2.0\",\"method\":\"initialize\",\"id\":\"1\"}".getBytes()));
transportProvider.handleRequest(responseObserver);
verify(httpRequest, times(2)).method();
verify(httpResponse).setStatus(anyInt());
}
@Test
void handleRequestHandlesDeleteRequest() {
when(httpRequest.method()).thenReturn(HttpMethods.DELETE.name());
when(httpRequest.header(DubboMcpStreamableTransportProvider.SESSION_ID_HEADER))
.thenReturn("test-session-id");
transportProvider.handleRequest(responseObserver);
verify(httpRequest, times(3)).method();
verify(httpResponse).setStatus(HttpStatus.NOT_FOUND.getCode());
verify(responseObserver).onCompleted();
}
@Test
void handleRequestIgnoresUnsupportedMethods() {
when(httpRequest.method()).thenReturn(HttpMethods.PUT.name());
transportProvider.handleRequest(responseObserver);
verify(httpRequest, times(5)).method();
verify(httpResponse).setStatus(HttpStatus.METHOD_NOT_ALLOWED.getCode());
verify(responseObserver).onError(any());
verify(responseObserver).onCompleted();
}
@Test
void handleGetReturnsBadRequestWhenSessionIdIsMissing() {
when(httpRequest.method()).thenReturn(HttpMethods.GET.name());
when(httpRequest.accept()).thenReturn("text/event-stream");
when(httpRequest.header(DubboMcpStreamableTransportProvider.SESSION_ID_HEADER))
.thenReturn(null);
transportProvider.handleRequest(responseObserver);
verify(httpRequest, times(1)).method();
verify(httpResponse).setStatus(HttpStatus.BAD_REQUEST.getCode());
verify(responseObserver).onError(any());
verify(responseObserver).onCompleted();
}
@Test
void handleGetReturnsNotFoundForUnknownSessionId() {
when(httpRequest.method()).thenReturn(HttpMethods.GET.name());
when(httpRequest.accept()).thenReturn("text/event-stream");
when(httpRequest.header(DubboMcpStreamableTransportProvider.SESSION_ID_HEADER))
.thenReturn("unknownSessionId");
transportProvider.handleRequest(responseObserver);
verify(httpRequest, times(1)).method();
verify(httpResponse).setStatus(HttpStatus.NOT_FOUND.getCode());
verify(responseObserver).onError(any());
verify(responseObserver).onCompleted();
}
@Test
void handleGetWithReplayRequestCallsSessionReplay() throws Exception {
// Create a transport provider subclass for testing to access private methods and fields
DubboMcpStreamableTransportProvider transportProviderUnderTest =
new DubboMcpStreamableTransportProvider(objectMapper);
transportProviderUnderTest.setSessionFactory(sessionFactory);
// Use reflection to put mockSession into the sessions map
java.lang.reflect.Field sessionsField = DubboMcpStreamableTransportProvider.class.getDeclaredField("sessions");
sessionsField.setAccessible(true);
Object sessionsMap = sessionsField.get(transportProviderUnderTest);
// Use reflection to call the put method
java.lang.reflect.Method putMethod = sessionsMap.getClass().getMethod("put", Object.class, Object.class);
putMethod.invoke(sessionsMap, "test-session-id", mockSession);
// Set up mock behavior
when(httpRequest.method()).thenReturn(HttpMethods.GET.name());
when(httpRequest.accept()).thenReturn("text/event-stream");
when(httpRequest.header(DubboMcpStreamableTransportProvider.SESSION_ID_HEADER))
.thenReturn("test-session-id");
when(httpRequest.header("Last-Event-ID")).thenReturn("12345");
// Mock the replay method to return a Flux that emits a test message
McpSchema.JSONRPCNotification testNotification =
new McpSchema.JSONRPCNotification("2.0", "test_method", Collections.singletonMap("key", "value"));
when(mockSession.replay("12345")).thenReturn(reactor.core.publisher.Flux.just(testNotification));
transportProviderUnderTest.handleRequest(responseObserver);
// Verify that the replay method is called
verify(mockSession).replay("12345");
// Verify that the message is sent
verify(responseObserver).onNext(any());
verify(responseObserver).onCompleted();
}
@AfterEach
public void tearDown() {
if (rpcContextMockedStatic != null) {
rpcContextMockedStatic.close();
}
}
}
| 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.