index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/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.rest.rest; import org.apache.dubbo.rpc.protocol.rest.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.APPLICATION_JSON}) 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.APPLICATION_JSON}) String headerMap(@HeaderParam("headers") Map<String, String> headers); }
5,700
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/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.rest.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(); } public static Map<String, Object> getAttachments() { return context; } }
5,701
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/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.rest.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; } }
5,702
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/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.rest.rest; import javax.ws.rs.*; 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); }
5,703
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/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.rest.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); } }
5,704
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ReferenceCountedClient.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.reference.ReferenceCountedResource; import org.apache.dubbo.remoting.http.RestClient; import org.apache.dubbo.remoting.http.factory.RestClientFactory; import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; public class ReferenceCountedClient<T extends RestClient> extends ReferenceCountedResource { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReferenceCountedClient.class); private ConcurrentMap<String, ReferenceCountedClient<? extends RestClient>> clients; private URL url; private RestClientFactory clientFactory; private T client; public ReferenceCountedClient( T client, ConcurrentMap<String, ReferenceCountedClient<? extends RestClient>> clients, RestClientFactory clientFactory, URL url) { this.client = client; this.clients = clients; this.clientFactory = clientFactory; this.url = url; } public T getClient() { // for client destroy and create right now, only lock current client synchronized (this) { ReferenceCountedClient<? extends RestClient> referenceCountedClient = clients.get(url.getAddress()); // for double check if (referenceCountedClient.isDestroyed()) { synchronized (this) { referenceCountedClient = clients.get(url.getAddress()); if (referenceCountedClient.isDestroyed()) { RestClient restClient = clientFactory.createRestClient(url); clients.put( url.getAddress(), new ReferenceCountedClient(restClient, clients, clientFactory, url)); return (T) restClient; } else { return (T) referenceCountedClient.client; } } } else { return client; } } } public boolean isDestroyed() { return client.isClosed(); } @Override protected void destroy() { try { client.close(); } catch (Exception e) { logger.error(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", "Close resteasy client error", e); } } }
5,705
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestHeaderEnum.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; public enum RestHeaderEnum { CONTENT_TYPE(RestConstant.CONTENT_TYPE), ACCEPT(RestConstant.ACCEPT), GROUP(RestConstant.REST_HEADER_PREFIX + RestConstant.GROUP), VERSION(RestConstant.REST_HEADER_PREFIX + RestConstant.VERSION), PATH(RestConstant.REST_HEADER_PREFIX + RestConstant.PATH), KEEP_ALIVE_HEADER(RestConstant.KEEP_ALIVE_HEADER), CONNECTION(RestConstant.CONNECTION), REST_HEADER_PREFIX(RestConstant.REST_HEADER_PREFIX), TOKEN_KEY(RestConstant.REST_HEADER_PREFIX + RestConstant.TOKEN_KEY), ; private final String header; RestHeaderEnum(String header) { this.header = header; } public String getHeader() { return header; } }
5,706
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/NettyHttpRestServer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import org.apache.dubbo.rpc.protocol.rest.netty.NettyServer; import org.apache.dubbo.rpc.protocol.rest.netty.RestHttpRequestDecoder; import org.apache.dubbo.rpc.protocol.rest.netty.UnSharedHandlerCreator; import org.apache.dubbo.rpc.protocol.rest.netty.ssl.SslServerTlsHandler; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelOption; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; import static org.apache.dubbo.common.constants.CommonConstants.BACKLOG_KEY; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY; import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY; import static org.apache.dubbo.remoting.Constants.DEFAULT_IO_THREADS; /** * netty http server */ public class NettyHttpRestServer implements RestProtocolServer { private ServiceDeployer serviceDeployer = new ServiceDeployer(); private NettyServer server = getNettyServer(); /** * for triple override * * @return */ protected NettyServer getNettyServer() { return new NettyServer(); } private String address; private final Map<String, Object> attributes = new ConcurrentHashMap<>(); @Override public String getAddress() { return address; } @Override public void setAddress(String address) { this.address = address; } @Override public void close() { server.stop(); } @Override public Map<String, Object> getAttributes() { return attributes; } @Override public void start(URL url) { registerExtension(url); String bindIp = url.getParameter(BIND_IP_KEY, url.getHost()); if (!url.isAnyHost() && NetUtils.isValidLocalHost(bindIp)) { server.setHostname(bindIp); } server.setPort(url.getParameter(BIND_PORT_KEY, url.getPort())); // child options server.setChildChannelOptions(getChildChannelOptionMap(url)); // set options server.setChannelOptions(getChannelOptionMap(url)); // set unshared callback server.setUnSharedHandlerCallBack(getUnSharedHttpChannelHandlers()); // set channel handler and @Shared server.setChannelHandlers(getChannelHandlers(url)); server.setIoWorkerCount(url.getParameter(IO_THREADS_KEY, DEFAULT_IO_THREADS)); server.start(url); } private UnSharedHandlerCreator getUnSharedHttpChannelHandlers() { return new UnSharedHandlerCreator() { @Override public List<ChannelHandler> getUnSharedHandlers(URL url) { return Arrays.asList( // add SslServerTlsHandler new SslServerTlsHandler(url), new HttpRequestDecoder( url.getParameter( RestConstant.MAX_INITIAL_LINE_LENGTH_PARAM, RestConstant.MAX_INITIAL_LINE_LENGTH), url.getParameter(RestConstant.MAX_HEADER_SIZE_PARAM, RestConstant.MAX_HEADER_SIZE), url.getParameter(RestConstant.MAX_CHUNK_SIZE_PARAM, RestConstant.MAX_CHUNK_SIZE)), new HttpObjectAggregator( url.getParameter(RestConstant.MAX_REQUEST_SIZE_PARAM, RestConstant.MAX_REQUEST_SIZE)), new HttpResponseEncoder(), new RestHttpRequestDecoder(url, serviceDeployer)); } }; } /** * create child channel options map * * @param url * @return */ protected Map<ChannelOption, Object> getChildChannelOptionMap(URL url) { Map<ChannelOption, Object> channelOption = new HashMap<>(); channelOption.put( ChannelOption.SO_KEEPALIVE, url.getParameter(Constants.KEEP_ALIVE_KEY, Constants.DEFAULT_KEEP_ALIVE)); return channelOption; } /** * create channel options map * * @param url * @return */ protected Map<ChannelOption, Object> getChannelOptionMap(URL url) { Map<ChannelOption, Object> options = new HashMap<>(); options.put(ChannelOption.SO_REUSEADDR, Boolean.TRUE); options.put(ChannelOption.TCP_NODELAY, Boolean.TRUE); options.put( ChannelOption.SO_BACKLOG, url.getPositiveParameter(BACKLOG_KEY, org.apache.dubbo.remoting.Constants.DEFAULT_BACKLOG)); options.put(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); return options; } /** * create channel handler * * @param url * @return */ protected List<ChannelHandler> getChannelHandlers(URL url) { List<ChannelHandler> channelHandlers = new ArrayList<>(); return channelHandlers; } @Override public void deploy(ServiceRestMetadata serviceRestMetadata, Invoker invoker) { serviceDeployer.deploy(serviceRestMetadata, invoker); } @Override public void undeploy(ServiceRestMetadata serviceRestMetadata) { serviceDeployer.undeploy(serviceRestMetadata); } private void registerExtension(URL url) { serviceDeployer.registerExtension(url); } }
5,707
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestConstraintViolation.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; @XmlRootElement(name = "constraintViolation") @XmlAccessorType(XmlAccessType.FIELD) public class RestConstraintViolation implements Serializable { private static final long serialVersionUID = -23497234978L; private String path; private String message; private String value; public RestConstraintViolation(String path, String message, String value) { this.path = path; this.message = message; this.value = value; } public RestConstraintViolation() {} public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
5,708
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocolServer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.common.URL; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProtocolServer; public interface RestProtocolServer extends ProtocolServer { void start(URL url); void deploy(ServiceRestMetadata serviceRestMetadata, Invoker invoker); void undeploy(ServiceRestMetadata serviceRestMetadata); }
5,709
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestRPCInvocationUtil.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.common.BaseServiceMetadata; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.metadata.rest.PathMatcher; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.protocol.rest.annotation.ParamParserManager; import org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.ProviderParseContext; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import org.apache.dubbo.rpc.protocol.rest.exception.ParamParseException; import org.apache.dubbo.rpc.protocol.rest.pair.InvokerAndRestMethodMetadataPair; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import org.apache.dubbo.rpc.protocol.rest.util.HttpHeaderUtil; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; public class RestRPCInvocationUtil { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RestRPCInvocationUtil.class); /** * service method real args parse * * @param rpcInvocation * @param request * @param servletRequest * @param servletResponse * @param restMethodMetadata */ public static void parseMethodArgs( RpcInvocation rpcInvocation, RequestFacade request, Object servletRequest, Object servletResponse, RestMethodMetadata restMethodMetadata) { try { ProviderParseContext parseContext = createParseContext(request, servletRequest, servletResponse, restMethodMetadata); Object[] args = ParamParserManager.providerParamParse(parseContext); List<ArgInfo> argInfos = parseContext.getArgInfos(); for (ArgInfo argInfo : argInfos) { // TODO set default value if (argInfo.getParamType().isPrimitive() && args[argInfo.getIndex()] == null) { throw new ParamParseException("\n dubbo provider primitive arg not exist in request, method is: " + restMethodMetadata.getReflectMethod() + "\n type is: " + argInfo.getParamType() + " \n and arg index is: " + argInfo.getIndex()); } } rpcInvocation.setArguments(args); } catch (Exception e) { logger.error("", e.getMessage(), "", "dubbo rest provider method args parse error: ", e); throw new ParamParseException(e.getMessage()); } } /** * create parseMethodArgs context * * @param request * @param originRequest * @param originResponse * @param restMethodMetadata * @return */ private static ProviderParseContext createParseContext( RequestFacade request, Object originRequest, Object originResponse, RestMethodMetadata restMethodMetadata) { ProviderParseContext parseContext = new ProviderParseContext(request); parseContext.setResponse(originResponse); parseContext.setRequest(originRequest); Object[] objects = new Object[restMethodMetadata.getArgInfos().size()]; parseContext.setArgs(Arrays.asList(objects)); parseContext.setArgInfos(restMethodMetadata.getArgInfos()); return parseContext; } /** * build RpcInvocation * * @param request * @param restMethodMetadata * @return */ public static RpcInvocation createBaseRpcInvocation(RequestFacade request, RestMethodMetadata restMethodMetadata) { RpcInvocation rpcInvocation = new RpcInvocation(); rpcInvocation.setParameterTypes(restMethodMetadata.getReflectMethod().getParameterTypes()); rpcInvocation.setReturnType(restMethodMetadata.getReflectMethod().getReturnType()); rpcInvocation.setMethodName(restMethodMetadata.getMethod().getName()); // TODO set protocolServiceKey ,but no set method // HttpHeaderUtil.parseRequest(rpcInvocation, request); String serviceKey = BaseServiceMetadata.buildServiceKey( request.getHeader(RestHeaderEnum.PATH.getHeader()), request.getHeader(RestHeaderEnum.GROUP.getHeader()), request.getHeader(RestHeaderEnum.VERSION.getHeader())); rpcInvocation.setTargetServiceUniqueName(serviceKey); return rpcInvocation; } /** * get InvokerAndRestMethodMetadataPair by path matcher * * @param pathMatcher * @return */ public static InvokerAndRestMethodMetadataPair getRestMethodMetadataAndInvokerPair( PathMatcher pathMatcher, ServiceDeployer serviceDeployer) { return serviceDeployer.getPathAndInvokerMapper().getRestMethodMetadata(pathMatcher); } /** * get InvokerAndRestMethodMetadataPair from rpc context * * @param request * @return */ public static InvokerAndRestMethodMetadataPair getRestMethodMetadataAndInvokerPair(RequestFacade request) { PathMatcher pathMather = createPathMatcher(request); return getRestMethodMetadataAndInvokerPair(pathMather, request.getServiceDeployer()); } /** * get invoker by request * * @param request * @return */ public static Invoker getInvokerByRequest(RequestFacade request) { PathMatcher pathMatcher = createPathMatcher(request); return getInvoker(pathMatcher, request.getServiceDeployer()); } /** * get invoker by service method * <p> * compare method`s name,param types * * @param serviceMethod * @return */ public static Invoker getInvokerByServiceInvokeMethod(Method serviceMethod, ServiceDeployer serviceDeployer) { if (serviceMethod == null) { return null; } PathMatcher pathMatcher = PathMatcher.getInvokeCreatePathMatcher(serviceMethod); InvokerAndRestMethodMetadataPair pair = getRestMethodMetadataAndInvokerPair(pathMatcher, serviceDeployer); if (pair == null) { return null; } return pair.getInvoker(); } /** * get invoker by path matcher * * @param pathMatcher * @return */ public static Invoker getInvoker(PathMatcher pathMatcher, ServiceDeployer serviceDeployer) { InvokerAndRestMethodMetadataPair pair = getRestMethodMetadataAndInvokerPair(pathMatcher, serviceDeployer); if (pair == null) { return null; } return pair.getInvoker(); } /** * create path matcher by request * * @param request * @return */ public static PathMatcher createPathMatcher(RequestFacade request) { String path = request.getPath(); String version = request.getHeader(RestHeaderEnum.VERSION.getHeader()); String group = request.getHeader(RestHeaderEnum.GROUP.getHeader()); String method = request.getMethod(); return PathMatcher.getInvokeCreatePathMatcher(path, version, group, null, method); } }
5,710
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ViolationReport.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; import java.util.LinkedList; import java.util.List; @XmlRootElement(name = "violationReport") @XmlAccessorType(XmlAccessType.FIELD) public class ViolationReport implements Serializable { private static final long serialVersionUID = -130498234L; private List<RestConstraintViolation> constraintViolations; public List<RestConstraintViolation> getConstraintViolations() { return constraintViolations; } public void setConstraintViolations(List<RestConstraintViolation> constraintViolations) { this.constraintViolations = constraintViolations; } public void addConstraintViolation(RestConstraintViolation constraintViolation) { if (constraintViolations == null) { constraintViolations = new LinkedList<RestConstraintViolation>(); } constraintViolations.add(constraintViolation); } }
5,711
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestServerFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest; /** * Only the server that implements servlet container * could support something like @Context injection of servlet objects. */ public class RestServerFactory { public RestProtocolServer createServer(String name) { return new NettyHttpRestServer(); } }
5,712
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RpcExceptionMapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler; import org.apache.dubbo.rpc.protocol.rest.util.ConstraintViolationExceptionConvert; public class RpcExceptionMapper implements ExceptionHandler<RpcException> { @Override public Object result(RpcException e) { // javax dependency judge if (violationDependency()) { // ConstraintViolationException judge if (ConstraintViolationExceptionConvert.needConvert(e)) { return ConstraintViolationExceptionConvert.handleConstraintViolationException(e); } } return "Internal server error: " + e.getMessage(); } private boolean violationDependency() { return ClassUtils.isPresent( "javax.validation.ConstraintViolationException", RpcExceptionMapper.class.getClassLoader()); } }
5,713
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.common.URL; import org.apache.dubbo.metadata.ParameterTypesComparator; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.remoting.http.RequestTemplate; import org.apache.dubbo.remoting.http.RestClient; import org.apache.dubbo.remoting.http.RestResult; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.protocol.AbstractInvoker; import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionCreateContext; import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; import org.apache.dubbo.rpc.protocol.rest.exception.ParamParseException; import org.apache.dubbo.rpc.protocol.rest.exception.PathNoFoundException; import org.apache.dubbo.rpc.protocol.rest.exception.RemoteServerInternalException; import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodecManager; import org.apache.dubbo.rpc.protocol.rest.util.HttpHeaderUtil; import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil; import java.lang.reflect.Method; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; public class RestInvoker<T> extends AbstractInvoker<T> { private final ServiceRestMetadata serviceRestMetadata; private final ReferenceCountedClient<? extends RestClient> referenceCountedClient; private final Set<HttpConnectionPreBuildIntercept> httpConnectionPreBuildIntercepts; public RestInvoker( Class type, URL url, ReferenceCountedClient<? extends RestClient> referenceCountedClient, Set<HttpConnectionPreBuildIntercept> httpConnectionPreBuildIntercepts, ServiceRestMetadata serviceRestMetadata) { super(type, url); this.serviceRestMetadata = serviceRestMetadata; this.referenceCountedClient = referenceCountedClient; this.httpConnectionPreBuildIntercepts = httpConnectionPreBuildIntercepts; } @Override protected Result doInvoke(Invocation invocation) { try { Map<String, Map<ParameterTypesComparator, RestMethodMetadata>> metadataMap = serviceRestMetadata.getMethodToServiceMap(); // get metadata RestMethodMetadata restMethodMetadata = metadataMap .get(invocation.getMethodName()) .get(ParameterTypesComparator.getInstance(invocation.getParameterTypes())); // create requestTemplate RequestTemplate requestTemplate = new RequestTemplate( invocation, restMethodMetadata.getRequest().getMethod(), getUrl().getAddress()); HttpConnectionCreateContext httpConnectionCreateContext = createHttpConnectionCreateContext( invocation, serviceRestMetadata, restMethodMetadata, requestTemplate); // fill real data for (HttpConnectionPreBuildIntercept intercept : httpConnectionPreBuildIntercepts) { intercept.intercept(httpConnectionCreateContext); } // TODO check rest client cannot be reused CompletableFuture<RestResult> future = referenceCountedClient.getClient().send(requestTemplate); CompletableFuture<AppResponse> responseFuture = new CompletableFuture<>(); AsyncRpcResult asyncRpcResult = new AsyncRpcResult(responseFuture, invocation); future.whenComplete((r, t) -> { if (t != null) { responseFuture.completeExceptionally(t); } else { AppResponse appResponse = new AppResponse(); try { int responseCode = r.getResponseCode(); MediaType mediaType = MediaType.TEXT_PLAIN; if (responseCode == 404) { responseFuture.completeExceptionally(new PathNoFoundException(r.getMessage())); } else if (400 <= responseCode && responseCode < 500) { responseFuture.completeExceptionally(new ParamParseException(r.getMessage())); // TODO add Exception Mapper } else if (responseCode >= 500) { responseFuture.completeExceptionally(new RemoteServerInternalException(r.getMessage())); } else if (responseCode < 400) { Method reflectMethod = restMethodMetadata.getReflectMethod(); mediaType = MediaTypeUtil.convertMediaType(reflectMethod.getReturnType(), r.getContentType()); Object value = HttpMessageCodecManager.httpMessageDecode( r.getBody(), reflectMethod.getReturnType(), reflectMethod.getGenericReturnType(), mediaType); appResponse.setValue(value); // resolve response attribute & attachment HttpHeaderUtil.parseResponseHeader(appResponse, r); responseFuture.complete(appResponse); } } catch (Exception e) { responseFuture.completeExceptionally(e); } } }); return asyncRpcResult; } catch (RpcException e) { throw e; } } /** * create intercept context * * @param invocation * @param serviceRestMetadata * @param restMethodMetadata * @param requestTemplate * @return */ private HttpConnectionCreateContext createHttpConnectionCreateContext( Invocation invocation, ServiceRestMetadata serviceRestMetadata, RestMethodMetadata restMethodMetadata, RequestTemplate requestTemplate) { HttpConnectionCreateContext httpConnectionCreateContext = new HttpConnectionCreateContext(); httpConnectionCreateContext.setRequestTemplate(requestTemplate); httpConnectionCreateContext.setRestMethodMetadata(restMethodMetadata); httpConnectionCreateContext.setServiceRestMetadata(serviceRestMetadata); httpConnectionCreateContext.setInvocation(invocation); httpConnectionCreateContext.setUrl(getUrl()); return httpConnectionCreateContext; } }
5,714
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import org.apache.dubbo.remoting.http.RestClient; import org.apache.dubbo.remoting.http.factory.RestClientFactory; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.AbstractExporter; import org.apache.dubbo.rpc.protocol.AbstractProtocol; import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; import org.apache.dubbo.rpc.protocol.rest.annotation.metadata.MetadataResolver; import java.util.LinkedHashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_SERVER; import static org.apache.dubbo.remoting.Constants.SERVER_KEY; import static org.apache.dubbo.rpc.protocol.rest.constans.RestConstant.PATH_SEPARATOR; public class RestProtocol extends AbstractProtocol { private static final int DEFAULT_PORT = 80; private static final String DEFAULT_SERVER = Constants.NETTY_HTTP; private final RestServerFactory serverFactory = new RestServerFactory(); private final ConcurrentMap<String, ReferenceCountedClient<? extends RestClient>> clients = new ConcurrentHashMap<>(); private final RestClientFactory clientFactory; private final Set<HttpConnectionPreBuildIntercept> httpConnectionPreBuildIntercepts; public RestProtocol(FrameworkModel frameworkModel) { this.clientFactory = frameworkModel.getExtensionLoader(RestClientFactory.class).getAdaptiveExtension(); this.httpConnectionPreBuildIntercepts = new LinkedHashSet<>(frameworkModel .getExtensionLoader(HttpConnectionPreBuildIntercept.class) .getActivateExtensions()); } @Override public int getDefaultPort() { return DEFAULT_PORT; } @Override @SuppressWarnings("unchecked") public <T> Exporter<T> export(final Invoker<T> invoker) throws RpcException { URL url = invoker.getUrl(); final String uri = serviceKey(url); Exporter<T> exporter = (Exporter<T>) exporterMap.get(uri); if (exporter != null) { // When modifying the configuration through override, you need to re-expose the newly modified service. if (Objects.equals(exporter.getInvoker().getUrl(), invoker.getUrl())) { return exporter; } } // resolve metadata ServiceRestMetadata serviceRestMetadata = MetadataResolver.resolveProviderServiceMetadata( url.getServiceModel().getProxyObject().getClass(), url, getContextPath(url)); // TODO add Extension filter // create rest server RestProtocolServer server = (RestProtocolServer) ConcurrentHashMapUtils.computeIfAbsent( (ConcurrentMap<? super String, ? super RestProtocolServer>) serverMap, getAddr(url), restServer -> { RestProtocolServer s = serverFactory.createServer(url.getParameter(SERVER_KEY, DEFAULT_SERVER)); s.setAddress(url.getAddress()); s.start(url); return s; }); server.deploy(serviceRestMetadata, invoker); exporter = new AbstractExporter<T>(invoker) { @Override public void afterUnExport() { destroyInternal(url); exporterMap.remove(uri); server.undeploy(serviceRestMetadata); } }; exporterMap.put(uri, exporter); return exporter; } @Override protected <T> Invoker<T> protocolBindingRefer(final Class<T> type, final URL url) throws RpcException { ReferenceCountedClient<? extends RestClient> refClient = clients.get(url.getAddress()); if (refClient == null || refClient.isDestroyed()) { synchronized (clients) { refClient = clients.get(url.getAddress()); if (refClient == null || refClient.isDestroyed()) { refClient = ConcurrentHashMapUtils.computeIfAbsent( clients, url.getAddress(), _key -> createReferenceCountedClient(url)); } } } refClient.retain(); String contextPathFromUrl = getContextPath(url); // resolve metadata ServiceRestMetadata serviceRestMetadata = MetadataResolver.resolveConsumerServiceMetadata(type, url, contextPathFromUrl); Invoker<T> invoker = new RestInvoker<T>(type, url, refClient, httpConnectionPreBuildIntercepts, serviceRestMetadata); invokers.add(invoker); return invoker; } /** * create rest ReferenceCountedClient * * @param url * @return * @throws RpcException */ private ReferenceCountedClient<? extends RestClient> createReferenceCountedClient(URL url) throws RpcException { // url -> RestClient RestClient restClient = clientFactory.createRestClient(url); return new ReferenceCountedClient<>(restClient, clients, clientFactory, url); } @Override public void destroy() { if (logger.isInfoEnabled()) { logger.info("Destroying protocol [" + this.getClass().getSimpleName() + "] ..."); } super.destroy(); for (Map.Entry<String, ProtocolServer> entry : serverMap.entrySet()) { try { if (logger.isInfoEnabled()) { logger.info("Closing the rest server at " + entry.getKey()); } entry.getValue().close(); } catch (Throwable t) { logger.warn(PROTOCOL_ERROR_CLOSE_SERVER, "", "", "Error closing rest server", t); } } serverMap.clear(); if (logger.isInfoEnabled()) { logger.info("Closing rest clients"); } for (ReferenceCountedClient<?> client : clients.values()) { try { // destroy directly regardless of the current reference count. client.destroy(); } catch (Throwable t) { logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", "Error closing rest client", t); } } clients.clear(); } /** * getPath() will return: [contextpath + "/" +] path * 1. contextpath is empty if user does not set through ProtocolConfig or ProviderConfig * 2. path will never be empty, its default value is the interface name. * * @return return path only if user has explicitly gave then a value. */ private String getContextPath(URL url) { String contextPath = url.getPath(); if (contextPath != null) { if (contextPath.equalsIgnoreCase(url.getParameter(INTERFACE_KEY))) { return ""; } if (contextPath.endsWith(url.getParameter(INTERFACE_KEY))) { contextPath = contextPath.substring(0, contextPath.lastIndexOf(url.getParameter(INTERFACE_KEY))); } return contextPath.endsWith(PATH_SEPARATOR) ? contextPath.substring(0, contextPath.length() - 1) : contextPath; } else { return ""; } } private void destroyInternal(URL url) { try { ReferenceCountedClient<?> referenceCountedClient = clients.get(url.getAddress()); if (referenceCountedClient != null && referenceCountedClient.release()) { clients.remove(url.getAddress()); } } catch (Exception e) { logger.warn( PROTOCOL_ERROR_CLOSE_CLIENT, "", "", "Failed to close unused resources in rest protocol. interfaceName [" + url.getServiceInterface() + "]", e); } } }
5,715
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/Constants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest; /** * Constants definition. */ public interface Constants { String KEEP_ALIVE_KEY = "keepalive"; boolean DEFAULT_KEEP_ALIVE = true; String EXTENSION_KEY = "extension"; // http server String NETTY_HTTP = "netty_http"; }
5,716
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/PathAndInvokerMapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.metadata.rest.PathMatcher; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.protocol.rest.exception.DoublePathCheckException; import org.apache.dubbo.rpc.protocol.rest.pair.InvokerAndRestMethodMetadataPair; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * save the path & metadata info mapping */ public class PathAndInvokerMapper { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PathAndInvokerMapper.class); private final Map<PathMatcher, InvokerAndRestMethodMetadataPair> pathToServiceMapContainPathVariable = new ConcurrentHashMap<>(); private final Map<PathMatcher, InvokerAndRestMethodMetadataPair> pathToServiceMapNoPathVariable = new ConcurrentHashMap<>(); // for http method compare 405 private final Map<PathMatcher, Set<String>> pathMatcherToHttpMethodMap = new HashMap<>(); /** * deploy path metadata * * @param metadataMap * @param invoker */ public void addPathAndInvoker(Map<PathMatcher, RestMethodMetadata> metadataMap, Invoker invoker) { metadataMap.entrySet().stream().forEach(entry -> { PathMatcher pathMatcher = entry.getKey(); if (pathMatcher.hasPathVariable()) { addPathMatcherToPathMap( pathMatcher, pathToServiceMapContainPathVariable, InvokerAndRestMethodMetadataPair.pair(invoker, entry.getValue())); } else { addPathMatcherToPathMap( pathMatcher, pathToServiceMapNoPathVariable, InvokerAndRestMethodMetadataPair.pair(invoker, entry.getValue())); } }); } /** * get rest method metadata by path matcher * * @param pathMatcher * @return */ public InvokerAndRestMethodMetadataPair getRestMethodMetadata(PathMatcher pathMatcher) { // first search from pathToServiceMapNoPathVariable if (pathToServiceMapNoPathVariable.containsKey(pathMatcher)) { return pathToServiceMapNoPathVariable.get(pathMatcher); } // second search from pathToServiceMapContainPathVariable if (pathToServiceMapContainPathVariable.containsKey(pathMatcher)) { return pathToServiceMapContainPathVariable.get(pathMatcher); } return null; } /** * undeploy path metadata * * @param pathMatcher */ public void removePath(PathMatcher pathMatcher) { InvokerAndRestMethodMetadataPair containPathVariablePair = pathToServiceMapContainPathVariable.remove(pathMatcher); InvokerAndRestMethodMetadataPair unContainPathVariablePair = pathToServiceMapNoPathVariable.remove(pathMatcher); logger.info("dubbo rest undeploy pathMatcher:" + pathMatcher + ", and path variable method is :" + (containPathVariablePair == null ? null : containPathVariablePair.getRestMethodMetadata().getReflectMethod()) + ", and no path variable method is :" + (unContainPathVariablePair == null ? null : unContainPathVariablePair.getRestMethodMetadata().getReflectMethod())); } public void addPathMatcherToPathMap( PathMatcher pathMatcher, Map<PathMatcher, InvokerAndRestMethodMetadataPair> pathMatcherPairMap, InvokerAndRestMethodMetadataPair invokerRestMethodMetadataPair) { if (pathMatcherPairMap.containsKey(pathMatcher)) { // cover the old service metadata when current interface is old interface & current method desc equals // old`s method desc,else ,throw double check exception InvokerAndRestMethodMetadataPair beforeMetadata = pathMatcherPairMap.get(pathMatcher); // true when reExport if (!invokerRestMethodMetadataPair.compareServiceMethod(beforeMetadata)) { throw new DoublePathCheckException("dubbo rest double path check error, current path is: " + pathMatcher + " ,and service method is: " + invokerRestMethodMetadataPair.getRestMethodMetadata().getReflectMethod() + "before service method is: " + beforeMetadata.getRestMethodMetadata().getReflectMethod()); } } pathMatcherPairMap.put(pathMatcher, invokerRestMethodMetadataPair); addPathMatcherToHttpMethodsMap(pathMatcher); logger.info("dubbo rest deploy pathMatcher:" + pathMatcher + ", and service method is :" + invokerRestMethodMetadataPair.getRestMethodMetadata().getReflectMethod()); } private void addPathMatcherToHttpMethodsMap(PathMatcher pathMatcher) { PathMatcher newPathMatcher = PathMatcher.convertPathMatcher(pathMatcher); if (!pathMatcherToHttpMethodMap.containsKey(newPathMatcher)) { HashSet<String> httpMethods = new HashSet<>(); httpMethods.add(pathMatcher.getHttpMethod()); pathMatcherToHttpMethodMap.put(newPathMatcher, httpMethods); } Set<String> httpMethods = pathMatcherToHttpMethodMap.get(newPathMatcher); httpMethods.add(newPathMatcher.getHttpMethod()); } public boolean isHttpMethodAllowed(PathMatcher pathMatcher) { PathMatcher newPathMatcher = PathMatcher.convertPathMatcher(pathMatcher); if (!pathMatcherToHttpMethodMap.containsKey(newPathMatcher)) { return false; } Set<String> httpMethods = pathMatcherToHttpMethodMap.get(newPathMatcher); return httpMethods.contains(newPathMatcher.getHttpMethod()); } public String pathHttpMethods(PathMatcher pathMatcher) { PathMatcher newPathMatcher = PathMatcher.convertPathMatcher(pathMatcher); if (!pathMatcherToHttpMethodMap.containsKey(newPathMatcher)) { return null; } Set<String> httpMethods = pathMatcherToHttpMethodMap.get(newPathMatcher); return httpMethods.toString(); } }
5,717
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/handler/NettyHttpHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.handler; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import org.apache.dubbo.rpc.protocol.rest.exception.MediaTypeUnSupportException; import org.apache.dubbo.rpc.protocol.rest.exception.ParamParseException; import org.apache.dubbo.rpc.protocol.rest.exception.PathNoFoundException; import org.apache.dubbo.rpc.protocol.rest.filter.RestFilter; import org.apache.dubbo.rpc.protocol.rest.filter.RestRequestFilter; import org.apache.dubbo.rpc.protocol.rest.filter.RestResponseFilter; import org.apache.dubbo.rpc.protocol.rest.filter.ServiceInvokeRestFilter; import org.apache.dubbo.rpc.protocol.rest.filter.context.RestFilterContext; import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; import org.apache.dubbo.rpc.protocol.rest.request.NettyRequestFacade; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * netty http request handler */ public class NettyHttpHandler implements HttpHandler<NettyRequestFacade, NettyHttpResponse> { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final ServiceDeployer serviceDeployer; private final URL url; private final List<RestFilter> restRequestFilters; private final List<RestFilter> restResponseFilters; public NettyHttpHandler(ServiceDeployer serviceDeployer, URL url) { this.serviceDeployer = serviceDeployer; this.url = url; restRequestFilters = new ArrayList<>(url.getOrDefaultFrameworkModel() .getExtensionLoader(RestRequestFilter.class) .getActivateExtensions()); restResponseFilters = new ArrayList<>(url.getOrDefaultFrameworkModel() .getExtensionLoader(RestResponseFilter.class) .getActivateExtensions()); } @Override public void handle(NettyRequestFacade requestFacade, NettyHttpResponse nettyHttpResponse) throws IOException { // set remote address RpcContext.getServiceContext().setRemoteAddress(requestFacade.getRemoteAddr(), requestFacade.getRemotePort()); // set local address RpcContext.getServiceContext().setLocalAddress(requestFacade.getLocalAddr(), requestFacade.getLocalPort()); // set request RpcContext.getServiceContext().setRequest(requestFacade); // set response RpcContext.getServiceContext().setResponse(nettyHttpResponse); Object nettyHttpRequest = requestFacade.getRequest(); RestFilterContext restFilterContext = new RestFilterContext(url, requestFacade, nettyHttpResponse, serviceDeployer); try { // first request filter executeFilters(restFilterContext, restRequestFilters); } catch (PathNoFoundException pathNoFoundException) { logger.error( "", pathNoFoundException.getMessage(), "", "dubbo rest protocol provider path no found ,raw request is :" + nettyHttpRequest, pathNoFoundException); nettyHttpResponse.sendError(404, pathNoFoundException.getMessage()); } catch (ParamParseException paramParseException) { logger.error( "", paramParseException.getMessage(), "", "dubbo rest protocol provider param parse error ,and raw request is :" + nettyHttpRequest, paramParseException); nettyHttpResponse.sendError(400, paramParseException.getMessage()); } catch (MediaTypeUnSupportException contentTypeException) { logger.error( "", contentTypeException.getMessage(), "", "dubbo rest protocol provider content-type un support" + nettyHttpRequest, contentTypeException); nettyHttpResponse.sendError(415, contentTypeException.getMessage()); } catch (Throwable throwable) { logger.error( "", throwable.getMessage(), "", "dubbo rest protocol provider error ,and raw request is " + nettyHttpRequest, throwable); nettyHttpResponse.sendError( 500, "dubbo rest invoke Internal error, message is " + throwable.getMessage() + " ,and exception type is : " + throwable.getClass() + " , stacktrace is: " + ServiceInvokeRestFilter.stackTraceToString(throwable)); } // second response filter try { executeFilters(restFilterContext, restResponseFilters); } catch (Throwable throwable) { logger.error( "", throwable.getMessage(), "", "dubbo rest protocol provider error ,and raw request is " + nettyHttpRequest, throwable); nettyHttpResponse.sendError( 500, "dubbo rest invoke Internal error, message is " + throwable.getMessage() + " ,and exception type is : " + throwable.getClass() + " , stacktrace is: " + ServiceInvokeRestFilter.stackTraceToString(throwable)); } } /** * execute rest filters * * @param restFilterContext * @param restFilters * @throws Exception */ public void executeFilters(RestFilterContext restFilterContext, List<RestFilter> restFilters) throws Exception { for (RestFilter restFilter : restFilters) { restFilter.filter(restFilterContext); if (restFilterContext.complete()) { break; } } } }
5,718
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/ResteasyContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.extension.resteasy; import org.apache.dubbo.common.URL; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter.DubboContainerResponseContextImpl; import org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter.DubboPreMatchContainerRequestContext; import org.apache.dubbo.rpc.protocol.rest.filter.ServiceInvokeRestFilter; import org.apache.dubbo.rpc.protocol.rest.netty.ChunkOutputStream; import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; import org.apache.dubbo.rpc.protocol.rest.request.NettyRequestFacade; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.MultivaluedMap; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Map; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpRequest; import org.jboss.resteasy.core.interception.ResponseContainerRequestContext; import org.jboss.resteasy.plugins.server.netty.NettyHttpRequest; import org.jboss.resteasy.plugins.server.netty.NettyUtil; import org.jboss.resteasy.specimpl.BuiltResponse; import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; import org.jboss.resteasy.spi.HttpResponse; import org.jboss.resteasy.spi.ResteasyUriInfo; public interface ResteasyContext { String HTTP_PROTOCOL = "http://"; String HTTP = "http"; String HTTPS_PROTOCOL = "https://"; /** * return extensions that are filtered by extension type * * @param extension * @param <T> * @return */ default <T> List<T> getExtension(ServiceDeployer serviceDeployer, Class<T> extension) { return serviceDeployer.getExtensions(extension); } default DubboPreMatchContainerRequestContext convertHttpRequestToContainerRequestContext( RequestFacade requestFacade, ContainerRequestFilter[] requestFilters) { NettyRequestFacade nettyRequestFacade = (NettyRequestFacade) requestFacade; HttpRequest request = (HttpRequest) requestFacade.getRequest(); NettyHttpRequest nettyRequest = createNettyHttpRequest(nettyRequestFacade, request); if (request instanceof HttpContent) { try { byte[] inputStream = requestFacade.getInputStream(); ByteBuf buffer = nettyRequestFacade.getNettyChannelContext().alloc().buffer(); buffer.writeBytes(inputStream); nettyRequest.setContentBuffer(buffer); } catch (IOException e) { } } return new DubboPreMatchContainerRequestContext(nettyRequest, requestFilters, null); } default ResteasyUriInfo extractUriInfo(HttpRequest request) { String host = HttpHeaders.getHost(request, "unknown"); if ("".equals(host)) { host = "unknown"; } String uri = request.getUri(); String uriString; // If we appear to have an absolute URL, don't try to recreate it from the host and request line. if (uri.startsWith(HTTP_PROTOCOL) || uri.startsWith(HTTPS_PROTOCOL)) { uriString = uri; } else { uriString = HTTP + "://" + host + uri; } URI absoluteURI = URI.create(uriString); return new ResteasyUriInfo(uriString, absoluteURI.getRawQuery(), ""); } default NettyHttpRequest createNettyHttpRequest(NettyRequestFacade nettyRequestFacade, HttpRequest request) { ResteasyHttpHeaders headers = NettyUtil.extractHttpHeaders(request); ResteasyUriInfo uriInfo = extractUriInfo(request); NettyHttpRequest nettyRequest = new NettyHttpRequest( nettyRequestFacade.getNettyChannelContext(), headers, uriInfo, request.getMethod().name(), null, null, HttpHeaders.is100ContinueExpected(request)); return nettyRequest; } default NettyHttpRequest createNettyHttpRequest(RequestFacade requestFacade) { NettyRequestFacade nettyRequestFacade = (NettyRequestFacade) requestFacade; HttpRequest request = (HttpRequest) requestFacade.getRequest(); ResteasyHttpHeaders headers = NettyUtil.extractHttpHeaders(request); ResteasyUriInfo uriInfo = extractUriInfo(request); NettyHttpRequest nettyRequest = new NettyHttpRequest( nettyRequestFacade.getNettyChannelContext(), headers, uriInfo, request.getMethod().name(), null, null, HttpHeaders.is100ContinueExpected(request)); return nettyRequest; } default void writeResteasyResponse( URL url, RequestFacade requestFacade, NettyHttpResponse response, BuiltResponse restResponse) throws Exception { if (restResponse.getMediaType() != null) { MediaType mediaType = MediaTypeUtil.convertMediaType( restResponse.getEntityClass(), restResponse.getMediaType().toString()); ServiceInvokeRestFilter.writeResult( response, url, restResponse.getEntity(), restResponse.getEntityClass(), mediaType); } else { ServiceInvokeRestFilter.writeResult( response, requestFacade, url, restResponse.getEntity(), restResponse.getEntityClass()); } } default MediaType getAcceptMediaType(RequestFacade request, Class<?> returnType) { return ServiceInvokeRestFilter.getAcceptMediaType(request, returnType); } default void addResponseHeaders(NettyHttpResponse response, MultivaluedMap<String, Object> headers) { if (headers == null || headers.isEmpty()) { return; } for (Map.Entry<String, List<Object>> entry : headers.entrySet()) { String key = entry.getKey(); if (entry.getValue() == null) { continue; } response.addOutputHeaders(key, entry.getValue().toString()); } } default DubboContainerResponseContextImpl createContainerResponseContext( Object originRequest, RequestFacade request, HttpResponse httpResponse, BuiltResponse jaxrsResponse, ContainerResponseFilter[] responseFilters) { NettyHttpRequest nettyHttpRequest = originRequest == null ? createNettyHttpRequest(request) : (NettyHttpRequest) originRequest; ResponseContainerRequestContext requestContext = new ResponseContainerRequestContext(nettyHttpRequest); DubboContainerResponseContextImpl responseContext = new DubboContainerResponseContextImpl( nettyHttpRequest, httpResponse, jaxrsResponse, requestContext, responseFilters, null, null); return responseContext; } default void restOutputStream(NettyHttpResponse response) throws IOException { ChunkOutputStream outputStream = (ChunkOutputStream) response.getOutputStream(); outputStream.reset(); } }
5,719
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/DubboServerWriterInterceptorContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.intercept; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.WriterInterceptor; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import org.jboss.resteasy.core.interception.ServerWriterInterceptorContext; import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.ResteasyProviderFactory; public class DubboServerWriterInterceptorContext extends ServerWriterInterceptorContext { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboServerWriterInterceptorContext.class); public DubboServerWriterInterceptorContext( WriterInterceptor[] interceptors, ResteasyProviderFactory providerFactory, Object entity, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream outputStream, HttpRequest request) { super( interceptors, providerFactory, entity, type, genericType, annotations, mediaType, headers, outputStream, request); } @Override public void proceed() throws IOException, WebApplicationException { logger.debug("Dubbo server writer intercept context: " + getClass().getName() + " Method : proceed"); if (interceptors == null || index >= interceptors.length) { return; } else { logger.debug("Dubbo server writer intercept context WriterInterceptor: " + interceptors[index].getClass().getName()); interceptors[index++].aroundWriteTo(this); } } }
5,720
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/ResteasyWriterInterceptorAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.intercept; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import org.apache.dubbo.rpc.protocol.rest.extension.resteasy.ResteasyContext; import org.apache.dubbo.rpc.protocol.rest.filter.RestResponseInterceptor; import org.apache.dubbo.rpc.protocol.rest.filter.context.RestInterceptContext; import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.WriterInterceptor; import java.io.ByteArrayOutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.List; import org.apache.commons.io.IOUtils; import org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext; import org.jboss.resteasy.plugins.server.netty.NettyHttpRequest; import org.jboss.resteasy.specimpl.MultivaluedMapImpl; import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.ResteasyProviderFactory; @Activate( value = "resteasy", onClass = { "javax.ws.rs.ext.WriterInterceptorContext", "org.jboss.resteasy.plugins.server.netty.NettyHttpRequest", "org.jboss.resteasy.plugins.server.netty.NettyHttpResponse" }) public class ResteasyWriterInterceptorAdapter implements RestResponseInterceptor, ResteasyContext { private ResteasyProviderFactory resteasyProviderFactory = getResteasyProviderFactory(); @Override public void intercept(RestInterceptContext restResponseInterceptor) throws Exception { RpcInvocation rpcInvocation = restResponseInterceptor.getRpcInvocation(); ServiceDeployer serviceDeployer = restResponseInterceptor.getServiceDeployer(); RequestFacade request = restResponseInterceptor.getRequestFacade(); NettyHttpResponse response = restResponseInterceptor.getResponse(); Object result = restResponseInterceptor.getResult(); Class<?> type = rpcInvocation.getReturnType(); List<WriterInterceptor> extension = serviceDeployer.getExtensions(WriterInterceptor.class); if (extension.isEmpty()) { return; } NettyHttpRequest nettyHttpRequest = (NettyHttpRequest) restResponseInterceptor.getOriginRequest(); HttpRequest restRequest = nettyHttpRequest == null ? createNettyHttpRequest(request) : nettyHttpRequest; MultivaluedMap<String, Object> headers = new MultivaluedMapImpl(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { // get content-type String value = getAcceptMediaType(request, type).value; MediaType mediaType = MediaType.valueOf(value); AbstractWriterInterceptorContext writerContext = getAbstractWriterInterceptorContext( restRequest, extension, result, type, type, mediaType, os, headers); writerContext.proceed(); ByteArrayOutputStream outputStream = (ByteArrayOutputStream) writerContext.getOutputStream(); addResponseHeaders(response, writerContext.getHeaders()); if (outputStream.size() <= 0) { return; } // intercept response first restOutputStream(response); byte[] bytes = outputStream.toByteArray(); response.getOutputStream().write(bytes); response.addOutputHeaders(RestHeaderEnum.CONTENT_TYPE.getHeader(), value); restResponseInterceptor.setComplete(true); } finally { IOUtils.close(os); } } private AbstractWriterInterceptorContext getAbstractWriterInterceptorContext( HttpRequest request, List<WriterInterceptor> extension, Object entity, Class type, Type genericType, MediaType mediaType, ByteArrayOutputStream os, MultivaluedMap<String, Object> headers) { AbstractWriterInterceptorContext writerContext = new DubboServerWriterInterceptorContext( extension.toArray(new WriterInterceptor[0]), resteasyProviderFactory, entity, type, genericType, new Annotation[0], mediaType, headers, os, request); return writerContext; } protected ResteasyProviderFactory getResteasyProviderFactory() { return new ResteasyProviderFactory(); } }
5,721
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyRequestContainerFilterAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import org.apache.dubbo.rpc.protocol.rest.extension.resteasy.ResteasyContext; import org.apache.dubbo.rpc.protocol.rest.filter.RestRequestFilter; import org.apache.dubbo.rpc.protocol.rest.filter.context.RestFilterContext; import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import javax.ws.rs.container.ContainerRequestFilter; import java.util.List; import org.jboss.resteasy.specimpl.BuiltResponse; @Activate( value = "resteasy", onClass = { "javax.ws.rs.container.ContainerRequestFilter", "org.jboss.resteasy.plugins.server.netty.NettyHttpRequest", "org.jboss.resteasy.plugins.server.netty.NettyHttpResponse" }, order = Integer.MAX_VALUE - 1) public class ResteasyRequestContainerFilterAdapter implements RestRequestFilter, ResteasyContext { @Override public void filter(RestFilterContext restFilterContext) throws Exception { ServiceDeployer serviceDeployer = restFilterContext.getServiceDeployer(); RequestFacade requestFacade = restFilterContext.getRequestFacade(); URL url = restFilterContext.getUrl(); NettyHttpResponse response = restFilterContext.getResponse(); List<ContainerRequestFilter> containerRequestFilters = getExtension(serviceDeployer, ContainerRequestFilter.class); if (containerRequestFilters.isEmpty()) { return; } DubboPreMatchContainerRequestContext containerRequestContext = convertHttpRequestToContainerRequestContext( requestFacade, containerRequestFilters.toArray(new ContainerRequestFilter[0])); // set resteasy request for save user`s custom request attribute restFilterContext.setOriginRequest(containerRequestContext.getHttpRequest()); try { BuiltResponse restResponse = containerRequestContext.filter(); if (restResponse == null) { return; } addResponseHeaders(response, restResponse.getHeaders()); writeResteasyResponse(url, requestFacade, response, restResponse); // completed restFilterContext.setComplete(true); } catch (Throwable e) { throw new RuntimeException("dubbo rest resteasy ContainerRequestFilter write response encode error", e); } } }
5,722
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboBuiltResponse.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter; import org.jboss.resteasy.specimpl.BuiltResponse; /** * wrapper resteasy BuiltResponse */ public class DubboBuiltResponse extends BuiltResponse { // user reset entity private boolean resetEntity; public DubboBuiltResponse(Object entity, int status, Class<?> entityClass) { this.entity = entity; this.entityClass = entityClass; this.status = status; } @Override public void setEntity(Object entity) { if (entity == null) { return; } if (entity.equals(this.entity)) { return; } // reset entity true this.resetEntity = true; super.setEntity(entity); } public boolean isResetEntity() { return resetEntity; } }
5,723
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboContainerResponseContextImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.HttpHeaders; 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; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.net.URI; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import org.jboss.resteasy.core.Dispatcher; import org.jboss.resteasy.core.ServerResponseWriter; import org.jboss.resteasy.core.SynchronousDispatcher; import org.jboss.resteasy.core.interception.ResponseContainerRequestContext; import org.jboss.resteasy.core.interception.jaxrs.SuspendableContainerResponseContext; import org.jboss.resteasy.specimpl.BuiltResponse; import org.jboss.resteasy.spi.ApplicationException; import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.HttpResponse; import org.jboss.resteasy.spi.ResteasyAsynchronousResponse; import org.jboss.resteasy.spi.ResteasyProviderFactory; public class DubboContainerResponseContextImpl implements SuspendableContainerResponseContext { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboContainerResponseContextImpl.class); protected final HttpRequest request; protected final HttpResponse httpResponse; protected final BuiltResponse jaxrsResponse; private ResponseContainerRequestContext requestContext; private ContainerResponseFilter[] responseFilters; private ServerResponseWriter.RunnableWithIOException continuation; private int currentFilter; private boolean suspended; private boolean filterReturnIsMeaningful = true; private Map<Class<?>, Object> contextDataMap; private boolean inFilter; private Throwable throwable; private Consumer<Throwable> onComplete; private boolean weSuspended; public DubboContainerResponseContextImpl( final HttpRequest request, final HttpResponse httpResponse, final BuiltResponse serverResponse, final ResponseContainerRequestContext requestContext, final ContainerResponseFilter[] responseFilters, final Consumer<Throwable> onComplete, final ServerResponseWriter.RunnableWithIOException continuation) { this.request = request; this.httpResponse = httpResponse; this.jaxrsResponse = serverResponse; this.requestContext = requestContext; this.responseFilters = responseFilters; this.continuation = continuation; this.onComplete = onComplete; contextDataMap = ResteasyProviderFactory.getContextDataMap(); } public BuiltResponse getJaxrsResponse() { return jaxrsResponse; } public HttpResponse getHttpResponse() { return httpResponse; } @Override public int getStatus() { return jaxrsResponse.getStatus(); } @Override public void setStatus(int code) { httpResponse.setStatus(code); jaxrsResponse.setStatus(code); } @Override public Response.StatusType getStatusInfo() { return jaxrsResponse.getStatusInfo(); } @Override public void setStatusInfo(Response.StatusType statusInfo) { httpResponse.setStatus(statusInfo.getStatusCode()); jaxrsResponse.setStatus(statusInfo.getStatusCode()); } @Override public Class<?> getEntityClass() { return jaxrsResponse.getEntityClass(); } @Override public Type getEntityType() { return jaxrsResponse.getGenericType(); } @Override public void setEntity(Object entity) { if (entity != null && jaxrsResponse.getEntity() != null) { if (logger.isDebugEnabled()) { logger.debug("Dubbo container response context filter set entity ,before entity is: " + jaxrsResponse.getEntity() + "and after entity is: " + entity); } } jaxrsResponse.setEntity(entity); // it resets the entity in a response filter which results // in a bad content-length being sent back to the client // so, we'll remove any content-length setting getHeaders().remove(HttpHeaders.CONTENT_LENGTH); } @Override public void setEntity(Object entity, Annotation[] annotations, MediaType mediaType) { if (entity != null && jaxrsResponse.getEntity() != null) { if (logger.isDebugEnabled()) { logger.debug("Dubbo container response context filter set entity ,before entity is: " + jaxrsResponse.getEntity() + "and after entity is: " + entity); } } jaxrsResponse.setEntity(entity); jaxrsResponse.setAnnotations(annotations); jaxrsResponse.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType); // it resets the entity in a response filter which results // in a bad content-length being sent back to the client // so, we'll remove any content-length setting getHeaders().remove(HttpHeaders.CONTENT_LENGTH); } @Override public MultivaluedMap<String, Object> getHeaders() { return jaxrsResponse.getMetadata(); } @Override public Set<String> getAllowedMethods() { return jaxrsResponse.getAllowedMethods(); } @Override public Date getDate() { return jaxrsResponse.getDate(); } @Override public Locale getLanguage() { return jaxrsResponse.getLanguage(); } @Override public int getLength() { return jaxrsResponse.getLength(); } @Override public MediaType getMediaType() { return jaxrsResponse.getMediaType(); } @Override public Map<String, NewCookie> getCookies() { return jaxrsResponse.getCookies(); } @Override public EntityTag getEntityTag() { return jaxrsResponse.getEntityTag(); } @Override public Date getLastModified() { return jaxrsResponse.getLastModified(); } @Override public URI getLocation() { return jaxrsResponse.getLocation(); } @Override public Set<Link> getLinks() { return jaxrsResponse.getLinks(); } @Override public boolean hasLink(String relation) { return jaxrsResponse.hasLink(relation); } @Override public Link getLink(String relation) { return jaxrsResponse.getLink(relation); } @Override public Link.Builder getLinkBuilder(String relation) { return jaxrsResponse.getLinkBuilder(relation); } @Override public boolean hasEntity() { return !jaxrsResponse.isClosed() && jaxrsResponse.hasEntity(); } @Override public Object getEntity() { return !jaxrsResponse.isClosed() ? jaxrsResponse.getEntity() : null; } @Override public OutputStream getEntityStream() { try { return httpResponse.getOutputStream(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void setEntityStream(OutputStream entityStream) { httpResponse.setOutputStream(entityStream); } @Override public Annotation[] getEntityAnnotations() { return jaxrsResponse.getAnnotations(); } @Override public MultivaluedMap<String, String> getStringHeaders() { return jaxrsResponse.getStringHeaders(); } @Override public String getHeaderString(String name) { return jaxrsResponse.getHeaderString(name); } @Override public synchronized void suspend() { if (continuation == null) throw new RuntimeException("Suspend not supported yet"); suspended = true; } @Override public synchronized void resume() { if (!suspended) throw new RuntimeException("Cannot resume: not suspended"); if (inFilter) { // suspend/resume within filter, same thread: just ignore and move on suspended = false; return; } // go on, but with proper exception handling try (ResteasyProviderFactory.CloseableContext c = ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { filter(); } catch (Throwable t) { // don't throw to client writeException(t); } } @Override public synchronized void resume(Throwable t) { if (!suspended) throw new RuntimeException("Cannot resume: not suspended"); if (inFilter) { // not suspended, or suspend/abortWith within filter, same thread: collect and move on throwable = t; suspended = false; } else { try (ResteasyProviderFactory.CloseableContext c = ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { writeException(t); } } } private void writeException(Throwable t) { /* * Here we cannot call AsyncResponse.resume(t) because that would invoke the response filters * and we should not invoke them because we're already in them. */ HttpResponse httpResponse = (HttpResponse) contextDataMap.get(HttpResponse.class); SynchronousDispatcher dispatcher = (SynchronousDispatcher) contextDataMap.get(Dispatcher.class); ResteasyAsynchronousResponse asyncResponse = request.getAsyncContext().getAsyncResponse(); dispatcher.unhandledAsynchronousException(httpResponse, t); onComplete.accept(t); asyncResponse.complete(); asyncResponse.completionCallbacks(t); } public synchronized void filter() throws IOException { while (currentFilter < responseFilters.length) { ContainerResponseFilter filter = responseFilters[currentFilter++]; try { suspended = false; throwable = null; inFilter = true; filter.filter(requestContext, this); } catch (IOException e) { throw new ApplicationException(e); } finally { inFilter = false; } if (suspended) { if (!request.getAsyncContext().isSuspended()) { request.getAsyncContext().suspend(); weSuspended = true; } // ignore any abort request until we are resumed filterReturnIsMeaningful = false; return; } if (throwable != null) { // handle the case where we've been suspended by a previous filter if (filterReturnIsMeaningful) SynchronousDispatcher.rethrow(throwable); else { writeException(throwable); return; } } } // here it means we reached the last filter // some frameworks don't support async request filters, in which case suspend() is forbidden // so if we get here we're still synchronous and don't have a continuation, which must be in // the caller if (continuation == null) return; // if we've never been suspended, the caller is valid so let it handle any exception if (filterReturnIsMeaningful) { continuation.run(); onComplete.accept(null); return; } // if we've been suspended then the caller is a filter and have to invoke our continuation // try to write it out try { continuation.run(); onComplete.accept(null); if (weSuspended) { // if we're the ones who turned the request async, nobody will call complete() for us, so we have to HttpServletRequest httpServletRequest = (HttpServletRequest) contextDataMap.get(HttpServletRequest.class); httpServletRequest.getAsyncContext().complete(); } } catch (IOException e) { logger.error( "", "Dubbo container response context filter error", "request method is: " + request.getHttpMethod() + "and request uri is:" + request.getUri().getPath(), "", e); } } }
5,724
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyResponseContainerFilterAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import org.apache.dubbo.rpc.protocol.rest.extension.resteasy.ResteasyContext; import org.apache.dubbo.rpc.protocol.rest.filter.RestResponseFilter; import org.apache.dubbo.rpc.protocol.rest.filter.context.RestFilterContext; import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import javax.ws.rs.container.ContainerResponseFilter; import java.util.List; import org.jboss.resteasy.spi.HttpResponse; @Activate( value = "resteasy", order = Integer.MAX_VALUE - 1000, onClass = { "org.jboss.resteasy.specimpl.BuiltResponse", "javax.ws.rs.container.ContainerResponseFilter", "org.jboss.resteasy.spi.HttpResponse", "org.jboss.resteasy.plugins.server.netty.NettyHttpResponse" }) public class ResteasyResponseContainerFilterAdapter implements RestResponseFilter, ResteasyContext { @Override public void filter(RestFilterContext restFilterContext) throws Exception { ServiceDeployer serviceDeployer = restFilterContext.getServiceDeployer(); RequestFacade requestFacade = restFilterContext.getRequestFacade(); NettyHttpResponse response = restFilterContext.getResponse(); URL url = restFilterContext.getUrl(); List<ContainerResponseFilter> containerRequestFilters = getExtension(serviceDeployer, ContainerResponseFilter.class); if (containerRequestFilters.isEmpty()) { return; } // response filter entity first // build jaxrsResponse from rest netty response DubboBuiltResponse dubboBuiltResponse = new DubboBuiltResponse(response.getResponseBody(), response.getStatus(), response.getEntityClass()); // NettyHttpResponse wrapper HttpResponse httpResponse = new ResteasyNettyHttpResponse(response); DubboContainerResponseContextImpl containerResponseContext = createContainerResponseContext( restFilterContext.getOriginRequest(), requestFacade, httpResponse, dubboBuiltResponse, containerRequestFilters.toArray(new ContainerResponseFilter[0])); containerResponseContext.filter(); // user reset entity if (dubboBuiltResponse.hasEntity() && dubboBuiltResponse.isResetEntity()) { // clean output stream data restOutputStream(response); writeResteasyResponse(url, requestFacade, response, dubboBuiltResponse); } addResponseHeaders(response, httpResponse.getOutputHeaders()); restFilterContext.setComplete(true); } }
5,725
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboPreMatchContainerRequestContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter; import javax.ws.rs.container.ContainerRequestFilter; 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.IOException; import java.io.InputStream; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.function.Supplier; import org.jboss.resteasy.core.interception.jaxrs.SuspendableContainerRequestContext; import org.jboss.resteasy.plugins.server.netty.NettyHttpRequest; import org.jboss.resteasy.specimpl.BuiltResponse; import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; import org.jboss.resteasy.spi.ApplicationException; import org.jboss.resteasy.spi.ResteasyProviderFactory; public class DubboPreMatchContainerRequestContext implements SuspendableContainerRequestContext { protected final NettyHttpRequest httpRequest; protected Response response; private ContainerRequestFilter[] requestFilters; private int currentFilter; private boolean suspended; private boolean filterReturnIsMeaningful = true; private Supplier<BuiltResponse> continuation; private Map<Class<?>, Object> contextDataMap; private boolean inFilter; private Throwable throwable; private boolean startedContinuation; public DubboPreMatchContainerRequestContext( final NettyHttpRequest request, final ContainerRequestFilter[] requestFilters, final Supplier<BuiltResponse> continuation) { this.httpRequest = request; this.requestFilters = requestFilters; this.continuation = continuation; contextDataMap = ResteasyProviderFactory.getContextDataMap(); } public NettyHttpRequest getHttpRequest() { return httpRequest; } public Response getResponseAbortedWith() { return response; } @Override public Object getProperty(String name) { return httpRequest.getAttribute(name); } @Override public Collection<String> getPropertyNames() { ArrayList<String> names = new ArrayList<String>(); Enumeration<String> enames = httpRequest.getAttributeNames(); while (enames.hasMoreElements()) { names.add(enames.nextElement()); } return names; } @Override public void setProperty(String name, Object object) { httpRequest.setAttribute(name, object); } @Override public void removeProperty(String name) { httpRequest.removeAttribute(name); } @Override public UriInfo getUriInfo() { return httpRequest.getUri(); } @Override public void setRequestUri(URI requestUri) throws IllegalStateException { httpRequest.setRequestUri(requestUri); } @Override public void setRequestUri(URI baseUri, URI requestUri) throws IllegalStateException { httpRequest.setRequestUri(baseUri, requestUri); } @Override public String getMethod() { return httpRequest.getHttpMethod(); } @Override public void setMethod(String method) { httpRequest.setHttpMethod(method); } @Override public MultivaluedMap<String, String> getHeaders() { return ((ResteasyHttpHeaders) httpRequest.getHttpHeaders()).getMutableHeaders(); } @Override public Date getDate() { return httpRequest.getHttpHeaders().getDate(); } @Override public Locale getLanguage() { return httpRequest.getHttpHeaders().getLanguage(); } @Override public int getLength() { return httpRequest.getHttpHeaders().getLength(); } @Override public MediaType getMediaType() { return httpRequest.getHttpHeaders().getMediaType(); } @Override public List<MediaType> getAcceptableMediaTypes() { return httpRequest.getHttpHeaders().getAcceptableMediaTypes(); } @Override public List<Locale> getAcceptableLanguages() { return httpRequest.getHttpHeaders().getAcceptableLanguages(); } @Override public Map<String, Cookie> getCookies() { return httpRequest.getHttpHeaders().getCookies(); } @Override public boolean hasEntity() { return getMediaType() != null; } @Override public InputStream getEntityStream() { return httpRequest.getInputStream(); } @Override public void setEntityStream(InputStream entityStream) { httpRequest.setInputStream(entityStream); } @Override public SecurityContext getSecurityContext() { return ResteasyProviderFactory.getContextData(SecurityContext.class); } @Override public void setSecurityContext(SecurityContext context) { ResteasyProviderFactory.pushContext(SecurityContext.class, context); } @Override public Request getRequest() { return ResteasyProviderFactory.getContextData(Request.class); } @Override public String getHeaderString(String name) { return httpRequest.getHttpHeaders().getHeaderString(name); } @Override public synchronized void suspend() { if (continuation == null) throw new RuntimeException("Suspend not supported yet"); suspended = true; } @Override public synchronized void abortWith(Response response) { if (suspended && !inFilter) { try (ResteasyProviderFactory.CloseableContext c = ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { httpRequest.getAsyncContext().getAsyncResponse().resume(response); } } else { // not suspended, or suspend/abortWith within filter, same thread: collect and move on this.response = response; suspended = false; } } @Override public synchronized void resume() { if (!suspended) throw new RuntimeException("Cannot resume: not suspended"); if (inFilter) { // suspend/resume within filter, same thread: just ignore and move on suspended = false; return; } // go on, but with proper exception handling try (ResteasyProviderFactory.CloseableContext c = ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { filter(); } catch (Throwable t) { // don't throw to client writeException(t); } } @Override public synchronized void resume(Throwable t) { if (!suspended) throw new RuntimeException("Cannot resume: not suspended"); if (inFilter) { // not suspended, or suspend/abortWith within filter, same thread: collect and move on throwable = t; suspended = false; } else { try (ResteasyProviderFactory.CloseableContext c = ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { writeException(t); } } } private void writeException(Throwable t) { /* * Here, contrary to ContainerResponseContextImpl.writeException, we can use the async response * to write the exception, because it calls the right response filters, complete() and callbacks */ httpRequest.getAsyncContext().getAsyncResponse().resume(t); } public synchronized BuiltResponse filter() throws Throwable { while (currentFilter < requestFilters.length) { ContainerRequestFilter filter = requestFilters[currentFilter++]; try { suspended = false; response = null; throwable = null; inFilter = true; filter.filter(this); } catch (IOException e) { throw new ApplicationException(e); } finally { inFilter = false; } if (suspended) { if (!httpRequest.getAsyncContext().isSuspended()) // ignore any abort request until we are resumed filterReturnIsMeaningful = false; response = null; return null; } BuiltResponse serverResponse = (BuiltResponse) getResponseAbortedWith(); if (serverResponse != null) { // handle the case where we've been suspended by a previous filter return serverResponse; } if (throwable != null) { // handle the case where we've been suspended by a previous filter throw throwable; } } // here it means we reached the last filter // some frameworks don't support async request filters, in which case suspend() is forbidden // so if we get here we're still synchronous and don't have a continuation, which must be in // the caller startedContinuation = true; if (continuation == null) return null; // in any case, return the continuation: sync will use it, and async will ignore it return continuation.get(); } public boolean startedContinuation() { return startedContinuation; } }
5,726
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyNettyHttpResponse.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter; import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.NewCookie; import java.io.IOException; import java.io.OutputStream; import java.util.List; import java.util.Map; import org.jboss.resteasy.specimpl.MultivaluedMapImpl; import org.jboss.resteasy.spi.HttpResponse; public class ResteasyNettyHttpResponse implements HttpResponse { private NettyHttpResponse response; private MultivaluedMap<String, Object> multivaluedMap = new MultivaluedMapImpl<>(); public ResteasyNettyHttpResponse(NettyHttpResponse response) { this.response = response; Map<String, List<String>> outputHeaders = response.getOutputHeaders(); for (Map.Entry<String, List<String>> headers : outputHeaders.entrySet()) { String key = headers.getKey(); List<String> value = headers.getValue(); multivaluedMap.add(key, value); } } @Override public int getStatus() { return response.getStatus(); } @Override public void setStatus(int status) { response.setStatus(status); } @Override public MultivaluedMap<String, Object> getOutputHeaders() { return multivaluedMap; } @Override public OutputStream getOutputStream() throws IOException { return response.getOutputStream(); } @Override public void setOutputStream(OutputStream os) { response.setOutputStream(os); } @Override public void addNewCookie(NewCookie cookie) {} @Override public void sendError(int status) throws IOException { response.sendError(status); } @Override public void sendError(int status, String message) throws IOException { response.sendError(status, message); } @Override public boolean isCommitted() { return false; } @Override public void reset() { response.reset(); } @Override public void flushBuffer() throws IOException {} }
5,727
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/DataParseUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.util; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.common.utils.StringUtils; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.StringTokenizer; public class DataParseUtils { public static Object stringTypeConvert(Class<?> targetType, String value) { if (StringUtils.isEmpty(value)) { return null; } if (targetType == Boolean.class || targetType == boolean.class) { return Boolean.valueOf(value); } if (targetType == String.class) { return value; } if (Number.class.isAssignableFrom(targetType)) { return NumberUtils.parseNumber(value, targetType); } if (targetType != null && targetType.isPrimitive()) { return NumberUtils.parseNumber(value, targetType); } return value; } public static boolean isTextType(Class targetType) { if (targetType == null) { return false; } return targetType == Boolean.class || targetType == boolean.class || targetType == String.class || Number.class.isAssignableFrom(targetType) || targetType.isPrimitive(); } /** * content-type text * * @param object * @param outputStream * @throws IOException */ public static void writeTextContent(Object object, OutputStream outputStream) throws IOException { outputStream.write(objectTextConvertToByteArray(object)); } /** * content-type json * * @param object * @param outputStream * @throws Exception */ public static void writeJsonContent(Object object, OutputStream outputStream) throws Exception { outputStream.write(JsonUtils.toJson(object).getBytes(StandardCharsets.UTF_8)); } /** * content-type form * * @param formData * @param outputStream * @throws Exception */ public static void writeFormContent(Map formData, OutputStream outputStream) throws Exception { outputStream.write(serializeForm(formData, Charset.defaultCharset()).getBytes()); } // TODO file multipart public static String serializeForm(Map formData, Charset charset) { StringBuilder builder = new StringBuilder(); formData.forEach((name, values) -> { if (name == null) { return; } ((List) values).forEach(value -> { try { if (builder.length() != 0) { builder.append('&'); } builder.append(URLEncoder.encode((String) name, charset.name())); if (value != null) { builder.append('='); builder.append(URLEncoder.encode(String.valueOf(value), charset.name())); } } catch (UnsupportedEncodingException ex) { throw new IllegalStateException(ex); } }); }); return builder.toString(); } public static byte[] objectTextConvertToByteArray(Object object) { Class<?> objectClass = object.getClass(); if (objectClass == Boolean.class || objectClass == boolean.class) { return object.toString().getBytes(); } if (objectClass == String.class) { return ((String) object).getBytes(); } if (objectClass.isAssignableFrom(Number.class) || objectClass.isPrimitive()) { return (byte[]) NumberUtils.numberToBytes((Number) object); } return object.toString().getBytes(); } public static Object jsonConvert(Type targetType, byte[] body) throws Exception { return JsonUtils.toJavaObject(new String(body, StandardCharsets.UTF_8), targetType); } public static Object multipartFormConvert(byte[] body, Charset charset, Class<?> targetType) throws Exception { String[] pairs = tokenizeToStringArray(new String(body, StandardCharsets.UTF_8), "&"); Object result = MultiValueCreator.providerCreateMultiValueMap(targetType); for (String pair : pairs) { int idx = pair.indexOf('='); if (idx == -1) { MultiValueCreator.add(result, URLDecoder.decode(pair, charset.name()), null); } else { String name = URLDecoder.decode(pair.substring(0, idx), charset.name()); String value = URLDecoder.decode(pair.substring(idx + 1), charset.name()); MultiValueCreator.add(result, name, value); } } return result; } public static Object multipartFormConvert(byte[] body, Class<?> targetType) throws Exception { return multipartFormConvert(body, Charset.defaultCharset(), targetType); } public static String[] tokenizeToStringArray(String str, String delimiters) { return tokenizeToStringArray(str, delimiters, true, true); } public static String[] tokenizeToStringArray( String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { if (str == null) { return null; } else { StringTokenizer st = new StringTokenizer(str, delimiters); ArrayList tokens = new ArrayList(); while (true) { String token; do { if (!st.hasMoreTokens()) { return toStringArray(tokens); } token = st.nextToken(); if (trimTokens) { token = token.trim(); } } while (ignoreEmptyTokens && token.length() <= 0); tokens.add(token); } } } public static String[] toStringArray(Collection<String> collection) { return collection == null ? null : collection.toArray(new String[collection.size()]); } }
5,728
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/NumberUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.util; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.StringUtils; import java.math.BigDecimal; import java.math.BigInteger; public class NumberUtils { public static <T> T parseNumber(String text, Class<T> targetClass) { Assert.notNull(text, "Text must not be null"); Assert.notNull(targetClass, "Target class must not be null"); String trimmed = trimAllWhitespace(text); if (Byte.class == targetClass || byte.class == targetClass) { return (T) (isHexNumber(trimmed) ? Byte.decode(trimmed) : Byte.valueOf(trimmed)); } else if (Short.class == targetClass || short.class == targetClass) { return (T) (isHexNumber(trimmed) ? Short.decode(trimmed) : Short.valueOf(trimmed)); } else if (Integer.class == targetClass || int.class == targetClass) { return (T) (isHexNumber(trimmed) ? Integer.decode(trimmed) : Integer.valueOf(trimmed)); } else if (Long.class == targetClass || long.class == targetClass) { return (T) (isHexNumber(trimmed) ? Long.decode(trimmed) : Long.valueOf(trimmed)); } else if (BigInteger.class == targetClass) { return (T) (isHexNumber(trimmed) ? decodeBigInteger(trimmed) : new BigInteger(trimmed)); } else if (Float.class == targetClass || float.class == targetClass) { return (T) Float.valueOf(trimmed); } else if (Double.class == targetClass || double.class == targetClass) { return (T) Double.valueOf(trimmed); } else if (BigDecimal.class == targetClass || Number.class == targetClass) { return (T) new BigDecimal(trimmed); } else { throw new IllegalArgumentException( "Cannot convert String [" + text + "] to target class [" + targetClass.getName() + "]"); } } private static boolean isHexNumber(String value) { int index = (value.startsWith("-") ? 1 : 0); return (value.startsWith("0x", index) || value.startsWith("0X", index) || value.startsWith("#", index)); } private static BigInteger decodeBigInteger(String value) { int radix = 10; int index = 0; boolean negative = false; // Handle minus sign, if present. if (value.startsWith("-")) { negative = true; index++; } // Handle radix specifier, if present. if (value.startsWith("0x", index) || value.startsWith("0X", index)) { index += 2; radix = 16; } else if (value.startsWith("#", index)) { index++; radix = 16; } else if (value.startsWith("0", index) && value.length() > 1 + index) { index++; radix = 8; } BigInteger result = new BigInteger(value.substring(index), radix); return (negative ? result.negate() : result); } public static String trimAllWhitespace(String str) { if (StringUtils.isEmpty(str)) { return str; } int len = str.length(); StringBuilder sb = new StringBuilder(str.length()); for (int i = 0; i < len; i++) { char c = str.charAt(i); if (!Character.isWhitespace(c)) { sb.append(c); } } return sb.toString(); } public static Object numberToBytes(Number number) { if (number instanceof Byte) { // Use default encoding. return Byte.toString(number.byteValue()).getBytes(); } else if (number instanceof Double) { return Double.toString(number.doubleValue()).getBytes(); } else if (number instanceof Float) { return Float.toString(number.floatValue()).getBytes(); } else if (number instanceof Integer) { return Float.toString(number.intValue()).getBytes(); } else if (number instanceof Long) { return Long.toString(number.longValue()).getBytes(); } else if (number instanceof Short) { return Short.toString(number.shortValue()).getBytes(); } else if (number instanceof BigDecimal) { return BigDecimal.class.cast(number).toString().getBytes(); } return number; } }
5,729
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/MultiValueCreator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.util; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.lang.reflect.Method; import java.util.Map; public class MultiValueCreator { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MultiValueCreator.class); private static final String SPRING_MultiValueMapImpl = "org.springframework.util.LinkedMultiValueMap"; private static final String SPRING_MultiValueMap = "org.springframework.util.MultiValueMap"; private static final String JAVAX_MultiValueMapImpl = "org.jboss.resteasy.specimpl.MultivaluedMapImpl"; private static final String JAVAX_MultiValueMap = "javax.ws.rs.core.MultivaluedMap"; private static Class springMultiValueMapImplClass = null; private static Class springMultiValueMapClass = null; private static Method springMultiValueMapAdd = null; private static Class jaxrsMultiValueMapImplClass = null; private static Class jaxrsMultiValueMapClass = null; private static Method jaxrsMultiValueMapAdd = null; static { springMultiValueMapClass = ReflectUtils.findClassTryException(SPRING_MultiValueMap); springMultiValueMapImplClass = ReflectUtils.findClassTryException(SPRING_MultiValueMapImpl); springMultiValueMapAdd = ReflectUtils.getMethodByName(springMultiValueMapImplClass, "add"); jaxrsMultiValueMapClass = ReflectUtils.findClassTryException(JAVAX_MultiValueMap); jaxrsMultiValueMapImplClass = ReflectUtils.findClassTryException(JAVAX_MultiValueMapImpl); jaxrsMultiValueMapAdd = ReflectUtils.getMethodByName(jaxrsMultiValueMapImplClass, "add"); } public static Object providerCreateMultiValueMap(Class<?> targetType) { try { if (typeJudge(springMultiValueMapClass, targetType)) { return springMultiValueMapImplClass.getDeclaredConstructor().newInstance(); } else if (typeJudge(jaxrsMultiValueMapClass, targetType)) { return jaxrsMultiValueMapImplClass.getDeclaredConstructor().newInstance(); } } catch (Exception e) { logger.error( "", e.getMessage(), "current param type is: " + targetType + "and support type is : " + springMultiValueMapClass + "or" + jaxrsMultiValueMapClass, "dubbo rest form content-type param construct error,un support param type: ", e); } return null; } private static boolean typeJudge(Class<?> parent, Class<?> targetType) { if (parent == null) { return false; } if (!Map.class.isAssignableFrom(targetType)) { return true; } return parent.isAssignableFrom(targetType) || parent.equals(targetType); } public static void add(Object multiValueMap, String key, Object value) { try { if (multiValueMap == null) { return; } Method multiValueMapAdd = null; if (springMultiValueMapImplClass.equals(multiValueMap.getClass())) { multiValueMapAdd = springMultiValueMapAdd; } else if (jaxrsMultiValueMapImplClass.equals(multiValueMap.getClass())) { multiValueMapAdd = jaxrsMultiValueMapAdd; } ReflectUtils.invokeAndTryCatch(multiValueMap, multiValueMapAdd, new Object[] {key, value}); } catch (Exception e) { logger.error("", e.getMessage(), "", "dubbo rest form content-type param add data error: ", e); } } }
5,730
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/MediaTypeUtil.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.util; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.rpc.protocol.rest.exception.UnSupportContentTypeException; import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodecManager; import java.util.Arrays; import java.util.List; public class MediaTypeUtil { private static final List<MediaType> mediaTypes = MediaType.getSupportMediaTypes(); /** * return first match , if any multiple content-type ,acquire mediaType by targetClass type .if contentTypes is empty * * @param contentTypes * @return */ public static MediaType convertMediaType(Class<?> targetType, String... contentTypes) { if (contentTypes == null || contentTypes.length == 0) { return HttpMessageCodecManager.typeSupport(targetType); } for (String contentType : contentTypes) { for (MediaType mediaType : mediaTypes) { if (contentType != null && contentType.contains(mediaType.value)) { return mediaType; } } if (contentType != null && contentType.contains(MediaType.ALL_VALUE.value)) { return HttpMessageCodecManager.typeSupport(targetType); } } throw new UnSupportContentTypeException(Arrays.toString(contentTypes)); } }
5,731
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/HttpHeaderUtil.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.util; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.http.RequestTemplate; import org.apache.dubbo.remoting.http.RestResult; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; public class HttpHeaderUtil { /** * convert attachment to Map<String, List<String>> * * @param attachmentMap * @return */ public static Map<String, List<String>> createAttachments(Map<String, Object> attachmentMap) { Map<String, List<String>> attachments = new HashMap<>(); int size = 0; for (Map.Entry<String, Object> entry : attachmentMap.entrySet()) { String key = entry.getKey(); String value = String.valueOf(entry.getValue()); if (value != null) { size += value.getBytes(StandardCharsets.UTF_8).length; } List<String> strings = attachments.get(key); if (strings == null) { strings = new ArrayList<>(); attachments.put(key, strings); } strings.add(value); } return attachments; } /** * add consumer attachment to request * * @param requestTemplate * @param attachmentMap */ public static void addRequestAttachments(RequestTemplate requestTemplate, Map<String, Object> attachmentMap) { Map<String, List<String>> attachments = createAttachments(attachmentMap); attachments.entrySet().forEach(attachment -> { requestTemplate.addHeaders(appendPrefixToAttachRealHeader(attachment.getKey()), attachment.getValue()); }); } /** * add provider attachment to response * * @param nettyHttpResponse */ public static void addResponseAttachments(NettyHttpResponse nettyHttpResponse) { Map<String, List<String>> attachments = createAttachments(RpcContext.getServerContext().getObjectAttachments()); attachments.entrySet().stream().forEach(attachment -> { nettyHttpResponse .getOutputHeaders() .put(appendPrefixToAttachRealHeader(attachment.getKey()), attachment.getValue()); }); } /** * parse rest request header attachment & header * * @param rpcInvocation * @param requestFacade */ public static void parseRequestHeader(RpcInvocation rpcInvocation, RequestFacade requestFacade) { Enumeration<String> headerNames = requestFacade.getHeaderNames(); while (headerNames.hasMoreElements()) { String header = headerNames.nextElement(); if (!isRestAttachHeader(header)) { // attribute rpcInvocation.put(header, requestFacade.getHeader(header)); continue; } // attachment rpcInvocation.setAttachment(subRestAttachRealHeaderPrefix(header.trim()), requestFacade.getHeader(header)); } } /** * for judge rest header or rest attachment * * @param header * @return */ public static boolean isRestAttachHeader(String header) { if (StringUtils.isEmpty(header) || !header.startsWith(RestHeaderEnum.REST_HEADER_PREFIX.getHeader())) { return false; } return true; } /** * for substring attachment prefix * * @param header * @return */ public static String subRestAttachRealHeaderPrefix(String header) { return header.substring(RestHeaderEnum.REST_HEADER_PREFIX.getHeader().length()); } /** * append prefix to rest header distinguish from normal header * * @param header * @return */ public static String appendPrefixToAttachRealHeader(String header) { return RestHeaderEnum.REST_HEADER_PREFIX.getHeader() + header; } /** * parse request attribute * @param rpcInvocation * @param request */ public static void parseRequestAttribute(RpcInvocation rpcInvocation, RequestFacade request) { int localPort = request.getLocalPort(); String localAddr = request.getLocalAddr(); int remotePort = request.getRemotePort(); String remoteAddr = request.getRemoteAddr(); rpcInvocation.put(RestConstant.REMOTE_ADDR, remoteAddr); rpcInvocation.put(RestConstant.LOCAL_ADDR, localAddr); rpcInvocation.put(RestConstant.REMOTE_PORT, remotePort); rpcInvocation.put(RestConstant.LOCAL_PORT, localPort); } /** * parse request * @param rpcInvocation * @param request */ public static void parseRequest(RpcInvocation rpcInvocation, RequestFacade request) { parseRequestHeader(rpcInvocation, request); parseRequestAttribute(rpcInvocation, request); } /** * parse rest response header to appResponse attribute & attachment * @param appResponse * @param restResult */ public static void parseResponseHeader(AppResponse appResponse, RestResult restResult) { Map<String, List<String>> headers = restResult.headers(); if (headers == null || headers.isEmpty()) { return; } headers.entrySet().stream().forEach(entry -> { String header = entry.getKey(); if (isRestAttachHeader(header)) { // attachment appResponse.setAttachment(subRestAttachRealHeaderPrefix(header), entry.getValue()); } else { // attribute appResponse.setAttribute(header, entry.getValue()); } }); } }
5,732
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/ReflectUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.util; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ReflectUtils { public static Class findClass(String name, ClassLoader classLoader) throws ClassNotFoundException { return classLoader.loadClass(name); } public static Class findClass(String name) throws ClassNotFoundException { return findClass(Thread.currentThread().getContextClassLoader(), name); } public static Class findClassAndTryCatch(String name, ClassLoader classLoader) { try { return findClass(name, classLoader); } catch (Throwable e) { } return null; } public static Class findClass(ClassLoader classLoader, String... name) throws ClassNotFoundException { String[] names = name; Class tmp; for (String s : names) { tmp = findClassAndTryCatch(s, classLoader); if (tmp == null) { continue; } else { return tmp; } } throw new ClassNotFoundException(); } public static Class findClassTryException(ClassLoader classLoader, String... name) { try { return findClass(classLoader, name); } catch (Exception e) { } return null; } public static List<Method> getMethodByNameList(Class clazz, String name) { return getMethodByNameList(clazz, name, false); } public static List<Method> getMethodByNameList(Class clazz, String name, boolean declare) { // prevent duplicate method Set<Method> methods = new HashSet<>(); try { filterMethod(name, methods, clazz.getDeclaredMethods()); } catch (Exception e) { } if (!declare) { return new ArrayList<>(methods); } try { filterMethod(name, methods, clazz.getMethods()); } catch (Exception e) { } return new ArrayList<>(methods); } public static List<Constructor<?>> getConstructList(Class clazz) { // prevent duplicate method Set<Constructor<?>> methods = new HashSet<>(); try { filterConstructMethod(methods, clazz.getDeclaredConstructors()); } catch (Exception e) { } try { filterConstructMethod(methods, clazz.getConstructors()); } catch (Exception e) { } return new ArrayList<Constructor<?>>(methods); } private static void filterConstructMethod(Set<Constructor<?>> methods, Constructor<?>[] declaredMethods) { for (Constructor<?> constructor : declaredMethods) { methods.add(constructor); } } private static void filterMethod(String name, Set<Method> methodList, Method[] methods) { for (Method declaredMethod : methods) { if (!name.equals(declaredMethod.getName())) { continue; } declaredMethod.setAccessible(true); methodList.add(declaredMethod); } } public static Method getMethodByName(Class clazz, String name) { List<Method> methodByNameList = getMethodByNameList(clazz, name, true); if (methodByNameList.isEmpty()) { return null; } else { return methodByNameList.get(0); } } public static Class findClassTryException(String... name) { return findClassTryException(Thread.currentThread().getContextClassLoader(), name); } public static Object invoke(Object object, Method method, Object[] params) throws InvocationTargetException, IllegalAccessException { return method.invoke(object, params); } public static Object invokeAndTryCatch(Object object, Method method, Object[] params) { try { return invoke(object, method, params); } catch (Exception e) { } return null; } }
5,733
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/ConstraintViolationExceptionConvert.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.util; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.protocol.rest.RestConstraintViolation; import org.apache.dubbo.rpc.protocol.rest.ViolationReport; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; public class ConstraintViolationExceptionConvert { public static Object handleConstraintViolationException(RpcException rpcException) { ConstraintViolationException cve = (ConstraintViolationException) rpcException.getCause(); ViolationReport report = new ViolationReport(); for (ConstraintViolation<?> cv : cve.getConstraintViolations()) { report.addConstraintViolation(new RestConstraintViolation( cv.getPropertyPath().toString(), cv.getMessage(), cv.getInvalidValue() == null ? "null" : cv.getInvalidValue().toString())); } return report; } public static boolean needConvert(RpcException e) { return isConstraintViolationException(e); } private static boolean isConstraintViolationException(RpcException e) { try { return e.getCause() instanceof ConstraintViolationException; } catch (Throwable throwable) { return false; } } }
5,734
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/deploy/ServiceDeployer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.deploy; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.metadata.rest.PathMatcher; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.protocol.rest.Constants; import org.apache.dubbo.rpc.protocol.rest.PathAndInvokerMapper; import org.apache.dubbo.rpc.protocol.rest.RpcExceptionMapper; import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionMapper; import org.apache.dubbo.rpc.protocol.rest.exception.mapper.RestEasyExceptionMapper; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; public class ServiceDeployer { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final PathAndInvokerMapper pathAndInvokerMapper = new PathAndInvokerMapper(); private final ExceptionMapper exceptionMapper = createExceptionMapper(); private final Set<Object> extensions = new HashSet<>(); public void deploy(ServiceRestMetadata serviceRestMetadata, Invoker invoker) { Map<PathMatcher, RestMethodMetadata> pathToServiceMapContainPathVariable = serviceRestMetadata.getPathContainPathVariableToServiceMap(); pathAndInvokerMapper.addPathAndInvoker(pathToServiceMapContainPathVariable, invoker); Map<PathMatcher, RestMethodMetadata> pathToServiceMapUnContainPathVariable = serviceRestMetadata.getPathUnContainPathVariableToServiceMap(); pathAndInvokerMapper.addPathAndInvoker(pathToServiceMapUnContainPathVariable, invoker); } public void undeploy(ServiceRestMetadata serviceRestMetadata) { Map<PathMatcher, RestMethodMetadata> pathToServiceMapContainPathVariable = serviceRestMetadata.getPathContainPathVariableToServiceMap(); pathToServiceMapContainPathVariable.keySet().stream().forEach(pathAndInvokerMapper::removePath); Map<PathMatcher, RestMethodMetadata> pathToServiceMapUnContainPathVariable = serviceRestMetadata.getPathUnContainPathVariableToServiceMap(); pathToServiceMapUnContainPathVariable.keySet().stream().forEach(pathAndInvokerMapper::removePath); } public void registerExtension(URL url) { for (String clazz : COMMA_SPLIT_PATTERN.split( url.getParameter(Constants.EXTENSION_KEY, RpcExceptionMapper.class.getName()))) { if (StringUtils.isEmpty(clazz)) { continue; } try { Class<?> aClass = ClassUtils.forName(clazz); // exception handler if (ExceptionMapper.isSupport(aClass)) { exceptionMapper.registerMapper(clazz); } else { extensions.add(aClass.newInstance()); } } catch (Exception e) { logger.warn("", "", "dubbo rest registerExtension error: ", e.getMessage(), e); } } } public PathAndInvokerMapper getPathAndInvokerMapper() { return pathAndInvokerMapper; } public ExceptionMapper getExceptionMapper() { return exceptionMapper; } public Set<Object> getExtensions() { return extensions; } /** * get extensions by type * * @param extensionClass * @param <T> * @return */ // TODO add javax.annotation.Priority sort public <T> List<T> getExtensions(Class<T> extensionClass) { ArrayList<T> exts = new ArrayList<>(); if (extensions.isEmpty()) { return exts; } for (Object extension : extensions) { if (extensionClass.isAssignableFrom(extension.getClass())) { exts.add((T) extension); } } return exts; } private ExceptionMapper createExceptionMapper() { if (ClassUtils.isPresent( "javax.ws.rs.ext.ExceptionMapper", Thread.currentThread().getContextClassLoader())) { return new RestEasyExceptionMapper(); } return new ExceptionMapper(); } public boolean isMethodAllowed(PathMatcher pathMatcher) { return pathAndInvokerMapper.isHttpMethodAllowed(pathMatcher); } public boolean hashRestMethod(PathMatcher pathMatcher) { return pathAndInvokerMapper.getRestMethodMetadata(pathMatcher) != null; } public String pathHttpMethods(PathMatcher pathMatcher) { return pathAndInvokerMapper.pathHttpMethods(pathMatcher); } }
5,735
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResource.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.integration.swagger; import org.apache.dubbo.config.annotation.Service; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.ws.rs.core.Application; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import com.fasterxml.jackson.core.JsonProcessingException; import io.swagger.jaxrs.listing.BaseApiListingResource; @Service public class DubboSwaggerApiListingResource extends BaseApiListingResource implements DubboSwaggerService { @Context ServletContext context; @Override public Response getListingJson(Application app, ServletConfig sc, HttpHeaders headers, UriInfo uriInfo) throws JsonProcessingException { Response response = getListingJsonResponse(app, context, sc, headers, uriInfo); response.getHeaders().add("Access-Control-Allow-Origin", "*"); response.getHeaders().add("Access-Control-Allow-Headers", "x-requested-with, ssi-token"); response.getHeaders().add("Access-Control-Max-Age", "3600"); response.getHeaders().add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); return response; } }
5,736
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.integration.swagger; import javax.servlet.ServletConfig; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Application; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import com.fasterxml.jackson.core.JsonProcessingException; @Path("dubbo") @Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) @Produces({MediaType.APPLICATION_JSON + "; " + "charset=UTF-8", MediaType.TEXT_XML + "; " + "charset=UTF-8"}) public interface DubboSwaggerService { @GET @Path("swagger") Response getListingJson( @Context Application app, @Context ServletConfig sc, @Context HttpHeaders headers, @Context UriInfo uriInfo) throws JsonProcessingException; }
5,737
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/ParamParserManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.BaseConsumerParamParser; import org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.ConsumerParseContext; import org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.BaseProviderParamParser; import org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.ProviderParseContext; import java.util.List; import java.util.Set; public class ParamParserManager { private static final Set<BaseConsumerParamParser> consumerParamParsers = FrameworkModel.defaultModel() .getExtensionLoader(BaseConsumerParamParser.class) .getSupportedExtensionInstances(); private static final Set<BaseProviderParamParser> providerParamParsers = FrameworkModel.defaultModel() .getExtensionLoader(BaseProviderParamParser.class) .getSupportedExtensionInstances(); /** * provider Design Description: * <p> * Object[] args=new Object[0]; * List<Object> argsList=new ArrayList<>;</> * <p> * setValueByIndex(int index,Object value); * <p> * args=toArray(new Object[0]); */ public static Object[] providerParamParse(ProviderParseContext parseContext) { List<ArgInfo> args = parseContext.getArgInfos(); for (int i = 0; i < args.size(); i++) { for (ParamParser paramParser : providerParamParsers) { paramParser.parse(parseContext, args.get(i)); } } // TODO add param require or default & body arg size pre judge return parseContext.getArgs().toArray(new Object[0]); } /** * consumer Design Description: * <p> * Object[] args=new Object[0]; * List<Object> argsList=new ArrayList<>;</> * <p> * setValueByIndex(int index,Object value); * <p> * args=toArray(new Object[0]); */ public static void consumerParamParse(ConsumerParseContext parseContext) { List<ArgInfo> argInfos = parseContext.getArgInfos(); for (int i = 0; i < argInfos.size(); i++) { for (BaseConsumerParamParser paramParser : consumerParamParsers) { ArgInfo argInfoByIndex = parseContext.getArgInfoByIndex(i); if (!paramParser.paramTypeMatch(argInfoByIndex)) { continue; } paramParser.parse(parseContext, argInfoByIndex); } } // TODO add param require or default } }
5,738
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/BaseParseContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation; import org.apache.dubbo.metadata.rest.ArgInfo; import java.util.List; public class BaseParseContext { protected List<Object> args; protected List<ArgInfo> argInfos; public List<Object> getArgs() { return args; } public void setArgs(List<Object> args) { this.args = args; } public List<ArgInfo> getArgInfos() { return argInfos; } public void setArgInfos(List<ArgInfo> argInfos) { this.argInfos = argInfos; } public ArgInfo getArgInfoByIndex(int index) { return getArgInfos().get(index); } }
5,739
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/ParamParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation; import org.apache.dubbo.metadata.rest.ArgInfo; public interface ParamParser<T> { void parse(T parseContext, ArgInfo argInfo); }
5,740
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ProviderParseContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; import org.apache.dubbo.rpc.protocol.rest.annotation.BaseParseContext; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; public class ProviderParseContext extends BaseParseContext { private RequestFacade requestFacade; private Object response; private Object request; public ProviderParseContext(RequestFacade request) { this.requestFacade = request; } public RequestFacade getRequestFacade() { return requestFacade; } public void setValueByIndex(int index, Object value) { this.args.set(index, value); } public Object getResponse() { return response; } public void setResponse(Object response) { this.response = response; } public Object getRequest() { return request; } public void setRequest(Object request) { this.request = request; } public String getPathVariable(int urlSplitIndex) { String[] split = getRequestFacade().getRequestURI().split("/"); return split[urlSplitIndex]; } }
5,741
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/HeaderProviderParamParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.metadata.rest.ParamType; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.Map; /** * header param parse */ @Activate(value = RestConstant.PROVIDER_HEADER_PARSE) public class HeaderProviderParamParser extends ProviderParamParser { @Override protected void doParse(ProviderParseContext parseContext, ArgInfo argInfo) { // TODO MAP<String,String> convert RequestFacade request = parseContext.getRequestFacade(); if (Map.class.isAssignableFrom(argInfo.getParamType())) { Map<String, String> headerMap = new LinkedHashMap<>(); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); headerMap.put(name, request.getHeader(name)); } parseContext.setValueByIndex(argInfo.getIndex(), headerMap); return; } String header = request.getHeader(argInfo.getAnnotationNameAttribute()); Object headerValue = paramTypeConvert(argInfo.getParamType(), header); parseContext.setValueByIndex(argInfo.getIndex(), headerValue); } @Override protected ParamType getParamType() { return ParamType.HEADER; } }
5,742
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/PathProviderParamParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.metadata.rest.ParamType; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; /** * path param parse */ @Activate(value = RestConstant.PROVIDER_PATH_PARSE) public class PathProviderParamParser extends ProviderParamParser { @Override protected void doParse(ProviderParseContext parseContext, ArgInfo argInfo) { String pathVariable = parseContext.getPathVariable(argInfo.getUrlSplitIndex()); Object pathVariableValue = paramTypeConvert(argInfo.getParamType(), pathVariable); parseContext.setValueByIndex(argInfo.getIndex(), pathVariableValue); } @Override protected ParamType getParamType() { return ParamType.PATH; } }
5,743
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/BodyProviderParamParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.metadata.rest.ParamType; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; import org.apache.dubbo.rpc.protocol.rest.exception.ParamParseException; import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodecManager; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil; /** * body param parse */ @Activate(value = RestConstant.PROVIDER_BODY_PARSE) public class BodyProviderParamParser extends ProviderParamParser { @Override protected void doParse(ProviderParseContext parseContext, ArgInfo argInfo) { RequestFacade request = parseContext.getRequestFacade(); try { String contentType = parseContext.getRequestFacade().getHeader(RestHeaderEnum.CONTENT_TYPE.getHeader()); MediaType mediaType = MediaTypeUtil.convertMediaType(argInfo.getParamType(), contentType); Object param = HttpMessageCodecManager.httpMessageDecode( request.getInputStream(), argInfo.getParamType(), argInfo.actualReflectType(), mediaType); parseContext.setValueByIndex(argInfo.getIndex(), param); } catch (Throwable e) { throw new ParamParseException("dubbo rest protocol provider body param parser error: " + e.getMessage()); } } @Override protected ParamType getParamType() { return ParamType.PROVIDER_BODY; } }
5,744
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ProviderParamParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.metadata.rest.ParamType; import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; public abstract class ProviderParamParser implements BaseProviderParamParser { public void parse(ProviderParseContext parseContext, ArgInfo argInfo) { if (!matchParseType(argInfo.getParamAnnotationType())) { return; } doParse(parseContext, argInfo); } protected abstract void doParse(ProviderParseContext parseContext, ArgInfo argInfo); public boolean matchParseType(Class paramAnno) { ParamType paramAnnotType = getParamType(); return paramAnnotType.supportAnno(paramAnno); } protected abstract ParamType getParamType(); protected Object paramTypeConvert(Class targetType, String value) { return DataParseUtils.stringTypeConvert(targetType, value); } }
5,745
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ParamProviderParamParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.metadata.rest.ParamType; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.Map; /** * Http Parameter param parse */ @Activate(value = RestConstant.PROVIDER_PARAM_PARSE) public class ParamProviderParamParser extends ProviderParamParser { @Override protected void doParse(ProviderParseContext parseContext, ArgInfo argInfo) { // TODO MAP<String,String> convert RequestFacade request = parseContext.getRequestFacade(); if (Map.class.isAssignableFrom(argInfo.getParamType())) { Map<String, String> paramMap = new LinkedHashMap<>(); Enumeration<String> parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { String name = parameterNames.nextElement(); paramMap.put(name, request.getParameter(name)); } parseContext.setValueByIndex(argInfo.getIndex(), paramMap); return; } String param = request.getParameter(argInfo.getAnnotationNameAttribute()); Object paramValue = paramTypeConvert(argInfo.getParamType(), param); parseContext.setValueByIndex(argInfo.getIndex(), paramValue); } @Override protected ParamType getParamType() { return ParamType.PARAM; } }
5,746
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/BaseProviderParamParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.rpc.protocol.rest.annotation.ParamParser; @SPI(scope = ExtensionScope.FRAMEWORK) public interface BaseProviderParamParser extends ParamParser<ProviderParseContext> {}
5,747
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/ConsumerParseContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer; import org.apache.dubbo.remoting.http.RequestTemplate; import org.apache.dubbo.rpc.protocol.rest.annotation.BaseParseContext; public class ConsumerParseContext extends BaseParseContext { private RequestTemplate requestTemplate; public ConsumerParseContext(RequestTemplate requestTemplate) { this.requestTemplate = requestTemplate; } public RequestTemplate getRequestTemplate() { return requestTemplate; } }
5,748
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/HeaderConsumerParamParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.metadata.rest.ParamType; import org.apache.dubbo.remoting.http.RequestTemplate; import java.util.List; import java.util.Map; @Activate("consumer-header") public class HeaderConsumerParamParser implements BaseConsumerParamParser { @Override public void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { List<Object> args = parseContext.getArgs(); RequestTemplate requestTemplate = parseContext.getRequestTemplate(); Object headerValue = args.get(argInfo.getIndex()); if (headerValue == null) { return; } // Map<String,String> if (Map.class.isAssignableFrom(argInfo.getParamType())) { Map headerValues = (Map) headerValue; for (Object name : headerValues.keySet()) { requestTemplate.addHeader(String.valueOf(name), headerValues.get(name)); } } else { // others requestTemplate.addHeader(argInfo.getAnnotationNameAttribute(), headerValue); } } @Override public boolean paramTypeMatch(ArgInfo argInfo) { return ParamType.HEADER.supportAnno(argInfo.getParamAnnotationType()); } }
5,749
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/BodyConsumerParamParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.metadata.rest.ParamType; import org.apache.dubbo.remoting.http.RequestTemplate; import java.util.List; @Activate("consumer-body") public class BodyConsumerParamParser implements BaseConsumerParamParser { @Override public void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { List<Object> args = parseContext.getArgs(); RequestTemplate requestTemplate = parseContext.getRequestTemplate(); requestTemplate.body(args.get(argInfo.getIndex()), argInfo.getParamType()); } @Override public boolean paramTypeMatch(ArgInfo argInfo) { return ParamType.BODY.supportAnno(argInfo.getParamAnnotationType()); } }
5,750
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/ParameterConsumerParamParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.metadata.rest.ParamType; import org.apache.dubbo.remoting.http.RequestTemplate; import java.util.List; import java.util.Map; @Activate("consumer-parameter") public class ParameterConsumerParamParser implements BaseConsumerParamParser { @Override public void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { List<Object> args = parseContext.getArgs(); RequestTemplate requestTemplate = parseContext.getRequestTemplate(); Object paramValue = args.get(argInfo.getIndex()); if (paramValue == null) { return; } if (Map.class.isAssignableFrom(argInfo.getParamType())) { Map paramValues = (Map) paramValue; for (Object name : paramValues.keySet()) { requestTemplate.addParam(String.valueOf(name), paramValues.get(name)); } } else { requestTemplate.addParam(argInfo.getAnnotationNameAttribute(), paramValue); } } @Override public boolean paramTypeMatch(ArgInfo argInfo) { return ParamType.PARAM.supportAnno(argInfo.getParamAnnotationType()); } }
5,751
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/FormConsumerParamParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.metadata.rest.ParamType; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.remoting.http.RequestTemplate; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; @Activate("consumer-form") public class FormConsumerParamParser implements BaseConsumerParamParser { @Override public void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { List<Object> args = parseContext.getArgs(); RequestTemplate requestTemplate = parseContext.getRequestTemplate(); Object value = args.get(argInfo.getIndex()); if (value == null) { return; } Map<String, List<String>> tmp = new HashMap<>(); if (DataParseUtils.isTextType(value.getClass())) { tmp.put(argInfo.getAnnotationNameAttribute(), Arrays.asList(String.valueOf(value))); requestTemplate.body(tmp, Map.class); } else if (value instanceof Map) { requestTemplate.body(value, Map.class); } else { Set<String> allFieldNames = ReflectUtils.getAllFieldNames(value.getClass()); allFieldNames.stream().forEach(entry -> { Object fieldValue = ReflectUtils.getFieldValue(value, entry); tmp.put(String.valueOf(entry), Arrays.asList(String.valueOf(fieldValue))); }); requestTemplate.body(tmp, Map.class); } Collection<String> headers = requestTemplate.getHeaders(RestConstant.CONTENT_TYPE); if (CollectionUtils.isEmpty(headers)) { requestTemplate.addHeader(RestConstant.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE.value); } } @Override public boolean paramTypeMatch(ArgInfo argInfo) { return ParamType.FORM.supportAnno(argInfo.getParamAnnotationType()); } }
5,752
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/BaseConsumerParamParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.rpc.protocol.rest.annotation.ParamParser; @SPI(scope = ExtensionScope.FRAMEWORK) public interface BaseConsumerParamParser extends ParamParser<ConsumerParseContext> { boolean paramTypeMatch(ArgInfo argInfo); }
5,753
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/HttpConnectionCreateContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.consumer; import org.apache.dubbo.common.URL; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import org.apache.dubbo.remoting.http.RequestTemplate; import org.apache.dubbo.rpc.Invocation; public class HttpConnectionCreateContext { private RequestTemplate requestTemplate; private RestMethodMetadata restMethodMetadata; private ServiceRestMetadata serviceRestMetadata; private Invocation invocation; private URL url; public HttpConnectionCreateContext() {} public void setRequestTemplate(RequestTemplate requestTemplate) { this.requestTemplate = requestTemplate; } public RequestTemplate getRequestTemplate() { return requestTemplate; } public ServiceRestMetadata getServiceRestMetadata() { return serviceRestMetadata; } public RestMethodMetadata getRestMethodMetadata() { return restMethodMetadata; } public void setRestMethodMetadata(RestMethodMetadata restMethodMetadata) { this.restMethodMetadata = restMethodMetadata; } public Invocation getInvocation() { return invocation; } public void setInvocation(Invocation invocation) { this.invocation = invocation; } public URL getUrl() { return url; } public void setUrl(URL url) { this.url = url; } public void setServiceRestMetadata(ServiceRestMetadata serviceRestMetadata) { this.serviceRestMetadata = serviceRestMetadata; } }
5,754
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/HttpConnectionPreBuildIntercept.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.consumer; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; /** * http request build intercept */ @SPI(scope = ExtensionScope.FRAMEWORK) public interface HttpConnectionPreBuildIntercept { void intercept(HttpConnectionCreateContext connectionCreateContext); }
5,755
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/SerializeBodyIntercept.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.remoting.http.RequestTemplate; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionCreateContext; import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodecManager; import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil; import java.io.ByteArrayOutputStream; import java.util.Collection; /** * for request body Serialize */ @Activate(value = RestConstant.SERIALIZE_INTERCEPT, order = Integer.MAX_VALUE) public class SerializeBodyIntercept implements HttpConnectionPreBuildIntercept { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SerializeBodyIntercept.class); @Override public void intercept(HttpConnectionCreateContext connectionCreateContext) { RequestTemplate requestTemplate = connectionCreateContext.getRequestTemplate(); if (requestTemplate.isBodyEmpty()) { return; } try { Object unSerializedBody = requestTemplate.getUnSerializedBody(); URL url = connectionCreateContext.getUrl(); // TODO pool ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Collection<String> headers = requestTemplate.getHeaders(RestConstant.CONTENT_TYPE); MediaType mediaType = MediaTypeUtil.convertMediaType(requestTemplate.getBodyType(), headers.toArray(new String[0])); // add mediaType by targetClass serialize if (mediaType != null && !mediaType.equals(MediaType.ALL_VALUE)) { headers.clear(); headers.add(mediaType.value); } HttpMessageCodecManager.httpMessageEncode( outputStream, unSerializedBody, url, mediaType, requestTemplate.getBodyType()); requestTemplate.serializeBody(outputStream.toByteArray()); outputStream.close(); } catch (Exception e) { logger.error( LoggerCodeConstants.PROTOCOL_ERROR_DESERIALIZE, "", "", "Rest SerializeBodyIntercept serialize error: {}", e); throw new RpcException(e); } } }
5,756
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/AttachmentIntercept.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http.RequestTemplate; import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionCreateContext; import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; import org.apache.dubbo.rpc.protocol.rest.util.HttpHeaderUtil; /** * add client rpc context to request geader */ @Activate(value = RestConstant.RPCCONTEXT_INTERCEPT, order = 3) public class AttachmentIntercept implements HttpConnectionPreBuildIntercept { @Override public void intercept(HttpConnectionCreateContext connectionCreateContext) { RequestTemplate requestTemplate = connectionCreateContext.getRequestTemplate(); HttpHeaderUtil.addRequestAttachments( requestTemplate, connectionCreateContext.getInvocation().getObjectAttachments()); } }
5,757
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/AddMustAttachmentIntercept.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import org.apache.dubbo.remoting.http.RequestTemplate; import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionCreateContext; import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; /** * add some must attachment */ @Activate(value = RestConstant.ADD_MUST_ATTTACHMENT, order = 1) public class AddMustAttachmentIntercept implements HttpConnectionPreBuildIntercept { @Override public void intercept(HttpConnectionCreateContext connectionCreateContext) { RequestTemplate requestTemplate = connectionCreateContext.getRequestTemplate(); ServiceRestMetadata serviceRestMetadata = connectionCreateContext.getServiceRestMetadata(); requestTemplate.addHeader(RestHeaderEnum.GROUP.getHeader(), serviceRestMetadata.getGroup()); requestTemplate.addHeader(RestHeaderEnum.VERSION.getHeader(), serviceRestMetadata.getVersion()); requestTemplate.addHeader(RestHeaderEnum.PATH.getHeader(), serviceRestMetadata.getServiceInterface()); requestTemplate.addHeader( RestHeaderEnum.TOKEN_KEY.getHeader(), connectionCreateContext.getUrl().getParameter(RestConstant.TOKEN_KEY)); } }
5,758
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/PathVariableIntercept.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.metadata.rest.PathUtil; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import org.apache.dubbo.remoting.http.RequestTemplate; import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionCreateContext; import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; import java.util.Arrays; import java.util.List; /** * resolve method args from path */ @Activate(value = RestConstant.PATH_INTERCEPT, order = 4) public class PathVariableIntercept implements HttpConnectionPreBuildIntercept { @Override public void intercept(HttpConnectionCreateContext connectionCreateContext) { RestMethodMetadata restMethodMetadata = connectionCreateContext.getRestMethodMetadata(); RequestTemplate requestTemplate = connectionCreateContext.getRequestTemplate(); List<ArgInfo> argInfos = restMethodMetadata.getArgInfos(); // path variable parse String path = PathUtil.resolvePathVariable( restMethodMetadata.getRequest().getPath(), argInfos, Arrays.asList(connectionCreateContext.getInvocation().getArguments())); requestTemplate.path(path); } }
5,759
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/RequestHeaderIntercept.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import org.apache.dubbo.remoting.http.RequestTemplate; import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionCreateContext; import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; import java.util.Collection; import java.util.Set; /** * resolve method args from header */ @Activate(value = RestConstant.REQUEST_HEADER_INTERCEPT, order = Integer.MAX_VALUE - 1) public class RequestHeaderIntercept implements HttpConnectionPreBuildIntercept { @Override public void intercept(HttpConnectionCreateContext connectionCreateContext) { RestMethodMetadata restMethodMetadata = connectionCreateContext.getRestMethodMetadata(); RequestTemplate requestTemplate = connectionCreateContext.getRequestTemplate(); Set<String> consumes = restMethodMetadata.getRequest().getConsumes(); requestTemplate.addHeaders(RestHeaderEnum.CONTENT_TYPE.getHeader(), consumes); Collection<String> produces = restMethodMetadata.getRequest().getProduces(); if (produces == null || produces.isEmpty()) { requestTemplate.addHeader(RestHeaderEnum.ACCEPT.getHeader(), RestConstant.DEFAULT_ACCEPT); } else { requestTemplate.addHeaders(RestHeaderEnum.ACCEPT.getHeader(), produces); } // URL url = connectionCreateContext.getUrl(); // // requestTemplate.addKeepAliveHeader(url.getParameter(RestConstant.KEEP_ALIVE_TIMEOUT_PARAM,RestConstant.KEEP_ALIVE_TIMEOUT)); } }
5,760
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/ParamParseIntercept.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.protocol.rest.annotation.ParamParserManager; import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionCreateContext; import org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept; import org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.ConsumerParseContext; import java.util.Arrays; /** * resolve method args by args info */ @Activate(value = "paramparse", order = 5) public class ParamParseIntercept implements HttpConnectionPreBuildIntercept { @Override public void intercept(HttpConnectionCreateContext connectionCreateContext) { ConsumerParseContext consumerParseContext = new ConsumerParseContext(connectionCreateContext.getRequestTemplate()); consumerParseContext.setArgInfos( connectionCreateContext.getRestMethodMetadata().getArgInfos()); consumerParseContext.setArgs( Arrays.asList(connectionCreateContext.getInvocation().getArguments())); ParamParserManager.consumerParamParse(consumerParseContext); } }
5,761
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/metadata/MetadataResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.annotation.metadata; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import org.apache.dubbo.metadata.rest.ServiceRestMetadataResolver; import org.apache.dubbo.rpc.protocol.rest.exception.CodeStyleNotSupportException; public class MetadataResolver { private MetadataResolver() {} /** * for consumer * * @param targetClass target service class * @param url consumer url * @return rest metadata * @throws CodeStyleNotSupportException not support type */ public static ServiceRestMetadata resolveConsumerServiceMetadata( Class<?> targetClass, URL url, String contextPathFromUrl) { ExtensionLoader<ServiceRestMetadataResolver> extensionLoader = url.getOrDefaultApplicationModel().getExtensionLoader(ServiceRestMetadataResolver.class); for (ServiceRestMetadataResolver serviceRestMetadataResolver : extensionLoader.getSupportedExtensionInstances()) { if (serviceRestMetadataResolver.supports(targetClass, true)) { ServiceRestMetadata serviceRestMetadata = new ServiceRestMetadata(url.getServiceInterface(), url.getVersion(), url.getGroup(), true); serviceRestMetadata.setContextPathFromUrl(contextPathFromUrl); ServiceRestMetadata resolve = serviceRestMetadataResolver.resolve(targetClass, serviceRestMetadata); return resolve; } } // TODO support Dubbo style service throw new CodeStyleNotSupportException("service is: " + targetClass + ", only support " + extensionLoader.getSupportedExtensions() + " annotation"); } public static ServiceRestMetadata resolveProviderServiceMetadata( Class serviceImpl, URL url, String contextPathFromUrl) { ExtensionLoader<ServiceRestMetadataResolver> extensionLoader = url.getOrDefaultApplicationModel().getExtensionLoader(ServiceRestMetadataResolver.class); for (ServiceRestMetadataResolver serviceRestMetadataResolver : extensionLoader.getSupportedExtensionInstances()) { boolean supports = serviceRestMetadataResolver.supports(serviceImpl); if (supports) { ServiceRestMetadata serviceRestMetadata = new ServiceRestMetadata(url.getServiceInterface(), url.getVersion(), url.getGroup(), false); serviceRestMetadata.setContextPathFromUrl(contextPathFromUrl); ServiceRestMetadata resolve = serviceRestMetadataResolver.resolve(serviceImpl, serviceRestMetadata); return resolve; } } throw new CodeStyleNotSupportException( "service is:" + serviceImpl + ",just support rest or spring-web annotation"); } }
5,762
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageEncode.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.message; import org.apache.dubbo.common.URL; public interface HttpMessageEncode<OutputStream> { void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception; }
5,763
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageDecode.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.message; import java.lang.reflect.Type; public interface HttpMessageDecode<InputStream> { Object decode(InputStream body, Class<?> targetType, Type actualTYpe) throws Exception; }
5,764
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.message; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.metadata.rest.media.MediaType; /** * for http body codec * @param <InputStream> * @param <OutputStream> */ @SPI(scope = ExtensionScope.FRAMEWORK) public interface HttpMessageCodec<InputStream, OutputStream> extends HttpMessageDecode<InputStream>, HttpMessageEncode<OutputStream> { /** * content-type support judge * @param mediaType * @param targetType * @return */ boolean contentTypeSupport(MediaType mediaType, Class<?> targetType); /** * class type support judge * @param targetType * @return */ boolean typeSupport(Class<?> targetType); MediaType contentType(); }
5,765
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/MediaTypeMatcher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.message; import org.apache.dubbo.metadata.rest.media.MediaType; import java.util.ArrayList; import java.util.List; public enum MediaTypeMatcher { MULTI_VALUE(createMediaList(MediaType.APPLICATION_FORM_URLENCODED_VALUE)), APPLICATION_JSON(createMediaList(MediaType.APPLICATION_JSON_VALUE)), TEXT_PLAIN(createMediaList(MediaType.TEXT_PLAIN, MediaType.OCTET_STREAM)), TEXT_XML(createMediaList(MediaType.TEXT_XML)), ; private List<MediaType> mediaTypes; MediaTypeMatcher(List<MediaType> mediaTypes) { this.mediaTypes = mediaTypes; } private static List<MediaType> createMediaList(MediaType... mediaTypes) { List<MediaType> mediaTypeList = getDefaultList(); for (MediaType mediaType : mediaTypes) { mediaTypeList.add(mediaType); } return mediaTypeList; } private static List<MediaType> getDefaultList() { List<MediaType> defaultList = new ArrayList<>(); return defaultList; } public boolean mediaSupport(MediaType mediaType) { return mediaTypes.contains(mediaType); } }
5,766
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageCodecManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.message; import org.apache.dubbo.common.URL; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.rest.exception.UnSupportContentTypeException; import org.apache.dubbo.rpc.protocol.rest.pair.MessageCodecResultPair; import java.io.OutputStream; import java.lang.reflect.Type; import java.util.Set; public class HttpMessageCodecManager { private static final Set<HttpMessageCodec> httpMessageCodecs = FrameworkModel.defaultModel() .getExtensionLoader(HttpMessageCodec.class) .getSupportedExtensionInstances(); public static Object httpMessageDecode(byte[] body, Class<?> type, Type actualType, MediaType mediaType) throws Exception { if (body == null || body.length == 0) { return null; } for (HttpMessageCodec httpMessageCodec : httpMessageCodecs) { if (httpMessageCodec.contentTypeSupport(mediaType, type) || typeJudge(mediaType, type, httpMessageCodec)) { return httpMessageCodec.decode(body, type, actualType); } } throw new UnSupportContentTypeException("UnSupport content-type :" + mediaType.value); } public static MessageCodecResultPair httpMessageEncode( OutputStream outputStream, Object unSerializedBody, URL url, MediaType mediaType, Class<?> bodyType) throws Exception { if (unSerializedBody == null) { for (HttpMessageCodec httpMessageCodec : httpMessageCodecs) { if (httpMessageCodec.contentTypeSupport(mediaType, bodyType) || typeJudge(mediaType, bodyType, httpMessageCodec)) { return MessageCodecResultPair.pair(false, httpMessageCodec.contentType()); } } } for (HttpMessageCodec httpMessageCodec : httpMessageCodecs) { if (httpMessageCodec.contentTypeSupport(mediaType, bodyType) || typeJudge(mediaType, bodyType, httpMessageCodec)) { httpMessageCodec.encode(outputStream, unSerializedBody, url); return MessageCodecResultPair.pair(true, httpMessageCodec.contentType()); } } throw new UnSupportContentTypeException("UnSupport content-type :" + mediaType.value); } /** * if content-type is null or all ,will judge media type by class type * * @param mediaType * @param bodyType * @param httpMessageCodec * @return */ private static boolean typeJudge(MediaType mediaType, Class<?> bodyType, HttpMessageCodec httpMessageCodec) { return (MediaType.ALL_VALUE.equals(mediaType) || mediaType == null) && bodyType != null && httpMessageCodec.typeSupport(bodyType); } public static MediaType typeSupport(Class<?> type) { for (HttpMessageCodec httpMessageCodec : httpMessageCodecs) { if (httpMessageCodec.typeSupport(type)) { return httpMessageCodec.contentType(); } } return null; } }
5,767
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/ByteArrayCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.message.codec; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec; import java.io.OutputStream; import java.lang.reflect.Type; /** * body type is byte array */ @Activate("byteArray") public class ByteArrayCodec implements HttpMessageCodec<byte[], OutputStream> { @Override public Object decode(byte[] body, Class<?> targetType, Type type) throws Exception { return body; } @Override public boolean contentTypeSupport(MediaType mediaType, Class<?> targetType) { return byte[].class.equals(targetType); } @Override public boolean typeSupport(Class<?> targetType) { return byte[].class.equals(targetType); } @Override public MediaType contentType() { return MediaType.OCTET_STREAM; } @Override public void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception { outputStream.write((byte[]) unSerializedBody); } }
5,768
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/JsonCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.message.codec; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec; import org.apache.dubbo.rpc.protocol.rest.message.MediaTypeMatcher; import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; import java.io.OutputStream; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.util.HashSet; import java.util.Set; /** * body is json */ @Activate("json") public class JsonCodec implements HttpMessageCodec<byte[], OutputStream> { private static final Set<Class> unSupportClasses = new HashSet<>(); static { unSupportClasses.add(byte[].class); unSupportClasses.add(String.class); } public static void addUnSupportClass(Class<?> unSupportClass) { unSupportClasses.add(unSupportClass); } @Override public Object decode(byte[] body, Class<?> targetType, Type actualType) throws Exception { return DataParseUtils.jsonConvert(actualType, body); } @Override public boolean contentTypeSupport(MediaType mediaType, Class<?> targetType) { return MediaTypeMatcher.APPLICATION_JSON.mediaSupport(mediaType) && !unSupportClasses.contains(targetType); } @Override public boolean typeSupport(Class<?> targetType) { return !unSupportClasses.contains(targetType) && !DataParseUtils.isTextType(targetType); } @Override public MediaType contentType() { return MediaType.APPLICATION_JSON_VALUE; } @Override public void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception { outputStream.write(JsonUtils.toJson(unSerializedBody).getBytes(StandardCharsets.UTF_8)); } }
5,769
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/TextCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.message.codec; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec; import org.apache.dubbo.rpc.protocol.rest.message.MediaTypeMatcher; import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; import java.io.OutputStream; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; /** * content-type is text/html */ @Activate("text") public class TextCodec implements HttpMessageCodec<byte[], OutputStream> { @Override public Object decode(byte[] body, Class<?> targetType, Type type) throws Exception { return DataParseUtils.stringTypeConvert(targetType, new String(body, StandardCharsets.UTF_8)); } @Override public boolean contentTypeSupport(MediaType mediaType, Class<?> targetType) { return MediaTypeMatcher.TEXT_PLAIN.mediaSupport(mediaType); } @Override public boolean typeSupport(Class<?> targetType) { return DataParseUtils.isTextType(targetType); } @Override public MediaType contentType() { return MediaType.TEXT_PLAIN; } @Override public void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception { DataParseUtils.writeTextContent(unSerializedBody, outputStream); } }
5,770
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/MultiValueCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.message.codec; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec; import org.apache.dubbo.rpc.protocol.rest.message.MediaTypeMatcher; import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; import java.io.OutputStream; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; /** * body is form */ @Activate("multiValue") public class MultiValueCodec implements HttpMessageCodec<byte[], OutputStream> { @Override public Object decode(byte[] body, Class<?> targetType, Type type) throws Exception { Object map = DataParseUtils.multipartFormConvert(body, targetType); Map valuesMap = (Map) map; if (Map.class.isAssignableFrom(targetType)) { return map; } else if (DataParseUtils.isTextType(targetType)) { // only fetch first Set set = valuesMap.keySet(); ArrayList arrayList = new ArrayList<>(set); Object key = arrayList.get(0); Object value = valuesMap.get(key); if (value == null) { return null; } return DataParseUtils.stringTypeConvert(targetType, String.valueOf(((List) value).get(0))); } else { Map<String, Field> beanPropertyFields = ReflectUtils.getBeanPropertyFields(targetType); Object emptyObject = ReflectUtils.getEmptyObject(targetType); beanPropertyFields.entrySet().stream().forEach(entry -> { try { List values = (List) valuesMap.get(entry.getKey()); String value = values == null ? null : String.valueOf(values.get(0)); entry.getValue() .set( emptyObject, DataParseUtils.stringTypeConvert( entry.getValue().getType(), value)); } catch (IllegalAccessException e) { } }); return emptyObject; } } @Override public boolean contentTypeSupport(MediaType mediaType, Class<?> targetType) { return MediaTypeMatcher.MULTI_VALUE.mediaSupport(mediaType); } @Override public boolean typeSupport(Class<?> targetType) { return false; } @Override public MediaType contentType() { return MediaType.APPLICATION_FORM_URLENCODED_VALUE; } @Override public void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception { DataParseUtils.writeFormContent((Map) unSerializedBody, outputStream); } }
5,771
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/StringCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.message.codec; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec; import java.io.OutputStream; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; /** * body is string */ @Activate("string") public class StringCodec implements HttpMessageCodec<byte[], OutputStream> { @Override public Object decode(byte[] body, Class<?> targetType, Type type) throws Exception { if (body == null || body.length == 0) { return null; } return new String(body); } @Override public boolean contentTypeSupport(MediaType mediaType, Class<?> targetType) { return String.class.equals(targetType); } @Override public boolean typeSupport(Class<?> targetType) { return String.class.equals(targetType); } @Override public MediaType contentType() { return MediaType.TEXT_PLAIN; } @Override public void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception { outputStream.write(((String) unSerializedBody).getBytes(StandardCharsets.UTF_8)); } }
5,772
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/ResteasyResponseCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.message.codec; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec; import java.io.OutputStream; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; @Activate(onClass = "javax.ws.rs.core.Response") public class ResteasyResponseCodec implements HttpMessageCodec<byte[], OutputStream> { private Class<?> responseClass; public ResteasyResponseCodec() { try { responseClass = ClassUtils.forName("javax.ws.rs.core.Response"); JsonCodec.addUnSupportClass(responseClass); } catch (Exception exception) { responseClass = null; } } @Override public boolean contentTypeSupport(MediaType mediaType, Class<?> targetType) { return isMatch(targetType); } @Override public boolean typeSupport(Class<?> targetType) { return isMatch(targetType); } @Override public MediaType contentType() { return MediaType.APPLICATION_JSON_VALUE; } @Override public Object decode(byte[] body, Class<?> targetType, Type type) throws Exception { if (null == body || body.length == 0) { return null; } Class<?> builtResponse = ClassUtils.forName("org.jboss.resteasy.specimpl.BuiltResponse"); Object o = builtResponse.newInstance(); Method method = builtResponse.getMethod("setEntity", Object.class); method.invoke(o, new String(body, StandardCharsets.UTF_8)); return o; } @Override public void encode(OutputStream os, Object target, URL url) throws Exception { if (target != null) { Method method = target.getClass().getMethod("getEntity"); method.setAccessible(true); Object result = method.invoke(target); os.write(JsonUtils.toJson(result).getBytes(StandardCharsets.UTF_8)); } } private boolean isMatch(Class<?> targetType) { return responseClass != null && null != targetType && responseClass.isAssignableFrom(targetType); } }
5,773
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/XMLCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.message.codec; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec; import org.apache.dubbo.rpc.protocol.rest.message.MediaTypeMatcher; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.Source; import javax.xml.transform.sax.SAXSource; import java.io.OutputStream; import java.io.StringReader; import java.lang.reflect.Type; import org.xml.sax.InputSource; /** * body content-type is xml */ @Activate("xml") public class XMLCodec implements HttpMessageCodec<byte[], OutputStream> { @Override public Object decode(byte[] body, Class<?> targetType, Type type) throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature("http://xml.org/sax/features/external-general-entities", false); spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); // Do unmarshall operation Source xmlSource = new SAXSource(spf.newSAXParser().getXMLReader(), new InputSource(new StringReader(new String(body)))); JAXBContext context = JAXBContext.newInstance(targetType); Unmarshaller unmarshaller = context.createUnmarshaller(); return unmarshaller.unmarshal(xmlSource); } @Override public boolean contentTypeSupport(MediaType mediaType, Class<?> targetType) { return MediaTypeMatcher.TEXT_XML.mediaSupport(mediaType); } @Override public boolean typeSupport(Class<?> targetType) { return false; } @Override public MediaType contentType() { return MediaType.TEXT_XML; } @Override public void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception { Marshaller marshaller = JAXBContext.newInstance(unSerializedBody.getClass()).createMarshaller(); marshaller.marshal(unSerializedBody, outputStream); } }
5,774
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/RestHttpRequestDecoder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.netty; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.common.utils.ExecutorUtil; import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import org.apache.dubbo.rpc.protocol.rest.handler.NettyHttpHandler; import org.apache.dubbo.rpc.protocol.rest.request.NettyRequestFacade; import java.io.IOException; import java.util.List; import java.util.concurrent.Executor; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageDecoder; import io.netty.handler.codec.http.HttpHeaders; import static org.apache.dubbo.config.Constants.SERVER_THREAD_POOL_NAME; public class RestHttpRequestDecoder extends MessageToMessageDecoder<io.netty.handler.codec.http.FullHttpRequest> { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final Executor executor; private final ServiceDeployer serviceDeployer; private final URL url; private final NettyHttpHandler nettyHttpHandler; public RestHttpRequestDecoder(URL url, ServiceDeployer serviceDeployer) { this.url = url; this.serviceDeployer = serviceDeployer; executor = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()) .createExecutorIfAbsent(ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME)); nettyHttpHandler = new NettyHttpHandler(serviceDeployer, url); } @Override protected void decode( ChannelHandlerContext ctx, io.netty.handler.codec.http.FullHttpRequest request, List<Object> out) throws Exception { boolean keepAlive = HttpHeaders.isKeepAlive(request); NettyHttpResponse nettyHttpResponse = new NettyHttpResponse(ctx, keepAlive, url); NettyRequestFacade requestFacade = new NettyRequestFacade(request, ctx, serviceDeployer); executor.execute(() -> { // business handler try { nettyHttpHandler.handle(requestFacade, nettyHttpResponse); } catch (IOException e) { logger.error( "", e.getCause().getMessage(), "dubbo rest rest http request handler error", e.getMessage(), e); } finally { // write response try { nettyHttpResponse.addOutputHeaders(RestHeaderEnum.CONNECTION.getHeader(), "close"); nettyHttpResponse.finish(); } catch (IOException e) { logger.error( "", e.getCause().getMessage(), "dubbo rest rest http response flush error", e.getMessage(), e); } } }); } }
5,775
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/UnSharedHandlerCreator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.netty; import org.apache.dubbo.common.URL; import java.util.List; import io.netty.channel.ChannelHandler; /** * FOR create netty un shared (no @Shared) handler */ public interface UnSharedHandlerCreator { List<ChannelHandler> getUnSharedHandlers(URL url); }
5,776
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ChunkOutputStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.netty; import org.apache.dubbo.remoting.transport.ExceedPayloadLimitException; import java.io.IOException; import java.io.OutputStream; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultHttpContent; public class ChunkOutputStream extends OutputStream { final ByteBuf buffer; final ChannelHandlerContext ctx; final NettyHttpResponse response; int chunkSize = 0; ChunkOutputStream(final NettyHttpResponse response, final ChannelHandlerContext ctx, final int chunkSize) { this.response = response; if (chunkSize < 1) { throw new IllegalArgumentException(); } this.buffer = Unpooled.buffer(0, chunkSize); this.chunkSize = chunkSize; this.ctx = ctx; } @Override public void write(int b) throws IOException { if (buffer.maxWritableBytes() < 1) { throwExceedPayloadLimitException(buffer.readableBytes() + 1); } buffer.writeByte(b); } private void throwExceedPayloadLimitException(int dataSize) throws ExceedPayloadLimitException { throw new ExceedPayloadLimitException("Data length too large: " + dataSize + ", max payload: " + chunkSize); } public void reset() { if (response.isCommitted()) throw new IllegalStateException(); buffer.clear(); } @Override public void close() throws IOException { flush(); super.close(); } @Override public void write(byte[] b, int off, int len) throws IOException { int dataLengthLeftToWrite = len; int dataToWriteOffset = off; if (buffer.maxWritableBytes() < dataLengthLeftToWrite) { throwExceedPayloadLimitException(buffer.readableBytes() + len); } buffer.writeBytes(b, dataToWriteOffset, dataLengthLeftToWrite); } @Override public void flush() throws IOException { int readable = buffer.readableBytes(); if (readable == 0) return; if (!response.isCommitted()) response.prepareChunkStream(); ctx.writeAndFlush(new DefaultHttpContent(buffer.copy())); buffer.clear(); super.flush(); } }
5,777
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/NettyHttpResponse.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.netty; import org.apache.dubbo.common.URL; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.LastHttpContent; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; /** * netty http response */ public class NettyHttpResponse implements HttpResponse { private static final int EMPTY_CONTENT_LENGTH = 0; private int status = 200; private OutputStream os; private Map<String, List<String>> outputHeaders; private final ChannelHandlerContext ctx; private boolean committed; private boolean keepAlive; private HttpMethod method; // raw response body private Object responseBody; // raw response class private Class<?> entityClass; public NettyHttpResponse(final ChannelHandlerContext ctx, final boolean keepAlive, URL url) { this(ctx, keepAlive, null, url); } public NettyHttpResponse(final ChannelHandlerContext ctx, final boolean keepAlive, HttpMethod method, URL url) { outputHeaders = new HashMap<>(); this.method = method; os = new ChunkOutputStream(this, ctx, url.getParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD)); this.ctx = ctx; this.keepAlive = keepAlive; } public void setOutputStream(OutputStream os) { this.os = os; } @Override public int getStatus() { return status; } @Override public void setStatus(int status) { if (status > 200) { addOutputHeaders(RestHeaderEnum.CONTENT_TYPE.getHeader(), MediaType.TEXT_PLAIN.value); } this.status = status; } @Override public Map<String, List<String>> getOutputHeaders() { return outputHeaders; } @Override public OutputStream getOutputStream() throws IOException { return os; } @Override public void sendError(int status) throws IOException { sendError(status, null); } @Override public void sendError(int status, String message) throws IOException { setStatus(status); setResponseBody(message); if (message != null) { getOutputStream().write(message.getBytes(StandardCharsets.UTF_8)); } } @Override public boolean isCommitted() { return committed; } @Override public void reset() { if (committed) { throw new IllegalStateException("Messages.MESSAGES.alreadyCommitted()"); } outputHeaders.clear(); outputHeaders.clear(); } public boolean isKeepAlive() { return keepAlive; } public DefaultHttpResponse getDefaultHttpResponse() { DefaultHttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.valueOf(getStatus())); transformResponseHeaders(res); return res; } public DefaultHttpResponse getEmptyHttpResponse() { DefaultFullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.valueOf(getStatus())); if (method == null || !method.equals(HttpMethod.HEAD)) { res.headers().add(Names.CONTENT_LENGTH, EMPTY_CONTENT_LENGTH); } transformResponseHeaders(res); return res; } private void transformResponseHeaders(io.netty.handler.codec.http.HttpResponse res) { transformHeaders(this, res); } public void prepareChunkStream() { committed = true; DefaultHttpResponse response = getDefaultHttpResponse(); HttpHeaders.setTransferEncodingChunked(response); ctx.write(response); } public void finish() throws IOException { if (os != null) os.flush(); ChannelFuture future; if (isCommitted()) { // if committed this means the output stream was used. future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { future = ctx.writeAndFlush(getEmptyHttpResponse()); } if (!isKeepAlive()) { future.addListener(ChannelFutureListener.CLOSE); } getOutputStream().close(); } @Override public void flushBuffer() throws IOException { if (os != null) os.flush(); ctx.flush(); } @Override public void addOutputHeaders(String name, String value) { List<String> values = outputHeaders.get(name); if (values == null) { values = new ArrayList<>(); outputHeaders.put(name, values); } values.add(value); } @SuppressWarnings({"rawtypes", "unchecked"}) public static void transformHeaders( NettyHttpResponse nettyResponse, io.netty.handler.codec.http.HttpResponse response) { // if (nettyResponse.isKeepAlive()) { // response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); // } else { // response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); // } for (Map.Entry<String, List<String>> entry : nettyResponse.getOutputHeaders().entrySet()) { String key = entry.getKey(); for (String value : entry.getValue()) { response.headers().set(key, value); } } } public Object getResponseBody() { return responseBody; } public void setResponseBody(Object responseBody) { this.responseBody = responseBody; if (responseBody != null) { this.entityClass = responseBody.getClass(); } } public Class<?> getEntityClass() { return entityClass; } }
5,778
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/NettyServer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.netty; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; import java.net.InetSocketAddress; import java.util.Collections; import java.util.List; import java.util.Map; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.timeout.IdleStateHandler; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_BOSS_POOL_NAME; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME; public class NettyServer { protected ServerBootstrap bootstrap = new ServerBootstrap(); protected String hostname = null; protected int configuredPort = 8080; protected int runtimePort = -1; private EventLoopGroup eventLoopGroup; private EventLoopGroup workerLoopGroup; private int ioWorkerCount = Runtime.getRuntime().availableProcessors() * 2; private List<ChannelHandler> channelHandlers = Collections.emptyList(); private Map<ChannelOption, Object> channelOptions = Collections.emptyMap(); private Map<ChannelOption, Object> childChannelOptions = Collections.emptyMap(); private UnSharedHandlerCreator unSharedHandlerCallBack; public NettyServer() {} /** * Specify the worker count to use. For more information about this please see the javadocs of {@link EventLoopGroup} * * @param ioWorkerCount worker count */ public void setIoWorkerCount(int ioWorkerCount) { this.ioWorkerCount = ioWorkerCount; } public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public int getPort() { return runtimePort > 0 ? runtimePort : configuredPort; } public void setPort(int port) { this.configuredPort = port; } /** * Add additional {@link io.netty.channel.ChannelHandler}s to the {@link io.netty.bootstrap.ServerBootstrap}. * <p>The additional channel handlers are being added <em>before</em> the HTTP handling.</p> * * @param channelHandlers the additional {@link io.netty.channel.ChannelHandler}s. */ public void setChannelHandlers(final List<ChannelHandler> channelHandlers) { this.channelHandlers = channelHandlers == null ? Collections.<ChannelHandler>emptyList() : channelHandlers; } /** * Add Netty {@link io.netty.channel.ChannelOption}s to the {@link io.netty.bootstrap.ServerBootstrap}. * * @param channelOptions the additional {@link io.netty.channel.ChannelOption}s. * @see io.netty.bootstrap.ServerBootstrap#option(io.netty.channel.ChannelOption, Object) */ public void setChannelOptions(final Map<ChannelOption, Object> channelOptions) { this.channelOptions = channelOptions == null ? Collections.<ChannelOption, Object>emptyMap() : channelOptions; } /** * Add child options to the {@link io.netty.bootstrap.ServerBootstrap}. * * @param channelOptions the additional child {@link io.netty.channel.ChannelOption}s. * @see io.netty.bootstrap.ServerBootstrap#childOption(io.netty.channel.ChannelOption, Object) */ public void setChildChannelOptions(final Map<ChannelOption, Object> channelOptions) { this.childChannelOptions = channelOptions == null ? Collections.<ChannelOption, Object>emptyMap() : channelOptions; } public void setUnSharedHandlerCallBack(UnSharedHandlerCreator unSharedHandlerCallBack) { this.unSharedHandlerCallBack = unSharedHandlerCallBack; } public void start(URL url) { eventLoopGroup = new NioEventLoopGroup(1, new NamedThreadFactory(EVENT_LOOP_BOSS_POOL_NAME)); workerLoopGroup = new NioEventLoopGroup(ioWorkerCount, new NamedThreadFactory(EVENT_LOOP_WORKER_POOL_NAME)); // Configure the server. bootstrap .group(eventLoopGroup, workerLoopGroup) .channel(NioServerSocketChannel.class) .childHandler(setupHandlers(url)); for (Map.Entry<ChannelOption, Object> entry : channelOptions.entrySet()) { bootstrap.option(entry.getKey(), entry.getValue()); } for (Map.Entry<ChannelOption, Object> entry : childChannelOptions.entrySet()) { bootstrap.childOption(entry.getKey(), entry.getValue()); } final InetSocketAddress socketAddress; if (null == getHostname() || getHostname().isEmpty()) { socketAddress = new InetSocketAddress(configuredPort); } else { socketAddress = new InetSocketAddress(hostname, configuredPort); } Channel channel = bootstrap.bind(socketAddress).syncUninterruptibly().channel(); runtimePort = ((InetSocketAddress) channel.localAddress()).getPort(); } protected ChannelHandler setupHandlers(URL url) { return new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline channelPipeline = ch.pipeline(); int idleTimeout = url.getParameter(RestConstant.IDLE_TIMEOUT_PARAM, RestConstant.IDLE_TIMEOUT); if (idleTimeout > 0) { channelPipeline.addLast(new IdleStateHandler(0, 0, idleTimeout)); } channelPipeline.addLast(channelHandlers.toArray(new ChannelHandler[channelHandlers.size()])); List<ChannelHandler> unSharedHandlers = unSharedHandlerCallBack.getUnSharedHandlers(url); for (ChannelHandler unSharedHandler : unSharedHandlers) { channelPipeline.addLast(unSharedHandler); } } }; } public void stop() { runtimePort = -1; eventLoopGroup.shutdownGracefully(); } }
5,779
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/HttpResponse.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.netty; import java.io.IOException; import java.io.OutputStream; import java.util.List; import java.util.Map; public interface HttpResponse { int getStatus(); void setStatus(int status); Map<String, List<String>> getOutputHeaders(); OutputStream getOutputStream() throws IOException; void setOutputStream(OutputStream os); void sendError(int status) throws IOException; void sendError(int status, String message) throws IOException; boolean isCommitted(); /** * reset status and headers. Will fail if response is committed */ void reset(); void flushBuffer() throws IOException; void addOutputHeaders(String name, String value); }
5,780
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ssl/SslContexts.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.netty.ssl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.ssl.AuthPolicy; import org.apache.dubbo.common.ssl.Cert; import org.apache.dubbo.common.ssl.CertManager; import org.apache.dubbo.common.ssl.ProviderCert; import javax.net.ssl.SSLException; import java.io.IOException; import java.io.InputStream; import java.security.Provider; import java.security.Security; import io.netty.handler.ssl.ClientAuth; import io.netty.handler.ssl.OpenSsl; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE_STREAM; public class SslContexts { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SslContexts.class); public static SslContext buildServerSslContext(ProviderCert providerConnectionConfig) { SslContextBuilder sslClientContextBuilder; InputStream serverKeyCertChainPathStream = null; InputStream serverPrivateKeyPathStream = null; InputStream serverTrustCertStream = null; try { serverKeyCertChainPathStream = providerConnectionConfig.getKeyCertChainInputStream(); serverPrivateKeyPathStream = providerConnectionConfig.getPrivateKeyInputStream(); serverTrustCertStream = providerConnectionConfig.getTrustCertInputStream(); String password = providerConnectionConfig.getPassword(); if (password != null) { sslClientContextBuilder = SslContextBuilder.forServer(serverKeyCertChainPathStream, serverPrivateKeyPathStream, password); } else { sslClientContextBuilder = SslContextBuilder.forServer(serverKeyCertChainPathStream, serverPrivateKeyPathStream); } if (serverTrustCertStream != null) { sslClientContextBuilder.trustManager(serverTrustCertStream); if (providerConnectionConfig.getAuthPolicy() == AuthPolicy.CLIENT_AUTH) { sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE); } else { sslClientContextBuilder.clientAuth(ClientAuth.OPTIONAL); } } } catch (Exception e) { throw new IllegalArgumentException("Could not find certificate file or the certificate is invalid.", e); } finally { safeCloseStream(serverTrustCertStream); safeCloseStream(serverKeyCertChainPathStream); safeCloseStream(serverPrivateKeyPathStream); } try { return sslClientContextBuilder.sslProvider(findSslProvider()).build(); } catch (SSLException e) { throw new IllegalStateException("Build SslSession failed.", e); } } public static SslContext buildClientSslContext(URL url) { CertManager certManager = url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); Cert consumerConnectionConfig = certManager.getConsumerConnectionConfig(url); if (consumerConnectionConfig == null) { return null; } SslContextBuilder builder = SslContextBuilder.forClient(); InputStream clientTrustCertCollectionPath = null; InputStream clientCertChainFilePath = null; InputStream clientPrivateKeyFilePath = null; try { clientTrustCertCollectionPath = consumerConnectionConfig.getTrustCertInputStream(); if (clientTrustCertCollectionPath != null) { builder.trustManager(clientTrustCertCollectionPath); } clientCertChainFilePath = consumerConnectionConfig.getKeyCertChainInputStream(); clientPrivateKeyFilePath = consumerConnectionConfig.getPrivateKeyInputStream(); if (clientCertChainFilePath != null && clientPrivateKeyFilePath != null) { String password = consumerConnectionConfig.getPassword(); if (password != null) { builder.keyManager(clientCertChainFilePath, clientPrivateKeyFilePath, password); } else { builder.keyManager(clientCertChainFilePath, clientPrivateKeyFilePath); } } } catch (Exception e) { throw new IllegalArgumentException("Could not find certificate file or find invalid certificate.", e); } finally { safeCloseStream(clientTrustCertCollectionPath); safeCloseStream(clientCertChainFilePath); safeCloseStream(clientPrivateKeyFilePath); } try { return builder.sslProvider(findSslProvider()).build(); } catch (SSLException e) { throw new IllegalStateException("Build SslSession failed.", e); } } /** * Returns OpenSSL if available, otherwise returns the JDK provider. */ private static SslProvider findSslProvider() { if (OpenSsl.isAvailable()) { logger.debug("Using OPENSSL provider."); return SslProvider.OPENSSL; } if (checkJdkProvider()) { logger.debug("Using JDK provider."); return SslProvider.JDK; } throw new IllegalStateException( "Could not find any valid TLS provider, please check your dependency or deployment environment, " + "usually netty-tcnative, Conscrypt, or Jetty NPN/ALPN is needed."); } private static boolean checkJdkProvider() { Provider[] jdkProviders = Security.getProviders("SSLContext.TLS"); return (jdkProviders != null && jdkProviders.length > 0); } private static void safeCloseStream(InputStream stream) { if (stream == null) { return; } try { stream.close(); } catch (IOException e) { logger.warn(TRANSPORT_FAILED_CLOSE_STREAM, "", "", "Failed to close a stream.", e); } } }
5,781
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ssl/SslServerTlsHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.netty.ssl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.ssl.AuthPolicy; import org.apache.dubbo.common.ssl.CertManager; import org.apache.dubbo.common.ssl.ProviderCert; import javax.net.ssl.SSLSession; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandshakeCompletionEvent; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; public class SslServerTlsHandler extends ByteToMessageDecoder { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SslServerTlsHandler.class); private final URL url; private final boolean sslDetected; public SslServerTlsHandler(URL url) { this.url = url; this.sslDetected = false; } public SslServerTlsHandler(URL url, boolean sslDetected) { this.url = url; this.sslDetected = sslDetected; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.error( INTERNAL_ERROR, "unknown error in remoting module", "", "TLS negotiation failed when trying to accept new connection.", cause); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt; if (handshakeEvent.isSuccess()) { SSLSession session = ctx.pipeline().get(SslHandler.class).engine().getSession(); logger.info("TLS negotiation succeed with: " + session.getPeerHost()); // Remove after handshake success. ctx.pipeline().remove(this); } else { logger.error( INTERNAL_ERROR, "", "", "TLS negotiation failed when trying to accept new connection.", handshakeEvent.cause()); ctx.close(); } } super.userEventTriggered(ctx, evt); } @Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception { // Will use the first five bytes to detect a protocol. if (byteBuf.readableBytes() < 5) { return; } if (sslDetected) { return; } CertManager certManager = url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); ProviderCert providerConnectionConfig = certManager.getProviderConnectionConfig( url, channelHandlerContext.channel().remoteAddress()); if (providerConnectionConfig == null) { ChannelPipeline p = channelHandlerContext.pipeline(); p.remove(this); return; } if (isSsl(byteBuf)) { SslContext sslContext = SslContexts.buildServerSslContext(providerConnectionConfig); enableSsl(channelHandlerContext, sslContext); return; } if (providerConnectionConfig.getAuthPolicy() == AuthPolicy.NONE) { ChannelPipeline p = channelHandlerContext.pipeline(); p.remove(this); } logger.error(INTERNAL_ERROR, "", "", "TLS negotiation failed when trying to accept new connection."); channelHandlerContext.close(); } private boolean isSsl(ByteBuf buf) { return SslHandler.isEncrypted(buf); } private void enableSsl(ChannelHandlerContext ctx, SslContext sslContext) { ChannelPipeline p = ctx.pipeline(); ctx.pipeline().addAfter(ctx.name(), null, sslContext.newHandler(ctx.alloc())); p.addLast("unificationA", new SslServerTlsHandler(url, true)); p.remove(this); } }
5,782
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/support/ContentType.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.support; import javax.ws.rs.core.MediaType; public class ContentType { public static final String APPLICATION_JSON_UTF_8 = MediaType.APPLICATION_JSON + "; " + MediaType.CHARSET_PARAMETER + "=UTF-8"; public static final String TEXT_XML_UTF_8 = MediaType.TEXT_XML + "; " + MediaType.CHARSET_PARAMETER + "=UTF-8"; public static final String TEXT_PLAIN_UTF_8 = MediaType.TEXT_PLAIN + "; " + MediaType.CHARSET_PARAMETER + "=UTF-8"; }
5,783
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/constans/RestConstant.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.constans; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.rpc.Constants; public interface RestConstant { String VERSION = CommonConstants.VERSION_KEY; String GROUP = CommonConstants.GROUP_KEY; String PATH = CommonConstants.PATH_KEY; String TOKEN_KEY = Constants.TOKEN_KEY; String LOCAL_ADDR = "LOCAL_ADDR"; String REMOTE_ADDR = "REMOTE_ADDR"; String LOCAL_PORT = "LOCAL_PORT"; String REMOTE_PORT = "REMOTE_PORT"; String PROVIDER_BODY_PARSE = "body"; String PROVIDER_PARAM_PARSE = "param"; String PROVIDER_HEADER_PARSE = "header"; String PROVIDER_PATH_PARSE = "path"; String ADD_MUST_ATTTACHMENT = "must-intercept"; String RPCCONTEXT_INTERCEPT = "rpc-context"; String SERIALIZE_INTERCEPT = "serialize"; String PATH_SEPARATOR = "/"; String REQUEST_HEADER_INTERCEPT = "header"; String PATH_INTERCEPT = "path"; String KEEP_ALIVE_HEADER = "Keep-Alive"; String CONNECTION = "Connection"; String CONTENT_TYPE = "Content-Type"; String TEXT_PLAIN = "text/plain"; String ACCEPT = "Accept"; String DEFAULT_ACCEPT = "*/*"; String REST_HEADER_PREFIX = "rest-service-"; // http String MAX_INITIAL_LINE_LENGTH_PARAM = "max.initial.line.length"; String MAX_HEADER_SIZE_PARAM = "max.header.size"; String MAX_CHUNK_SIZE_PARAM = "max.chunk.size"; String MAX_REQUEST_SIZE_PARAM = "max.request.size"; String IDLE_TIMEOUT_PARAM = "idle.timeout"; String KEEP_ALIVE_TIMEOUT_PARAM = "keep.alive.timeout"; int MAX_REQUEST_SIZE = 1024 * 1024 * 10; int MAX_INITIAL_LINE_LENGTH = 4096; int MAX_HEADER_SIZE = 8192; int MAX_CHUNK_SIZE = 8192; int IDLE_TIMEOUT = -1; int KEEP_ALIVE_TIMEOUT = 60; /** * ServerAttachment pathAndInvokerMapper key */ String PATH_AND_INVOKER_MAPPER = "pathAndInvokerMapper"; }
5,784
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/RequestFacade.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.request; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; /** * request facade for different request * * @param <T> */ public abstract class RequestFacade<T> { protected Map<String, ArrayList<String>> headers = new HashMap<>(); protected Map<String, ArrayList<String>> parameters = new HashMap<>(); protected String path; protected T request; protected byte[] body = new byte[0]; protected ServiceDeployer serviceDeployer; public RequestFacade(T request) { this.request = request; initHeaders(); initParameters(); parseBody(); } public RequestFacade(T request, ServiceDeployer serviceDeployer) { this(request); this.serviceDeployer = serviceDeployer; } protected void initHeaders() {} protected void initParameters() { String requestURI = getRequestURI(); if (requestURI != null && requestURI.contains("?")) { String queryString = requestURI.substring(requestURI.indexOf("?") + 1); path = requestURI.substring(0, requestURI.indexOf("?")); String[] split = queryString.split("&"); for (String params : split) { // key a= ;value b==c int index = params.indexOf("="); if (index <= 0) { continue; } String name = params.substring(0, index); String value = params.substring(index + 1); if (!StringUtils.isEmpty(name)) { ArrayList<String> values = parameters.get(name); if (values == null) { values = new ArrayList<>(); parameters.put(name, values); } values.add(value); } } } else { path = requestURI; } } public T getRequest() { return request; } public abstract String getHeader(String name); public abstract Enumeration<String> getHeaders(String name); public abstract Enumeration<String> getHeaderNames(); public abstract String getMethod(); public abstract String getPath(); public abstract String getContextPath(); public abstract String getRequestURI(); public abstract String getParameter(String name); public abstract Enumeration<String> getParameterNames(); public abstract String[] getParameterValues(String name); public abstract Map<String, String[]> getParameterMap(); public abstract String getRemoteAddr(); public abstract String getRemoteHost(); public abstract int getRemotePort(); public abstract String getLocalAddr(); public abstract String getLocalHost(); public abstract int getLocalPort(); public abstract byte[] getInputStream() throws IOException; protected abstract void parseBody(); public ServiceDeployer getServiceDeployer() { return serviceDeployer; } }
5,785
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/NettyRequestFacade.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.request; import org.apache.dubbo.common.utils.IOUtils; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpContent; /** * netty request facade */ public class NettyRequestFacade extends RequestFacade<FullHttpRequest> { private ChannelHandlerContext context; public NettyRequestFacade(Object request, ChannelHandlerContext context) { super((FullHttpRequest) request); this.context = context; } public NettyRequestFacade(Object request, ChannelHandlerContext context, ServiceDeployer serviceDeployer) { super((FullHttpRequest) request, serviceDeployer); this.context = context; } protected void initHeaders() { for (Map.Entry<String, String> header : request.headers()) { String key = header.getKey(); ArrayList<String> tmpHeaders = headers.get(key); if (tmpHeaders == null) { tmpHeaders = new ArrayList<>(); headers.put(key, tmpHeaders); } tmpHeaders.add(header.getValue()); } } @Override public String getHeader(String name) { List<String> values = headers.get(name); if (values == null && name != null) { values = headers.get(name.toLowerCase()); } if (values == null || values.isEmpty()) { return null; } else { return values.get(0); } } @Override public Enumeration<String> getHeaders(String name) { List<String> list = headers.get(name); if (list == null) { list = new ArrayList<>(); } ListIterator<String> stringListIterator = list.listIterator(); return new Enumeration<String>() { @Override public boolean hasMoreElements() { return stringListIterator.hasNext(); } @Override public String nextElement() { return stringListIterator.next(); } }; } @Override public Enumeration<String> getHeaderNames() { Iterator<String> strings = headers.keySet().iterator(); return new Enumeration<String>() { @Override public boolean hasMoreElements() { return strings.hasNext(); } @Override public String nextElement() { return strings.next(); } }; } @Override public String getMethod() { return request.method().name(); } @Override public String getPath() { return path; } @Override public String getContextPath() { // TODO add ContextPath return null; } @Override public String getRequestURI() { return request.uri(); } @Override public String getParameter(String name) { ArrayList<String> strings = parameters.get(name); String value = null; if (strings != null && !strings.isEmpty()) { value = strings.get(0); } return value; } @Override public Enumeration<String> getParameterNames() { Iterator<String> iterator = parameters.keySet().iterator(); return new Enumeration<String>() { @Override public boolean hasMoreElements() { return iterator.hasNext(); } @Override public String nextElement() { return iterator.next(); } }; } @Override public String[] getParameterValues(String name) { if (!parameters.containsKey(name)) { return null; } return parameters.get(name).toArray(new String[0]); } @Override public Map<String, String[]> getParameterMap() { HashMap<String, String[]> map = new HashMap<>(); parameters.entrySet().forEach(entry -> { map.put(entry.getKey(), entry.getValue().toArray(new String[0])); }); return map; } @Override public String getRemoteAddr() { return getChannel().remoteAddress().getHostString(); } @Override public String getRemoteHost() { return getRemoteAddr() + ":" + getRemotePort(); } @Override public int getRemotePort() { return getChannel().remoteAddress().getPort(); } @Override public String getLocalAddr() { return getChannel().localAddress().getHostString(); } @Override public String getLocalHost() { return getRemoteAddr() + ":" + getLocalPort(); } private NioSocketChannel getChannel() { return (NioSocketChannel) context.channel(); } @Override public int getLocalPort() { return getChannel().localAddress().getPort(); } @Override public byte[] getInputStream() throws IOException { return body; } protected void parseBody() { ByteBuf byteBuf = ((HttpContent) request).content(); if (byteBuf.readableBytes() > 0) { try { body = IOUtils.toByteArray(new ByteBufInputStream(byteBuf)); } catch (IOException e) { } } } public ChannelHandlerContext getNettyChannelContext() { return context; } }
5,786
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestResponseFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.filter; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; /** * Rest response filter will be invoked when response is written to channel */ @SPI(scope = ExtensionScope.FRAMEWORK) public interface RestResponseFilter extends RestFilter {}
5,787
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.filter; import org.apache.dubbo.rpc.protocol.rest.filter.context.RestFilterContext; /** * Rest filter is extended by rest request & response filter */ public interface RestFilter { void filter(RestFilterContext restFilterContext) throws Exception; }
5,788
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestRequestFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.filter; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; /** * Rest filter will be invoked before http handler */ @SPI(scope = ExtensionScope.FRAMEWORK) public interface RestRequestFilter extends RestFilter {}
5,789
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/ServiceInvokeRestFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.metadata.rest.PathMatcher; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; import org.apache.dubbo.rpc.protocol.rest.RestRPCInvocationUtil; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import org.apache.dubbo.rpc.protocol.rest.exception.PathNoFoundException; import org.apache.dubbo.rpc.protocol.rest.exception.UnSupportContentTypeException; import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandlerResult; import org.apache.dubbo.rpc.protocol.rest.filter.context.RestFilterContext; import org.apache.dubbo.rpc.protocol.rest.filter.context.RestInterceptContext; import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodecManager; import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; import org.apache.dubbo.rpc.protocol.rest.pair.InvokerAndRestMethodMetadataPair; import org.apache.dubbo.rpc.protocol.rest.pair.MessageCodecResultPair; import org.apache.dubbo.rpc.protocol.rest.request.NettyRequestFacade; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil; import java.util.List; import java.util.Objects; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpRequest; @Activate(value = "invoke", order = Integer.MAX_VALUE) public class ServiceInvokeRestFilter implements RestRequestFilter { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final List<RestResponseInterceptor> restResponseInterceptors; public ServiceInvokeRestFilter(FrameworkModel frameworkModel) { restResponseInterceptors = frameworkModel.getExtensionLoader(RestResponseInterceptor.class).getActivateExtensions(); } @Override public void filter(RestFilterContext restFilterContext) throws Exception { NettyRequestFacade nettyRequestFacade = (NettyRequestFacade) restFilterContext.getRequestFacade(); FullHttpRequest nettyHttpRequest = nettyRequestFacade.getRequest(); doHandler( nettyHttpRequest, restFilterContext.getResponse(), restFilterContext.getRequestFacade(), restFilterContext.getUrl(), restFilterContext.getOriginRequest(), restFilterContext.getServiceDeployer()); } private void doHandler( HttpRequest nettyHttpRequest, NettyHttpResponse nettyHttpResponse, RequestFacade request, URL url, Object originRequest, // resteasy request ServiceDeployer serviceDeployer) throws Exception { PathMatcher pathMatcher = RestRPCInvocationUtil.createPathMatcher(request); // path NoFound 404 if (!serviceDeployer.hashRestMethod(pathMatcher)) { throw new PathNoFoundException("rest service Path no found, current path info:" + pathMatcher); } // method disallowed if (!serviceDeployer.isMethodAllowed(pathMatcher)) { nettyHttpResponse.sendError( 405, "service require request method is : " + serviceDeployer.pathHttpMethods(pathMatcher) + ", but current request method is: " + request.getMethod()); return; } // compare http method and acquire metadata by request InvokerAndRestMethodMetadataPair restMethodMetadataPair = RestRPCInvocationUtil.getRestMethodMetadataAndInvokerPair( pathMatcher.compareHttpMethod(true), serviceDeployer); Invoker invoker = restMethodMetadataPair.getInvoker(); RestMethodMetadata restMethodMetadata = restMethodMetadataPair.getRestMethodMetadata(); // content-type support judge,throw unSupportException acceptSupportJudge(request, restMethodMetadata.getReflectMethod().getReturnType()); // build RpcInvocation RpcInvocation rpcInvocation = RestRPCInvocationUtil.createBaseRpcInvocation(request, restMethodMetadata); // parse method real args RestRPCInvocationUtil.parseMethodArgs( rpcInvocation, request, nettyHttpRequest, nettyHttpResponse, restMethodMetadata); // execute business method invoke Result result = invoker.invoke(rpcInvocation); // set raw response nettyHttpResponse.setResponseBody(result.getValue()); if (result.hasException()) { Throwable exception = result.getException(); logger.error( "", exception.getMessage(), "", "dubbo rest protocol provider Invoker invoke error", exception); if (serviceDeployer.getExceptionMapper().hasExceptionMapper(exception)) { ExceptionHandlerResult exceptionToResult = serviceDeployer.getExceptionMapper().exceptionToResult(result.getException()); writeResult( nettyHttpResponse, request, url, exceptionToResult.getEntity(), rpcInvocation.getReturnType()); nettyHttpResponse.setStatus(exceptionToResult.getStatus()); } else { nettyHttpResponse.sendError( 500, "\n dubbo rest business exception, error cause is: " + result.getException().getCause() + "\n message is: " + result.getException().getMessage() + "\n stacktrace is: " + stackTraceToString(exception)); } } try { RestInterceptContext restFilterContext = new RestInterceptContext( url, request, nettyHttpResponse, serviceDeployer, result.getValue(), rpcInvocation); // set filter request restFilterContext.setOriginRequest(originRequest); // invoke the intercept chain before Result write to response executeResponseIntercepts(restFilterContext); } catch (Exception exception) { logger.error( "", exception.getMessage(), "", "dubbo rest protocol execute ResponseIntercepts error", exception); throw exception; } } /** * write return value by accept * * @param nettyHttpResponse * @param request * @param value * @param returnType * @throws Exception */ public static void writeResult( NettyHttpResponse nettyHttpResponse, RequestFacade<?> request, URL url, Object value, Class<?> returnType) throws Exception { MediaType mediaType = getAcceptMediaType(request, returnType); writeResult(nettyHttpResponse, url, value, returnType, mediaType); } public static void writeResult( NettyHttpResponse nettyHttpResponse, URL url, Object value, Class<?> returnType, MediaType mediaType) throws Exception { MessageCodecResultPair booleanMediaTypePair = HttpMessageCodecManager.httpMessageEncode( nettyHttpResponse.getOutputStream(), value, url, mediaType, returnType); // reset raw response result nettyHttpResponse.setResponseBody(value); nettyHttpResponse.addOutputHeaders( RestHeaderEnum.CONTENT_TYPE.getHeader(), booleanMediaTypePair.getMediaType().value); } /** * return first match , if any multiple content-type * * @param request * @return */ public static MediaType getAcceptMediaType(RequestFacade request, Class<?> returnType) { String accept = request.getHeader(RestHeaderEnum.ACCEPT.getHeader()); accept = Objects.isNull(accept) ? MediaType.ALL_VALUE.value : accept; MediaType mediaType = MediaTypeUtil.convertMediaType(returnType, accept); return mediaType; } /** * accept can not support will throw UnSupportAcceptException * * @param requestFacade */ private void acceptSupportJudge(RequestFacade requestFacade, Class<?> returnType) { try { // media type judge getAcceptMediaType(requestFacade, returnType); } catch (UnSupportContentTypeException e) { // return type judge MediaType mediaType = HttpMessageCodecManager.typeSupport(returnType); String accept = requestFacade.getHeader(RestHeaderEnum.ACCEPT.getHeader()); if (mediaType == null || accept == null) { throw e; } if (!accept.contains(mediaType.value)) { throw e; } } } public static String stackTraceToString(Throwable throwable) { StackTraceElement[] stackTrace = throwable.getStackTrace(); StringBuilder stringBuilder = new StringBuilder("\n"); for (StackTraceElement traceElement : stackTrace) { stringBuilder.append("\tat " + traceElement).append("\n"); } return stringBuilder.toString(); } /** * execute response Intercepts * * @param restFilterContext * @throws Exception */ public void executeResponseIntercepts(RestInterceptContext restFilterContext) throws Exception { for (RestResponseInterceptor restResponseInterceptor : restResponseInterceptors) { restResponseInterceptor.intercept(restFilterContext); if (restFilterContext.complete()) { break; } } } }
5,790
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/ServiceInvokeRestResponseInterceptor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.filter; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.protocol.rest.filter.context.RestInterceptContext; import static org.apache.dubbo.rpc.protocol.rest.filter.ServiceInvokeRestFilter.writeResult; /** * default RestResponseInterceptor */ @Activate(value = "invoke", order = Integer.MAX_VALUE) public class ServiceInvokeRestResponseInterceptor implements RestResponseInterceptor { @Override public void intercept(RestInterceptContext restInterceptContext) throws Exception { writeResult( restInterceptContext.getResponse(), restInterceptContext.getRequestFacade(), restInterceptContext.getUrl(), restInterceptContext.getResult(), restInterceptContext.getRpcInvocation().getReturnType()); } }
5,791
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestResponseInterceptor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.filter; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.rpc.protocol.rest.filter.context.RestInterceptContext; /** * RestResponseInterceptorChain will take effect before result is written to response */ @SPI(scope = ExtensionScope.FRAMEWORK) public interface RestResponseInterceptor { void intercept(RestInterceptContext restResponseInterceptor) throws Exception; }
5,792
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/RestFilterContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.filter.context; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; public class RestFilterContext implements FilterContext { protected URL url; protected RequestFacade requestFacade; protected NettyHttpResponse response; protected ServiceDeployer serviceDeployer; protected boolean completed; protected Object originRequest; protected Object originResponse; public RestFilterContext( URL url, RequestFacade requestFacade, NettyHttpResponse response, ServiceDeployer serviceDeployer) { this.url = url; this.requestFacade = requestFacade; this.response = response; this.serviceDeployer = serviceDeployer; } @Override public URL getUrl() { return url; } @Override public RequestFacade getRequestFacade() { return requestFacade; } @Override public NettyHttpResponse getResponse() { return response; } @Override public ServiceDeployer getServiceDeployer() { return serviceDeployer; } @Override public boolean complete() { return completed; } @Override public void setComplete(boolean complete) { this.completed = complete; } @Override public Object getOriginRequest() { return originRequest; } @Override public Object getOriginResponse() { return originResponse; } public void setOriginRequest(Object originRequest) { if (this.originRequest != null) { return; } this.originRequest = originRequest; } public void setOriginResponse(Object originResponse) { this.originResponse = originResponse; } }
5,793
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/FilterContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.filter.context; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import org.apache.dubbo.rpc.protocol.rest.netty.HttpResponse; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; public interface FilterContext { URL getUrl(); RequestFacade getRequestFacade(); HttpResponse getResponse(); ServiceDeployer getServiceDeployer(); boolean complete(); void setComplete(boolean complete); Object getOriginRequest(); Object getOriginResponse(); }
5,794
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/RestInterceptContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.filter.context; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; public class RestInterceptContext extends RestFilterContext { private Object result; private RpcInvocation rpcInvocation; public RestInterceptContext( URL url, RequestFacade requestFacade, NettyHttpResponse response, ServiceDeployer serviceDeployer, Object result, RpcInvocation rpcInvocation) { super(url, requestFacade, response, serviceDeployer); this.result = result; this.rpcInvocation = rpcInvocation; } public Object getResult() { return result; } public RpcInvocation getRpcInvocation() { return rpcInvocation; } }
5,795
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/DoublePathCheckException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.exception; /** * path mapper contains current path will throw */ public class DoublePathCheckException extends RuntimeException { public DoublePathCheckException(String message) { super(message); } }
5,796
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/RestException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.exception; /** * rest exception super */ public class RestException extends RuntimeException { public RestException(String message) { super(message); } }
5,797
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/MediaTypeUnSupportException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.exception; public class MediaTypeUnSupportException extends RestException { public MediaTypeUnSupportException(String message) { super(message); } }
5,798
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/RemoteServerInternalException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.rest.exception; /** * response status code : 500 */ public class RemoteServerInternalException extends RestException { public RemoteServerInternalException(String message) { super("dubbo http rest protocol remote error :" + message); } }
5,799