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-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/SpringResponseRestFilter.java
dubbo-plugin/dubbo-rest-spring/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/spring/SpringResponseRestFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.spring; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.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.rpc.Result; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants; import org.apache.dubbo.rpc.protocol.tri.rest.RestException; import org.apache.dubbo.rpc.protocol.tri.rest.argument.ArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.argument.CompositeArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter.Listener; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMapping; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.HandlerMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ResponseMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ServiceMeta; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; @Activate(order = -10000, onClass = "org.springframework.http.ResponseEntity") public class SpringResponseRestFilter implements RestFilter, Listener { private final ArgumentResolver argumentResolver; private final Map<Key, Optional<MethodMeta>> cache = CollectionUtils.newConcurrentHashMap(); public SpringResponseRestFilter(FrameworkModel frameworkModel) { argumentResolver = frameworkModel.getOrRegisterBean(CompositeArgumentResolver.class); } @Override public void onResponse(Result result, HttpRequest request, HttpResponse response) { if (result.hasException()) { HandlerMeta handler = request.attribute(RestConstants.HANDLER_ATTRIBUTE); if (handler == null) { return; } Throwable t = result.getException(); Key key = new Key(handler.getMethod().getMethod(), t.getClass()); cache.computeIfAbsent(key, k -> findSuitableExceptionHandler(handler.getService(), k.type)) .ifPresent(m -> { try { result.setValue(invokeExceptionHandler(m, t, request, response)); result.setException(null); } catch (Throwable th) { result.setException(th); } }); return; } Object value = result.getValue(); if (value instanceof ResponseEntity) { ResponseEntity<?> entity = (ResponseEntity<?>) value; result.setValue(HttpResult.builder() .body(entity.getBody()) .status(Helper.getStatusCode(entity)) .headers(entity.getHeaders()) .build()); return; } RequestMapping mapping = request.attribute(RestConstants.MAPPING_ATTRIBUTE); if (mapping == null) { return; } ResponseMeta responseMeta = mapping.getResponse(); if (responseMeta == null) { return; } String reason = responseMeta.getReason(); result.setValue(HttpResult.builder() .body(reason == null ? result.getValue() : reason) .status(responseMeta.getStatus()) .build()); } private Optional<MethodMeta> findSuitableExceptionHandler(ServiceMeta serviceMeta, Class<?> exType) { if (serviceMeta.getExceptionHandlers() == null) { return Optional.empty(); } List<Pair<Class<?>, MethodMeta>> candidates = new ArrayList<>(); for (MethodMeta methodMeta : serviceMeta.getExceptionHandlers()) { ExceptionHandler anno = methodMeta.getMethod().getAnnotation(ExceptionHandler.class); if (anno == null) { continue; } for (Class<?> type : anno.value()) { if (type.isAssignableFrom(exType)) { candidates.add(Pair.of(type, methodMeta)); } } } int size = candidates.size(); if (size == 0) { return Optional.empty(); } if (size > 1) { candidates.sort((o1, o2) -> { Class<?> c1 = o1.getLeft(); Class<?> c2 = o2.getLeft(); if (c1.equals(c2)) { return 0; } return c1.isAssignableFrom(c2) ? 1 : -1; }); } return Optional.of(candidates.get(0).getRight()); } private Object invokeExceptionHandler(MethodMeta meta, Throwable t, HttpRequest request, HttpResponse response) { ParameterMeta[] parameters = meta.getParameters(); int len = parameters.length; Object[] args = new Object[len]; for (int i = 0; i < len; i++) { ParameterMeta parameter = parameters[i]; if (parameter.getType().isInstance(t)) { args[i] = t; } else { args[i] = argumentResolver.resolve(parameter, request, response); } } Object value; try { value = meta.getMethod().invoke(meta.getServiceMeta().getService(), args); } catch (Exception e) { throw new RestException("Failed to invoke exception handler method: " + meta.getMethod(), e); } AnnotationMeta<?> rs = meta.getAnnotation(ResponseStatus.class); if (rs == null) { return value; } HttpStatus status = rs.getEnum("value"); String reason = rs.getString("reason"); return HttpResult.builder() .body(StringUtils.isEmpty(reason) ? value : reason) .status(status.value()) .build(); } private static final class Key { private final Method method; private final Class<?> type; Key(Method method, Class<?> type) { this.method = method; this.type = type; } @Override @SuppressWarnings({"EqualsWhichDoesntCheckParameterClass", "EqualsDoesntCheckParameterClass"}) public boolean equals(Object obj) { Key other = (Key) obj; return method.equals(other.method) && type.equals(other.type); } @Override public int hashCode() { return method.hashCode() * 31 + type.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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/service/ParamConverterProviderImpl.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/service/ParamConverterProviderImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.service; import org.apache.dubbo.common.utils.StringUtils; import javax.ws.rs.ext.ParamConverter; import javax.ws.rs.ext.ParamConverterProvider; import java.lang.annotation.Annotation; import java.lang.reflect.Type; public class ParamConverterProviderImpl implements ParamConverterProvider { @Override @SuppressWarnings("unchecked") public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) { if (rawType.isAssignableFrom(User.class)) { return (ParamConverter<T>) new UserParamConverter(); } return null; } static final class UserParamConverter implements ParamConverter<User> { @Override public User fromString(String value) { String[] arr = StringUtils.tokenize(value, ','); User user = new User(); if (arr.length > 1) { user.setId(Long.valueOf(arr[0])); user.setName(arr[1]); } return user; } @Override public String toString(User user) { return "User{" + "id=" + user.getId() + ", name='" + user.getName() + "\"}"; } } }
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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/service/UserForm.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/service/UserForm.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.service; import javax.ws.rs.FormParam; import javax.ws.rs.HeaderParam; public class UserForm { @FormParam("first") String firstName; @FormParam("last") String lastName; @HeaderParam("Content-Type") String contentType; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } }
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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/service/User.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/service/User.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.service; import javax.ws.rs.BeanParam; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; public class User { @PathParam("id") private Long id; @QueryParam("name") private String name; @BeanParam private User owner; @BeanParam private UserForm form; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public User getOwner() { return owner; } public void setOwner(User owner) { this.owner = owner; } public UserForm getForm() { return form; } public void setForm(UserForm form) { this.form = form; } }
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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/service/JaxrsDemoServiceImpl.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/service/JaxrsDemoServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.service; import javax.ws.rs.core.MultivaluedMap; public class JaxrsDemoServiceImpl implements JaxrsDemoService { @Override public UserForm formTest(UserForm userForm) { return userForm; } @Override public User getTest(User user) { return user; } @Override public User convertTest(User user) { return user; } @Override public MultivaluedMap<String, Integer> multiValueMapTest(MultivaluedMap<String, Integer> params) { return params; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/service/JaxrsDemoService.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/service/JaxrsDemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.service; import javax.ws.rs.BeanParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MultivaluedMap; import org.jboss.resteasy.annotations.Form; public interface JaxrsDemoService { @POST @Path("/formTest") UserForm formTest(@Form(prefix = "user") UserForm userForm); @POST @Path("/beanTest/{id}") User getTest(@BeanParam User user); @GET @Path("/convertTest") User convertTest(@QueryParam("user") User user); @POST @Path("/multivaluedMapTest") MultivaluedMap<String, Integer> multiValueMapTest(MultivaluedMap<String, Integer> params); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/ResteasyExceptionMapper.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/ResteasyExceptionMapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.compatible; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; public class ResteasyExceptionMapper implements ExceptionMapper<RuntimeException> { @Override public Response toResponse(RuntimeException exception) { return Response.status(200).entity("test-exception").build(); } }
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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/JaxrsRestProtocolTest.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/JaxrsRestProtocolTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.compatible; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.compatible.filter.TestContainerRequestFilter; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.compatible.filter.TraceFilter; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.compatible.filter.TraceRequestAndResponseFilter; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.compatible.intercept.DynamicTraceInterceptor; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.compatible.rest.AnotherUserRestService; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.compatible.rest.AnotherUserRestServiceImpl; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.compatible.rest.HttpMethodService; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.compatible.rest.HttpMethodServiceImpl; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.compatible.rest.RestDemoForTestException; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.compatible.rest.RestDemoService; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.compatible.rest.RestDemoServiceImpl; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import org.hamcrest.CoreMatchers; import org.jboss.resteasy.specimpl.MultivaluedMapImpl; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.apache.dubbo.remoting.Constants.SERVER_KEY; import static org.apache.dubbo.rpc.protocol.tri.rest.RestConstants.EXTENSION_KEY; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @Disabled class JaxrsRestProtocolTest { private final Protocol tProtocol = ApplicationModel.defaultModel().getExtensionLoader(Protocol.class).getExtension("tri"); private final Protocol protocol = ApplicationModel.defaultModel().getExtensionLoader(Protocol.class).getExtension("rest"); private final ProxyFactory proxy = ApplicationModel.defaultModel() .getExtensionLoader(ProxyFactory.class) .getAdaptiveExtension(); private final int availablePort = NetUtils.getAvailablePort(); private final URL exportUrl = URL.valueOf("tri://127.0.0.1:" + availablePort + "/rest?interface=" + DemoService.class.getName()); private static final String SERVER = "netty4"; private final ModuleServiceRepository repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); @AfterEach public void tearDown() { tProtocol.destroy(); protocol.destroy(); FrameworkModel.destroyAll(); } @Test void testRestProtocol() { URL url = URL.valueOf("tri://127.0.0.1:" + NetUtils.getAvailablePort() + "/?version=1.0.0&interface=" + DemoService.class.getName()); DemoServiceImpl server = new DemoServiceImpl(); url = registerProvider(url, server, DemoService.class); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(server, DemoService.class, url)); Invoker<DemoService> invoker = protocol.refer(DemoService.class, url); Assertions.assertFalse(server.isCalled()); DemoService client = proxy.getProxy(invoker); String result = client.sayHello("haha"); Assertions.assertTrue(server.isCalled()); Assertions.assertEquals("Hello, haha", result); String header = client.header("header test"); Assertions.assertEquals("header test", header); Assertions.assertEquals(1, client.headerInt(1)); invoker.destroy(); exporter.unexport(); } @Test void testAnotherUserRestProtocolByDifferentRestClient() { testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.OK_HTTP); testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.APACHE_HTTP_CLIENT); testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.URL_CONNECTION); } void testAnotherUserRestProtocol(String restClient) { URL url = URL.valueOf("tri://127.0.0.1:" + NetUtils.getAvailablePort() + "/?version=1.0.0&interface=" + AnotherUserRestService.class.getName() + "&" + org.apache.dubbo.remoting.Constants.CLIENT_KEY + "=" + restClient); AnotherUserRestServiceImpl server = new AnotherUserRestServiceImpl(); url = this.registerProvider(url, server, AnotherUserRestService.class); Exporter<AnotherUserRestService> exporter = tProtocol.export(proxy.getInvoker(server, AnotherUserRestService.class, url)); Invoker<AnotherUserRestService> invoker = protocol.refer(AnotherUserRestService.class, url); AnotherUserRestService client = proxy.getProxy(invoker); User result = client.getUser(123l); Assertions.assertEquals(123l, result.getId()); result.setName("dubbo"); Assertions.assertEquals(123l, client.registerUser(result).getId()); Assertions.assertEquals("context", client.getContext()); byte[] bytes = {1, 2, 3, 4}; Assertions.assertTrue(Arrays.equals(bytes, client.bytes(bytes))); Assertions.assertEquals(1l, client.number(1l)); HashMap<String, String> map = new HashMap<>(); map.put("headers", "h1"); Assertions.assertEquals("h1", client.headerMap(map)); Assertions.assertEquals(null, client.headerMap(null)); invoker.destroy(); exporter.unexport(); } @Test void testRestProtocolWithContextPath() { DemoServiceImpl server = new DemoServiceImpl(); Assertions.assertFalse(server.isCalled()); int port = NetUtils.getAvailablePort(); URL url = URL.valueOf( "tri://127.0.0.1:" + port + "/a/b/c?version=1.0.0&interface=" + DemoService.class.getName()); url = this.registerProvider(url, server, DemoService.class); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(server, DemoService.class, url)); url = URL.valueOf( "rest://127.0.0.1:" + port + "/a/b/c/?version=1.0.0&interface=" + DemoService.class.getName()); Invoker<DemoService> invoker = protocol.refer(DemoService.class, url); DemoService client = proxy.getProxy(invoker); String result = client.sayHello("haha"); Assertions.assertTrue(server.isCalled()); Assertions.assertEquals("Hello, haha", result); invoker.destroy(); exporter.unexport(); } @Test void testExport() { DemoService server = new DemoServiceImpl(); URL url = this.registerProvider(exportUrl, server, DemoService.class); RpcContext.getClientAttachment().setAttachment("timeout", "20000"); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(server, DemoService.class, url)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, url)); Integer echoString = demoService.hello(1, 2); assertThat(echoString, is(3)); exporter.unexport(); } @Test void testNettyServer() { DemoService server = new DemoServiceImpl(); URL url = this.registerProvider(exportUrl, server, DemoService.class); URL nettyUrl = url.addParameter(SERVER_KEY, SERVER); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); Integer echoString = demoService.hello(10, 10); assertThat(echoString, is(20)); exporter.unexport(); } @Test void testInvoke() { DemoService server = new DemoServiceImpl(); URL url = this.registerProvider(exportUrl, server, DemoService.class); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(server, DemoService.class, url)); RpcInvocation rpcInvocation = new RpcInvocation( "hello", DemoService.class.getName(), "", new Class[] {Integer.class, Integer.class}, new Integer[] { 2, 3 }); rpcInvocation.setTargetServiceUniqueName(url.getServiceKey()); Result result = exporter.getInvoker().invoke(rpcInvocation); assertThat(result.getValue(), CoreMatchers.<Object>is(5)); } @Test void testDefaultPort() { assertThat(protocol.getDefaultPort(), is(80)); } @Test void testRestExceptionMapper() { DemoService server = new DemoServiceImpl(); URL url = this.registerProvider(exportUrl, server, DemoService.class); URL exceptionUrl = url.addParameter(EXTENSION_KEY, ResteasyExceptionMapper.class.getName()); tProtocol.export(proxy.getInvoker(server, DemoService.class, exceptionUrl)); DemoService referDemoService = this.proxy.getProxy(protocol.refer(DemoService.class, exceptionUrl)); Assertions.assertEquals("test-exception", referDemoService.error()); } @Test void testFormConsumerParser() { DemoService server = new DemoServiceImpl(); URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); Long number = demoService.testFormBody(18l); Assertions.assertEquals(18l, number); exporter.unexport(); } @Test void test404() { Assertions.assertThrows(RpcException.class, () -> { DemoService server = new DemoServiceImpl(); URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); URL referUrl = URL.valueOf( "tri://127.0.0.1:" + availablePort + "/rest?interface=" + RestDemoForTestException.class.getName()); RestDemoForTestException restDemoForTestException = this.proxy.getProxy(protocol.refer(RestDemoForTestException.class, referUrl)); restDemoForTestException.test404(); exporter.unexport(); }); } @Test void test400() { Assertions.assertThrows(RpcException.class, () -> { DemoService server = new DemoServiceImpl(); URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); URL referUrl = URL.valueOf( "tri://127.0.0.1:" + availablePort + "/rest?interface=" + RestDemoForTestException.class.getName()); RestDemoForTestException restDemoForTestException = this.proxy.getProxy(protocol.refer(RestDemoForTestException.class, referUrl)); restDemoForTestException.test400("abc", "edf"); exporter.unexport(); }); } @Test void testPrimitive() { DemoService server = new DemoServiceImpl(); URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); Integer result = demoService.primitiveInt(1, 2); Long resultLong = demoService.primitiveLong(1, 2l); long resultByte = demoService.primitiveByte((byte) 1, 2l); long resultShort = demoService.primitiveShort((short) 1, 2l, 1); assertThat(result, is(3)); assertThat(resultShort, is(3l)); assertThat(resultLong, is(3l)); assertThat(resultByte, is(3l)); exporter.unexport(); } @Test void testMapParam() { DemoService server = new DemoServiceImpl(); URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); Map<String, String> params = new HashMap<>(); params.put("param", "P1"); ; Map<String, String> headers = new HashMap<>(); headers.put("header", "H1"); Assertions.assertEquals("P1", demoService.testMapParam(params)); Assertions.assertEquals("H1", demoService.testMapHeader(headers)); MultivaluedMapImpl<String, String> forms = new MultivaluedMapImpl<>(); forms.put("form", Arrays.asList("F1")); Assertions.assertEquals(Arrays.asList("F1"), demoService.testMapForm(forms)); exporter.unexport(); } @Test void testNoArgParam() { DemoService server = new DemoServiceImpl(); URL url = this.registerProvider(exportUrl, server, DemoService.class); URL nettyUrl = url.addParameter(SERVER_KEY, SERVER); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); Assertions.assertEquals(null, demoService.noStringHeader(null)); Assertions.assertEquals(null, demoService.noStringParam(null)); /* Assertions.assertThrows(RpcException.class, () -> { demoService.noIntHeader(1); }); Assertions.assertThrows(RpcException.class, () -> { demoService.noIntParam(1); });*/ Assertions.assertEquals(null, demoService.noBodyArg(null)); exporter.unexport(); } @Test void testHttpMethods() { testHttpMethod(org.apache.dubbo.remoting.Constants.OK_HTTP); testHttpMethod(org.apache.dubbo.remoting.Constants.APACHE_HTTP_CLIENT); testHttpMethod(org.apache.dubbo.remoting.Constants.URL_CONNECTION); } void testHttpMethod(String restClient) { HttpMethodService server = new HttpMethodServiceImpl(); URL url = URL.valueOf("tri://127.0.0.1:" + NetUtils.getAvailablePort() + "/?version=1.0.0&interface=" + HttpMethodService.class.getName() + "&" + org.apache.dubbo.remoting.Constants.CLIENT_KEY + "=" + restClient); url = this.registerProvider(url, server, HttpMethodService.class); Exporter<HttpMethodService> exporter = tProtocol.export(proxy.getInvoker(server, HttpMethodService.class, url)); HttpMethodService demoService = this.proxy.getProxy(protocol.refer(HttpMethodService.class, url)); String expect = "hello"; Assertions.assertEquals(null, demoService.sayHelloHead()); Assertions.assertEquals(expect, demoService.sayHelloDelete("hello")); Assertions.assertEquals(expect, demoService.sayHelloGet("hello")); Assertions.assertEquals(expect, demoService.sayHelloOptions("hello")); // Assertions.assertEquals(expect, demoService.sayHelloPatch("hello")); Assertions.assertEquals(expect, demoService.sayHelloPost("hello")); Assertions.assertEquals(expect, demoService.sayHelloPut("hello")); exporter.unexport(); } @Test void test405() { int availablePort = NetUtils.getAvailablePort(); URL url = URL.valueOf("tri://127.0.0.1:" + availablePort + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoService&"); RestDemoServiceImpl server = new RestDemoServiceImpl(); url = this.registerProvider(url, server, RestDemoService.class); Exporter<RestDemoService> exporter = tProtocol.export(proxy.getInvoker(server, RestDemoService.class, url)); URL consumer = URL.valueOf("rest://127.0.0.1:" + availablePort + "/?version=1.0.0&interface=" + RestDemoForTestException.class.getName()); consumer = this.registerProvider(consumer, server, RestDemoForTestException.class); Invoker<RestDemoForTestException> invoker = protocol.refer(RestDemoForTestException.class, consumer); RestDemoForTestException client = proxy.getProxy(invoker); Assertions.assertThrows(RpcException.class, () -> { client.testMethodDisallowed("aaa"); }); invoker.destroy(); exporter.unexport(); } @Test void testContainerRequestFilter() { DemoService server = new DemoServiceImpl(); URL url = this.registerProvider(exportUrl, server, DemoService.class); URL nettyUrl = url.addParameter(EXTENSION_KEY, TestContainerRequestFilter.class.getName()); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); Assertions.assertEquals("return-success", demoService.sayHello("hello")); exporter.unexport(); } @Test void testIntercept() { DemoService server = new DemoServiceImpl(); URL url = this.registerProvider(exportUrl, server, DemoService.class); URL nettyUrl = url.addParameter(EXTENSION_KEY, DynamicTraceInterceptor.class.getName()); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); Assertions.assertEquals("intercept", demoService.sayHello("hello")); exporter.unexport(); } @Test void testResponseFilter() { DemoService server = new DemoServiceImpl(); URL url = this.registerProvider(exportUrl, server, DemoService.class); URL nettyUrl = url.addParameter(EXTENSION_KEY, TraceFilter.class.getName()); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); Assertions.assertEquals("response-filter", demoService.sayHello("hello")); exporter.unexport(); } @Test void testCollectionResult() { DemoService server = new DemoServiceImpl(); URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); Assertions.assertEquals( User.getInstance(), demoService.list(Arrays.asList(User.getInstance())).get(0)); HashSet<User> objects = new HashSet<>(); objects.add(User.getInstance()); Assertions.assertEquals(User.getInstance(), new ArrayList<>(demoService.set(objects)).get(0)); Assertions.assertEquals(User.getInstance(), demoService.array(objects.toArray(new User[0]))[0]); Map<String, User> map = new HashMap<>(); map.put("map", User.getInstance()); Assertions.assertEquals(User.getInstance(), demoService.stringMap(map).get("map")); // Map<User, User> maps = new HashMap<>(); // maps.put(User.getInstance(), User.getInstance()); // Assertions.assertEquals(User.getInstance(), demoService.userMap(maps).get(User.getInstance())); exporter.unexport(); } @Test void testRequestAndResponseFilter() { DemoService server = new DemoServiceImpl(); URL exportUrl = URL.valueOf("tri://127.0.0.1:" + availablePort + "/rest?interface=" + DemoService.class.getName() + "&extension=" + TraceRequestAndResponseFilter.class.getName()); URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); Assertions.assertEquals("header-result", demoService.sayHello("hello")); exporter.unexport(); } @Test void testFormBody() { DemoService server = new DemoServiceImpl(); URL url = this.registerProvider(exportUrl, server, DemoService.class); URL nettyUrl = url.addParameter(SERVER_KEY, SERVER); Exporter<DemoService> exporter = tProtocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); User user = demoService.formBody(User.getInstance()); Assertions.assertEquals("formBody", user.getName()); exporter.unexport(); } private URL registerProvider(URL url, Object impl, Class<?> interfaceClass) { ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); repository.registerProvider(providerModel); return url.setServiceModel(providerModel); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/DemoServiceImpl.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/DemoServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.compatible; import org.apache.dubbo.rpc.RpcContext; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import java.util.List; import java.util.Map; import java.util.Set; import io.netty.handler.codec.http.DefaultFullHttpRequest; @Path("/demoService") public class DemoServiceImpl implements DemoService { private static Map<String, Object> context; private boolean called; @POST @Path("/say") @Consumes({MediaType.TEXT_PLAIN}) @Override public String sayHello(String name) { called = true; return "Hello, " + name; } @Override public Long testFormBody(Long number) { return number; } public boolean isCalled() { return called; } @Override public int primitiveInt(int a, int b) { return a + b; } @Override public long primitiveLong(long a, Long b) { return a + b; } @Override public long primitiveByte(byte a, Long b) { return a + b; } @Override public long primitiveShort(short a, Long b, int c) { return a + b; } @Override public void request(DefaultFullHttpRequest defaultFullHttpRequest) {} @Override public String testMapParam(Map<String, String> params) { return params.get("param"); } @Override public String testMapHeader(Map<String, String> headers) { return headers.get("header"); } @Override public List<String> testMapForm(MultivaluedMap<String, String> params) { return params.get("form"); } @Override public String header(String header) { return header; } @Override public int headerInt(int header) { return header; } @Override public String noStringParam(String param) { return param; } @Override public String noStringHeader(String header) { return header; } @POST @Path("/noIntHeader") @Consumes({MediaType.TEXT_PLAIN}) @Override public int noIntHeader(@HeaderParam("header") int header) { return header; } @POST @Path("/noIntParam") @Consumes({MediaType.TEXT_PLAIN}) @Override public int noIntParam(@QueryParam("header") int header) { return header; } @Override public User noBodyArg(User user) { return user; } @GET @Path("/hello") @Override public Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b) { context = RpcContext.getServerAttachment().getObjectAttachments(); return a + b; } @GET @Path("/error") @Override public String error() { throw new RuntimeException("test error"); } public static Map<String, Object> getAttachments() { return context; } @Override public List<User> list(List<User> users) { return users; } @Override public Set<User> set(Set<User> users) { return users; } @Override public User[] array(User[] users) { return users; } @Override public Map<String, User> stringMap(Map<String, User> userMap) { return userMap; } @Override public Map<User, User> userMap(Map<User, User> userMap) { return userMap; } @Override public User formBody(User user) { user.setName("formBody"); return user; } }
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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/DemoService.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/DemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.compatible; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import java.util.List; import java.util.Map; import java.util.Set; import io.netty.handler.codec.http.DefaultFullHttpRequest; import org.jboss.resteasy.annotations.Form; @Path("/demoService") public interface DemoService { @GET @Path("/hello") Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b); @GET @Path("/error") @Consumes({MediaType.TEXT_PLAIN}) @Produces({MediaType.TEXT_PLAIN}) String error(); @POST @Path("/say") @Consumes({MediaType.TEXT_PLAIN}) String sayHello(String name); @POST @Path("number") Long testFormBody(@FormParam("number") Long number); boolean isCalled(); @GET @Path("/primitive") int primitiveInt(@QueryParam("a") int a, @QueryParam("b") int b); @GET @Path("/primitiveLong") long primitiveLong(@QueryParam("a") long a, @QueryParam("b") Long b); @GET @Path("/primitiveByte") long primitiveByte(@QueryParam("a") byte a, @QueryParam("b") Long b); @POST @Path("/primitiveShort") long primitiveShort(@QueryParam("a") short a, @QueryParam("b") Long b, int c); @GET @Path("/request") void request(DefaultFullHttpRequest defaultFullHttpRequest); @GET @Path("testMapParam") @Produces({MediaType.TEXT_PLAIN}) @Consumes({MediaType.TEXT_PLAIN}) String testMapParam(@QueryParam("test") Map<String, String> params); @GET @Path("testMapHeader") @Produces({MediaType.TEXT_PLAIN}) @Consumes({MediaType.TEXT_PLAIN}) String testMapHeader(@HeaderParam("test") Map<String, String> headers); @POST @Path("testMapForm") @Produces({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_FORM_URLENCODED}) List<String> testMapForm(MultivaluedMap<String, String> params); @POST @Path("/header") @Consumes({MediaType.TEXT_PLAIN}) String header(@HeaderParam("header") String header); @POST @Path("/headerInt") @Consumes({MediaType.TEXT_PLAIN}) int headerInt(@HeaderParam("header") int header); @POST @Path("/noStringParam") @Consumes({MediaType.TEXT_PLAIN}) String noStringParam(@QueryParam("param") String param); @POST @Path("/noStringHeader") @Consumes({MediaType.TEXT_PLAIN}) String noStringHeader(@HeaderParam("header") String header); @POST @Path("/noIntHeader") @Consumes({MediaType.TEXT_PLAIN}) int noIntHeader(int header); @POST @Path("/noIntParam") @Consumes({MediaType.TEXT_PLAIN}) int noIntParam(int header); @POST @Path("/noBodyArg") @Consumes({MediaType.APPLICATION_JSON}) User noBodyArg(User user); @POST @Path("/list") List<User> list(List<User> users); @POST @Path("/set") Set<User> set(Set<User> users); @POST @Path("/array") User[] array(User[] users); @POST @Path("/stringMap") Map<String, User> stringMap(Map<String, User> userMap); @POST @Path("/map") Map<User, User> userMap(Map<User, User> userMap); @POST @Path("/formBody") User formBody(@Form User user); }
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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/User.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/User.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.compatible; import java.io.Serializable; import java.util.Objects; /** * User Entity * * @since 2.7.6 */ public class User implements Serializable { private Long id; private String name; private Integer age; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public static User getInstance() { User user = new User(); user.setAge(18); user.setName("dubbo"); user.setId(404l); return user; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } User user = (User) o; return Objects.equals(id, user.id) && Objects.equals(name, user.name) && Objects.equals(age, user.age); } @Override public int hashCode() { return Objects.hash(id, name, age); } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/filter/TraceRequestAndResponseFilter.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/filter/TraceRequestAndResponseFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.compatible.filter; import javax.annotation.Priority; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import java.io.IOException; @Priority(Priorities.USER) public class TraceRequestAndResponseFilter implements ContainerRequestFilter, ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { requestContext.getHeaders().add("test-response", "header-result"); } @Override public void filter( ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException { String headerString = containerRequestContext.getHeaderString("test-response"); containerResponseContext.setEntity(headerString); } }
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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/filter/TestContainerRequestFilter.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/filter/TestContainerRequestFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.compatible.filter; import javax.annotation.Priority; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.Response; import java.io.IOException; @Priority(Priorities.USER) public class TestContainerRequestFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { requestContext.abortWith(Response.status(200).entity("return-success").build()); } }
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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/filter/TraceFilter.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/filter/TraceFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.compatible.filter; import javax.annotation.Priority; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Priority(Priorities.USER) public class TraceFilter implements ContainerRequestFilter, ContainerResponseFilter { private static final Logger logger = LoggerFactory.getLogger(TraceFilter.class); @Override public void filter(ContainerRequestContext requestContext) throws IOException { logger.info("Request filter invoked: {}", requestContext.getUriInfo().getAbsolutePath()); } @Override public void filter( ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException { containerResponseContext.setEntity("response-filter"); logger.info("Response filter invoked."); } }
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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/intercept/DynamicTraceInterceptor.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/intercept/DynamicTraceInterceptor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.compatible.intercept; import javax.annotation.Priority; import javax.ws.rs.Priorities; import javax.ws.rs.WebApplicationException; import javax.ws.rs.ext.ReaderInterceptor; import javax.ws.rs.ext.ReaderInterceptorContext; import javax.ws.rs.ext.WriterInterceptor; import javax.ws.rs.ext.WriterInterceptorContext; import java.io.IOException; import java.nio.charset.StandardCharsets; @Priority(Priorities.USER) public class DynamicTraceInterceptor implements ReaderInterceptor, WriterInterceptor { public DynamicTraceInterceptor() {} @Override public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) throws IOException, WebApplicationException { return readerInterceptorContext.proceed(); } @Override public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException { writerInterceptorContext.getOutputStream().write("intercept".getBytes(StandardCharsets.UTF_8)); writerInterceptorContext.proceed(); } }
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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/rest/RestDemoForTestException.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/rest/RestDemoForTestException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.compatible.rest; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; @Path("/demoService") public interface RestDemoForTestException { @POST @Path("/noFound") @Produces(MediaType.TEXT_PLAIN) String test404(); @GET @Consumes({MediaType.TEXT_PLAIN}) @Path("/hello") Integer test400(@QueryParam("a") String a, @QueryParam("b") String b); @POST @Path("{uid}") String testMethodDisallowed(@PathParam("uid") String uid); }
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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/rest/RegistrationResult.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/rest/RegistrationResult.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.compatible.rest; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; import java.util.Objects; /** * DTO to customize the returned message */ @XmlRootElement public class RegistrationResult implements Serializable { private Long id; public RegistrationResult() {} public RegistrationResult(Long id) { this.id = id; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RegistrationResult that = (RegistrationResult) o; return Objects.equals(id, that.id); } @Override public int hashCode() { return Objects.hash(id); } }
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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/rest/RestDemoServiceImpl.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/rest/RestDemoServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.compatible.rest; import org.apache.dubbo.rpc.RpcContext; import javax.ws.rs.core.Response; import java.util.HashMap; import java.util.Map; import org.jboss.resteasy.specimpl.BuiltResponse; public class RestDemoServiceImpl implements RestDemoService { private static Map<String, Object> context; private boolean called; @Override public String sayHello(String name) { called = true; return "Hello, " + name; } @Override public Long testFormBody(Long number) { return number; } public boolean isCalled() { return called; } @Override public String deleteUserByUid(String uid) { return uid; } @Override public Integer hello(Integer a, Integer b) { context = RpcContext.getServerAttachment().getObjectAttachments(); return a + b; } @Override public Response findUserById(Integer id) { Map<String, Object> content = new HashMap<>(); content.put("username", "jack"); content.put("id", id); return BuiltResponse.ok(content).build(); } @Override public String error() { throw new RuntimeException(); } @Override public Response deleteUserById(String uid) { return Response.status(300).entity("deleted").build(); } public static Map<String, Object> getAttachments() { return 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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/rest/HttpMethodService.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/rest/HttpMethodService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.compatible.rest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HEAD; import javax.ws.rs.OPTIONS; import javax.ws.rs.PATCH; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; @Path("/demoService") public interface HttpMethodService { @POST @Path("/sayPost") @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) String sayHelloPost(@QueryParam("name") String name); @DELETE @Path("/sayDelete") @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) String sayHelloDelete(@QueryParam("name") String name); @HEAD @Path("/sayHead") @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) String sayHelloHead(); @GET @Path("/sayGet") @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) String sayHelloGet(@QueryParam("name") String name); @PUT @Path("/sayPut") @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) String sayHelloPut(@QueryParam("name") String name); @PATCH @Path("/sayPatch") @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) String sayHelloPatch(@QueryParam("name") String name); @OPTIONS @Path("/sayOptions") @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) String sayHelloOptions(@QueryParam("name") String 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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/rest/AnotherUserRestServiceImpl.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/rest/AnotherUserRestServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.compatible.rest; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.compatible.User; import java.util.Map; public class AnotherUserRestServiceImpl implements AnotherUserRestService { @Override public User getUser(Long id) { User user = new User(); user.setId(id); return user; } @Override public RegistrationResult registerUser(User user) { return new RegistrationResult(user.getId()); } @Override public String getContext() { return "context"; } @Override public byte[] bytes(byte[] bytes) { return bytes; } @Override public Long number(Long number) { return number; } @Override public String headerMap(Map<String, String> headers) { return headers.get("headers"); } }
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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/rest/HttpMethodServiceImpl.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/rest/HttpMethodServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.compatible.rest; public class HttpMethodServiceImpl implements HttpMethodService { @Override public String sayHelloPost(String name) { return name; } @Override public String sayHelloDelete(String name) { return name; } @Override public String sayHelloHead() { return "hello"; } @Override public String sayHelloGet(String name) { return name; } @Override public String sayHelloPut(String name) { return name; } @Override public String sayHelloPatch(String name) { return name; } @Override public String sayHelloOptions(String name) { return 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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/rest/RestDemoService.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/rest/RestDemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.compatible.rest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("/demoService") public interface RestDemoService { @GET @Path("/hello") Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b); @GET @Path("/findUserById") Response findUserById(@QueryParam("id") Integer id); @GET @Path("/error") String error(); @POST @Path("/say") @Consumes({MediaType.TEXT_PLAIN}) String sayHello(String name); @POST @Path("number") @Produces({MediaType.APPLICATION_FORM_URLENCODED}) @Consumes({MediaType.APPLICATION_FORM_URLENCODED}) Long testFormBody(@FormParam("number") Long number); boolean isCalled(); @DELETE @Path("{uid}") String deleteUserByUid(@PathParam("uid") String uid); @DELETE @Path("/deleteUserById/{uid}") public Response deleteUserById(@PathParam("uid") String uid); }
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-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/rest/AnotherUserRestService.java
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/compatible/rest/AnotherUserRestService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.compatible.rest; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.compatible.User; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.Map; @Path("u") @Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) public interface AnotherUserRestService { @GET @Path("{id : \\d+}") @Produces({MediaType.APPLICATION_JSON}) User getUser(@PathParam("id") Long id); @POST @Path("register") @Produces("text/xml; charset=UTF-8") RegistrationResult registerUser(User user); @GET @Path("context") @Produces({MediaType.TEXT_PLAIN}) String getContext(); @POST @Path("bytes") @Produces({MediaType.APPLICATION_JSON}) byte[] bytes(byte[] bytes); @POST @Path("number") @Produces({MediaType.APPLICATION_JSON}) Long number(Long number); @POST @Path("headerMap") @Produces({MediaType.TEXT_PLAIN}) String headerMap(@HeaderParam("headers") Map<String, String> headers); }
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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/CookieParamArgumentResolver.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/CookieParamArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.remoting.http12.HttpCookie; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; @Activate(onClass = "javax.ws.rs.CookieParam") public class CookieParamArgumentResolver extends AbstractJaxrsArgumentResolver { @Override public Class<Annotation> accept() { return Annotations.CookieParam.type(); } @Override protected ParamType getParamType(NamedValueMeta meta) { return ParamType.Cookie; } @Override protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.cookie(meta.name()); } @Override protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { Collection<HttpCookie> cookies = request.cookies(); if (cookies.isEmpty()) { return Collections.emptyList(); } String name = meta.name(); List<HttpCookie> result = new ArrayList<>(cookies.size()); for (HttpCookie cookie : cookies) { if (name.equals(cookie.name())) { result.add(cookie); } } return result; } @Override protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { Collection<HttpCookie> cookies = request.cookies(); if (cookies.isEmpty()) { return Collections.emptyMap(); } Map<String, List<HttpCookie>> mapValue = CollectionUtils.newLinkedHashMap(cookies.size()); for (HttpCookie cookie : cookies) { mapValue.computeIfAbsent(cookie.name(), k -> new ArrayList<>()).add(cookie); } return mapValue; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/JaxrsHttpRequestAdapter.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/JaxrsHttpRequestAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import java.io.InputStream; import java.net.URI; import java.util.Collections; import java.util.Enumeration; import java.util.List; import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; import org.jboss.resteasy.spi.ResteasyAsynchronousContext; import org.jboss.resteasy.spi.ResteasyUriInfo; public final class JaxrsHttpRequestAdapter implements org.jboss.resteasy.spi.HttpRequest { private final HttpRequest request; private HttpHeaders headers; private ResteasyUriInfo uriInfo; public JaxrsHttpRequestAdapter(HttpRequest request) { this.request = request; } @Override public HttpHeaders getHttpHeaders() { HttpHeaders headers = this.headers; if (headers == null) { headers = new ResteasyHttpHeaders(new MultivaluedMapWrapper<>(request.headers())); this.headers = headers; } return headers; } @Override public MultivaluedMap<String, String> getMutableHeaders() { return headers.getRequestHeaders(); } @Override public InputStream getInputStream() { return request.inputStream(); } @Override public void setInputStream(InputStream stream) { request.setInputStream(stream); } @Override public ResteasyUriInfo getUri() { ResteasyUriInfo uriInfo = this.uriInfo; if (uriInfo == null) { uriInfo = new ResteasyUriInfo(request.rawPath(), request.query(), "/"); this.uriInfo = uriInfo; } return uriInfo; } @Override public String getHttpMethod() { return request.method(); } @Override public void setHttpMethod(String method) { request.setMethod(method); } @Override public void setRequestUri(URI requestUri) throws IllegalStateException { String query = requestUri.getRawQuery(); request.setUri(requestUri.getRawPath() + (query == null ? "" : '?' + query)); } @Override public void setRequestUri(URI baseUri, URI requestUri) throws IllegalStateException { String query = requestUri.getRawQuery(); request.setUri(baseUri.getRawPath() + requestUri.getRawPath() + (query == null ? "" : '?' + query)); } @Override public MultivaluedMap<String, String> getFormParameters() { MultivaluedMap<String, String> result = new MultivaluedHashMap<>(); for (String name : request.formParameterNames()) { List<String> values = request.formParameterValues(name); if (values == null) { continue; } for (String value : values) { result.add(name, RequestUtils.encodeURL(value)); } } return result; } @Override public MultivaluedMap<String, String> getDecodedFormParameters() { return new MultivaluedMapWrapper<>(RequestUtils.getFormParametersMap(request)); } @Override public Object getAttribute(String attribute) { return request.attribute(attribute); } @Override public void setAttribute(String name, Object value) { request.setAttribute(name, value); } @Override public void removeAttribute(String name) { request.removeAttribute(name); } @Override public Enumeration<String> getAttributeNames() { return Collections.enumeration(request.attributeNames()); } @Override public ResteasyAsynchronousContext getAsyncContext() { throw new UnsupportedOperationException(); } @Override public boolean isInitial() { return false; } @Override public void forward(String path) { throw new UnsupportedOperationException(); } @Override public boolean wasForwarded() { return false; } }
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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/PathParamArgumentResolver.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/PathParamArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.Messages; import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants; import org.apache.dubbo.rpc.protocol.tri.rest.RestParameterException; import org.apache.dubbo.rpc.protocol.tri.rest.argument.AnnotationBaseArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import java.lang.annotation.Annotation; import java.util.Map; @Activate(onClass = "javax.ws.rs.PathParam") public class PathParamArgumentResolver implements AnnotationBaseArgumentResolver<Annotation> { @Override public Class<Annotation> accept() { return Annotations.PathParam.type(); } @Override public NamedValueMeta getNamedValueMeta(ParameterMeta parameter, AnnotationMeta<Annotation> annotation) { return new NamedValueMeta(annotation.getValue(), true).setParamType(ParamType.PathVariable); } @Override public Object resolve( ParameterMeta parameter, AnnotationMeta<Annotation> annotation, HttpRequest request, HttpResponse response) { Map<String, String> variableMap = request.attribute(RestConstants.URI_TEMPLATE_VARIABLES_ATTRIBUTE); String name = annotation.getValue(); if (StringUtils.isEmpty(name)) { name = parameter.getRequiredName(); } if (variableMap == null) { if (Helper.isRequired(parameter)) { throw new RestParameterException(Messages.ARGUMENT_VALUE_MISSING, name, parameter.getType()); } return null; } String value = variableMap.get(name); if (value == null) { return null; } int index = value.indexOf(';'); if (index != -1) { value = value.substring(0, index); } return parameter.isAnnotated(Annotations.Encoded) ? value : RequestUtils.decodeURL(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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/HeaderParamArgumentResolver.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/HeaderParamArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import java.lang.annotation.Annotation; @Activate(onClass = "javax.ws.rs.HeaderParam") public class HeaderParamArgumentResolver extends AbstractJaxrsArgumentResolver { @Override public Class<Annotation> accept() { return Annotations.HeaderParam.type(); } @Override protected ParamType getParamType(NamedValueMeta meta) { return ParamType.Header; } @Override protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.header(meta.name()); } @Override protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.headerValues(meta.name()); } @Override protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.headers().asMap(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/BeanArgumentBinder.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/BeanArgumentBinder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.Pair; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.rpc.protocol.tri.rest.Messages; import org.apache.dubbo.rpc.protocol.tri.rest.RestException; import org.apache.dubbo.rpc.protocol.tri.rest.argument.ArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.argument.CompositeArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta.ConstructorMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.BeanMeta.PropertyMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils; import java.util.HashSet; import java.util.Map; import java.util.Set; final class BeanArgumentBinder { private static final ThreadLocal<Set<Class<?>>> LOCAL = new ThreadLocal<>(); private final Map<Pair<Class<?>, String>, BeanMeta> cache = CollectionUtils.newConcurrentHashMap(); private final ArgumentResolver argumentResolver; BeanArgumentBinder(CompositeArgumentResolver argumentResolver) { this.argumentResolver = argumentResolver; } public Object bind(ParameterMeta paramMeta, HttpRequest request, HttpResponse response) { Set<Class<?>> walked = LOCAL.get(); if (walked == null) { LOCAL.set(new HashSet<>()); } try { return resolveArgument(paramMeta, request, response); } catch (Exception e) { throw new RestException(e, Messages.ARGUMENT_BIND_ERROR, paramMeta.getName(), paramMeta.getType()); } finally { if (walked == null) { LOCAL.remove(); } } } private Object resolveArgument(ParameterMeta paramMeta, HttpRequest request, HttpResponse response) { if (paramMeta.isSimple()) { return argumentResolver.resolve(paramMeta, request, response); } // Prevent infinite loops if (LOCAL.get().add(paramMeta.getActualType())) { AnnotationMeta<?> form = paramMeta.findAnnotation(Annotations.Form); if (form != null || paramMeta.isHierarchyAnnotated(Annotations.BeanParam)) { String prefix = form == null ? null : form.getString("prefix"); BeanMeta beanMeta = cache.computeIfAbsent( Pair.of(paramMeta.getActualType(), prefix), k -> new BeanMeta(paramMeta.getToolKit(), k.getValue(), k.getKey())); ConstructorMeta constructor = beanMeta.getConstructor(); ParameterMeta[] parameters = constructor.getParameters(); Object bean; int len = parameters.length; if (len == 0) { bean = constructor.newInstance(); } else { Object[] args = new Object[len]; for (int i = 0; i < len; i++) { args[i] = resolveArgument(parameters[i], request, response); } bean = constructor.newInstance(args); } for (PropertyMeta propertyMeta : beanMeta.getProperties()) { if (propertyMeta.canSetValue()) { propertyMeta.setValue(bean, resolveArgument(propertyMeta, request, response)); } } return bean; } } return TypeUtils.nullDefault(paramMeta.getType()); } }
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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/MatrixParamArgumentResolver.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/MatrixParamArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import java.lang.annotation.Annotation; import java.util.List; import java.util.Map; @Activate(onClass = "javax.ws.rs.MatrixParam") public class MatrixParamArgumentResolver extends AbstractJaxrsArgumentResolver { @Override public Class<Annotation> accept() { return Annotations.MatrixParam.type(); } @Override protected ParamType getParamType(NamedValueMeta meta) { return ParamType.MatrixVariable; } @Override protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return CollectionUtils.first(doResolveCollectionValue(meta, request)); } @Override protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return doResolveCollectionValue(meta, request); } private static List<String> doResolveCollectionValue(NamedValueMeta meta, HttpRequest request) { Map<String, String> variableMap = request.attribute(RestConstants.URI_TEMPLATE_VARIABLES_ATTRIBUTE); return RequestUtils.parseMatrixVariableValues(variableMap, meta.name()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/JaxrsRequestMappingResolver.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/JaxrsRequestMappingResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.config.nested.RestConfig; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.tri.rest.cors.CorsUtils; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMapping; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMapping.Builder; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMappingResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationSupport; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.CorsMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.MethodMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ServiceMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RestToolKit; @Activate(onClass = {"javax.ws.rs.Path", "javax.ws.rs.container.ContainerRequestContext"}) public class JaxrsRequestMappingResolver implements RequestMappingResolver { private final RestToolKit toolKit; private RestConfig restConfig; private CorsMeta globalCorsMeta; public JaxrsRequestMappingResolver(FrameworkModel frameworkModel) { toolKit = new JaxrsRestToolKit(frameworkModel); } @Override public RestToolKit getRestToolKit() { return toolKit; } @Override public void setRestConfig(RestConfig restConfig) { this.restConfig = restConfig; } @Override public RequestMapping resolve(ServiceMeta serviceMeta) { AnnotationMeta<?> path = serviceMeta.findAnnotation(Annotations.Path); if (path == null) { return null; } return builder(serviceMeta, path, null) .name(serviceMeta.getType().getSimpleName()) .contextPath(serviceMeta.getContextPath()) .build(); } @Override public RequestMapping resolve(MethodMeta methodMeta) { AnnotationMeta<?> path = methodMeta.findAnnotation(Annotations.Path); if (path == null) { return null; } AnnotationMeta<?> httpMethod = methodMeta.findMergedAnnotation(Annotations.HttpMethod); if (httpMethod == null) { return null; } ServiceMeta serviceMeta = methodMeta.getServiceMeta(); if (globalCorsMeta == null) { globalCorsMeta = CorsUtils.getGlobalCorsMeta(restConfig); } return builder(methodMeta, path, httpMethod) .name(methodMeta.getMethodName()) .contextPath(methodMeta.getServiceMeta().getContextPath()) .service(serviceMeta.getServiceGroup(), serviceMeta.getServiceVersion()) .cors(globalCorsMeta) .build(); } private Builder builder(AnnotationSupport meta, AnnotationMeta<?> path, AnnotationMeta<?> httpMethod) { Builder builder = RequestMapping.builder().path(path.getValue()); if (httpMethod == null) { httpMethod = meta.findMergedAnnotation(Annotations.HttpMethod); } if (httpMethod != null) { builder.method(httpMethod.getValue()); } AnnotationMeta<?> produces = meta.findAnnotation(Annotations.Produces); if (produces != null) { builder.produce(produces.getValueArray()); } AnnotationMeta<?> consumes = meta.findAnnotation(Annotations.Consumes); if (consumes != null) { builder.consume(consumes.getValueArray()); } return builder; } }
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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/JaxrsRestToolKit.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/JaxrsRestToolKit.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.AbstractRestToolKit; import javax.ws.rs.ext.ParamConverter; final class JaxrsRestToolKit extends AbstractRestToolKit { private final BeanArgumentBinder binder; private final ParamConverterFactory paramConverterFactory; public JaxrsRestToolKit(FrameworkModel frameworkModel) { super(frameworkModel); binder = new BeanArgumentBinder(argumentResolver); paramConverterFactory = new ParamConverterFactory(); } @Override public int getDialect() { return RestConstants.DIALECT_JAXRS; } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public Object convert(Object value, ParameterMeta parameter) { ParamConverter converter = paramConverterFactory.getParamConverter( parameter.getType(), parameter.getGenericType(), parameter.getRawAnnotations()); if (converter != null) { return value instanceof String ? converter.fromString((String) value) : converter.toString(value); } return super.convert(value, parameter); } @Override public Object bind(ParameterMeta parameter, HttpRequest request, HttpResponse response) { return binder.bind(parameter, request, response); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/FallbackArgumentResolver.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/FallbackArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.io.StreamUtils; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants; import org.apache.dubbo.rpc.protocol.tri.rest.RestException; import org.apache.dubbo.rpc.protocol.tri.rest.argument.AbstractArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils; import java.io.IOException; @Activate(order = Integer.MAX_VALUE - 10000, onClass = "javax.ws.rs.Path") public class FallbackArgumentResolver extends AbstractArgumentResolver { @Override public boolean accept(ParameterMeta param) { return param.getToolKit().getDialect() == RestConstants.DIALECT_JAXRS; } @Override protected NamedValueMeta createNamedValueMeta(ParameterMeta param) { return new NamedValueMeta(null, param.isAnnotated(Annotations.Nonnull), Helper.defaultValue(param)) .setParamType(param.isSimple() ? null : ParamType.Body); } @Override protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { Object value = RequestUtils.decodeBody(request, meta.genericType()); if (value != null) { return value; } if (meta.parameter().isStream()) { return null; } if (meta.parameter().isSimple()) { return request.parameter(meta.name()); } return null; } @Override protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { Class<?> type = meta.type(); if (type == byte[].class) { try { return StreamUtils.readBytes(request.inputStream()); } catch (IOException e) { throw new RestException(e); } } Object value = RequestUtils.decodeBody(request, meta.genericType()); if (value != null) { return value; } if (TypeUtils.isSimpleProperty(meta.nestedType(0))) { return request.parameterValues(meta.name()); } return null; } @Override protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { Object value = RequestUtils.decodeBody(request, meta.genericType()); if (value != null) { return value; } if (TypeUtils.isSimpleProperty(meta.nestedType(1))) { return RequestUtils.getParametersMap(request); } return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/FormParamArgumentResolver.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/FormParamArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import java.lang.annotation.Annotation; /** * TODO: support nested values: (e.g., 'telephoneNumbers[0].countryCode' 'address[INVOICE].street') */ @Activate(onClass = "javax.ws.rs.FormParam") public class FormParamArgumentResolver extends AbstractJaxrsArgumentResolver { @Override public Class<Annotation> accept() { return Annotations.FormParam.type(); } @Override protected ParamType getParamType(NamedValueMeta meta) { return ParamType.Form; } @Override protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return CollectionUtils.first(request.formParameterValues(getFullName(meta))); } @Override protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.formParameterValues(getFullName(meta)); } private String getFullName(NamedValueMeta meta) { String prefix = meta.parameter().getPrefix(); return prefix == null ? meta.name() : prefix + '.' + meta.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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/QueryParamArgumentResolver.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/QueryParamArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import java.lang.annotation.Annotation; @Activate(onClass = "javax.ws.rs.QueryParam") public class QueryParamArgumentResolver extends AbstractJaxrsArgumentResolver { @Override public Class<Annotation> accept() { return Annotations.QueryParam.type(); } @Override protected ParamType getParamType(NamedValueMeta meta) { return ParamType.Param; } @Override protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.parameter(meta.name()); } @Override protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return request.parameterValues(meta.name()); } @Override protected Object resolveMapValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) { return RequestUtils.getParametersMap(request); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/JaxrsMiscArgumentResolver.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/JaxrsMiscArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.rpc.protocol.tri.rest.argument.ArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.Form; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; import org.jboss.resteasy.spi.ResteasyUriInfo; @Activate(onClass = "javax.ws.rs.Path") public class JaxrsMiscArgumentResolver implements ArgumentResolver { private static final Set<Class<?>> SUPPORTED_TYPES = new HashSet<>(); static { SUPPORTED_TYPES.add(Cookie.class); SUPPORTED_TYPES.add(Form.class); SUPPORTED_TYPES.add(HttpHeaders.class); SUPPORTED_TYPES.add(MediaType.class); SUPPORTED_TYPES.add(MultivaluedMap.class); SUPPORTED_TYPES.add(UriInfo.class); } @Override public boolean accept(ParameterMeta parameter) { return SUPPORTED_TYPES.contains(parameter.getActualType()); } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public Object resolve(ParameterMeta parameter, HttpRequest request, HttpResponse response) { Class<?> type = parameter.getActualType(); if (Cookie.class.isAssignableFrom(type)) { return Helper.convert(request.cookie(parameter.getRequiredName())); } if (Form.class.isAssignableFrom(type)) { return RequestUtils.getFormParametersMap(request); } if (HttpHeaders.class.isAssignableFrom(type)) { return new ResteasyHttpHeaders(new MultivaluedMapWrapper<>(request.headers())); } if (MediaType.class.isAssignableFrom(type)) { return Helper.toMediaType(request.mediaType()); } if (MultivaluedMap.class.isAssignableFrom(type)) { return new MultivaluedMapWrapper<>((Map) RequestUtils.getParametersMap(request)); } if (UriInfo.class.isAssignableFrom(type)) { return new ResteasyUriInfo(request.rawPath(), request.query(), "/"); } 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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/JaxrsResponseRestFilter.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/JaxrsResponseRestFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter.Listener; import javax.ws.rs.core.Response; @Activate(order = -10000, onClass = "javax.ws.rs.Path") public class JaxrsResponseRestFilter implements RestFilter, Listener { @Override public void onResponse(Result result, HttpRequest request, HttpResponse response) { if (result.hasException()) { return; } Object value = result.getValue(); if (value instanceof Response) { result.setValue(Helper.toBody((Response) 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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/BeanParamArgumentResolver.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/BeanParamArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.rpc.protocol.tri.rest.argument.AnnotationBaseArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import java.lang.annotation.Annotation; @Activate(onClass = "javax.ws.rs.BeanParam") public class BeanParamArgumentResolver implements AnnotationBaseArgumentResolver<Annotation> { @Override public Class<Annotation> accept() { return Annotations.BeanParam.type(); } @Override public NamedValueMeta getNamedValueMeta(ParameterMeta parameter, AnnotationMeta<Annotation> annotation) { return null; } @Override public Object resolve( ParameterMeta parameter, AnnotationMeta<Annotation> annotation, HttpRequest request, HttpResponse response) { return parameter.bind(request, response); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/JaxrsHttpResponseAdapter.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/JaxrsHttpResponseAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.remoting.http12.HttpCookie; import org.apache.dubbo.remoting.http12.HttpResponse; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.NewCookie; import java.io.OutputStream; public final class JaxrsHttpResponseAdapter implements org.jboss.resteasy.spi.HttpResponse { private final HttpResponse response; private MultivaluedMap<String, Object> headers; public JaxrsHttpResponseAdapter(HttpResponse response) { this.response = response; } @Override public int getStatus() { return response.status(); } @Override public void setStatus(int status) { response.setStatus(status); } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public MultivaluedMap<String, Object> getOutputHeaders() { MultivaluedMap<String, Object> headers = this.headers; if (headers == null) { headers = new MultivaluedMapWrapper(response.headers()); this.headers = headers; } return headers; } @Override public OutputStream getOutputStream() { return response.outputStream(); } @Override public void setOutputStream(OutputStream os) { response.setOutputStream(os); } @Override public void addNewCookie(NewCookie cookie) { HttpCookie hCookie = new HttpCookie(cookie.getName(), cookie.getValue()); hCookie.setDomain(cookie.getDomain()); hCookie.setPath(cookie.getPath()); hCookie.setMaxAge(cookie.getMaxAge()); hCookie.setSecure(cookie.isSecure()); hCookie.setHttpOnly(cookie.isHttpOnly()); response.addCookie(hCookie); } @Override public void sendError(int status) { response.sendError(status); } @Override public void sendError(int status, String message) { response.sendError(status, message); } @Override public boolean isCommitted() { return response.isCommitted(); } @Override public void reset() { response.reset(); } @Override public void flushBuffer() {} }
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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/BodyArgumentResolver.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/BodyArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.io.StreamUtils; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.RestException; import org.apache.dubbo.rpc.protocol.tri.rest.argument.AnnotationBaseArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import org.apache.dubbo.rpc.protocol.tri.rest.util.RequestUtils; import java.io.IOException; import java.lang.annotation.Annotation; @Activate(onClass = "org.jboss.resteasy.annotations.Body") public class BodyArgumentResolver implements AnnotationBaseArgumentResolver<Annotation> { @Override public Class<Annotation> accept() { return Annotations.Body.type(); } @Override public NamedValueMeta getNamedValueMeta(ParameterMeta parameter, AnnotationMeta<Annotation> annotation) { return new NamedValueMeta().setParamType(ParamType.Body); } @Override public Object resolve( ParameterMeta parameter, AnnotationMeta<Annotation> annotation, HttpRequest request, HttpResponse response) { Class<?> type = parameter.getActualType(); if (type == byte[].class) { try { return StreamUtils.readBytes(request.inputStream()); } catch (IOException e) { throw new RestException(e); } } return RequestUtils.decodeBody(request, parameter.getActualGenericType()); } }
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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/MultivaluedMapCreator.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/MultivaluedMapCreator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.protocol.tri.rest.argument.ArgumentConverter; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; @Activate(onClass = "javax.ws.rs.core.MultivaluedMap") public class MultivaluedMapCreator implements ArgumentConverter<Integer, MultivaluedMap<?, ?>> { @Override public MultivaluedMap<?, ?> convert(Integer value, ParameterMeta parameter) { return new MultivaluedHashMap<>(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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/AbstractJaxrsArgumentResolver.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/AbstractJaxrsArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.rpc.protocol.tri.rest.argument.AbstractAnnotationBaseArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import java.lang.annotation.Annotation; public abstract class AbstractJaxrsArgumentResolver extends AbstractAnnotationBaseArgumentResolver { @Override protected NamedValueMeta createNamedValueMeta(ParameterMeta param, AnnotationMeta<Annotation> anno) { return new NamedValueMeta(anno.getValue(), Helper.isRequired(param), Helper.defaultValue(param)); } }
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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/MultivaluedMapWrapper.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/MultivaluedMapWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.remoting.http12.HttpHeaders; import javax.ws.rs.core.AbstractMultivaluedMap; import java.util.List; import java.util.Map; public final class MultivaluedMapWrapper<K, V> extends AbstractMultivaluedMap<K, V> { public MultivaluedMapWrapper(Map<K, List<V>> store) { super(store); } @SuppressWarnings({"unchecked", "rawtypes"}) public MultivaluedMapWrapper(HttpHeaders headers) { super((Map) headers.asMap()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/FormArgumentResolver.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/FormArgumentResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.rest.ParamType; import org.apache.dubbo.rpc.protocol.tri.rest.argument.AnnotationBaseArgumentResolver; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.NamedValueMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import java.lang.annotation.Annotation; @Activate(onClass = "org.jboss.resteasy.annotations.Form") public class FormArgumentResolver implements AnnotationBaseArgumentResolver<Annotation> { @Override public Class<Annotation> accept() { return Annotations.Form.type(); } @Override public NamedValueMeta getNamedValueMeta(ParameterMeta parameter, AnnotationMeta<Annotation> annotation) { return new NamedValueMeta().setParamType(ParamType.Body); } @Override public Object resolve( ParameterMeta parameter, AnnotationMeta<Annotation> annotation, HttpRequest request, HttpResponse response) { return parameter.bind(request, response); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/ParamConverterFactory.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/ParamConverterFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.utils.CollectionUtils; import javax.ws.rs.ext.ParamConverter; import javax.ws.rs.ext.ParamConverterProvider; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.ServiceLoader; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ERROR_LOAD_EXTENSION; import static org.apache.dubbo.common.logger.LoggerFactory.getErrorTypeAwareLogger; final class ParamConverterFactory { private static final ErrorTypeAwareLogger logger = getErrorTypeAwareLogger(ParamConverterFactory.class); private final Map<List<Object>, Optional<ParamConverter<?>>> cache = CollectionUtils.newConcurrentHashMap(); private final List<ParamConverterProvider> providers = new ArrayList<>(); ParamConverterFactory() { Iterator<ParamConverterProvider> it = ServiceLoader.load(ParamConverterProvider.class).iterator(); while (it.hasNext()) { try { providers.add(it.next()); } catch (Throwable t) { logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", "Failed to load ParamConverterProvider", t); } } } @SuppressWarnings("unchecked") public <T> ParamConverter<T> getParamConverter(Class<T> type, Type genericType, Annotation[] annotations) { if (providers.isEmpty()) { return null; } List<Object> key = new ArrayList<>(annotations.length + 2); key.add(type); key.add(genericType); Collections.addAll(key, annotations); return (ParamConverter<T>) cache.computeIfAbsent(key, k -> { for (ParamConverterProvider provider : providers) { ParamConverter<T> converter = provider.getConverter(type, genericType, annotations); if (converter != null) { return Optional.of(converter); } } return Optional.empty(); }) .orElse(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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/Annotations.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/Annotations.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationEnum; import java.lang.annotation.Annotation; public enum Annotations implements AnnotationEnum { Path, HttpMethod, Produces, Consumes, PathParam, MatrixParam, QueryParam, HeaderParam, CookieParam, FormParam, BeanParam, Body("org.jboss.resteasy.annotations.Body"), Form("org.jboss.resteasy.annotations.Form"), Context("javax.ws.rs.core.Context"), Suspended("javax.ws.rs.container.Suspended"), DefaultValue, Encoded, Nonnull("javax.annotation.Nonnull"); private final String className; private Class<Annotation> type; Annotations(String className) { this.className = className; } Annotations() { className = "javax.ws.rs." + name(); } public String className() { return className; } @Override public Class<Annotation> type() { if (type == null) { type = loadType(); } return type; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/Helper.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/Helper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs; import org.apache.dubbo.remoting.http12.HttpCookie; import org.apache.dubbo.remoting.http12.HttpResult; import org.apache.dubbo.remoting.http12.HttpUtils; import org.apache.dubbo.remoting.http12.message.DefaultHttpResult.Builder; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.AnnotationMeta; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.ParameterMeta; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.Response; import java.util.List; import java.util.stream.Collectors; public final class Helper { private Helper() {} public static boolean isRequired(ParameterMeta parameter) { return parameter.isHierarchyAnnotated(Annotations.Nonnull); } public static String defaultValue(ParameterMeta parameter) { AnnotationMeta<?> meta = parameter.findAnnotation(Annotations.DefaultValue); return meta == null ? null : meta.getValue(); } public static HttpResult<Object> toBody(Response response) { Builder<Object> builder = HttpResult.builder().status(response.getStatus()); if (response.hasEntity()) { builder.body(response.getEntity()); } builder.headers(response.getStringHeaders()); return builder.build(); } public static MediaType toMediaType(String mediaType) { if (mediaType == null) { return null; } int index = mediaType.indexOf('/'); if (index == -1) { return null; } return new MediaType(mediaType.substring(0, index), mediaType.substring(index + 1)); } public static String toString(MediaType mediaType) { return mediaType.getType() + '/' + mediaType.getSubtype(); } public static List<MediaType> toMediaTypes(String accept) { return HttpUtils.parseAccept(accept).stream().map(Helper::toMediaType).collect(Collectors.toList()); } public static NewCookie convert(HttpCookie cookie) { return new NewCookie( cookie.name(), cookie.value(), cookie.path(), cookie.domain(), null, (int) cookie.maxAge(), cookie.secure(), cookie.httpOnly()); } }
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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/ReaderInterceptorContextImpl.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/ReaderInterceptorContextImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.filter; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter.FilterChain; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.Helper; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.MultivaluedMapWrapper; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.ReaderInterceptorContext; import java.io.IOException; import java.io.InputStream; final class ReaderInterceptorContextImpl extends InterceptorContextImpl implements ReaderInterceptorContext { private final HttpResponse response; private final FilterChain chain; private MultivaluedMap<String, String> headers; public ReaderInterceptorContextImpl(HttpRequest request, HttpResponse response, FilterChain chain) { super(request); this.response = response; this.chain = chain; headers = new MultivaluedMapWrapper<>(request.headers()); } @Override public Object proceed() throws IOException, WebApplicationException { try { chain.doFilter(request, response); } catch (RuntimeException | IOException e) { throw e; } catch (Exception e) { throw new WebApplicationException(e); } return null; } @Override public InputStream getInputStream() { return request.inputStream(); } @Override public void setInputStream(InputStream is) { request.setInputStream(is); } @Override public MultivaluedMap<String, String> getHeaders() { MultivaluedMap<String, String> headers = this.headers; if (headers == null) { headers = new MultivaluedMapWrapper<>(request.headers()); this.headers = headers; } return headers; } @Override public MediaType getMediaType() { return Helper.toMediaType(request.mediaType()); } @Override public void setMediaType(MediaType mediaType) { request.setContentType(Helper.toString(mediaType)); } }
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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/ContainerRequestFilterAdapter.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/ContainerRequestFilterAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.filter; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.rpc.protocol.tri.rest.filter.AbstractRestFilter; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestExtensionAdapter; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter; import javax.ws.rs.container.ContainerRequestFilter; @Activate(onClass = "javax.ws.rs.container.ContainerResponseFilter") public class ContainerRequestFilterAdapter implements RestExtensionAdapter<ContainerRequestFilter> { @Override public boolean accept(Object extension) { return extension instanceof ContainerRequestFilter; } @Override public RestFilter adapt(ContainerRequestFilter extension) { return new Filter(extension); } private static final class Filter extends AbstractRestFilter<ContainerRequestFilter> { public Filter(ContainerRequestFilter extension) { super(extension); } @Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws Exception { ContainerRequestContextImpl context = new ContainerRequestContextImpl(request, response); extension.filter(context); if (context.isAborted()) { return; } chain.doFilter(request, response); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/ExceptionMapperAdapter.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/ExceptionMapperAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.filter; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.protocol.tri.rest.filter.AbstractRestFilter; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestExtensionAdapter; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter.Listener; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.Helper; import org.apache.dubbo.rpc.protocol.tri.rest.util.TypeUtils; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import java.util.Objects; @Activate(onClass = "javax.ws.rs.ext.ExceptionMapper") public final class ExceptionMapperAdapter implements RestExtensionAdapter<ExceptionMapper<Throwable>> { @Override public boolean accept(Object extension) { return extension instanceof ExceptionMapper; } @Override public RestFilter adapt(ExceptionMapper<Throwable> extension) { return new Filter(extension); } private static final class Filter extends AbstractRestFilter<ExceptionMapper<Throwable>> implements Listener { private final Class<?> exceptionType; public Filter(ExceptionMapper<Throwable> extension) { super(extension); exceptionType = Objects.requireNonNull(TypeUtils.getSuperGenericType(extension.getClass())); } @Override public void onResponse(Result result, HttpRequest request, HttpResponse response) throws Exception { if (result.hasException()) { Throwable t = result.getException(); if (exceptionType.isInstance(t)) { try (Response r = extension.toResponse(t)) { response.setBody(Helper.toBody(r)); } } } } @Override public void onError(Throwable t, HttpRequest request, HttpResponse response) { if (exceptionType.isInstance(t)) { try (Response r = extension.toResponse(t)) { response.setBody(Helper.toBody(r)); } } } } }
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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/WriterInterceptorContextImpl.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/WriterInterceptorContextImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.filter; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.Helper; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.MultivaluedMapWrapper; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.WriterInterceptorContext; import java.io.OutputStream; final class WriterInterceptorContextImpl extends InterceptorContextImpl implements WriterInterceptorContext { private final HttpResponse response; private final Result result; private MultivaluedMap<String, Object> headers; public WriterInterceptorContextImpl(HttpRequest request, HttpResponse response, Result result) { super(request); this.response = response; this.result = result; } @Override public void proceed() throws WebApplicationException {} @Override public Object getEntity() { return result.getValue(); } @Override public void setEntity(Object entity) { result.setValue(entity); } @Override public OutputStream getOutputStream() { return response.outputStream(); } @Override public void setOutputStream(OutputStream os) { response.setOutputStream(os); } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public MultivaluedMap<String, Object> getHeaders() { MultivaluedMap<String, Object> headers = this.headers; if (headers == null) { headers = new MultivaluedMapWrapper(response.headers()); this.headers = headers; } return headers; } @Override public MediaType getMediaType() { return Helper.toMediaType(response.mediaType()); } @Override public void setMediaType(MediaType mediaType) { response.setContentType(Helper.toString(mediaType)); } }
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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/ReadInterceptorAdapter.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/ReadInterceptorAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.filter; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.rpc.protocol.tri.rest.filter.AbstractRestFilter; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestExtensionAdapter; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter; import javax.ws.rs.ext.ReaderInterceptor; @Activate(onClass = "javax.ws.rs.ext.ReaderInterceptor") public final class ReadInterceptorAdapter implements RestExtensionAdapter<ReaderInterceptor> { @Override public boolean accept(Object extension) { return extension instanceof ReaderInterceptor; } @Override public RestFilter adapt(ReaderInterceptor extension) { return new Filter(extension); } private static final class Filter extends AbstractRestFilter<ReaderInterceptor> { public Filter(ReaderInterceptor extension) { super(extension); } @Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws Exception { extension.aroundReadFrom(new ReaderInterceptorContextImpl(request, response, chain)); } } }
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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/InterceptorContextImpl.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/InterceptorContextImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.filter; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.HandlerMeta; import javax.ws.rs.ext.InterceptorContext; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Collection; public abstract class InterceptorContextImpl implements InterceptorContext { protected final HttpRequest request; public InterceptorContextImpl(HttpRequest request) { this.request = request; } @Override public Object getProperty(String name) { return request.attribute(name); } @Override public Collection<String> getPropertyNames() { return request.parameterNames(); } @Override public void setProperty(String name, Object object) { request.setAttribute(name, object); } @Override public void removeProperty(String name) { request.removeAttribute(name); } @Override public Annotation[] getAnnotations() { return getHandler().getMethod().getRawAnnotations(); } @Override public void setAnnotations(Annotation[] annotations) {} @Override public Class<?> getType() { return getHandler().getMethod().getReturnType(); } @Override public void setType(Class<?> type) {} @Override public Type getGenericType() { return getHandler().getMethod().getGenericReturnType(); } @Override public void setGenericType(Type genericType) {} private HandlerMeta getHandler() { return request.attribute(RestConstants.HANDLER_ATTRIBUTE); } }
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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/WriterInterceptorAdapter.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/WriterInterceptorAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.filter; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.protocol.tri.rest.filter.AbstractRestFilter; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestExtensionAdapter; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter.Listener; import javax.ws.rs.ext.WriterInterceptor; @Activate(onClass = "javax.ws.rs.ext.WriterInterceptor") public final class WriterInterceptorAdapter implements RestExtensionAdapter<WriterInterceptor> { @Override public boolean accept(Object extension) { return extension instanceof WriterInterceptor; } @Override public RestFilter adapt(WriterInterceptor extension) { return new Filter(extension); } private static final class Filter extends AbstractRestFilter<WriterInterceptor> implements Listener { public Filter(WriterInterceptor extension) { super(extension); } @Override public void onResponse(Result result, HttpRequest request, HttpResponse response) throws Exception { extension.aroundWriteTo(new WriterInterceptorContextImpl(request, response, result)); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/ContainerRequestContextImpl.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/ContainerRequestContextImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.filter; import org.apache.dubbo.remoting.http12.HttpCookie; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.Helper; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.JaxrsHttpRequestAdapter; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.JaxrsHttpResponseAdapter; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.MultivaluedMapWrapper; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import java.io.InputStream; import java.net.URI; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.jboss.resteasy.specimpl.RequestImpl; import org.jboss.resteasy.spi.ResteasyUriInfo; final class ContainerRequestContextImpl implements ContainerRequestContext { private final HttpRequest request; private final HttpResponse response; private Request req; private MultivaluedMap<String, String> headers; private UriInfo uriInfo; private boolean aborted; public ContainerRequestContextImpl(HttpRequest request, HttpResponse response) { this.request = request; this.response = response; } @Override public Object getProperty(String name) { return request.attribute(name); } @Override public Collection<String> getPropertyNames() { return request.parameterNames(); } @Override public void setProperty(String name, Object object) { request.setAttribute(name, object); } @Override public void removeProperty(String name) { request.removeAttribute(name); } @Override public UriInfo getUriInfo() { UriInfo uriInfo = this.uriInfo; if (uriInfo == null) { uriInfo = new ResteasyUriInfo(request.rawPath(), request.query(), "/"); this.uriInfo = uriInfo; } return uriInfo; } @Override public void setRequestUri(URI requestUri) { String query = requestUri.getRawQuery(); request.setUri(requestUri.getRawPath() + (query == null ? "" : '?' + query)); } @Override public void setRequestUri(URI baseUri, URI requestUri) { String query = requestUri.getRawQuery(); request.setUri(baseUri.getRawPath() + requestUri.getRawPath() + (query == null ? "" : '?' + query)); } @Override public Request getRequest() { Request req = this.req; if (req == null) { req = new RequestImpl(new JaxrsHttpRequestAdapter(request), new JaxrsHttpResponseAdapter(response)); this.req = req; } return req; } @Override public String getMethod() { return request.method(); } @Override public void setMethod(String method) { request.setMethod(method); } @Override public MultivaluedMap<String, String> getHeaders() { MultivaluedMap<String, String> headers = this.headers; if (headers == null) { headers = new MultivaluedMapWrapper<>(request.headers()); this.headers = headers; } return headers; } @Override public String getHeaderString(String name) { return request.header(name); } @Override public Date getDate() { return null; } @Override public Locale getLanguage() { return request.locale(); } @Override public int getLength() { return request.contentLength(); } @Override public MediaType getMediaType() { return Helper.toMediaType(request.mediaType()); } @Override public List<MediaType> getAcceptableMediaTypes() { return Helper.toMediaTypes(request.accept()); } @Override public List<Locale> getAcceptableLanguages() { return request.locales(); } @Override public Map<String, Cookie> getCookies() { Collection<HttpCookie> cookies = request.cookies(); Map<String, Cookie> result = new HashMap<>(cookies.size()); for (HttpCookie cookie : cookies) { result.put(cookie.name(), Helper.convert(cookie)); } return result; } @Override @SuppressWarnings("resource") public boolean hasEntity() { return request.inputStream() != null; } @Override public InputStream getEntityStream() { return request.inputStream(); } @Override public void setEntityStream(InputStream input) { request.setInputStream(input); } @Override public SecurityContext getSecurityContext() { return null; } @Override public void setSecurityContext(SecurityContext context) {} @Override public void abortWith(Response response) { this.response.setBody(Helper.toBody(response)); aborted = true; } public boolean isAborted() { return aborted; } }
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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/ContainerResponseContextImpl.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/ContainerResponseContextImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.filter; import org.apache.dubbo.remoting.http12.HttpCookie; import org.apache.dubbo.remoting.http12.HttpHeaderNames; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.remoting.http12.HttpUtils; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.protocol.tri.rest.RestConstants; import org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.HandlerMeta; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.Helper; import org.apache.dubbo.rpc.protocol.tri.rest.support.jaxrs.MultivaluedMapWrapper; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.Link; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.Response.StatusType; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.net.URI; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import io.netty.handler.codec.DateFormatter; final class ContainerResponseContextImpl implements ContainerResponseContext { private final HttpRequest request; private final HttpResponse response; private final Result result; private MultivaluedMap<String, String> headers; public ContainerResponseContextImpl(HttpRequest request, HttpResponse response, Result result) { this.request = request; this.response = response; this.result = result; } @Override public int getStatus() { return response.status(); } @Override public void setStatus(int code) { response.setStatus(code); } @Override public StatusType getStatusInfo() { return Status.fromStatusCode(response.status()); } @Override public void setStatusInfo(StatusType statusInfo) { response.setStatus(statusInfo.getStatusCode()); } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public MultivaluedMap<String, Object> getHeaders() { return (MultivaluedMap) getStringHeaders(); } @Override public MultivaluedMap<String, String> getStringHeaders() { MultivaluedMap<String, String> headers = this.headers; if (headers == null) { headers = new MultivaluedMapWrapper<>(response.headers()); this.headers = headers; } return headers; } @Override public String getHeaderString(String name) { return response.header(name); } @Override public Set<String> getAllowedMethods() { return Collections.singleton(request.method()); } @Override public Date getDate() { return null; } @Override public Locale getLanguage() { return HttpUtils.parseLocale(response.locale()); } @Override public int getLength() { return -1; } @Override public MediaType getMediaType() { return Helper.toMediaType(response.mediaType()); } @Override public Map<String, NewCookie> getCookies() { Collection<HttpCookie> cookies = request.cookies(); Map<String, NewCookie> result = new HashMap<>(cookies.size()); for (HttpCookie cookie : cookies) { result.put(cookie.name(), Helper.convert(cookie)); } return result; } @Override public EntityTag getEntityTag() { return null; } @Override public Date getLastModified() { String value = response.header(HttpHeaderNames.LAST_MODIFIED.getKey()); return value == null ? null : DateFormatter.parseHttpDate(value); } @Override public URI getLocation() { String location = response.header(HttpHeaderNames.LOCATION.getKey()); return location == null ? null : URI.create(location); } @Override public Set<Link> getLinks() { return null; } @Override public boolean hasLink(String relation) { return false; } @Override public Link getLink(String relation) { return null; } @Override public Link.Builder getLinkBuilder(String relation) { return null; } @Override public boolean hasEntity() { return getEntity() != null; } @Override public Object getEntity() { return result.getValue(); } @Override public Class<?> getEntityClass() { return getHandler().getMethod().getReturnType(); } @Override public Type getEntityType() { return getHandler().getMethod().getGenericReturnType(); } @Override public void setEntity(Object entity) { result.setValue(entity); } @Override public void setEntity(Object entity, Annotation[] annotations, MediaType mediaType) { result.setValue(entity); response.setContentType(Helper.toString(mediaType)); } @Override public Annotation[] getEntityAnnotations() { return new Annotation[0]; } @Override public OutputStream getEntityStream() { return response.outputStream(); } @Override public void setEntityStream(OutputStream outputStream) { response.setOutputStream(outputStream); } private HandlerMeta getHandler() { return request.attribute(RestConstants.HANDLER_ATTRIBUTE); } }
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-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/ContainerResponseFilterAdapter.java
dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/filter/ContainerResponseFilterAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.jaxrs.filter; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http12.HttpRequest; import org.apache.dubbo.remoting.http12.HttpResponse; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.protocol.tri.rest.filter.AbstractRestFilter; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestExtensionAdapter; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter; import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter.Listener; import javax.ws.rs.container.ContainerResponseFilter; @Activate(onClass = "javax.ws.rs.container.ContainerResponseFilter") public class ContainerResponseFilterAdapter implements RestExtensionAdapter<ContainerResponseFilter> { @Override public boolean accept(Object extension) { return extension instanceof ContainerResponseFilter; } @Override public RestFilter adapt(ContainerResponseFilter extension) { return new Filter(extension); } private static final class Filter extends AbstractRestFilter<ContainerResponseFilter> implements Listener { public Filter(ContainerResponseFilter extension) { super(extension); } @Override public void onResponse(Result result, HttpRequest request, HttpResponse response) throws Exception { extension.filter( new ContainerRequestContextImpl(request, response), new ContainerResponseContextImpl(request, response, result)); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/AbstractCacheFactoryTest.java
dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/AbstractCacheFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.RpcInvocation; public abstract class AbstractCacheFactoryTest { protected Cache constructCache() { URL url = URL.valueOf("test://test:11/test?cache=lru"); Invocation invocation = new RpcInvocation(); return getCacheFactory().getCache(url, invocation); } protected abstract AbstractCacheFactory getCacheFactory(); }
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-cache/src/test/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactoryTest.java
dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support.threadlocal; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.support.AbstractCacheFactory; import org.apache.dubbo.cache.support.AbstractCacheFactoryTest; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; class ThreadLocalCacheFactoryTest extends AbstractCacheFactoryTest { @Test void testThreadLocalCacheFactory() throws Exception { Cache cache = super.constructCache(); assertThat(cache instanceof ThreadLocalCache, is(true)); } @Override protected AbstractCacheFactory getCacheFactory() { return new ThreadLocalCacheFactory(); } }
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-cache/src/test/java/org/apache/dubbo/cache/support/lru/LruCacheFactoryTest.java
dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/lru/LruCacheFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support.lru; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.support.AbstractCacheFactory; import org.apache.dubbo.cache.support.AbstractCacheFactoryTest; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; class LruCacheFactoryTest extends AbstractCacheFactoryTest { @Test void testLruCacheFactory() throws Exception { Cache cache = super.constructCache(); assertThat(cache instanceof LruCache, is(true)); } @Override protected AbstractCacheFactory getCacheFactory() { return new LruCacheFactory(); } }
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-cache/src/test/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactoryTest.java
dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support.expiring; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.support.AbstractCacheFactory; import org.apache.dubbo.cache.support.AbstractCacheFactoryTest; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.RpcInvocation; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; class ExpiringCacheFactoryTest extends AbstractCacheFactoryTest { private static final String EXPIRING_CACHE_URL = "test://test:12/test?cache=expiring&cache.seconds=1&cache.interval=1"; @Test void testExpiringCacheFactory() throws Exception { Cache cache = super.constructCache(); assertThat(cache instanceof ExpiringCache, is(true)); } @Test void testExpiringCacheGetExpired() throws Exception { URL url = URL.valueOf("test://test:12/test?cache=expiring&cache.seconds=1&cache.interval=1"); AbstractCacheFactory cacheFactory = getCacheFactory(); Invocation invocation = new RpcInvocation(); Cache cache = cacheFactory.getCache(url, invocation); cache.put("testKey", "testValue"); Thread.sleep(2100); assertNull(cache.get("testKey")); } @Test void testExpiringCacheUnExpired() throws Exception { URL url = URL.valueOf("test://test:12/test?cache=expiring&cache.seconds=0&cache.interval=1"); AbstractCacheFactory cacheFactory = getCacheFactory(); Invocation invocation = new RpcInvocation(); Cache cache = cacheFactory.getCache(url, invocation); cache.put("testKey", "testValue"); Thread.sleep(1100); assertNotNull(cache.get("testKey")); } @Test void testExpiringCache() throws Exception { Cache cache = constructCache(); assertThat(cache instanceof ExpiringCache, is(true)); // 500ms TimeUnit.MILLISECONDS.sleep(500); cache.put("testKey", "testValue"); // 800ms TimeUnit.MILLISECONDS.sleep(300); assertNotNull(cache.get("testKey")); // 1300ms TimeUnit.MILLISECONDS.sleep(500); assertNotNull(cache.get("testKey")); } @Test void testExpiringCacheExpired() throws Exception { Cache cache = constructCache(); assertThat(cache instanceof ExpiringCache, is(true)); // 500ms TimeUnit.MILLISECONDS.sleep(500); cache.put("testKey", "testValue"); // 1000ms ExpireThread clear all expire cache TimeUnit.MILLISECONDS.sleep(500); // 1700ms get should be null TimeUnit.MILLISECONDS.sleep(700); assertNull(cache.get("testKey")); } @Override protected Cache constructCache() { URL url = URL.valueOf(EXPIRING_CACHE_URL); Invocation invocation = new RpcInvocation(); return getCacheFactory().getCache(url, invocation); } @Override protected AbstractCacheFactory getCacheFactory() { return new ExpiringCacheFactory(); } }
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-cache/src/test/java/org/apache/dubbo/cache/support/jcache/JCacheFactoryTest.java
dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/jcache/JCacheFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support.jcache; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.support.AbstractCacheFactory; import org.apache.dubbo.cache.support.AbstractCacheFactoryTest; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.RpcInvocation; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.junit.jupiter.api.Assertions.assertNull; class JCacheFactoryTest extends AbstractCacheFactoryTest { @Test void testJCacheFactory() { Cache cache = super.constructCache(); assertThat(cache instanceof JCache, is(true)); } @Test void testJCacheGetExpired() throws Exception { URL url = URL.valueOf("test://test:12/test?cache=jacache&cache.write.expire=1"); AbstractCacheFactory cacheFactory = getCacheFactory(); Invocation invocation = new RpcInvocation(); Cache cache = cacheFactory.getCache(url, invocation); cache.put("testKey", "testValue"); Thread.sleep(10); assertNull(cache.get("testKey")); } @Override protected AbstractCacheFactory getCacheFactory() { return new JCacheFactory(); } }
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-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java
dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.filter; import org.apache.dubbo.cache.CacheFactory; import org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory; import org.apache.dubbo.cache.support.jcache.JCacheFactory; import org.apache.dubbo.cache.support.lru.LruCacheFactory; import org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcInvocation; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; class CacheFilterTest { private RpcInvocation invocation; private CacheFilter cacheFilter = new CacheFilter(); private Invoker<?> invoker = mock(Invoker.class); private Invoker<?> invoker1 = mock(Invoker.class); private Invoker<?> invoker2 = mock(Invoker.class); private Invoker<?> invoker3 = mock(Invoker.class); private Invoker<?> invoker4 = mock(Invoker.class); static Stream<Arguments> cacheFactories() { return Stream.of( Arguments.of("lru", new LruCacheFactory()), Arguments.of("jcache", new JCacheFactory()), Arguments.of("threadlocal", new ThreadLocalCacheFactory()), Arguments.of("expiring", new ExpiringCacheFactory())); } public void setUp(String cacheType, CacheFactory cacheFactory) { invocation = new RpcInvocation(); cacheFilter.setCacheFactory(cacheFactory); URL url = URL.valueOf("test://test:11/test?cache=" + cacheType); given(invoker.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult("value", invocation)); given(invoker.getUrl()).willReturn(url); given(invoker1.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult("value1", invocation)); given(invoker1.getUrl()).willReturn(url); given(invoker2.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult("value2", invocation)); given(invoker2.getUrl()).willReturn(url); given(invoker3.invoke(invocation)) .willReturn(AsyncRpcResult.newDefaultAsyncResult(new RuntimeException(), invocation)); given(invoker3.getUrl()).willReturn(url); given(invoker4.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult(invocation)); given(invoker4.getUrl()).willReturn(url); } @ParameterizedTest @MethodSource("cacheFactories") public void testNonArgsMethod(String cacheType, CacheFactory cacheFactory) { setUp(cacheType, cacheFactory); invocation.setMethodName("echo"); invocation.setParameterTypes(new Class<?>[] {}); invocation.setArguments(new Object[] {}); cacheFilter.invoke(invoker, invocation); cacheFilter.invoke(invoker, invocation); Result rpcResult1 = cacheFilter.invoke(invoker1, invocation); Result rpcResult2 = cacheFilter.invoke(invoker2, invocation); Assertions.assertEquals(rpcResult1.getValue(), rpcResult2.getValue()); Assertions.assertEquals(rpcResult1.getValue(), "value"); } @ParameterizedTest @MethodSource("cacheFactories") public void testMethodWithArgs(String cacheType, CacheFactory cacheFactory) { setUp(cacheType, cacheFactory); invocation.setMethodName("echo1"); invocation.setParameterTypes(new Class<?>[] {String.class}); invocation.setArguments(new Object[] {"arg1"}); cacheFilter.invoke(invoker, invocation); cacheFilter.invoke(invoker, invocation); Result rpcResult1 = cacheFilter.invoke(invoker1, invocation); Result rpcResult2 = cacheFilter.invoke(invoker2, invocation); Assertions.assertEquals(rpcResult1.getValue(), rpcResult2.getValue()); Assertions.assertEquals(rpcResult1.getValue(), "value"); } @ParameterizedTest @MethodSource("cacheFactories") public void testException(String cacheType, CacheFactory cacheFactory) { setUp(cacheType, cacheFactory); invocation.setMethodName("echo1"); invocation.setParameterTypes(new Class<?>[] {String.class}); invocation.setArguments(new Object[] {"arg2"}); cacheFilter.invoke(invoker3, invocation); cacheFilter.invoke(invoker3, invocation); Result rpcResult = cacheFilter.invoke(invoker2, invocation); Assertions.assertEquals(rpcResult.getValue(), "value2"); } @ParameterizedTest @MethodSource("cacheFactories") public void testNull(String cacheType, CacheFactory cacheFactory) { setUp(cacheType, cacheFactory); invocation.setMethodName("echo1"); invocation.setParameterTypes(new Class<?>[] {String.class}); invocation.setArguments(new Object[] {"arg3"}); cacheFilter.invoke(invoker4, invocation); cacheFilter.invoke(invoker4, invocation); Result result1 = cacheFilter.invoke(invoker1, invocation); Result result2 = cacheFilter.invoke(invoker2, invocation); Assertions.assertNull(result1.getValue()); Assertions.assertNull(result2.getValue()); } }
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-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.rpc.Invocation; /** * Interface needs to be implemented by all the cache store provider.Along with implementing <b>CacheFactory</b> interface * entry needs to be added in org.apache.dubbo.cache.CacheFactory file in a classpath META-INF sub directories. * * @see Cache */ @SPI("lru") public interface CacheFactory { /** * CacheFactory implementation class needs to implement this return underlying cache instance for method against * url and invocation. * @param url * @param invocation * @return Instance of Cache containing cached value against method url and invocation. */ @Adaptive("cache") Cache getCache(URL url, Invocation invocation); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache; /** * Cache interface to support storing and retrieval of value against a lookup key. It has two operation <b>get</b> and <b>put</b>. * <li><b>put</b>-Storing value against a key.</li> * <li><b>get</b>-Retrieval of object.</li> * @see org.apache.dubbo.cache.support.lru.LruCache * @see org.apache.dubbo.cache.support.jcache.JCache * @see org.apache.dubbo.cache.support.expiring.ExpiringCache * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCache */ public interface Cache { /** * API to store value against a key * @param key Unique identifier for the object being store. * @param value Value getting store */ void put(Object key, Object value); /** * API to return stored value using a key. * @param key Unique identifier for cache lookup * @return Return stored object against key */ Object get(Object 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-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.CacheFactory; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; /** * AbstractCacheFactory is a default implementation of {@link CacheFactory}. It abstract out the key formation from URL along with * invocation method. It initially check if the value for key already present in own local in-memory store then it won't check underlying storage cache {@link Cache}. * Internally it used {@link ConcurrentHashMap} to store do level-1 caching. * * @see CacheFactory * @see org.apache.dubbo.cache.support.jcache.JCacheFactory * @see org.apache.dubbo.cache.support.lru.LruCacheFactory * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory * @see org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory */ public abstract class AbstractCacheFactory implements CacheFactory { /** * This is used to store factory level-1 cached data. */ private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<>(); private final Object MONITOR = new Object(); /** * Takes URL and invocation instance and return cache instance for a given url. * * @param url url of the method * @param invocation invocation context. * @return Instance of cache store used as storage for caching return values. */ @Override public Cache getCache(URL url, Invocation invocation) { url = url.addParameter(METHOD_KEY, invocation.getMethodName()); String key = url.getServiceKey() + invocation.getMethodName(); Cache cache = caches.get(key); // get from cache first. if (null != cache) { return cache; } synchronized (MONITOR) { // double check. cache = caches.get(key); if (null != cache) { return cache; } cache = createCache(url); caches.put(key, cache); } return cache; } /** * Takes url as an method argument and return new instance of cache store implemented by AbstractCacheFactory subclass. * * @param url url of the method * @return Create and return new instance of cache store used as storage for caching return values. */ protected abstract Cache createCache(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-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support.threadlocal; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.support.AbstractCacheFactory; import org.apache.dubbo.common.URL; /** * Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide * instance of new {@link ThreadLocalCache}. Note about this class is, each thread does not have a local copy of factory. * * @see AbstractCacheFactory * @see ThreadLocalCache * @see Cache */ public class ThreadLocalCacheFactory extends AbstractCacheFactory { /** * Takes url as an method argument and return new instance of cache store implemented by ThreadLocalCache. * @param url url of the method * @return ThreadLocalCache instance of cache */ @Override protected Cache createCache(URL url) { return new ThreadLocalCache(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-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support.threadlocal; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.common.URL; import java.util.HashMap; import java.util.Map; /** * This class store the cache value per thread. If a service,method,consumer or provided is configured with key <b>cache</b> * with value <b>threadlocal</b>, dubbo initialize the instance of this class using {@link ThreadLocalCacheFactory} to store method's returns value * to server from store without making method call. * <pre> * e.g. &lt;dubbo:service cache="threadlocal" /&gt; * </pre> * <pre> * As this ThreadLocalCache stores key-value in memory without any expiry or delete support per thread wise, if number threads and number of key-value are high then jvm should be * configured with appropriate memory. * </pre> * * @see org.apache.dubbo.cache.support.AbstractCacheFactory * @see org.apache.dubbo.cache.filter.CacheFilter * @see Cache */ public class ThreadLocalCache implements Cache { /** * Thread local variable to store cached data. */ private final ThreadLocal<Map<Object, Object>> store; /** * Taken URL as an argument to create an instance of ThreadLocalCache. In this version of implementation constructor * argument is not getting used in the scope of this class. * @param url */ public ThreadLocalCache(URL url) { this.store = ThreadLocal.withInitial(HashMap::new); } /** * API to store value against a key in the calling thread scope. * @param key Unique identifier for the object being store. * @param value Value getting store */ @Override public void put(Object key, Object value) { store.get().put(key, value); } /** * API to return stored value using a key against the calling thread specific store. * @param key Unique identifier for cache lookup * @return Return stored object against key */ @Override public Object get(Object key) { return store.get().get(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-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCache.java
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCache.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support.lfu; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.LFUCache; /** * This class store the cache value per thread. If a service,method,consumer or provided is configured with key <b>cache</b> * with value <b>lfu</b>, dubbo initialize the instance of this class using {@link LfuCacheFactory} to store method's returns value * to server from store without making method call. * <pre> * e.g. 1) &lt;dubbo:service cache="lfu" cache.size="5000" cache.evictionFactor="0.3"/&gt; * 2) &lt;dubbo:consumer cache="lfu" /&gt; * </pre> * <pre> * LfuCache uses url's <b>cache.size</b> value for its max store size, url's <b>cache.evictionFactor</b> value for its eviction factor, * default store size value will be 1000, default eviction factor will be 0.3 * </pre> * * @see Cache * @see LfuCacheFactory * @see org.apache.dubbo.cache.support.AbstractCacheFactory * @see org.apache.dubbo.cache.filter.CacheFilter */ public class LfuCache implements Cache { /** * This is used to store cache records */ @SuppressWarnings("rawtypes") private final LFUCache store; /** * Initialize LfuCache, it uses constructor argument <b>cache.size</b> value as its storage max size. * If nothing is provided then it will use 1000 as default size value. <b>cache.evictionFactor</b> value as its eviction factor. * If nothing is provided then it will use 0.3 as default value. * @param url A valid URL instance */ @SuppressWarnings("rawtypes") public LfuCache(URL url) { final int max = url.getParameter("cache.size", 1000); final float factor = url.getParameter("cache.evictionFactor", 0.75f); this.store = new LFUCache(max, factor); } /** * API to store value against a key in the calling thread scope. * @param key Unique identifier for the object being store. * @param value Value getting store */ @SuppressWarnings("unchecked") @Override public void put(Object key, Object value) { store.put(key, value); } /** * API to return stored value using a key against the calling thread specific store. * @param key Unique identifier for cache lookup * @return Return stored object against key */ @SuppressWarnings("unchecked") @Override public Object get(Object key) { return store.get(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-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCacheFactory.java
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCacheFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support.lfu; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.support.AbstractCacheFactory; import org.apache.dubbo.common.URL; /** * Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide * instance of new {@link LfuCache}. * * @see AbstractCacheFactory * @see LfuCache * @see Cache */ public class LfuCacheFactory extends AbstractCacheFactory { /** * Takes url as an method argument and return new instance of cache store implemented by LfuCache. * @param url url of the method * @return ThreadLocalCache instance of cache */ @Override protected Cache createCache(URL url) { return new LfuCache(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-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support.lru; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.LRU2Cache; import java.util.Map; /** * This class store the cache value per thread. If a service,method,consumer or provided is configured with key <b>cache</b> * with value <b>lru</b>, dubbo initialize the instance of this class using {@link LruCacheFactory} to store method's returns value * to server from store without making method call. * <pre> * e.g. 1) &lt;dubbo:service cache="lru" cache.size="5000"/&gt; * 2) &lt;dubbo:consumer cache="lru" /&gt; * </pre> * <pre> * LruCache uses url's <b>cache.size</b> value for its max store size, if nothing is provided then * default value will be 1000 * </pre> * * @see Cache * @see LruCacheFactory * @see org.apache.dubbo.cache.support.AbstractCacheFactory * @see org.apache.dubbo.cache.filter.CacheFilter */ public class LruCache implements Cache { /** * This is used to store cache records */ private final Map<Object, Object> store; /** * Initialize LruCache, it uses constructor argument <b>cache.size</b> value as its storage max size. * If nothing is provided then it will use 1000 as default value. * @param url A valid URL instance */ public LruCache(URL url) { final int max = url.getParameter("cache.size", 1000); this.store = new LRU2Cache<>(max); } /** * API to store value against a key in the calling thread scope. * @param key Unique identifier for the object being store. * @param value Value getting store */ @Override public void put(Object key, Object value) { store.put(key, value); } /** * API to return stored value using a key against the calling thread specific store. * @param key Unique identifier for cache lookup * @return Return stored object against key */ @Override public Object get(Object key) { return store.get(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-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support.lru; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.support.AbstractCacheFactory; import org.apache.dubbo.common.URL; /** * Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide * instance of new {@link LruCache}. * * @see AbstractCacheFactory * @see LruCache * @see Cache */ public class LruCacheFactory extends AbstractCacheFactory { /** * Takes url as an method argument and return new instance of cache store implemented by LruCache. * @param url url of the method * @return ThreadLocalCache instance of cache */ @Override protected Cache createCache(URL url) { return new LruCache(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-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactory.java
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support.expiring; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.support.AbstractCacheFactory; import org.apache.dubbo.common.URL; /** * Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide * instance of new {@link ExpiringCache}. * * @see AbstractCacheFactory * @see ExpiringCache * @see Cache */ public class ExpiringCacheFactory extends AbstractCacheFactory { /** * Takes url as an method argument and return new instance of cache store implemented by JCache. * @param url url of the method * @return ExpiringCache instance of cache */ @Override protected Cache createCache(URL url) { return new ExpiringCache(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-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support.expiring; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * can be expired map * Contains a background thread that periodically checks if the data is out of date */ public class ExpiringMap<K, V> implements Map<K, V> { /** * default time to live (second) */ private static final int DEFAULT_TIME_TO_LIVE = 180; /** * default expire check interval (second) */ private static final int DEFAULT_EXPIRATION_INTERVAL = 1; private static final AtomicInteger expireCount = new AtomicInteger(1); private final ConcurrentHashMap<K, ExpiryObject> delegateMap; private final ExpireThread expireThread; public ExpiringMap() { this(DEFAULT_TIME_TO_LIVE, DEFAULT_EXPIRATION_INTERVAL); } /** * Constructor * * @param timeToLive time to live (second) */ public ExpiringMap(int timeToLive) { this(timeToLive, DEFAULT_EXPIRATION_INTERVAL); } public ExpiringMap(int timeToLive, int expirationInterval) { this(new ConcurrentHashMap<>(), timeToLive, expirationInterval); } private ExpiringMap(ConcurrentHashMap<K, ExpiryObject> delegateMap, int timeToLive, int expirationInterval) { this.delegateMap = delegateMap; this.expireThread = new ExpireThread(); expireThread.setTimeToLive(timeToLive); expireThread.setExpirationInterval(expirationInterval); } @Override public V put(K key, V value) { ExpiryObject answer = delegateMap.put(key, new ExpiryObject(key, value, System.currentTimeMillis())); if (answer == null) { return null; } return answer.getValue(); } @Override public V get(Object key) { ExpiryObject object = delegateMap.get(key); if (object != null) { long timeIdle = System.currentTimeMillis() - object.getLastAccessTime(); int timeToLive = expireThread.getTimeToLive(); if (timeToLive > 0 && timeIdle >= timeToLive * 1000L) { delegateMap.remove(object.getKey()); return null; } object.setLastAccessTime(System.currentTimeMillis()); return object.getValue(); } return null; } @Override public V remove(Object key) { ExpiryObject answer = delegateMap.remove(key); if (answer == null) { return null; } return answer.getValue(); } @Override public boolean containsKey(Object key) { return delegateMap.containsKey(key); } @Override public boolean containsValue(Object value) { return delegateMap.containsValue(value); } @Override public int size() { return delegateMap.size(); } @Override public boolean isEmpty() { return delegateMap.isEmpty(); } @Override public void clear() { delegateMap.clear(); expireThread.stopExpiring(); } @Override public int hashCode() { return delegateMap.hashCode(); } @Override public Set<K> keySet() { return delegateMap.keySet(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } return delegateMap.equals(obj); } @Override public void putAll(Map<? extends K, ? extends V> inMap) { for (Entry<? extends K, ? extends V> e : inMap.entrySet()) { this.put(e.getKey(), e.getValue()); } } @Override public Collection<V> values() { List<V> list = new ArrayList<>(); Set<Entry<K, ExpiryObject>> delegatedSet = delegateMap.entrySet(); for (Entry<K, ExpiryObject> entry : delegatedSet) { ExpiryObject value = entry.getValue(); list.add(value.getValue()); } return list; } @Override public Set<Entry<K, V>> entrySet() { throw new UnsupportedOperationException(); } public ExpireThread getExpireThread() { return expireThread; } public int getExpirationInterval() { return expireThread.getExpirationInterval(); } public void setExpirationInterval(int expirationInterval) { expireThread.setExpirationInterval(expirationInterval); } public int getTimeToLive() { return expireThread.getTimeToLive(); } public void setTimeToLive(int timeToLive) { expireThread.setTimeToLive(timeToLive); } @Override public String toString() { return "ExpiringMap{" + "delegateMap=" + delegateMap.toString() + ", expireThread=" + expireThread.toString() + '}'; } /** * can be expired object */ private class ExpiryObject { private K key; private V value; private AtomicLong lastAccessTime; ExpiryObject(K key, V value, long lastAccessTime) { if (value == null) { throw new IllegalArgumentException("An expiring object cannot be null."); } this.key = key; this.value = value; this.lastAccessTime = new AtomicLong(lastAccessTime); } public long getLastAccessTime() { return lastAccessTime.get(); } public void setLastAccessTime(long lastAccessTime) { this.lastAccessTime.set(lastAccessTime); } public K getKey() { return key; } public V getValue() { return value; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } return value.equals(obj); } @Override public int hashCode() { return value.hashCode(); } @Override public String toString() { return "ExpiryObject{" + "key=" + key + ", value=" + value + ", lastAccessTime=" + lastAccessTime + '}'; } } /** * Background thread, periodically checking if the data is out of date */ public class ExpireThread implements Runnable { private long timeToLiveMillis; private long expirationIntervalMillis; private volatile boolean running = false; private final Thread expirerThread; @Override public String toString() { return "ExpireThread{" + ", timeToLiveMillis=" + timeToLiveMillis + ", expirationIntervalMillis=" + expirationIntervalMillis + ", running=" + running + ", expirerThread=" + expirerThread + '}'; } public ExpireThread() { expirerThread = new Thread(this, "ExpiryMapExpire-" + expireCount.getAndIncrement()); expirerThread.setDaemon(true); } @Override public void run() { while (running) { processExpires(); try { Thread.sleep(expirationIntervalMillis); } catch (InterruptedException e) { running = false; } } } private void processExpires() { long timeNow = System.currentTimeMillis(); if (timeToLiveMillis <= 0) { return; } for (ExpiryObject o : delegateMap.values()) { long timeIdle = timeNow - o.getLastAccessTime(); if (timeIdle >= timeToLiveMillis) { delegateMap.remove(o.getKey()); } } } /** * start expiring Thread */ public void startExpiring() { if (!running) { running = true; expirerThread.start(); } } /** * start thread */ public void startExpiryIfNotStarted() { if (running && timeToLiveMillis <= 0) { return; } startExpiring(); } /** * stop thread */ public void stopExpiring() { if (running) { running = false; expirerThread.interrupt(); } } /** * get thread state * * @return thread state */ public boolean isRunning() { return running; } /** * get time to live * * @return time to live */ public int getTimeToLive() { return (int) timeToLiveMillis / 1000; } /** * update time to live * * @param timeToLive time to live */ public void setTimeToLive(long timeToLive) { this.timeToLiveMillis = timeToLive * 1000; } /** * get expiration interval * * @return expiration interval (second) */ public int getExpirationInterval() { return (int) expirationIntervalMillis / 1000; } /** * set expiration interval * * @param expirationInterval expiration interval (second) */ public void setExpirationInterval(long expirationInterval) { this.expirationIntervalMillis = expirationInterval * 1000; } } }
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-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCache.java
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCache.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support.expiring; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.common.URL; import java.util.Map; /** * ExpiringCache - With the characteristic of expiration time. */ /** * This class store the cache value with the characteristic of expiration time. If a service,method,consumer or provided is configured with key <b>cache</b> * with value <b>expiring</b>, dubbo initialize the instance of this class using {@link ExpiringCacheFactory} to store method's returns value * to server from store without making method call. * <pre> * e.g. 1) &lt;dubbo:service cache="expiring" cache.seconds="60" cache.interval="10"/&gt; * 2) &lt;dubbo:consumer cache="expiring" /&gt; * </pre> * <li>It used constructor argument url instance <b>cache.seconds</b> value to decide time to live of cached object.Default value of it is 180 second.</li> * <li>It used constructor argument url instance <b>cache.interval</b> value for cache value expiration interval.Default value of this is 4 second</li> * @see Cache * @see ExpiringCacheFactory * @see org.apache.dubbo.cache.support.AbstractCacheFactory * @see org.apache.dubbo.cache.filter.CacheFilter */ public class ExpiringCache implements Cache { private final Map<Object, Object> store; public ExpiringCache(URL url) { // cache time (second) final int secondsToLive = url.getParameter("cache.seconds", 180); // Cache check interval (second) final int intervalSeconds = url.getParameter("cache.interval", 4); ExpiringMap<Object, Object> expiringMap = new ExpiringMap<>(secondsToLive, intervalSeconds); expiringMap.getExpireThread().startExpiryIfNotStarted(); this.store = expiringMap; } /** * API to store value against a key in the calling thread scope. * @param key Unique identifier for the object being store. * @param value Value getting store */ @Override public void put(Object key, Object value) { store.put(key, value); } /** * API to return stored value using a key against the calling thread specific store. * @param key Unique identifier for cache lookup * @return Return stored object against key */ @Override public Object get(Object key) { return store.get(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-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support.jcache; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import javax.cache.Cache; import javax.cache.CacheException; import javax.cache.CacheManager; import javax.cache.Caching; import javax.cache.configuration.MutableConfiguration; import javax.cache.expiry.CreatedExpiryPolicy; import javax.cache.expiry.Duration; import javax.cache.spi.CachingProvider; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; /** * This class store the cache value per thread. If a service,method,consumer or provided is configured with key <b>cache</b> * with value <b>jcache</b>, dubbo initialize the instance of this class using {@link JCacheFactory} to store method's returns value * to server from store without making method call. * * @see Cache * @see JCacheFactory * @see org.apache.dubbo.cache.support.AbstractCacheFactory * @see org.apache.dubbo.cache.filter.CacheFilter */ public class JCache implements org.apache.dubbo.cache.Cache { private final Cache<Object, Object> store; public JCache(URL url) { String method = url.getParameter(METHOD_KEY, ""); String key = url.getAddress() + "." + url.getServiceKey() + "." + method; // jcache parameter is the full-qualified class name of SPI implementation String type = url.getParameter("jcache"); CachingProvider provider = StringUtils.isEmpty(type) ? Caching.getCachingProvider() : Caching.getCachingProvider(type); CacheManager cacheManager = provider.getCacheManager(); Cache<Object, Object> cache = cacheManager.getCache(key); if (cache == null) { try { // configure the cache MutableConfiguration config = new MutableConfiguration<>() .setTypes(Object.class, Object.class) .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration( TimeUnit.MILLISECONDS, url.getMethodParameter(method, "cache.write.expire", 60 * 1000)))) .setStoreByValue(false) .setManagementEnabled(true) .setStatisticsEnabled(true); cache = cacheManager.createCache(key, config); } catch (CacheException e) { // concurrent cache initialization cache = cacheManager.getCache(key); } } this.store = cache; } @Override public void put(Object key, Object value) { store.put(key, value); } @Override public Object get(Object key) { return store.get(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-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.support.jcache; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.support.AbstractCacheFactory; import org.apache.dubbo.common.URL; import javax.cache.spi.CachingProvider; /** * JCacheFactory is factory class to provide instance of javax spi cache.Implement {@link org.apache.dubbo.cache.CacheFactory} by * extending {@link AbstractCacheFactory} and provide * @see AbstractCacheFactory * @see JCache * @see org.apache.dubbo.cache.filter.CacheFilter * @see Cache * @see CachingProvider * @see javax.cache.Cache * @see javax.cache.CacheManager */ public class JCacheFactory extends AbstractCacheFactory { /** * Takes url as an method argument and return new instance of cache store implemented by JCache. * @param url url of the method * @return JCache instance of cache */ @Override protected Cache createCache(URL url) { return new JCache(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-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.cache.filter; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.CacheFactory; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.StringUtils; 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 java.io.Serializable; 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.CACHE_KEY; /** * CacheFilter is a core component of dubbo.Enabling <b>cache</b> key of service,method,consumer or provider dubbo will cache method return value. * Along with cache key we need to configure cache type. Dubbo default implemented cache types are * <li>lru</li> * <li>threadlocal</li> * <li>jcache</li> * <li>expiring</li> * * <pre> * e.g. 1)&lt;dubbo:service cache="lru" /&gt; * 2)&lt;dubbo:service /&gt; &lt;dubbo:method name="method2" cache="threadlocal" /&gt; &lt;dubbo:service/&gt; * 3)&lt;dubbo:provider cache="expiring" /&gt; * 4)&lt;dubbo:consumer cache="jcache" /&gt; * *If cache type is defined in method level then method level type will get precedence. According to above provided *example, if service has two method, method1 and method2, method2 will have cache type as <b>threadlocal</b> where others will *be backed by <b>lru</b> *</pre> * * @see org.apache.dubbo.rpc.Filter * @see org.apache.dubbo.cache.support.lru.LruCacheFactory * @see org.apache.dubbo.cache.support.lru.LruCache * @see org.apache.dubbo.cache.support.jcache.JCacheFactory * @see org.apache.dubbo.cache.support.jcache.JCache * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCache * @see org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory * @see org.apache.dubbo.cache.support.expiring.ExpiringCache * */ @Activate( group = {CONSUMER, PROVIDER}, value = CACHE_KEY) public class CacheFilter implements Filter { private CacheFactory cacheFactory; /** * Dubbo will populate and set the cache factory instance based on service/method/consumer/provider configured * cache attribute value. Dubbo will search for the class name implementing configured <b>cache</b> in file org.apache.dubbo.cache.CacheFactory * under META-INF sub folders. * * @param cacheFactory instance of CacheFactory based on <b>cache</b> type */ public void setCacheFactory(CacheFactory cacheFactory) { this.cacheFactory = cacheFactory; } /** * If cache is configured, dubbo will invoke method on each method call. If cache value is returned by cache store * then it will return otherwise call the remote method and return value. If remote method's return value has error * then it will not cache the value. * @param invoker service * @param invocation invocation. * @return Cache returned value if found by the underlying cache store. If cache miss it will call target method. * @throws RpcException */ @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if (cacheFactory == null || ConfigUtils.isEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), CACHE_KEY))) { return invoker.invoke(invocation); } Cache cache = cacheFactory.getCache(invoker.getUrl(), invocation); if (cache == null) { return invoker.invoke(invocation); } String key = StringUtils.toArgumentString(invocation.getArguments()); Object value = cache.get(key); return (value != null) ? onCacheValuePresent(invocation, value) : onCacheValueNotPresent(invoker, invocation, cache, key); } private Result onCacheValuePresent(Invocation invocation, Object value) { if (value instanceof ValueWrapper) { return AsyncRpcResult.newDefaultAsyncResult(((ValueWrapper) value).get(), invocation); } return AsyncRpcResult.newDefaultAsyncResult(value, invocation); } private Result onCacheValueNotPresent(Invoker<?> invoker, Invocation invocation, Cache cache, String key) { Result result = invoker.invoke(invocation); if (!result.hasException()) { cache.put(key, new ValueWrapper(result.getValue())); } return result; } /** * Cache value wrapper. */ static class ValueWrapper implements Serializable { private static final long serialVersionUID = -1777337318019193256L; private final Object value; public ValueWrapper(Object value) { this.value = value; } public Object get() { return this.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-native/src/test/java/org/apache/dubbo/aot/generate/ResourcePatternDescriberTest.java
dubbo-plugin/dubbo-native/src/test/java/org/apache/dubbo/aot/generate/ResourcePatternDescriberTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.generate; import org.apache.dubbo.aot.api.ResourcePatternDescriber; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class ResourcePatternDescriberTest { @Test public void testToRegex() { ResourcePatternDescriber describer = new ResourcePatternDescriber( "META-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionInjector", null); Assertions.assertEquals( "\\QMETA-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionInjector\\E", describer.toRegex().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-native/src/main/java/org/apache/dubbo/aot/generate/BasicJsonWriter.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/BasicJsonWriter.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.generate; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.function.Consumer; /** * Very basic json writer for the purposes of translating runtime hints to native * configuration. */ class BasicJsonWriter { private final IndentingWriter writer; /** * Create a new instance with the specified indent value. * * @param writer the writer to use * @param singleIndent the value of one indent */ public BasicJsonWriter(Writer writer, String singleIndent) { this.writer = new IndentingWriter(writer, singleIndent); } /** * Create a new instance using two whitespaces for the indent. * * @param writer the writer to use */ public BasicJsonWriter(Writer writer) { this(writer, " "); } /** * Write an object with the specified attributes. Each attribute is * written according to its value type: * <ul> * <li>Map: write the value as a nested object</li> * <li>List: write the value as a nested array</li> * <li>Otherwise, write a single value</li> * </ul> * * @param attributes the attributes of the object */ public void writeObject(Map<String, Object> attributes) { writeObject(attributes, true); } /** * Write an array with the specified items. Each item in the * list is written either as a nested object or as an attribute * depending on its type. * * @param items the items to write * @see #writeObject(Map) */ public void writeArray(List<?> items) { writeArray(items, true); } private void writeObject(Map<String, Object> attributes, boolean newLine) { if (attributes.isEmpty()) { this.writer.print("{ }"); } else { this.writer.println("{").indented(writeAll(attributes.entrySet().iterator(), entry -> writeAttribute(entry.getKey(), entry.getValue()))).print("}"); } if (newLine) { this.writer.println(); } } private void writeArray(List<?> items, boolean newLine) { if (items.isEmpty()) { this.writer.print("[ ]"); } else { this.writer.println("[") .indented(writeAll(items.iterator(), this::writeValue)).print("]"); } if (newLine) { this.writer.println(); } } private <T> Runnable writeAll(Iterator<T> it, Consumer<T> writer) { return () -> { while (it.hasNext()) { writer.accept(it.next()); if (it.hasNext()) { this.writer.println(","); } else { this.writer.println(); } } }; } private void writeAttribute(String name, Object value) { this.writer.print(quote(name) + ": "); writeValue(value); } @SuppressWarnings("unchecked") private void writeValue(Object value) { if (value instanceof Map<?, ?>) { writeObject((Map<String, Object>) value, false); } else if (value instanceof List<?>) { writeArray((List<?>) value, false); } else if (value instanceof CharSequence) { this.writer.print(quote(escape((CharSequence) value))); } else if (value instanceof Boolean) { this.writer.print(Boolean.toString((Boolean) value)); } else { throw new IllegalStateException("unsupported type: " + value.getClass()); } } private String quote(String name) { return "\"" + name + "\""; } private static String escape(CharSequence input) { StringBuilder builder = new StringBuilder(); input.chars().forEach(c -> { if (c == '"') { builder.append("\\\""); } else if (c == '\\') { builder.append("\\\\"); } else if (c == '\b') { builder.append("\\b"); } else if (c == '\f') { builder.append("\\f"); } else if (c == '\n') { builder.append("\\n"); } else if (c == '\r') { builder.append("\\r"); } else if (c == '\t') { builder.append("\\t"); } else if (c <= 0x1F) { builder.append(String.format("\\u%04x", c)); } else { builder.append((char) c); } }); return builder.toString(); } static class IndentingWriter extends Writer { private final Writer out; private final String singleIndent; private int level = 0; private String currentIndent = ""; private boolean prependIndent = false; IndentingWriter(Writer out, String singleIndent) { this.out = out; this.singleIndent = singleIndent; } /** * Write the specified text. * * @param string the content to write */ public IndentingWriter print(String string) { write(string.toCharArray(), 0, string.length()); return this; } /** * Write the specified text and append a new line. * * @param string the content to write */ public IndentingWriter println(String string) { write(string.toCharArray(), 0, string.length()); return println(); } /** * Write a new line. */ public IndentingWriter println() { String separator = System.lineSeparator(); try { this.out.write(separator.toCharArray(), 0, separator.length()); } catch (IOException ex) { throw new IllegalStateException(ex); } this.prependIndent = true; return this; } /** * Increase the indentation level and execute the {@link Runnable}. Decrease the * indentation level on completion. * * @param runnable the code to execute within an extra indentation level */ public IndentingWriter indented(Runnable runnable) { indent(); runnable.run(); return outdent(); } /** * Increase the indentation level. */ private IndentingWriter indent() { this.level++; return refreshIndent(); } /** * Decrease the indentation level. */ private IndentingWriter outdent() { this.level--; return refreshIndent(); } private IndentingWriter refreshIndent() { int count = Math.max(0, this.level); StringBuilder str = new StringBuilder(); for (int i = 0; i < count; i++) { str.append(this.singleIndent); } this.currentIndent = str.toString(); return this; } @Override public void write(char[] chars, int offset, int length) { try { if (this.prependIndent) { this.out.write(this.currentIndent.toCharArray(), 0, this.currentIndent.length()); this.prependIndent = false; } this.out.write(chars, offset, length); } catch (IOException ex) { throw new IllegalStateException(ex); } } @Override public void flush() throws IOException { this.out.flush(); } @Override public void close() throws IOException { this.out.close(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ProxyConfigWriter.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ProxyConfigWriter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.generate; import org.apache.dubbo.aot.api.JdkProxyDescriber; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; /** * Write a {@link ProxyConfigMetadataRepository} to the JSON output expected by the GraalVM * {@code native-image} compiler, typically named {@code proxy-config.json}. */ public class ProxyConfigWriter { public static final ProxyConfigWriter INSTANCE = new ProxyConfigWriter(); public void write(BasicJsonWriter writer, ProxyConfigMetadataRepository repository) { writer.writeArray( repository.getProxyDescribers().stream().map(this::toAttributes).collect(Collectors.toList())); } private Map<String, Object> toAttributes(JdkProxyDescriber describer) { Map<String, Object> attributes = new LinkedHashMap<>(); handleCondition(attributes, describer); attributes.put("interfaces", describer.getProxiedInterfaces()); return attributes; } private void handleCondition(Map<String, Object> attributes, JdkProxyDescriber describer) { if (describer.getReachableType() != null) { Map<String, Object> conditionAttributes = new LinkedHashMap<>(); conditionAttributes.put("typeReachable", describer.getReachableType()); attributes.put("condition", conditionAttributes); } } }
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/generate/ClassSourceScanner.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ClassSourceScanner.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.generate; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.AbstractConfig; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /** * A scanner for processing and filtering specific types of classes */ public class ClassSourceScanner extends JarScanner { public static final ClassSourceScanner INSTANCE = new ClassSourceScanner(); /** * Filter out the spi classes with adaptive annotations * from all the class collections that can be loaded. * @return All spi classes with adaptive annotations */ public List<Class<?>> spiClassesWithAdaptive() { Map<String, Class<?>> allClasses = getClasses(); List<Class<?>> spiClasses = new ArrayList<>(allClasses.values()) .stream() .filter(it -> { if (null == it) { return false; } Annotation anno = it.getAnnotation(SPI.class); if (null == anno) { return false; } Optional<Method> optional = Arrays.stream(it.getMethods()) .filter(it2 -> it2.getAnnotation(Adaptive.class) != null) .findAny(); return optional.isPresent(); }) .collect(Collectors.toList()); return spiClasses; } /** * The required adaptive class. * For example: LoadBalance$Adaptive.class * @return adaptive class */ public Map<String, Class<?>> adaptiveClasses() { List<String> res = spiClassesWithAdaptive().stream() .map((c) -> c.getName() + "$Adaptive") .collect(Collectors.toList()); return forNames(res); } /** * The required configuration class, which is a subclass of AbstractConfig, * but which excludes abstract classes. * @return configuration class */ public List<Class<?>> configClasses() { return getClasses().values().stream() .filter(c -> AbstractConfig.class.isAssignableFrom(c) && !Modifier.isAbstract(c.getModifiers())) .collect(Collectors.toList()); } public Map<String, Class<?>> distinctSpiExtensionClasses(Set<String> spiResource) { Map<String, Class<?>> extensionClasses = new HashMap<>(); spiResource.forEach((fileName) -> { Enumeration<URL> resources; try { resources = ClassLoader.getSystemResources(fileName); if (resources != null) { while (resources.hasMoreElements()) { extensionClasses.putAll(loadResource(resources.nextElement())); } } } catch (IOException e) { throw new RuntimeException(e); } }); return extensionClasses; } /** * Beans that need to be injected in advance in different ScopeModels. * For example, the RouterSnapshotSwitcher that needs to be injected when ClusterScopeModelInitializer executes initializeFrameworkModel * @return Beans that need to be injected in advance */ public List<Class<?>> scopeModelInitializer() { List<Class<?>> classes = new ArrayList<>(); classes.addAll(FrameworkModel.defaultModel().getBeanFactory().getRegisteredClasses()); classes.addAll(FrameworkModel.defaultModel() .defaultApplication() .getBeanFactory() .getRegisteredClasses()); classes.addAll(FrameworkModel.defaultModel() .defaultApplication() .getDefaultModule() .getBeanFactory() .getRegisteredClasses()); return classes.stream().distinct().collect(Collectors.toList()); } private Map<String, Class<?>> loadResource(URL resourceUrl) { Map<String, Class<?>> extensionClasses = new HashMap<>(); try { List<String> newContentList = getResourceContent(resourceUrl); String clazz; for (String line : newContentList) { try { int i = line.indexOf('='); if (i > 0) { clazz = line.substring(i + 1).trim(); } else { clazz = line; } if (StringUtils.isNotEmpty(clazz)) { extensionClasses.put(clazz, getClasses().get(clazz)); } } catch (Throwable t) { } } } catch (Throwable t) { } return extensionClasses; } private List<String> getResourceContent(URL resourceUrl) throws IOException { List<String> newContentList = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceUrl.openStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { final int ci = line.indexOf('#'); if (ci >= 0) { line = line.substring(0, ci); } line = line.trim(); if (line.length() > 0) { newContentList.add(line); } } } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } return newContentList; } }
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/generate/ReflectConfigMetadataRepository.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectConfigMetadataRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.generate; import org.apache.dubbo.aot.api.ExecutableDescriber; import org.apache.dubbo.aot.api.MemberCategory; import org.apache.dubbo.aot.api.TypeDescriber; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import static org.apache.dubbo.aot.api.ExecutableMode.INVOKE; public class ReflectConfigMetadataRepository { List<TypeDescriber> types; public ReflectConfigMetadataRepository() { this.types = new ArrayList<>(); } protected ReflectConfigMetadataRepository registerSpiExtensionType(List<Class<?>> classes) { types.addAll(classes.stream() .filter(Objects::nonNull) .map(this::buildTypeDescriberWithConstructor) .collect(Collectors.toList())); return this; } protected ReflectConfigMetadataRepository registerAdaptiveType(List<Class<?>> classes) { types.addAll(classes.stream() .filter(Objects::nonNull) .map(this::buildTypeDescriberWithConstructor) .collect(Collectors.toList())); return this; } protected ReflectConfigMetadataRepository registerBeanType(List<Class<?>> classes) { types.addAll(classes.stream() .filter(Objects::nonNull) .map(this::buildTypeDescriberWithConstructor) .collect(Collectors.toList())); return this; } protected ReflectConfigMetadataRepository registerConfigType(List<Class<?>> classes) { types.addAll(classes.stream() .filter(Objects::nonNull) .map(this::buildTypeDescriberWithConstructor) .collect(Collectors.toList())); return this; } private TypeDescriber buildTypeDescriberWithConstructor(Class<?> c) { Set<ExecutableDescriber> constructors = Arrays.stream(c.getConstructors()) .map((constructor) -> new ExecutableDescriber(constructor, INVOKE)) .collect(Collectors.toSet()); Set<MemberCategory> memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_PUBLIC_METHODS); return new TypeDescriber(c.getName(), null, new HashSet<>(), constructors, new HashSet<>(), memberCategories); } protected ReflectConfigMetadataRepository registerFieldType(List<Class<?>> classes) { types.addAll(classes.stream() .filter(Objects::nonNull) .map(this::buildTypeDescriberWithField) .collect(Collectors.toList())); return this; } private TypeDescriber buildTypeDescriberWithField(Class<?> c) { Set<ExecutableDescriber> constructors = Arrays.stream(c.getConstructors()) .map((constructor) -> new ExecutableDescriber(constructor, INVOKE)) .collect(Collectors.toSet()); Set<MemberCategory> memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.PUBLIC_FIELDS); return new TypeDescriber(c.getName(), null, new HashSet<>(), constructors, new HashSet<>(), memberCategories); } public void registerTypeDescriber(List<TypeDescriber> typeDescribers) { types.addAll(typeDescribers.stream().filter(Objects::nonNull).collect(Collectors.toList())); } public List<TypeDescriber> getTypes() { return types; } }
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/generate/NativeConfigurationWriter.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeConfigurationWriter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.generate; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.nio.file.Path; import java.util.function.Consumer; /** * Write Write configuration metadata information in * {@link ResourceConfigMetadataRepository} and {@link ReflectConfigMetadataRepository} * as GraalVM native configuration. * * @see <a href="https://www.graalvm.org/latest/reference-manual/native-image/overview/BuildConfiguration/">Native Image Build Configuration</a> */ public class NativeConfigurationWriter { private final Path basePath; private final String groupId; private final String artifactId; public NativeConfigurationWriter(Path basePath, String groupId, String artifactId) { this.basePath = basePath; this.groupId = groupId; this.artifactId = artifactId; } protected void writeTo(String fileName, Consumer<BasicJsonWriter> writer) { try { File file = createIfNecessary(fileName); try (FileWriter out = new FileWriter(file)) { writer.accept(createJsonWriter(out)); } } catch (IOException ex) { throw new IllegalStateException("Failed to write native configuration for " + fileName, ex); } } private File createIfNecessary(String filename) throws IOException { Path outputDirectory = this.basePath.resolve("META-INF").resolve("native-image"); if (this.groupId != null && this.artifactId != null) { outputDirectory = outputDirectory .resolve(this.groupId) .resolve(this.artifactId) .resolve("dubbo"); } outputDirectory.toFile().mkdirs(); File file = outputDirectory.resolve(filename).toFile(); file.createNewFile(); return file; } public void writeReflectionConfig(ReflectConfigMetadataRepository repository) { writeTo("reflect-config.json", writer -> ReflectionConfigWriter.INSTANCE.write(writer, repository)); } public void writeResourceConfig(ResourceConfigMetadataRepository repository) { writeTo("resource-config.json", writer -> ResourceConfigWriter.INSTANCE.write(writer, repository)); } public void writeProxyConfig(ProxyConfigMetadataRepository repository) { writeTo("proxy-config.json", writer -> ProxyConfigWriter.INSTANCE.write(writer, repository)); } private BasicJsonWriter createJsonWriter(Writer out) { return new BasicJsonWriter(out); } }
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/generate/ProxyConfigMetadataRepository.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ProxyConfigMetadataRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.generate; import org.apache.dubbo.aot.api.JdkProxyDescriber; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; public class ProxyConfigMetadataRepository { private final Set<JdkProxyDescriber> jdkProxyDescribers; public ProxyConfigMetadataRepository() { this.jdkProxyDescribers = new LinkedHashSet<>(); } public ProxyConfigMetadataRepository registerProxyDescriber(JdkProxyDescriber describer) { this.jdkProxyDescribers.add(describer); return this; } public ProxyConfigMetadataRepository registerProxyDescribers(List<JdkProxyDescriber> describers) { this.jdkProxyDescribers.addAll( describers.stream().filter(Objects::nonNull).collect(Collectors.toList())); return this; } public Set<JdkProxyDescriber> getProxyDescribers() { return jdkProxyDescribers; } }
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/generate/JarScanner.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/JarScanner.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.generate; import java.io.File; import java.net.JarURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * A scanner that scan the dependent jar packages * to obtain the classes source and resources in them. */ public class JarScanner { private static final String PACKAGE_NAME_PREFIX = "org/apache/dubbo"; private final Map<String, String> classNameCache; private Map<String, Class<?>> classesCache; private final List<String> resourcePathCache; protected Map<String, Class<?>> getClasses() { if (classesCache == null || classesCache.size() == 0) { this.classesCache = forNames(classNameCache.values()); } return classesCache; } public JarScanner() { classNameCache = new HashMap<>(); resourcePathCache = new ArrayList<>(); scanURL(PACKAGE_NAME_PREFIX); } protected Map<String, Class<?>> forNames(Collection<String> classNames) { Map<String, Class<?>> classes = new HashMap<>(); classNames.forEach((it) -> { try { Class<?> c = Class.forName(it); classes.put(it, c); } catch (Throwable ignored) { } }); return classes; } private void scanURL(String prefixName) { try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Enumeration<URL> resources = classLoader.getResources(prefixName); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); String protocol = resource.getProtocol(); if ("file".equals(protocol)) { scanFile(resource.getPath()); } else if ("jar".equals(protocol)) { try (JarFile jar = ((JarURLConnection) resource.openConnection()).getJarFile()) { scanJar(jar); } } } } catch (Throwable ex) { throw new RuntimeException(ex); } } private void scanFile(String resource) { File directory = new File(resource); File[] listFiles = directory.listFiles(); if (listFiles != null) { for (File file : listFiles) { if (file.isDirectory()) { scanFile(file.getPath()); } else { String path = file.getPath(); if (matchedDubboClasses(path)) { classNameCache.put(path, toClassName(path)); } } } } } private void scanJar(JarFile jar) { Enumeration<JarEntry> entry = jar.entries(); JarEntry jarEntry; String name; while (entry.hasMoreElements()) { jarEntry = entry.nextElement(); name = jarEntry.getName(); if (name.charAt(0) == '/') { name = name.substring(1); } if (jarEntry.isDirectory()) { continue; } if (matchedDubboClasses(name)) { classNameCache.put(name, toClassName(name)); } else { resourcePathCache.add(name); } } } protected List<String> getResourcePath() { return resourcePathCache; } private boolean matchedDubboClasses(String path) { return path.startsWith(PACKAGE_NAME_PREFIX) && path.endsWith(".class"); } private String toClassName(String path) { return path.contains(File.separator) ? path.substring(0, path.length() - 6).replace(File.separator, ".") : path.substring(0, path.length() - 6).replace("/", "."); } }
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/generate/ResourceConfigMetadataRepository.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigMetadataRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.generate; import org.apache.dubbo.aot.api.ResourceBundleDescriber; import org.apache.dubbo.aot.api.ResourcePatternDescriber; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public class ResourceConfigMetadataRepository { private final List<ResourcePatternDescriber> includes; private final List<ResourcePatternDescriber> excludes; private final Set<ResourceBundleDescriber> resourceBundles; public ResourceConfigMetadataRepository() { this.includes = new ArrayList<>(); this.excludes = new ArrayList<>(); this.resourceBundles = new LinkedHashSet<>(); } public ResourceConfigMetadataRepository registerIncludesPatterns(String... patterns) { for (String pattern : patterns) { registerIncludesPattern(new ResourcePatternDescriber(pattern, null)); } return this; } public ResourceConfigMetadataRepository registerIncludesPattern(ResourcePatternDescriber describer) { this.includes.add(describer); return this; } public ResourceConfigMetadataRepository registerExcludesPattern(ResourcePatternDescriber describer) { this.excludes.add(describer); return this; } public ResourceConfigMetadataRepository registerBundles(ResourceBundleDescriber describer) { this.resourceBundles.add(describer); return this; } public List<ResourcePatternDescriber> getIncludes() { return includes; } public List<ResourcePatternDescriber> getExcludes() { return excludes; } public Set<ResourceBundleDescriber> getResourceBundles() { return resourceBundles; } }
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/generate/ResourceScanner.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceScanner.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.generate; import java.util.Set; import java.util.stream.Collectors; /** * A scanner for processing and filtering specific resource. */ public class ResourceScanner extends JarScanner { private static final String DUBBO_INTERNAL_RESOURCE_DIRECTORY = "META-INF/dubbo/internal/"; private static final String DUBBO_RESOURCE_DIRECTORY = "META-INF/dubbo/"; private static final String SERVICES_RESOURCE_DIRECTORY = "META-INF/services/"; private static final String SECURITY_RESOURCE_DIRECTORY = "security/"; public static final ResourceScanner INSTANCE = new ResourceScanner(); public Set<String> distinctSpiResource() { return getResourcePath().stream() .distinct() .filter(this::matchedSpiResource) .collect(Collectors.toSet()); } public Set<String> distinctSecurityResource() { return getResourcePath().stream() .distinct() .filter(this::matchedSecurityResource) .collect(Collectors.toSet()); } private boolean matchedSecurityResource(String path) { return path.startsWith(SECURITY_RESOURCE_DIRECTORY); } private boolean matchedSpiResource(String path) { return path.startsWith(DUBBO_INTERNAL_RESOURCE_DIRECTORY) || path.startsWith(DUBBO_RESOURCE_DIRECTORY) || path.startsWith(SERVICES_RESOURCE_DIRECTORY); } }
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/generate/AotProcessor.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/AotProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.generate; import org.apache.dubbo.aot.api.JdkProxyDescriber; import org.apache.dubbo.aot.api.ProxyDescriberRegistrar; import org.apache.dubbo.aot.api.ReflectionTypeDescriberRegistrar; import org.apache.dubbo.aot.api.ResourceBundleDescriber; import org.apache.dubbo.aot.api.ResourceDescriberRegistrar; import org.apache.dubbo.aot.api.ResourcePatternDescriber; import org.apache.dubbo.aot.api.TypeDescriber; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.rpc.model.FrameworkModel; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * generate related self-adaptive code (native image does not support dynamic code generation. Therefore, code needs to be generated before compilation) */ public class AotProcessor { public static void main(String[] args) { String generatedSources = args[1]; List<Class<?>> classes = ClassSourceScanner.INSTANCE.spiClassesWithAdaptive(); NativeClassSourceWriter.INSTANCE.writeTo(classes, generatedSources); NativeConfigurationWriter writer = new NativeConfigurationWriter(Paths.get(args[2]), args[4], args[5]); ResourceConfigMetadataRepository resourceRepository = new ResourceConfigMetadataRepository(); resourceRepository.registerIncludesPatterns( ResourceScanner.INSTANCE.distinctSpiResource().toArray(new String[] {})); resourceRepository.registerIncludesPatterns( ResourceScanner.INSTANCE.distinctSecurityResource().toArray(new String[] {})); for (ResourcePatternDescriber resourcePatternDescriber : getResourcePatternDescribers()) { resourceRepository.registerIncludesPattern(resourcePatternDescriber); } for (ResourceBundleDescriber resourceBundleDescriber : getResourceBundleDescribers()) { resourceRepository.registerBundles(resourceBundleDescriber); } writer.writeResourceConfig(resourceRepository); ReflectConfigMetadataRepository reflectRepository = new ReflectConfigMetadataRepository(); reflectRepository .registerSpiExtensionType(new ArrayList<>(ClassSourceScanner.INSTANCE .distinctSpiExtensionClasses(ResourceScanner.INSTANCE.distinctSpiResource()) .values())) .registerAdaptiveType(new ArrayList<>( ClassSourceScanner.INSTANCE.adaptiveClasses().values())) .registerBeanType(ClassSourceScanner.INSTANCE.scopeModelInitializer()) .registerConfigType(ClassSourceScanner.INSTANCE.configClasses()) .registerFieldType(getCustomClasses()) .registerTypeDescriber(getTypes()); writer.writeReflectionConfig(reflectRepository); ProxyConfigMetadataRepository proxyRepository = new ProxyConfigMetadataRepository(); proxyRepository.registerProxyDescribers(getProxyDescribers()); writer.writeProxyConfig(proxyRepository); } private static List<TypeDescriber> getTypes() { List<TypeDescriber> typeDescribers = new ArrayList<>(); FrameworkModel.defaultModel() .defaultApplication() .getExtensionLoader(ReflectionTypeDescriberRegistrar.class) .getSupportedExtensionInstances() .forEach(reflectionTypeDescriberRegistrar -> { List<TypeDescriber> describers = new ArrayList<>(); try { describers = reflectionTypeDescriberRegistrar.getTypeDescribers(); } catch (Throwable e) { // The ReflectionTypeDescriberRegistrar implementation classes are shaded, causing some unused // classes to be loaded. // When loading a dependent class may appear that cannot be found, it does not affect. // ignore } typeDescribers.addAll(describers); }); return typeDescribers; } private static List<ResourcePatternDescriber> getResourcePatternDescribers() { List<ResourcePatternDescriber> resourcePatternDescribers = new ArrayList<>(); FrameworkModel.defaultModel() .defaultApplication() .getExtensionLoader(ResourceDescriberRegistrar.class) .getSupportedExtensionInstances() .forEach(reflectionTypeDescriberRegistrar -> { List<ResourcePatternDescriber> describers = new ArrayList<>(); try { describers = reflectionTypeDescriberRegistrar.getResourcePatternDescribers(); } catch (Throwable e) { // The ResourceDescriberRegistrar implementation classes are shaded, causing some unused // classes to be loaded. // When loading a dependent class may appear that cannot be found, it does not affect. // ignore } resourcePatternDescribers.addAll(describers); }); return resourcePatternDescribers; } private static List<ResourceBundleDescriber> getResourceBundleDescribers() { List<ResourceBundleDescriber> resourceBundleDescribers = new ArrayList<>(); FrameworkModel.defaultModel() .defaultApplication() .getExtensionLoader(ResourceDescriberRegistrar.class) .getSupportedExtensionInstances() .forEach(reflectionTypeDescriberRegistrar -> { List<ResourceBundleDescriber> describers = new ArrayList<>(); try { describers = reflectionTypeDescriberRegistrar.getResourceBundleDescribers(); } catch (Throwable e) { // The ResourceDescriberRegistrar implementation classes are shaded, causing some unused // classes to be loaded. // When loading a dependent class may appear that cannot be found, it does not affect. // ignore } resourceBundleDescribers.addAll(describers); }); return resourceBundleDescribers; } private static List<JdkProxyDescriber> getProxyDescribers() { List<JdkProxyDescriber> jdkProxyDescribers = new ArrayList<>(); FrameworkModel.defaultModel() .defaultApplication() .getExtensionLoader(ProxyDescriberRegistrar.class) .getSupportedExtensionInstances() .forEach(reflectionTypeDescriberRegistrar -> { jdkProxyDescribers.addAll(reflectionTypeDescriberRegistrar.getJdkProxyDescribers()); }); return jdkProxyDescribers; } private static List<Class<?>> getCustomClasses() { Class<?>[] configClasses = new Class[] { CommonConstants.SystemProperty.class, CommonConstants.ThirdPartyProperty.class, CommonConstants.DubboProperty.class }; return new ArrayList<>(Arrays.asList(configClasses)); } }
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/generate/ReflectionConfigWriter.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectionConfigWriter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.generate; import org.apache.dubbo.aot.api.ExecutableDescriber; import org.apache.dubbo.aot.api.ExecutableMode; import org.apache.dubbo.aot.api.FieldDescriber; import org.apache.dubbo.aot.api.MemberCategory; import org.apache.dubbo.aot.api.TypeDescriber; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * Write {@link ReflectConfigMetadataRepository} to the JSON output expected by the GraalVM * {@code native-image} compiler, typically named {@code reflect-config.json} * or {@code jni-config.json}. */ public class ReflectionConfigWriter { public static final ReflectionConfigWriter INSTANCE = new ReflectionConfigWriter(); public void write(BasicJsonWriter writer, ReflectConfigMetadataRepository repository) { writer.writeArray(repository.getTypes().stream().map(this::toAttributes).collect(Collectors.toList())); } private Map<String, Object> toAttributes(TypeDescriber describer) { Map<String, Object> attributes = new LinkedHashMap<>(); attributes.put("name", describer.getName()); handleCondition(attributes, describer); handleCategories(attributes, describer.getMemberCategories()); handleFields(attributes, describer.getFields()); handleExecutables(attributes, describer.getConstructors()); handleExecutables(attributes, describer.getMethods()); return attributes; } private void handleCondition(Map<String, Object> attributes, TypeDescriber describer) { if (describer.getReachableType() != null) { Map<String, Object> conditionAttributes = new LinkedHashMap<>(); conditionAttributes.put("typeReachable", describer.getReachableType()); attributes.put("condition", conditionAttributes); } } private void handleFields(Map<String, Object> attributes, Set<FieldDescriber> fieldDescribers) { addIfNotEmpty( attributes, "fields", fieldDescribers.stream().map(this::toAttributes).collect(Collectors.toList())); } private Map<String, Object> toAttributes(FieldDescriber describer) { Map<String, Object> attributes = new LinkedHashMap<>(); attributes.put("name", describer.getName()); return attributes; } private void handleExecutables(Map<String, Object> attributes, Set<ExecutableDescriber> executableDescribers) { addIfNotEmpty( attributes, "methods", executableDescribers.stream() .filter(h -> h.getMode().equals(ExecutableMode.INVOKE)) .map(this::toAttributes) .collect(Collectors.toList())); addIfNotEmpty( attributes, "queriedMethods", executableDescribers.stream() .filter(h -> h.getMode().equals(ExecutableMode.INTROSPECT)) .map(this::toAttributes) .collect(Collectors.toList())); } private Map<String, Object> toAttributes(ExecutableDescriber describer) { Map<String, Object> attributes = new LinkedHashMap<>(); attributes.put("name", describer.getName()); attributes.put("parameterTypes", describer.getParameterTypes()); return attributes; } private void handleCategories(Map<String, Object> attributes, Set<MemberCategory> categories) { categories.forEach(category -> { switch (category) { case PUBLIC_FIELDS: attributes.put("allPublicFields", true); break; case DECLARED_FIELDS: attributes.put("allDeclaredFields", true); break; case INTROSPECT_PUBLIC_CONSTRUCTORS: attributes.put("queryAllPublicConstructors", true); break; case INTROSPECT_DECLARED_CONSTRUCTORS: attributes.put("queryAllDeclaredConstructors", true); break; case INVOKE_PUBLIC_CONSTRUCTORS: attributes.put("allPublicConstructors", true); break; case INVOKE_DECLARED_CONSTRUCTORS: attributes.put("allDeclaredConstructors", true); break; case INTROSPECT_PUBLIC_METHODS: attributes.put("queryAllPublicMethods", true); break; case INTROSPECT_DECLARED_METHODS: attributes.put("queryAllDeclaredMethods", true); break; case INVOKE_PUBLIC_METHODS: attributes.put("allPublicMethods", true); break; case INVOKE_DECLARED_METHODS: attributes.put("allDeclaredMethods", true); break; case PUBLIC_CLASSES: attributes.put("allPublicClasses", true); break; case DECLARED_CLASSES: attributes.put("allDeclaredClasses", true); break; default: break; } }); } private void addIfNotEmpty(Map<String, Object> attributes, String name, Object value) { if ((value instanceof Collection<?> && ((Collection<?>) value).size() != 0)) { 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-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigWriter.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigWriter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.generate; import org.apache.dubbo.aot.api.ConditionalDescriber; import org.apache.dubbo.aot.api.ResourceBundleDescriber; import org.apache.dubbo.aot.api.ResourcePatternDescriber; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * Write a {@link ResourceConfigMetadataRepository} to the JSON output expected by the GraalVM * {@code native-image} compiler, typically named {@code resource-config.json}. */ public class ResourceConfigWriter { public static final ResourceConfigWriter INSTANCE = new ResourceConfigWriter(); public void write(BasicJsonWriter writer, ResourceConfigMetadataRepository repository) { Map<String, Object> attributes = new LinkedHashMap<>(); addIfNotEmpty(attributes, "resources", toAttributes(repository.getIncludes(), repository.getExcludes())); handleResourceBundles(attributes, repository.getResourceBundles()); writer.writeObject(attributes); } private Map<String, Object> toAttributes( List<ResourcePatternDescriber> includes, List<ResourcePatternDescriber> excludes) { Map<String, Object> attributes = new LinkedHashMap<>(); addIfNotEmpty( attributes, "includes", includes.stream().distinct().map(this::toAttributes).collect(Collectors.toList())); addIfNotEmpty( attributes, "excludes", excludes.stream().distinct().map(this::toAttributes).collect(Collectors.toList())); return attributes; } private void handleResourceBundles( Map<String, Object> attributes, Set<ResourceBundleDescriber> resourceBundleDescribers) { addIfNotEmpty( attributes, "bundles", resourceBundleDescribers.stream().map(this::toAttributes).collect(Collectors.toList())); } private Map<String, Object> toAttributes(ResourceBundleDescriber describer) { Map<String, Object> attributes = new LinkedHashMap<>(); handleCondition(attributes, describer); attributes.put("name", describer.getName()); return attributes; } private Map<String, Object> toAttributes(ResourcePatternDescriber describer) { Map<String, Object> attributes = new LinkedHashMap<>(); handleCondition(attributes, describer); attributes.put("pattern", describer.toRegex().toString()); return attributes; } private void addIfNotEmpty(Map<String, Object> attributes, String name, Object value) { if (value instanceof Collection<?>) { if (!((Collection<?>) value).isEmpty()) { attributes.put(name, value); } } else if (value instanceof Map<?, ?>) { if (!((Map<?, ?>) value).isEmpty()) { attributes.put(name, value); } } else if (value != null) { attributes.put(name, value); } } private void handleCondition(Map<String, Object> attributes, ConditionalDescriber conditionalDescriber) { if (conditionalDescriber.getReachableType() != null) { Map<String, Object> conditionAttributes = new LinkedHashMap<>(); conditionAttributes.put("typeReachable", conditionalDescriber.getReachableType()); attributes.put("condition", conditionAttributes); } } }
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/generate/NativeClassSourceWriter.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeClassSourceWriter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.generate; import org.apache.dubbo.common.extension.AdaptiveClassCodeGenerator; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.common.utils.StringUtils; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Paths; import java.util.List; import java.util.regex.Matcher; import org.apache.commons.io.FileUtils; /** * Write the Adaptive bytecode class dynamically generated. */ public class NativeClassSourceWriter { public static final NativeClassSourceWriter INSTANCE = new NativeClassSourceWriter(); public void writeTo(List<Class<?>> classes, String generatedSources) { classes.forEach(it -> { SPI spi = it.getAnnotation(SPI.class); String value = spi.value(); if (StringUtils.isEmpty(value)) { value = "adaptive"; } AdaptiveClassCodeGenerator codeGenerator = new AdaptiveClassCodeGenerator(it, value); String code = codeGenerator.generate(true); try { String file = generatedSources + File.separator + it.getName().replaceAll("\\.", Matcher.quoteReplacement(File.separator)); String dir = Paths.get(file).getParent().toString(); FileUtils.forceMkdir(new File(dir)); code = LICENSED_STR + code + "\n"; String fileName = file + "$Adaptive.java"; FileUtils.write(new File(fileName), code, Charset.defaultCharset()); } catch (IOException e) { throw new IllegalStateException("Failed to generated adaptive class sources", e); } }); } private static final String LICENSED_STR = "/*\n" + " * Licensed to the Apache Software Foundation (ASF) under one or more\n" + " * contributor license agreements. See the NOTICE file distributed with\n" + " * this work for additional information regarding copyright ownership.\n" + " * The ASF licenses this file to You under the Apache License, Version 2.0\n" + " * (the \"License\"); you may not use this file except in compliance with\n" + " * the License. You may obtain a copy of the License at\n" + " *\n" + " * http://www.apache.org/licenses/LICENSE-2.0\n" + " *\n" + " * Unless required by applicable law or agreed to in writing, software\n" + " * distributed under the License is distributed on an \"AS IS\" BASIS,\n" + " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + " * See the License for the specific language governing permissions and\n" + " * limitations under the License.\n" + " */\n"; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ReflectionTypeDescriberRegistrar.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ReflectionTypeDescriberRegistrar.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 ReflectionTypeDescriberRegistrar { List<TypeDescriber> getTypeDescribers(); }
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/TypeDescriber.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/TypeDescriber.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.Set; /** * A describer that describes the need for reflection on a type. */ public class TypeDescriber implements ConditionalDescriber { private final String name; private final String reachableType; private final Set<FieldDescriber> fields; private final Set<ExecutableDescriber> constructors; private final Set<ExecutableDescriber> methods; private final Set<MemberCategory> memberCategories; public TypeDescriber( String name, String reachableType, Set<FieldDescriber> fields, Set<ExecutableDescriber> constructors, Set<ExecutableDescriber> methods, Set<MemberCategory> memberCategories) { this.name = name; this.reachableType = reachableType; this.fields = fields; this.constructors = constructors; this.methods = methods; this.memberCategories = memberCategories; } public String getName() { return name; } public Set<MemberCategory> getMemberCategories() { return memberCategories; } public Set<FieldDescriber> getFields() { return fields; } public Set<ExecutableDescriber> getConstructors() { return constructors; } public Set<ExecutableDescriber> getMethods() { return methods; } @Override public String getReachableType() { return 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/ResourceBundleDescriber.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ResourceBundleDescriber.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.ResourceBundle; /** * A describer that describes the need to access a {@link ResourceBundle}. */ public class ResourceBundleDescriber implements ConditionalDescriber { private final String name; private final List<String> locales; private final String reachableType; public ResourceBundleDescriber(String name, List<String> locales, String reachableType) { this.name = name; this.locales = locales; this.reachableType = reachableType; } public String getName() { return name; } public List<String> getLocales() { return locales; } @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; } ResourceBundleDescriber that = (ResourceBundleDescriber) o; return name.equals(that.name) && locales.equals(that.locales) && reachableType.equals(that.reachableType); } @Override public int hashCode() { return Objects.hash(name, locales, 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/MemberDescriber.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/MemberDescriber.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.Member; /** * Base describer that describes the need for reflection on a {@link Member}. * */ public class MemberDescriber { private final String name; protected MemberDescriber(String name) { this.name = name; } /** * Return the name of the member. * @return the name */ public String getName() { return this.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-native/src/main/java/org/apache/dubbo/aot/api/FieldDescriber.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/FieldDescriber.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.Field; /** * A describer that describes the need for reflection on a {@link Field}. */ public class FieldDescriber extends MemberDescriber { protected FieldDescriber(String name) { super(name); } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object obj) { return super.equals(obj); } }
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/ConditionalDescriber.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ConditionalDescriber.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; /** * A describer that describes the conditions for the configuration to take effect. */ public interface ConditionalDescriber { String getReachableType(); }
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/ResourceDescriberRegistrar.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ResourceDescriberRegistrar.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 ResourceDescriberRegistrar { List<ResourcePatternDescriber> getResourcePatternDescribers(); List<ResourceBundleDescriber> getResourceBundleDescribers(); }
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/ExecutableMode.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ExecutableMode.java
/* * Copyright 2002-2022 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.Executable; /** * Represent the need of reflection for a given {@link Executable}. */ public enum ExecutableMode { /** * Only retrieving the {@link Executable} and its metadata is required. */ INTROSPECT, /** * Full reflection support is required, including the ability to invoke * the {@link Executable}. */ INVOKE; /** * Specify if this mode already includes the specified {@code other} mode. * @param other the other mode to check * @return {@code true} if this mode includes the other mode */ boolean includes(ExecutableMode other) { return (other == null || this.ordinal() >= other.ordinal()); } }
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/ResourcePatternDescriber.java
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ResourcePatternDescriber.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.Arrays; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * A describer that describes resources that should be made available at runtime. */ public class ResourcePatternDescriber implements ConditionalDescriber { private final String pattern; private final String reachableType; public ResourcePatternDescriber(String pattern, String reachableType) { this.pattern = pattern; this.reachableType = reachableType; } public String getPattern() { return pattern; } @Override public String getReachableType() { return reachableType; } public Pattern toRegex() { String prefix = (this.pattern.startsWith("*") ? ".*" : ""); String suffix = (this.pattern.endsWith("*") ? ".*" : ""); String regex = Arrays.stream(this.pattern.split("\\*")) .filter(s -> !s.isEmpty()) .map(Pattern::quote) .collect(Collectors.joining(".*", prefix, suffix)); return Pattern.compile(regex); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false