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-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/ExcludedParamsFilter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.filter;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.metadata.MetadataParamsFilter;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
@Activate(order = 1) // Will take effect before ExcludedParamsFilter
public class ExcludedParamsFilter implements MetadataParamsFilter {
@Override
public String[] serviceParamsIncluded() {
return new String[0];
}
@Override
public String[] serviceParamsExcluded() {
return new String[] {TIMEOUT_KEY, GROUP_KEY, "anyhost"};
}
/**
* Not included in this test
*/
@Override
public String[] instanceParamsIncluded() {
return new String[0];
}
@Override
public String[] instanceParamsExcluded() {
return new String[0];
}
}
| 7,200 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.config.annotation.Service;
import java.util.Map;
/**
* The default implementation of {@link RestService}
*
* @since 2.7.6
*/
@Service(version = "1.0.0")
public class DefaultRestService implements RestService {
@Override
public String param(String param) {
return null;
}
@Override
public String params(int a, String b) {
return null;
}
@Override
public String headers(String header, String header2, Integer param) {
return null;
}
@Override
public String pathVariables(String path1, String path2, String param) {
return null;
}
@Override
public String form(String form) {
return null;
}
@Override
public User requestBodyMap(Map<String, Object> data, String param) {
return null;
}
@Override
public Map<String, Object> requestBodyUser(User user) {
return null;
}
@Override
public void noAnnotationJsonBody(User user) {}
@Override
public void noAnnotationFormBody(User user) {}
@Override
public void noAnnotationParam(String text) {}
public User user(User user) {
return user;
}
}
| 7,201 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/User.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import java.io.Serializable;
/**
* User Entity
*
* @since 2.7.6
*/
public class User implements Serializable {
private Long id;
private String name;
private Integer age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}';
}
}
| 7,202 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.config.annotation.DubboService;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;
/**
* JAX-RS {@link RestService}
*/
@DubboService(
version = "3.0.0",
protocol = {"dubbo", "rest"},
group = "standard")
@Path("/")
public class StandardRestService implements RestService {
@Override
@Path("param")
@GET
public String param(@QueryParam("param") String param) {
return param;
}
@Override
@Path("params")
@POST
public String params(@QueryParam("a") int a, @QueryParam("b") String b) {
return a + b;
}
@Override
@Path("headers")
@GET
public String headers(
@HeaderParam("h") String header, @HeaderParam("h2") String header2, @QueryParam("v") Integer param) {
String result = header + " , " + header2 + " , " + param;
return result;
}
@Override
@Path("path-variables/{p1}/{p2}")
@GET
public String pathVariables(
@PathParam("p1") String path1, @PathParam("p2") String path2, @QueryParam("v") String param) {
String result = path1 + " , " + path2 + " , " + param;
return result;
}
// @CookieParam does not support : https://github.com/OpenFeign/feign/issues/913
// @CookieValue also does not support
@Override
@Path("form")
@POST
public String form(@FormParam("f") String form) {
return String.valueOf(form);
}
@Override
@Path("request/body/map")
@POST
@Produces("application/json;charset=UTF-8")
public User requestBodyMap(Map<String, Object> data, @QueryParam("param") String param) {
User user = new User();
user.setId(((Integer) data.get("id")).longValue());
user.setName((String) data.get("name"));
user.setAge((Integer) data.get("age"));
return user;
}
@Path("request/body/user")
@POST
@Override
@Consumes("application/json;charset=UTF-8")
public Map<String, Object> requestBodyUser(User user) {
Map<String, Object> map = new HashMap<>();
map.put("id", user.getId());
map.put("name", user.getName());
map.put("age", user.getAge());
return map;
}
@Path("noAnnotationJsonBody/json")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Override
public void noAnnotationJsonBody(User user) {}
@Path("noAnnotationFormBody/form")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@POST
@Override
public void noAnnotationFormBody(User user) {}
@Path("noAnnotationParam/text")
@POST
@Override
public void noAnnotationParam(String text) {}
}
| 7,203 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.config.annotation.DubboService;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Spring MVC {@link RestService}
*
* @since 2.7.6
*/
@DubboService(version = "2.0.0", group = "spring")
@RestController
public class SpringRestService implements RestService {
@Override
@GetMapping(value = "/param")
public String param(@RequestParam(defaultValue = "value-param") String param) {
return null;
}
@Override
@PostMapping("/params")
public String params(
@RequestParam(defaultValue = "value-a") int a, @RequestParam(defaultValue = "value-b") String b) {
return null;
}
@Override
@GetMapping("/headers")
public String headers(
@RequestHeader(name = "h", defaultValue = "value-h") String header,
@RequestHeader(name = "h2", defaultValue = "value-h2") String header2,
@RequestParam(value = "v", defaultValue = "1") Integer param) {
return null;
}
@Override
@GetMapping("/path-variables/{p1}/{p2}")
public String pathVariables(
@PathVariable("p1") String path1, @PathVariable("p2") String path2, @RequestParam("v") String param) {
return null;
}
@Override
@PostMapping("/form")
public String form(@RequestParam("f") String form) {
return String.valueOf(form);
}
@Override
@PostMapping(value = "/request/body/map", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public User requestBodyMap(@RequestBody Map<String, Object> data, @RequestParam("param") String param) {
User user = new User();
user.setId(((Integer) data.get("id")).longValue());
user.setName((String) data.get("name"));
user.setAge((Integer) data.get("age"));
return user;
}
@PostMapping(value = "/request/body/user", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Override
public Map<String, Object> requestBodyUser(@RequestBody User user) {
Map<String, Object> map = new HashMap<>();
map.put("id", user.getId());
map.put("name", user.getName());
map.put("age", user.getAge());
return map;
}
@PostMapping(value = "/request/body/user/json", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Override
public void noAnnotationJsonBody(User user) {}
@PostMapping(value = "/request/body/user/form", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@Override
public void noAnnotationFormBody(User user) {}
@PostMapping(value = "/request/body/user/param")
@Override
public void noAnnotationParam(String text) {}
}
| 7,204 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/NoAnnotationApiDemoResolverTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver;
import org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver;
import org.apache.dubbo.rpc.model.ApplicationModel;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
public class NoAnnotationApiDemoResolverTest {
private JAXRSServiceRestMetadataResolver jaxrsServiceRestMetadataResolver =
new JAXRSServiceRestMetadataResolver(ApplicationModel.defaultModel());
private SpringMvcServiceRestMetadataResolver springMvcServiceRestMetadataResolver =
new SpringMvcServiceRestMetadataResolver(ApplicationModel.defaultModel());
@Test
void testNoAnnotationApiResolver() {
Assertions.assertTrue(jaxrsServiceRestMetadataResolver.supports(JaxrsNoAnnotationApiDemoImpl.class));
Assertions.assertTrue(springMvcServiceRestMetadataResolver.supports(SpringMvcNoAnnotationApiDemoImpl.class));
}
}
class JaxrsNoAnnotationApiDemoImpl implements NoAnnotationApiDemo {
@Override
@Path("/test")
@GET
public String test(@QueryParam("test") String test) {
return "success" + test;
}
}
class SpringMvcNoAnnotationApiDemoImpl implements NoAnnotationApiDemo {
@Override
@RequestMapping("/test")
public String test(@RequestBody() String test) {
return "success" + test;
}
}
interface NoAnnotationApiDemo {
String test(String test);
}
| 7,205 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/RestService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import java.util.Map;
/**
* An interface for REST service
*
* @since 2.7.6
*/
public interface RestService {
String param(String param);
String params(int a, String b);
String headers(String header, String header2, Integer param);
String pathVariables(String path1, String path2, String param);
String form(String form);
User requestBodyMap(Map<String, Object> data, String param);
Map<String, Object> requestBodyUser(User user);
void noAnnotationJsonBody(User user);
void noAnnotationFormBody(User user);
void noAnnotationParam(String text);
}
| 7,206 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/SpringControllerService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.api;
import org.apache.dubbo.metadata.rest.User;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SpringControllerService {
@RequestMapping(
value = "/param",
method = RequestMethod.GET,
consumes = MediaType.TEXT_PLAIN_VALUE,
produces = MediaType.TEXT_PLAIN_VALUE)
public String param(@RequestParam String param) {
return param;
}
@RequestMapping(
value = "/header",
method = RequestMethod.GET,
consumes = MediaType.TEXT_PLAIN_VALUE,
produces = MediaType.TEXT_PLAIN_VALUE)
public String header(@RequestHeader String header) {
return header;
}
@RequestMapping(
value = "/body",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public User body(@RequestBody User user) {
return user;
}
@RequestMapping(
value = "/multiValue",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public MultiValueMap multiValue(@RequestBody MultiValueMap map) {
return map;
}
@RequestMapping(
value = "/pathVariable/{a}",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String pathVariable(@PathVariable String a) {
return a;
}
@RequestMapping(
value = "/noAnnoParam",
method = RequestMethod.POST,
consumes = MediaType.TEXT_PLAIN_VALUE,
produces = MediaType.TEXT_PLAIN_VALUE)
public String noAnnoParam(String a) {
return a;
}
@RequestMapping(
value = "/noAnnoNumber",
method = RequestMethod.POST,
consumes = MediaType.ALL_VALUE,
produces = MediaType.ALL_VALUE)
public int noAnnoNumber(Integer b) {
return b;
}
@RequestMapping(
value = "/noAnnoPrimitive",
method = RequestMethod.POST,
consumes = MediaType.ALL_VALUE,
produces = MediaType.ALL_VALUE)
public int noAnnoPrimitive(int c) {
return c;
}
}
| 7,207 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.api;
import org.apache.dubbo.metadata.rest.User;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SpringRestServiceImpl implements SpringRestService {
@Override
public String param(String param) {
return param;
}
@Override
public String header(String header) {
return header;
}
@Override
public User body(User user) {
return user;
}
@Override
public MultiValueMap multiValue(MultiValueMap map) {
return map;
}
@Override
public String pathVariable(String a) {
return a;
}
@Override
public String noAnnoParam(String a) {
return a;
}
@Override
public int noAnnoNumber(Integer b) {
return b;
}
@Override
public int noAnnoPrimitive(int c) {
return c;
}
}
| 7,208 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsUsingService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.api;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("usingService")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public interface JaxrsUsingService {
@GET
Response getUsers();
@POST
Response createUser(Object user);
@GET
@Path("{uid}")
Response getUserByUid(@PathParam("uid") String uid);
@DELETE
@Path("{uid}")
Response deleteUserByUid(@PathParam("uid") String uid);
}
| 7,209 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.api;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path("/test")
public interface JaxrsRestDoubleCheckService {
@Path("/param")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
@GET
String param(@QueryParam("param") String param);
@Path("/param")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
@GET
String header(@HeaderParam("header") String header);
}
| 7,210 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/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.metadata.rest.api;
import org.apache.dubbo.metadata.rest.User;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("u")
@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
@Produces({MediaType.APPLICATION_JSON})
public interface AnotherUserRestService {
@GET
@Path("{id : \\d+}")
User getUser(@PathParam("id") Long id);
@POST
@Path("register")
String registerUser(User user);
@GET
@Path("context")
String getContext();
}
| 7,211 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.api;
import org.apache.dubbo.metadata.rest.User;
import javax.ws.rs.core.MultivaluedMap;
public class JaxrsRestServiceImpl implements JaxrsRestService {
@Override
public String param(String param) {
return param;
}
@Override
public String header(String header) {
return header;
}
@Override
public User body(User user) {
return user;
}
@Override
public MultivaluedMap multiValue(MultivaluedMap map) {
return map;
}
@Override
public String pathVariable(String a) {
return a;
}
@Override
public String noAnno(String a) {
return a;
}
}
| 7,212 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckContainsPathVariableService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.api;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
@Path("/test")
public interface JaxrsRestDoubleCheckContainsPathVariableService {
@Path("/a/{b}")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
@GET
String param(@QueryParam("param") String param);
@Path("/{b}/b")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
@GET
String header(@HeaderParam("header") String header);
}
| 7,213 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.api;
import org.apache.dubbo.metadata.rest.User;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public interface SpringRestService {
@RequestMapping(
value = "/param",
method = RequestMethod.GET,
consumes = MediaType.TEXT_PLAIN_VALUE,
produces = MediaType.TEXT_PLAIN_VALUE)
String param(@RequestParam("param") String param);
@RequestMapping(
value = "/header",
method = RequestMethod.GET,
consumes = MediaType.TEXT_PLAIN_VALUE,
produces = MediaType.TEXT_PLAIN_VALUE)
String header(@RequestHeader("header") String header);
@RequestMapping(
value = "/body",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
User body(@RequestBody User user);
@RequestMapping(
value = "/multiValue",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
MultiValueMap multiValue(@RequestBody MultiValueMap map);
@RequestMapping(
value = "/pathVariable/{a}",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
String pathVariable(@PathVariable String a);
@RequestMapping(
value = "/noAnnoParam",
method = RequestMethod.POST,
consumes = MediaType.TEXT_PLAIN_VALUE,
produces = MediaType.TEXT_PLAIN_VALUE)
String noAnnoParam(String a);
@RequestMapping(
value = "/noAnnoNumber",
method = RequestMethod.POST,
consumes = MediaType.ALL_VALUE,
produces = MediaType.ALL_VALUE)
int noAnnoNumber(Integer b);
@RequestMapping(
value = "/noAnnoPrimitive",
method = RequestMethod.POST,
consumes = MediaType.ALL_VALUE,
produces = MediaType.ALL_VALUE)
int noAnnoPrimitive(int c);
}
| 7,214 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.api;
import org.apache.dubbo.metadata.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.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
public interface JaxrsRestService {
@Path("/param")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
@GET
String param(@QueryParam("param") String param);
@Path("/header")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
@GET
String header(@HeaderParam("header") String header);
@Path("/body")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@POST
User body(User user);
@Path("/multiValue")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_FORM_URLENCODED)
@POST
MultivaluedMap multiValue(MultivaluedMap map);
@Path("/pathVariable/{a}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_FORM_URLENCODED)
@POST
String pathVariable(@PathParam("a") String a);
@Path("/noAnno")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
@POST
String noAnno(String a);
}
| 7,215 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolverTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.jaxrs;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.metadata.rest.ClassPathServiceRestMetadataReader;
import org.apache.dubbo.metadata.rest.DefaultRestService;
import org.apache.dubbo.metadata.rest.PathUtil;
import org.apache.dubbo.metadata.rest.RestMethodMetadata;
import org.apache.dubbo.metadata.rest.RestService;
import org.apache.dubbo.metadata.rest.ServiceRestMetadata;
import org.apache.dubbo.metadata.rest.StandardRestService;
import org.apache.dubbo.metadata.rest.api.AnotherUserRestService;
import org.apache.dubbo.metadata.rest.api.JaxrsRestService;
import org.apache.dubbo.metadata.rest.api.JaxrsRestServiceImpl;
import org.apache.dubbo.metadata.rest.api.SpringRestService;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link JAXRSServiceRestMetadataResolver} Test
*
* @since 2.7.6
*/
class JAXRSServiceRestMetadataResolverTest {
private JAXRSServiceRestMetadataResolver instance =
new JAXRSServiceRestMetadataResolver(ApplicationModel.defaultModel());
@Test
void testSupports() {
// JAX-RS RestService class
assertTrue(instance.supports(StandardRestService.class));
// Spring MVC RestService class
assertFalse(instance.supports(SpringRestService.class));
// Default RestService class
assertFalse(instance.supports(DefaultRestService.class));
// No annotated RestService class
assertFalse(instance.supports(RestService.class));
// null
assertFalse(instance.supports(null));
}
@Test
@Disabled
void testResolve() {
// Generated by "dubbo-metadata-processor"
ClassPathServiceRestMetadataReader reader =
new ClassPathServiceRestMetadataReader("META-INF/dubbo/jax-rs-service-rest-metadata.json");
List<ServiceRestMetadata> serviceRestMetadataList = reader.read();
ServiceRestMetadata expectedServiceRestMetadata = serviceRestMetadataList.get(0);
ServiceRestMetadata serviceRestMetadata = instance.resolve(StandardRestService.class);
assertTrue(CollectionUtils.equals(expectedServiceRestMetadata.getMeta(), serviceRestMetadata.getMeta()));
assertEquals(expectedServiceRestMetadata, serviceRestMetadata);
}
@Test
void testResolves() {
testResolve(JaxrsRestService.class);
testResolve(JaxrsRestServiceImpl.class);
}
void testResolve(Class service) {
// Generated by "dubbo-metadata-processor"
List<String> jsons = Arrays.asList(
"{\"argInfos\":[{\"annotationNameAttribute\":\"a\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.BodyTag\",\"paramName\":\"a\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/noAnno\",\"produces\":[\"text/plain\"]}}",
"{\"argInfos\":[{\"annotationNameAttribute\":\"a\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"javax.ws.rs.PathParam\",\"paramName\":\"a\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":2}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/x-www-form-urlencoded\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/pathVariable/{a}\",\"produces\":[\"application/x-www-form-urlencoded\"]}}",
"{\"argInfos\":[{\"annotationNameAttribute\":\"map\",\"formContentType\":true,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.BodyTag\",\"paramName\":\"map\",\"paramType\":\"javax.ws.rs.core.MultivaluedMap\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"map\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/x-www-form-urlencoded\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/multiValue\",\"produces\":[\"application/x-www-form-urlencoded\"]}}",
"{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.BodyTag\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/body\",\"produces\":[\"application/json\"]}}",
"{\"argInfos\":[{\"annotationNameAttribute\":\"param\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"javax.ws.rs.QueryParam\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[],\"headers\":{},\"method\":\"GET\",\"paramNames\":[\"param\"],\"params\":{\"param\":[\"{0}\"]},\"path\":\"/param\",\"produces\":[\"text/plain\"]}}",
"{\"argInfos\":[{\"annotationNameAttribute\":\"header\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"javax.ws.rs.HeaderParam\",\"paramName\":\"header\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"header\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[\"header\"],\"headers\":{\"header\":[\"{0}\"]},\"method\":\"GET\",\"paramNames\":[],\"params\":{},\"path\":\"/header\",\"produces\":[\"text/plain\"]}}");
ServiceRestMetadata jaxrsRestMetadata = new ServiceRestMetadata();
jaxrsRestMetadata.setServiceInterface(service.getName());
ServiceRestMetadata jaxrsMetadata = instance.resolve(service, jaxrsRestMetadata);
List<String> jsonsTmp = new ArrayList<>();
for (RestMethodMetadata restMethodMetadata : jaxrsMetadata.getMeta()) {
restMethodMetadata.setReflectMethod(null);
restMethodMetadata.setMethod(null);
jsonsTmp.add(JsonUtils.toJson(restMethodMetadata));
}
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
};
jsons.sort(comparator);
jsonsTmp.sort(comparator);
for (int i = 0; i < jsons.size(); i++) {
assertEquals(jsons.get(i), jsonsTmp.get(i));
}
}
@Test
void testJaxrsPathPattern() {
Class service = AnotherUserRestService.class;
ServiceRestMetadata jaxrsRestMetadata = new ServiceRestMetadata();
jaxrsRestMetadata.setServiceInterface(service.getName());
ServiceRestMetadata jaxrsMetadata = instance.resolve(service, jaxrsRestMetadata);
RestMethodMetadata[] objects = jaxrsMetadata.getMeta().toArray(new RestMethodMetadata[0]);
RestMethodMetadata object = null;
for (RestMethodMetadata obj : objects) {
if ("getUser".equals(obj.getReflectMethod().getName())) {
object = obj;
}
}
Assertions.assertEquals(
"/u/1", PathUtil.resolvePathVariable("/u/{id : \\d+}", object.getArgInfos(), Arrays.asList(1)));
}
}
| 7,216 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JaxrsRestDoubleCheckTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.jaxrs;
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.metadata.rest.api.JaxrsRestDoubleCheckContainsPathVariableService;
import org.apache.dubbo.metadata.rest.api.JaxrsRestDoubleCheckService;
import org.apache.dubbo.metadata.rest.api.JaxrsUsingService;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class JaxrsRestDoubleCheckTest {
private JAXRSServiceRestMetadataResolver instance =
new JAXRSServiceRestMetadataResolver(ApplicationModel.defaultModel());
@Test
void testDoubleCheckException() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
ServiceRestMetadata resolve = new ServiceRestMetadata();
resolve.setServiceInterface(JaxrsRestDoubleCheckService.class.getName());
instance.resolve(JaxrsRestDoubleCheckService.class, resolve);
});
Assertions.assertThrows(IllegalArgumentException.class, () -> {
ServiceRestMetadata resolve = new ServiceRestMetadata();
resolve.setServiceInterface(JaxrsRestDoubleCheckContainsPathVariableService.class.getName());
instance.resolve(JaxrsRestDoubleCheckContainsPathVariableService.class, resolve);
});
}
@Test
void testSameHttpMethodException() {
Assertions.assertDoesNotThrow(() -> {
ServiceRestMetadata resolve = new ServiceRestMetadata();
resolve.setServiceInterface(JaxrsUsingService.class.getName());
instance.resolve(JaxrsUsingService.class, resolve);
});
ServiceRestMetadata resolve = new ServiceRestMetadata();
resolve.setServiceInterface(JaxrsUsingService.class.getName());
instance.resolve(JaxrsUsingService.class, resolve);
Map<PathMatcher, RestMethodMetadata> pathContainPathVariableToServiceMap =
resolve.getPathContainPathVariableToServiceMap();
RestMethodMetadata restMethodMetadata = pathContainPathVariableToServiceMap.get(
PathMatcher.getInvokeCreatePathMatcher("/usingService/aaa", null, null, null, "TEST"));
Assertions.assertNotNull(restMethodMetadata);
}
}
| 7,217 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolverTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.springmvc;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.metadata.rest.ClassPathServiceRestMetadataReader;
import org.apache.dubbo.metadata.rest.DefaultRestService;
import org.apache.dubbo.metadata.rest.PathMatcher;
import org.apache.dubbo.metadata.rest.RestMethodMetadata;
import org.apache.dubbo.metadata.rest.RestService;
import org.apache.dubbo.metadata.rest.ServiceRestMetadata;
import org.apache.dubbo.metadata.rest.StandardRestService;
import org.apache.dubbo.metadata.rest.api.SpringControllerService;
import org.apache.dubbo.metadata.rest.api.SpringRestService;
import org.apache.dubbo.metadata.rest.api.SpringRestServiceImpl;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link SpringMvcServiceRestMetadataResolver} Test
*
* @since 2.7.9
*/
class SpringMvcServiceRestMetadataResolverTest {
private SpringMvcServiceRestMetadataResolver instance =
new SpringMvcServiceRestMetadataResolver(ApplicationModel.defaultModel());
@Test
void testSupports() {
// Spring MVC RestService class
assertTrue(instance.supports(SpringRestService.class, true));
// JAX-RS RestService class
assertFalse(instance.supports(StandardRestService.class, true));
// Default RestService class
assertFalse(instance.supports(DefaultRestService.class, true));
// No annotated RestService class
assertFalse(instance.supports(RestService.class, true));
// null
assertFalse(instance.supports(null, true));
}
@Test
@Disabled
void testResolve() {
// Generated by "dubbo-metadata-processor"
ClassPathServiceRestMetadataReader reader =
new ClassPathServiceRestMetadataReader("META-INF/dubbo/spring-mvc-service-rest-metadata.json");
List<ServiceRestMetadata> serviceRestMetadataList = reader.read();
ServiceRestMetadata expectedServiceRestMetadata = serviceRestMetadataList.get(0);
ServiceRestMetadata serviceRestMetadata = instance.resolve(SpringRestService.class);
assertTrue(CollectionUtils.equals(expectedServiceRestMetadata.getMeta(), serviceRestMetadata.getMeta()));
assertEquals(expectedServiceRestMetadata, serviceRestMetadata);
}
@Test
void testResolves() {
testResolve(SpringRestService.class);
testResolve(SpringRestServiceImpl.class);
testResolve(SpringControllerService.class);
}
void testResolve(Class service) {
List<String> jsons = Arrays.asList(
"{\"argInfos\":[{\"annotationNameAttribute\":\"b\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.ParamTag\",\"paramName\":\"b\",\"paramType\":\"java.lang.Integer\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"b\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"*/*\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/noAnnoNumber\",\"produces\":[\"*/*\"]}}",
"{\"argInfos\":[{\"annotationNameAttribute\":\"c\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.ParamTag\",\"paramName\":\"c\",\"paramType\":\"int\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"c\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"*/*\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/noAnnoPrimitive\",\"produces\":[\"*/*\"]}}",
"{\"argInfos\":[{\"annotationNameAttribute\":\"a\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.ParamTag\",\"paramName\":\"a\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/noAnnoParam\",\"produces\":[\"text/plain\"]}}",
"{\"argInfos\":[{\"annotationNameAttribute\":\"\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.PathVariable\",\"paramName\":\"a\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":2}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/x-www-form-urlencoded\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/pathVariable/{a}\",\"produces\":[\"application/x-www-form-urlencoded\"]}}",
"{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.RequestBody\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/body\",\"produces\":[\"application/json\"]}}",
"{\"argInfos\":[{\"annotationNameAttribute\":\"param\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.RequestParam\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[],\"headers\":{},\"method\":\"GET\",\"paramNames\":[\"param\"],\"params\":{\"param\":[\"{0}\"]},\"path\":\"/param\",\"produces\":[\"text/plain\"]}}",
"{\"argInfos\":[{\"annotationNameAttribute\":\"map\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.RequestBody\",\"paramName\":\"map\",\"paramType\":\"org.springframework.util.MultiValueMap\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"map\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/x-www-form-urlencoded\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/multiValue\",\"produces\":[\"application/x-www-form-urlencoded\"]}}",
"{\"argInfos\":[{\"annotationNameAttribute\":\"header\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.RequestHeader\",\"paramName\":\"header\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"header\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[\"header\"],\"headers\":{\"header\":[\"{0}\"]},\"method\":\"GET\",\"paramNames\":[],\"params\":{},\"path\":\"/header\",\"produces\":[\"text/plain\"]}}");
ServiceRestMetadata springRestMetadata = new ServiceRestMetadata();
springRestMetadata.setServiceInterface(service.getName());
ServiceRestMetadata springMetadata = instance.resolve(service, springRestMetadata);
List<String> jsonsTmp = new ArrayList<>();
for (RestMethodMetadata restMethodMetadata : springMetadata.getMeta()) {
restMethodMetadata.setReflectMethod(null);
restMethodMetadata.setMethod(null);
jsonsTmp.add(JsonUtils.toJson(restMethodMetadata));
}
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
};
jsons.sort(comparator);
jsonsTmp.sort(comparator);
for (int i = 0; i < jsons.size(); i++) {
assertEquals(jsons.get(i), jsonsTmp.get(i));
}
}
@Test
void testDoubleCheck() {
ServiceRestMetadata springRestMetadata = new ServiceRestMetadata();
springRestMetadata.setServiceInterface(SpringRestServiceImpl.class.getName());
ServiceRestMetadata springMetadata = instance.resolve(SpringRestServiceImpl.class, springRestMetadata);
springMetadata.setContextPathFromUrl("context");
Assertions.assertEquals("context", springMetadata.getContextPathFromUrl());
springMetadata.setContextPathFromUrl("//context");
Assertions.assertEquals("/context", springMetadata.getContextPathFromUrl());
springMetadata.setPort(404);
Map<PathMatcher, RestMethodMetadata> pathContainPathVariableToServiceMap =
springMetadata.getPathContainPathVariableToServiceMap();
for (PathMatcher pathMatcher : pathContainPathVariableToServiceMap.keySet()) {
Assertions.assertTrue(pathMatcher.hasPathVariable());
Assertions.assertEquals(404, pathMatcher.getPort());
}
Map<PathMatcher, RestMethodMetadata> pathUnContainPathVariableToServiceMap =
springMetadata.getPathUnContainPathVariableToServiceMap();
for (PathMatcher pathMatcher : pathUnContainPathVariableToServiceMap.keySet()) {
Assertions.assertFalse(pathMatcher.hasPathVariable());
Assertions.assertEquals(404, pathMatcher.getPort());
}
}
}
| 7,218 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/RetryTestService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store;
/**
* 2018/10/26
*/
public interface RetryTestService {
void sayHello(String input);
String getName();
}
| 7,219 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/InterfaceNameTestService2.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store;
/**
* 2018/9/19
*/
public interface InterfaceNameTestService2 {
void test2();
}
| 7,220 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/InterfaceNameTestService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store;
/**
* 2018/9/19
*/
public interface InterfaceNameTestService {
void test();
}
| 7,221 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import org.apache.dubbo.rpc.service.Destroyable;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
import static java.util.Collections.emptySet;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR;
import static org.apache.dubbo.common.extension.ExtensionScope.APPLICATION;
/**
* This will interact with remote metadata center to find the interface-app mapping and will cache the data locally.
*
* Call variants of getCachedMapping() methods whenever need to use the mapping data.
*/
@SPI(value = "metadata", scope = APPLICATION)
public interface ServiceNameMapping extends Destroyable {
String DEFAULT_MAPPING_GROUP = "mapping";
/**
* Map the specified Dubbo service interface, group, version and protocol to current Dubbo service name
*/
boolean map(URL url);
boolean hasValidMetadataCenter();
/**
* Get the default extension of {@link ServiceNameMapping}
*
* @return non-null {@link ServiceNameMapping}
*/
static ServiceNameMapping getDefaultExtension(ScopeModel scopeModel) {
return ScopeModelUtil.getApplicationModel(scopeModel).getDefaultExtension(ServiceNameMapping.class);
}
static String buildMappingKey(URL url) {
return buildGroup(url.getServiceInterface());
}
static String buildGroup(String serviceInterface) {
// the issue : https://github.com/apache/dubbo/issues/4671
// return DEFAULT_MAPPING_GROUP + SLASH + serviceInterface;
return serviceInterface;
}
static String toStringKeys(Set<String> serviceNames) {
if (CollectionUtils.isEmpty(serviceNames)) {
return "";
}
StringBuilder builder = new StringBuilder();
for (String n : serviceNames) {
builder.append(n);
builder.append(COMMA_SEPARATOR);
}
builder.deleteCharAt(builder.length() - 1);
return builder.toString();
}
static Set<String> getAppNames(String content) {
if (StringUtils.isBlank(content)) {
return emptySet();
}
return new TreeSet<>(Arrays.asList(content.split(COMMA_SEPARATOR)));
}
static Set<String> getMappingByUrl(URL consumerURL) {
String providedBy = consumerURL.getParameter(RegistryConstants.PROVIDED_BY);
if (StringUtils.isBlank(providedBy)) {
return null;
}
return AbstractServiceNameMapping.parseServices(providedBy);
}
/**
* Get the latest mapping result from remote center and register listener at the same time to get notified once mapping changes.
*
* @param listener listener that will be notified on mapping change
* @return the latest mapping result from remote center
*/
Set<String> getAndListen(URL registryURL, URL subscribedURL, MappingListener listener);
MappingListener stopListen(URL subscribeURL, MappingListener listener);
void putCachedMapping(String serviceKey, Set<String> apps);
Set<String> getMapping(URL consumerURL);
Set<String> getRemoteMapping(URL consumerURL);
Set<String> removeCachedMapping(String serviceKey);
}
| 7,222 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingChangedEvent.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata;
import java.util.Set;
public class MappingChangedEvent {
private final String serviceKey;
private final Set<String> apps;
public MappingChangedEvent(String serviceKey, Set<String> apps) {
this.serviceKey = serviceKey;
this.apps = apps;
}
public String getServiceKey() {
return serviceKey;
}
public Set<String> getApps() {
return apps;
}
@Override
public String toString() {
return "{serviceKey: " + serviceKey + ", apps: " + apps.toString() + "}";
}
}
| 7,223 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataInfo.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata;
import org.apache.dubbo.common.ProtocolServiceKey;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.url.component.URLParam;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.StringUtils;
import java.beans.Transient;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.DOT_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_CHAR_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.metadata.RevisionResolver.EMPTY_REVISION;
public class MetadataInfo implements Serializable {
public static final MetadataInfo EMPTY = new MetadataInfo();
private static final Logger logger = LoggerFactory.getLogger(MetadataInfo.class);
private String app;
// revision that will report to registry or remote meta center, must always update together with rawMetadataInfo,
// check {@link this#calAndGetRevision}
private volatile String revision;
// key format is '{group}/{interface name}:{version}:{protocol}'
private final Map<String, ServiceInfo> services;
/* used at runtime */
private transient AtomicBoolean initiated = new AtomicBoolean(false);
// Json formatted metadata that will report to remote meta center, must always update together with revision, check
// {@link this#calAndGetRevision}
private transient volatile String rawMetadataInfo;
// key format is '{group}/{interface name}:{version}'
private transient Map<String, Set<ServiceInfo>> subscribedServices;
private final transient Map<String, String> extendParams;
private final transient Map<String, String> instanceParams;
protected transient volatile boolean updated = false;
private transient ConcurrentNavigableMap<String, SortedSet<URL>> subscribedServiceURLs;
private transient ConcurrentNavigableMap<String, SortedSet<URL>> exportedServiceURLs;
private transient ExtensionLoader<MetadataParamsFilter> loader;
public MetadataInfo() {
this(null);
}
public MetadataInfo(String app) {
this(app, null, null);
}
public MetadataInfo(String app, String revision, Map<String, ServiceInfo> services) {
this.app = app;
this.revision = revision;
this.services = services == null ? new ConcurrentHashMap<>() : services;
this.extendParams = new ConcurrentHashMap<>();
this.instanceParams = new ConcurrentHashMap<>();
}
private MetadataInfo(
String app,
String revision,
Map<String, ServiceInfo> services,
AtomicBoolean initiated,
Map<String, String> extendParams,
Map<String, String> instanceParams,
boolean updated,
ConcurrentNavigableMap<String, SortedSet<URL>> subscribedServiceURLs,
ConcurrentNavigableMap<String, SortedSet<URL>> exportedServiceURLs,
ExtensionLoader<MetadataParamsFilter> loader) {
this.app = app;
this.revision = revision;
this.services = new ConcurrentHashMap<>(services);
this.initiated = new AtomicBoolean(initiated.get());
this.extendParams = new ConcurrentHashMap<>(extendParams);
this.instanceParams = new ConcurrentHashMap<>(instanceParams);
this.updated = updated;
this.subscribedServiceURLs =
subscribedServiceURLs == null ? null : new ConcurrentSkipListMap<>(subscribedServiceURLs);
this.exportedServiceURLs =
exportedServiceURLs == null ? null : new ConcurrentSkipListMap<>(exportedServiceURLs);
this.loader = loader;
}
/**
* Initialize is needed when MetadataInfo is created from deserialization on the consumer side before being used for RPC call.
*/
public void init() {
if (!initiated.compareAndSet(false, true)) {
return;
}
if (CollectionUtils.isNotEmptyMap(services)) {
services.forEach((_k, serviceInfo) -> {
serviceInfo.init();
// create duplicate serviceKey(without protocol)->serviceInfo mapping to support metadata search when
// protocol is not specified on consumer side.
if (subscribedServices == null) {
subscribedServices = new HashMap<>();
}
Set<ServiceInfo> serviceInfos =
subscribedServices.computeIfAbsent(serviceInfo.getServiceKey(), _key -> new HashSet<>());
serviceInfos.add(serviceInfo);
});
}
}
public synchronized void addService(URL url) {
// fixme, pass in application mode context during initialization of MetadataInfo.
if (this.loader == null) {
this.loader = url.getOrDefaultApplicationModel().getExtensionLoader(MetadataParamsFilter.class);
}
List<MetadataParamsFilter> filters = loader.getActivateExtension(url, "params-filter");
// generate service level metadata
ServiceInfo serviceInfo = new ServiceInfo(url, filters);
this.services.put(serviceInfo.getMatchKey(), serviceInfo);
// extract common instance level params
extractInstanceParams(url, filters);
if (exportedServiceURLs == null) {
exportedServiceURLs = new ConcurrentSkipListMap<>();
}
addURL(exportedServiceURLs, url);
updated = true;
}
public synchronized void removeService(URL url) {
if (url == null) {
return;
}
this.services.remove(url.getProtocolServiceKey());
if (exportedServiceURLs != null) {
removeURL(exportedServiceURLs, url);
}
updated = true;
}
public String getRevision() {
return revision;
}
/**
* Calculation of this instance's status like revision and modification of the same instance must be synchronized among different threads.
* <p>
* Usage of this method is strictly restricted to certain points such as when during registration. Always try to use {@link this#getRevision()} instead.
*/
public synchronized String calAndGetRevision() {
if (revision != null && !updated) {
return revision;
}
updated = false;
if (CollectionUtils.isEmptyMap(services)) {
this.revision = EMPTY_REVISION;
} else {
StringBuilder sb = new StringBuilder();
sb.append(app);
for (Map.Entry<String, ServiceInfo> entry : new TreeMap<>(services).entrySet()) {
sb.append(entry.getValue().toDescString());
}
String tempRevision = RevisionResolver.calRevision(sb.toString());
if (!StringUtils.isEquals(this.revision, tempRevision)) {
if (logger.isInfoEnabled()) {
logger.info(String.format(
"metadata revision changed: %s -> %s, app: %s, services: %d",
this.revision, tempRevision, this.app, this.services.size()));
}
this.revision = tempRevision;
this.rawMetadataInfo = JsonUtils.toJson(this);
}
}
return revision;
}
public void setRevision(String revision) {
this.revision = revision;
}
@Transient
public String getContent() {
return this.rawMetadataInfo;
}
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public Map<String, ServiceInfo> getServices() {
return services;
}
/**
* Get service info of an interface with specified group, version and protocol
* @param protocolServiceKey key is of format '{group}/{interface name}:{version}:{protocol}'
* @return the specific service info related to protocolServiceKey
*/
public ServiceInfo getServiceInfo(String protocolServiceKey) {
return services.get(protocolServiceKey);
}
/**
* Get service infos of an interface with specified group, version.
* There may have several service infos of different protocols, this method will simply pick the first one.
*
* @param serviceKeyWithoutProtocol key is of format '{group}/{interface name}:{version}'
* @return the first service info related to serviceKey
*/
public ServiceInfo getNoProtocolServiceInfo(String serviceKeyWithoutProtocol) {
if (CollectionUtils.isEmptyMap(subscribedServices)) {
return null;
}
Set<ServiceInfo> subServices = subscribedServices.get(serviceKeyWithoutProtocol);
if (CollectionUtils.isNotEmpty(subServices)) {
return subServices.iterator().next();
}
return null;
}
public ServiceInfo getValidServiceInfo(String serviceKey) {
ServiceInfo serviceInfo = getServiceInfo(serviceKey);
if (serviceInfo == null) {
serviceInfo = getNoProtocolServiceInfo(serviceKey);
if (serviceInfo == null) {
return null;
}
}
return serviceInfo;
}
public List<ServiceInfo> getMatchedServiceInfos(ProtocolServiceKey consumerProtocolServiceKey) {
return getServices().values().stream()
.filter(serviceInfo -> serviceInfo.matchProtocolServiceKey(consumerProtocolServiceKey))
.collect(Collectors.toList());
}
public Map<String, String> getExtendParams() {
return extendParams;
}
public Map<String, String> getInstanceParams() {
return instanceParams;
}
public String getParameter(String key, String serviceKey) {
ServiceInfo serviceInfo = getValidServiceInfo(serviceKey);
if (serviceInfo == null) return null;
return serviceInfo.getParameter(key);
}
public Map<String, String> getParameters(String serviceKey) {
ServiceInfo serviceInfo = getValidServiceInfo(serviceKey);
if (serviceInfo == null) {
return Collections.emptyMap();
}
return serviceInfo.getAllParams();
}
public String getServiceString(String protocolServiceKey) {
if (protocolServiceKey == null) {
return null;
}
ServiceInfo serviceInfo = getValidServiceInfo(protocolServiceKey);
if (serviceInfo == null) {
return null;
}
return serviceInfo.toFullString();
}
public synchronized void addSubscribedURL(URL url) {
if (subscribedServiceURLs == null) {
subscribedServiceURLs = new ConcurrentSkipListMap<>();
}
addURL(subscribedServiceURLs, url);
}
public boolean removeSubscribedURL(URL url) {
if (subscribedServiceURLs == null) {
return true;
}
return removeURL(subscribedServiceURLs, url);
}
public ConcurrentNavigableMap<String, SortedSet<URL>> getSubscribedServiceURLs() {
return subscribedServiceURLs;
}
public ConcurrentNavigableMap<String, SortedSet<URL>> getExportedServiceURLs() {
return exportedServiceURLs;
}
public Set<URL> collectExportedURLSet() {
if (exportedServiceURLs == null) {
return Collections.emptySet();
}
return exportedServiceURLs.values().stream()
.filter(CollectionUtils::isNotEmpty)
.flatMap(Collection::stream)
.collect(Collectors.toSet());
}
private boolean addURL(Map<String, SortedSet<URL>> serviceURLs, URL url) {
SortedSet<URL> urls = serviceURLs.computeIfAbsent(url.getServiceKey(), this::newSortedURLs);
// make sure the parameters of tmpUrl is variable
return urls.add(url);
}
boolean removeURL(Map<String, SortedSet<URL>> serviceURLs, URL url) {
String key = url.getServiceKey();
SortedSet<URL> urls = serviceURLs.getOrDefault(key, null);
if (urls == null) {
return true;
}
boolean r = urls.remove(url);
// if it is empty
if (urls.isEmpty()) {
serviceURLs.remove(key);
}
return r;
}
private SortedSet<URL> newSortedURLs(String serviceKey) {
return new TreeSet<>(URLComparator.INSTANCE);
}
@Override
public int hashCode() {
return Objects.hash(app, services);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof MetadataInfo)) {
return false;
}
MetadataInfo other = (MetadataInfo) obj;
return Objects.equals(app, other.getApp())
&& ((services == null && other.services == null)
|| (services != null && services.equals(other.services)));
}
private void extractInstanceParams(URL url, List<MetadataParamsFilter> filters) {
if (CollectionUtils.isEmpty(filters)) {
return;
}
String[] included, excluded;
if (filters.size() == 1) {
MetadataParamsFilter filter = filters.get(0);
included = filter.instanceParamsIncluded();
excluded = filter.instanceParamsExcluded();
} else {
Set<String> includedList = new HashSet<>();
Set<String> excludedList = new HashSet<>();
filters.forEach(filter -> {
if (ArrayUtils.isNotEmpty(filter.instanceParamsIncluded())) {
includedList.addAll(Arrays.asList(filter.instanceParamsIncluded()));
}
if (ArrayUtils.isNotEmpty(filter.instanceParamsExcluded())) {
excludedList.addAll(Arrays.asList(filter.instanceParamsExcluded()));
}
});
included = includedList.toArray(new String[0]);
excluded = excludedList.toArray(new String[0]);
}
Map<String, String> tmpInstanceParams = new HashMap<>();
if (ArrayUtils.isNotEmpty(included)) {
for (String p : included) {
String value = url.getParameter(p);
if (value != null) {
tmpInstanceParams.put(p, value);
}
}
} else if (ArrayUtils.isNotEmpty(excluded)) {
tmpInstanceParams.putAll(url.getParameters());
for (String p : excluded) {
tmpInstanceParams.remove(p);
}
}
tmpInstanceParams.forEach((key, value) -> {
String oldValue = instanceParams.put(key, value);
if (!TIMESTAMP_KEY.equals(key) && oldValue != null && !oldValue.equals(value)) {
throw new IllegalStateException(String.format(
"Inconsistent instance metadata found in different services: %s, %s", oldValue, value));
}
});
}
@Override
public String toString() {
return "metadata{" + "app='"
+ app + "'," + "revision='"
+ revision + "'," + "size="
+ (services == null ? 0 : services.size()) + "," + "services="
+ getSimplifiedServices(services) + "}";
}
public String toFullString() {
return "metadata{" + "app='" + app + "'," + "revision='" + revision + "'," + "services=" + services + "}";
}
private String getSimplifiedServices(Map<String, ServiceInfo> services) {
if (services == null) {
return "[]";
}
return services.keySet().toString();
}
@Override
public synchronized MetadataInfo clone() {
return new MetadataInfo(
app,
revision,
services,
initiated,
extendParams,
instanceParams,
updated,
subscribedServiceURLs,
exportedServiceURLs,
loader);
}
private Object readResolve() {
// create a new object from the deserialized one, in order to call constructor
return new MetadataInfo(this.app, this.revision, this.services);
}
public static class ServiceInfo implements Serializable {
private String name;
private String group;
private String version;
private String protocol;
private int port = -1;
private String path; // most of the time, path is the same with the interface name.
private Map<String, String> params;
// params configured on consumer side,
private transient volatile Map<String, String> consumerParams;
// cached method params
private transient volatile Map<String, Map<String, String>> methodParams;
private transient volatile Map<String, Map<String, String>> consumerMethodParams;
// cached numbers
private transient volatile Map<String, Number> numbers;
private transient volatile Map<String, Map<String, Number>> methodNumbers;
// service + group + version
private transient volatile String serviceKey;
// service + group + version + protocol
private transient volatile String matchKey;
private transient volatile ProtocolServiceKey protocolServiceKey;
private transient URL url;
public ServiceInfo() {}
public ServiceInfo(URL url, List<MetadataParamsFilter> filters) {
this(
url.getServiceInterface(),
url.getGroup(),
url.getVersion(),
url.getProtocol(),
url.getPort(),
url.getPath(),
null);
this.url = url;
Map<String, String> params = extractServiceParams(url, filters);
// initialize method params caches.
this.methodParams = URLParam.initMethodParameters(params);
this.consumerMethodParams = URLParam.initMethodParameters(consumerParams);
}
public ServiceInfo(
String name,
String group,
String version,
String protocol,
int port,
String path,
Map<String, String> params) {
this.name = name;
this.group = group;
this.version = version;
this.protocol = protocol;
this.port = port;
this.path = path;
this.params = params == null ? new ConcurrentHashMap<>() : params;
this.serviceKey = buildServiceKey(name, group, version);
this.matchKey = buildMatchKey();
}
private Map<String, String> extractServiceParams(URL url, List<MetadataParamsFilter> filters) {
Map<String, String> params = new HashMap<>();
if (CollectionUtils.isEmpty(filters)) {
params.putAll(url.getParameters());
this.params = params;
return params;
}
String[] included, excluded;
if (filters.size() == 1) {
included = filters.get(0).serviceParamsIncluded();
excluded = filters.get(0).serviceParamsExcluded();
} else {
Set<String> includedList = new HashSet<>();
Set<String> excludedList = new HashSet<>();
for (MetadataParamsFilter filter : filters) {
if (ArrayUtils.isNotEmpty(filter.serviceParamsIncluded())) {
includedList.addAll(Arrays.asList(filter.serviceParamsIncluded()));
}
if (ArrayUtils.isNotEmpty(filter.serviceParamsExcluded())) {
excludedList.addAll(Arrays.asList(filter.serviceParamsExcluded()));
}
}
included = includedList.toArray(new String[0]);
excluded = excludedList.toArray(new String[0]);
}
if (ArrayUtils.isNotEmpty(included)) {
String[] methods = url.getParameter(METHODS_KEY, (String[]) null);
for (String p : included) {
String value = url.getParameter(p);
if (StringUtils.isNotEmpty(value) && params.get(p) == null) {
params.put(p, value);
}
appendMethodParams(url, params, methods, p);
}
} else if (ArrayUtils.isNotEmpty(excluded)) {
for (Map.Entry<String, String> entry : url.getParameters().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
boolean shouldAdd = true;
for (String excludeKey : excluded) {
if (key.equalsIgnoreCase(excludeKey) || key.contains("." + excludeKey)) {
shouldAdd = false;
break;
}
}
if (shouldAdd) {
params.put(key, value);
}
}
}
this.params = params;
return params;
}
private void appendMethodParams(URL url, Map<String, String> params, String[] methods, String p) {
if (methods != null) {
for (String method : methods) {
String mValue = url.getMethodParameterStrict(method, p);
if (StringUtils.isNotEmpty(mValue)) {
params.put(method + DOT_SEPARATOR + p, mValue);
}
}
}
}
/**
* Initialize necessary caches right after deserialization on the consumer side
*/
protected void init() {
buildMatchKey();
buildServiceKey(name, group, version);
// init method params
this.methodParams = URLParam.initMethodParameters(params);
// Actually, consumer params is empty after deserialized on the consumer side, so no need to initialize.
// Check how InstanceAddressURL operates on consumer url for more detail.
// this.consumerMethodParams = URLParam.initMethodParameters(consumerParams);
// no need to init numbers for it's only for cache purpose
}
public String getMatchKey() {
if (matchKey != null) {
return matchKey;
}
buildMatchKey();
return matchKey;
}
private String buildMatchKey() {
matchKey = getServiceKey();
if (StringUtils.isNotEmpty(protocol)) {
matchKey = getServiceKey() + GROUP_CHAR_SEPARATOR + protocol;
}
return matchKey;
}
public boolean matchProtocolServiceKey(ProtocolServiceKey protocolServiceKey) {
return ProtocolServiceKey.Matcher.isMatch(protocolServiceKey, getProtocolServiceKey());
}
public ProtocolServiceKey getProtocolServiceKey() {
if (protocolServiceKey != null) {
return protocolServiceKey;
}
protocolServiceKey = new ProtocolServiceKey(name, version, group, protocol);
return protocolServiceKey;
}
private String buildServiceKey(String name, String group, String version) {
this.serviceKey = URL.buildKey(name, group, version);
return this.serviceKey;
}
public String getServiceKey() {
if (serviceKey != null) {
return serviceKey;
}
buildServiceKey(name, group, version);
return serviceKey;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public Map<String, String> getParams() {
if (params == null) {
return Collections.emptyMap();
}
return params;
}
public void setParams(Map<String, String> params) {
this.params = params;
}
@Transient
public Map<String, String> getAllParams() {
if (consumerParams != null) {
Map<String, String> allParams =
new HashMap<>((int) ((params.size() + consumerParams.size()) / 0.75f + 1));
allParams.putAll(params);
allParams.putAll(consumerParams);
return allParams;
}
return params;
}
public String getParameter(String key) {
if (consumerParams != null) {
String value = consumerParams.get(key);
if (value != null) {
return value;
}
}
return params.get(key);
}
public String getMethodParameter(String method, String key, String defaultValue) {
String value = getMethodParameter(method, key, consumerMethodParams);
if (value != null) {
return value;
}
value = getMethodParameter(method, key, methodParams);
return value == null ? defaultValue : value;
}
private String getMethodParameter(String method, String key, Map<String, Map<String, String>> map) {
String value = null;
if (map == null) {
return value;
}
Map<String, String> keyMap = map.get(method);
if (keyMap != null) {
value = keyMap.get(key);
}
return value;
}
public boolean hasMethodParameter(String method, String key) {
String value = this.getMethodParameter(method, key, (String) null);
return StringUtils.isNotEmpty(value);
}
public boolean hasMethodParameter(String method) {
return (consumerMethodParams != null && consumerMethodParams.containsKey(method))
|| (methodParams != null && methodParams.containsKey(method));
}
public String toDescString() {
return this.getMatchKey() + port + path + new TreeMap<>(getParams());
}
public void addParameter(String key, String value) {
if (consumerParams != null) {
this.consumerParams.put(key, value);
}
// refresh method params
consumerMethodParams = URLParam.initMethodParameters(consumerParams);
}
public void addParameterIfAbsent(String key, String value) {
if (consumerParams != null) {
this.consumerParams.putIfAbsent(key, value);
}
// refresh method params
consumerMethodParams = URLParam.initMethodParameters(consumerParams);
}
public void addConsumerParams(Map<String, String> params) {
// copy once for one service subscription
if (consumerParams == null) {
consumerParams = new ConcurrentHashMap<>(params);
// init method params
consumerMethodParams = URLParam.initMethodParameters(consumerParams);
}
}
public Map<String, Number> getNumbers() {
// concurrent initialization is tolerant
if (numbers == null) {
numbers = new ConcurrentHashMap<>();
}
return numbers;
}
public Map<String, Map<String, Number>> getMethodNumbers() {
if (methodNumbers == null) { // concurrent initialization is tolerant
methodNumbers = new ConcurrentHashMap<>();
}
return methodNumbers;
}
public URL getUrl() {
return url;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof ServiceInfo)) {
return false;
}
ServiceInfo serviceInfo = (ServiceInfo) obj;
/**
* Equals to Objects.equals(this.getMatchKey(), serviceInfo.getMatchKey()), but match key will not get initialized
* on json deserialization.
*/
return Objects.equals(this.getVersion(), serviceInfo.getVersion())
&& Objects.equals(this.getGroup(), serviceInfo.getGroup())
&& Objects.equals(this.getName(), serviceInfo.getName())
&& Objects.equals(this.getProtocol(), serviceInfo.getProtocol())
&& Objects.equals(this.getPort(), serviceInfo.getPort())
&& this.getParams().equals(serviceInfo.getParams());
}
@Override
public int hashCode() {
return Objects.hash(getVersion(), getGroup(), getName(), getProtocol(), getPort(), getParams());
}
@Override
public String toString() {
return getMatchKey();
}
public String toFullString() {
return "service{" + "name='"
+ name + "'," + "group='"
+ group + "'," + "version='"
+ version + "'," + "protocol='"
+ protocol + "'," + "port='"
+ port + "'," + "params="
+ params + "," + "}";
}
}
static class URLComparator implements Comparator<URL> {
public static final URLComparator INSTANCE = new URLComparator();
@Override
public int compare(URL o1, URL o2) {
return o1.toFullString().compareTo(o2.toFullString());
}
}
}
| 7,224 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DefaultMetadataParamsFilter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata;
import org.apache.dubbo.common.extension.Activate;
import static org.apache.dubbo.common.constants.CommonConstants.IPV6_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY;
import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP;
import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE;
import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST;
import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT;
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.HEARTBEAT_TIMEOUT_KEY;
import static org.apache.dubbo.rpc.Constants.INTERFACES;
@Activate
public class DefaultMetadataParamsFilter implements MetadataParamsFilter {
private final String[] excludedServiceParams;
private final String[] includedInstanceParams;
public DefaultMetadataParamsFilter() {
this.includedInstanceParams = new String[] {HEARTBEAT_TIMEOUT_KEY, TIMESTAMP_KEY, IPV6_KEY};
this.excludedServiceParams = new String[] {
MONITOR_KEY,
BIND_IP_KEY,
BIND_PORT_KEY,
QOS_ENABLE,
QOS_HOST,
QOS_PORT,
ACCEPT_FOREIGN_IP,
VALIDATION_KEY,
INTERFACES,
PID_KEY,
TIMESTAMP_KEY,
HEARTBEAT_TIMEOUT_KEY,
IPV6_KEY
};
}
@Override
public String[] instanceParamsIncluded() {
return includedInstanceParams;
}
@Override
public String[] serviceParamsExcluded() {
return excludedServiceParams;
}
}
| 7,225 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/RevisionResolver.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata;
import org.apache.dubbo.common.utils.MD5Utils;
public class RevisionResolver {
public static final String EMPTY_REVISION = "0";
private static MD5Utils md5Utils = new MD5Utils();
public static String calRevision(String metadata) {
return md5Utils.getMd5(metadata);
}
}
| 7,226 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingCacheManager.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.model.ScopeModel;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
/**
* TODO, Using randomly accessible file-based cache can be another choice if memory consumption turns to be an issue.
*/
public class MappingCacheManager extends AbstractCacheManager<Set<String>> {
private static final String DEFAULT_FILE_NAME = ".mapping";
private static final int DEFAULT_ENTRY_SIZE = 10000;
public static MappingCacheManager getInstance(ScopeModel scopeModel) {
return scopeModel.getBeanFactory().getOrRegisterBean(MappingCacheManager.class);
}
public MappingCacheManager(boolean enableFileCache, String name, ScheduledExecutorService executorService) {
String filePath = System.getProperty("dubbo.mapping.cache.filePath");
String fileName = System.getProperty("dubbo.mapping.cache.fileName");
if (StringUtils.isEmpty(fileName)) {
fileName = DEFAULT_FILE_NAME;
}
if (StringUtils.isNotEmpty(name)) {
fileName = fileName + "." + name;
}
String rawEntrySize = System.getProperty("dubbo.mapping.cache.entrySize");
int entrySize = StringUtils.parseInteger(rawEntrySize);
entrySize = (entrySize == 0 ? DEFAULT_ENTRY_SIZE : entrySize);
String rawMaxFileSize = System.getProperty("dubbo.mapping.cache.maxFileSize");
long maxFileSize = StringUtils.parseLong(rawMaxFileSize);
init(enableFileCache, filePath, fileName, entrySize, maxFileSize, 50, executorService);
}
@Override
protected Set<String> toValueType(String value) {
return new HashSet<>(JsonUtils.toJavaList(value, String.class));
}
@Override
protected String getName() {
return "mapping";
}
}
| 7,227 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractServiceNameMapping.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata;
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.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static java.util.Collections.emptySet;
import static java.util.Collections.unmodifiableSet;
import static java.util.stream.Collectors.toSet;
import static java.util.stream.Stream.of;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_LOAD_MAPPING_CACHE;
import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBED_SERVICE_NAMES_KEY;
import static org.apache.dubbo.common.utils.CollectionUtils.toTreeSet;
import static org.apache.dubbo.common.utils.StringUtils.isBlank;
public abstract class AbstractServiceNameMapping implements ServiceNameMapping {
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
protected ApplicationModel applicationModel;
private final MappingCacheManager mappingCacheManager;
private final Map<String, Set<MappingListener>> mappingListeners = new ConcurrentHashMap<>();
// mapping lock is shared among registries of the same application.
private final ConcurrentMap<String, ReentrantLock> mappingLocks = new ConcurrentHashMap<>();
public AbstractServiceNameMapping(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
boolean enableFileCache = true;
Optional<ApplicationConfig> application =
applicationModel.getApplicationConfigManager().getApplication();
if (application.isPresent()) {
enableFileCache = Boolean.TRUE.equals(application.get().getEnableFileCache()) ? true : false;
}
this.mappingCacheManager = new MappingCacheManager(
enableFileCache,
applicationModel.tryGetApplicationName(),
applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getCacheRefreshingScheduledExecutor());
}
// just for test
public void setApplicationModel(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
/**
* Get the service names from the specified Dubbo service interface, group, version and protocol
*
* @return
*/
public abstract Set<String> get(URL url);
/**
* Get the service names from the specified Dubbo service interface, group, version and protocol
*
* @return
*/
public abstract Set<String> getAndListen(URL url, MappingListener mappingListener);
protected abstract void removeListener(URL url, MappingListener mappingListener);
@Override
public Set<String> getAndListen(URL registryURL, URL subscribedURL, MappingListener listener) {
String key = ServiceNameMapping.buildMappingKey(subscribedURL);
// use previously cached services.
Set<String> mappingServices = mappingCacheManager.get(key);
// Asynchronously register listener in case previous cache does not exist or cache expired.
if (CollectionUtils.isEmpty(mappingServices)) {
try {
logger.info("Local cache mapping is empty");
mappingServices = (new AsyncMappingTask(listener, subscribedURL, false)).call();
} catch (Exception e) {
// ignore
}
if (CollectionUtils.isEmpty(mappingServices)) {
String registryServices = registryURL.getParameter(SUBSCRIBED_SERVICE_NAMES_KEY);
if (StringUtils.isNotEmpty(registryServices)) {
logger.info(subscribedURL.getServiceInterface() + " mapping to " + registryServices
+ " instructed by registry subscribed-services.");
mappingServices = parseServices(registryServices);
}
}
if (CollectionUtils.isNotEmpty(mappingServices)) {
this.putCachedMapping(ServiceNameMapping.buildMappingKey(subscribedURL), mappingServices);
}
} else {
ExecutorService executorService = applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getMappingRefreshingExecutor();
executorService.submit(new AsyncMappingTask(listener, subscribedURL, true));
}
return mappingServices;
}
@Override
public MappingListener stopListen(URL subscribeURL, MappingListener listener) {
synchronized (mappingListeners) {
if (listener != null) {
String mappingKey = ServiceNameMapping.buildMappingKey(subscribeURL);
Set<MappingListener> listeners = mappingListeners.get(mappingKey);
// todo, remove listener from remote metadata center
if (CollectionUtils.isNotEmpty(listeners)) {
listeners.remove(listener);
listener.stop();
removeListener(subscribeURL, listener);
}
if (CollectionUtils.isEmpty(listeners)) {
mappingListeners.remove(mappingKey);
removeCachedMapping(mappingKey);
removeMappingLock(mappingKey);
}
}
return listener;
}
}
static Set<String> parseServices(String literalServices) {
return isBlank(literalServices)
? emptySet()
: unmodifiableSet(new TreeSet<>(of(literalServices.split(","))
.map(String::trim)
.filter(StringUtils::isNotEmpty)
.collect(toSet())));
}
@Override
public void putCachedMapping(String serviceKey, Set<String> apps) {
mappingCacheManager.put(serviceKey, toTreeSet(apps));
}
protected void putCachedMappingIfAbsent(String serviceKey, Set<String> apps) {
Lock lock = getMappingLock(serviceKey);
try {
lock.lock();
if (CollectionUtils.isEmpty(mappingCacheManager.get(serviceKey))) {
mappingCacheManager.put(serviceKey, toTreeSet(apps));
}
} finally {
lock.unlock();
}
}
@Override
public Set<String> getMapping(URL consumerURL) {
Set<String> mappingByUrl = ServiceNameMapping.getMappingByUrl(consumerURL);
if (mappingByUrl != null) {
return mappingByUrl;
}
return mappingCacheManager.get(ServiceNameMapping.buildMappingKey(consumerURL));
}
@Override
public Set<String> getRemoteMapping(URL consumerURL) {
return get(consumerURL);
}
@Override
public Set<String> removeCachedMapping(String serviceKey) {
return mappingCacheManager.remove(serviceKey);
}
public Lock getMappingLock(String key) {
return mappingLocks.computeIfAbsent(key, _k -> new ReentrantLock());
}
protected void removeMappingLock(String key) {
Lock lock = mappingLocks.get(key);
if (lock != null) {
try {
lock.lock();
mappingLocks.remove(key);
} finally {
lock.unlock();
}
}
}
@Override
public void $destroy() {
mappingCacheManager.destroy();
mappingListeners.clear();
mappingLocks.clear();
}
private class AsyncMappingTask implements Callable<Set<String>> {
private final MappingListener listener;
private final URL subscribedURL;
private final boolean notifyAtFirstTime;
public AsyncMappingTask(MappingListener listener, URL subscribedURL, boolean notifyAtFirstTime) {
this.listener = listener;
this.subscribedURL = subscribedURL;
this.notifyAtFirstTime = notifyAtFirstTime;
}
@Override
public Set<String> call() throws Exception {
synchronized (mappingListeners) {
Set<String> mappedServices = emptySet();
try {
String mappingKey = ServiceNameMapping.buildMappingKey(subscribedURL);
if (listener != null) {
mappedServices = toTreeSet(getAndListen(subscribedURL, listener));
Set<MappingListener> listeners =
mappingListeners.computeIfAbsent(mappingKey, _k -> new HashSet<>());
listeners.add(listener);
if (CollectionUtils.isNotEmpty(mappedServices)) {
if (notifyAtFirstTime) {
// guarantee at-least-once notification no matter what kind of underlying meta server is
// used.
// listener notification will also cause updating of mapping cache.
listener.onEvent(new MappingChangedEvent(mappingKey, mappedServices));
}
}
} else {
mappedServices = get(subscribedURL);
if (CollectionUtils.isNotEmpty(mappedServices)) {
AbstractServiceNameMapping.this.putCachedMapping(mappingKey, mappedServices);
}
}
} catch (Exception e) {
logger.error(
COMMON_FAILED_LOAD_MAPPING_CACHE,
"",
"",
"Failed getting mapping info from remote center. ",
e);
}
return mappedServices;
}
}
}
}
| 7,228 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata;
import org.apache.dubbo.common.URL;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static java.util.Collections.unmodifiableSortedSet;
import static org.apache.dubbo.common.URL.buildKey;
/**
* This service is used to expose the metadata information inside a Dubbo process.
* Typical uses include:
* 1. The Consumer queries the metadata information of the Provider to list the interfaces and each interface's configuration
* 2. The Console (dubbo-admin) queries for the metadata of a specific process, or aggregate data of all processes.
*/
public interface MetadataService {
/**
* The value of All service instances
*/
String ALL_SERVICE_INTERFACES = "*";
/**
* The contract version of {@link MetadataService}, the future update must make sure compatible.
*/
String VERSION = "1.0.0";
/**
* Gets the current Dubbo Service name
*
* @return non-null
*/
String serviceName();
/**
* Gets the version of {@link MetadataService} that always equals {@link #VERSION}
*
* @return non-null
* @see #VERSION
*/
default String version() {
return VERSION;
}
URL getMetadataURL();
/**
* the list of String that presents all Dubbo subscribed {@link URL urls}
*
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting the {@link URL URLs}
* @see #toSortedStrings(Stream)
* @see URL#toFullString()
*/
default SortedSet<String> getSubscribedURLs() {
throw new UnsupportedOperationException("This operation is not supported for consumer.");
}
/**
* Get the {@link SortedSet sorted set} of String that presents all Dubbo exported {@link URL urls}
*
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting the {@link URL URLs}
* @see #toSortedStrings(Stream)
* @see URL#toFullString()
*/
default SortedSet<String> getExportedURLs() {
return getExportedURLs(ALL_SERVICE_INTERFACES);
}
/**
* Get the {@link SortedSet sorted set} of String that presents the specified Dubbo exported {@link URL urls} by the <code>serviceInterface</code>
*
* @param serviceInterface The class name of Dubbo service interface
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting the {@link URL URLs}
* @see #toSortedStrings(Stream)
* @see URL#toFullString()
*/
default SortedSet<String> getExportedURLs(String serviceInterface) {
return getExportedURLs(serviceInterface, null);
}
/**
* Get the {@link SortedSet sorted set} of String that presents the specified Dubbo exported {@link URL urls} by the
* <code>serviceInterface</code> and <code>group</code>
*
* @param serviceInterface The class name of Dubbo service interface
* @param group the Dubbo Service Group (optional)
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting the {@link URL URLs}
* @see #toSortedStrings(Stream)
* @see URL#toFullString()
*/
default SortedSet<String> getExportedURLs(String serviceInterface, String group) {
return getExportedURLs(serviceInterface, group, null);
}
/**
* Get the {@link SortedSet sorted set} of String that presents the specified Dubbo exported {@link URL urls} by the
* <code>serviceInterface</code>, <code>group</code> and <code>version</code>
*
* @param serviceInterface The class name of Dubbo service interface
* @param group the Dubbo Service Group (optional)
* @param version the Dubbo Service Version (optional)
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting the {@link URL URLs}
* @see #toSortedStrings(Stream)
* @see URL#toFullString()
*/
default SortedSet<String> getExportedURLs(String serviceInterface, String group, String version) {
return getExportedURLs(serviceInterface, group, version, null);
}
/**
* Get the sorted set of String that presents the specified Dubbo exported {@link URL urls} by the
* <code>serviceInterface</code>, <code>group</code>, <code>version</code> and <code>protocol</code>
*
* @param serviceInterface The class name of Dubbo service interface
* @param group the Dubbo Service Group (optional)
* @param version the Dubbo Service Version (optional)
* @param protocol the Dubbo Service Protocol (optional)
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting the {@link URL URLs}
* @see #toSortedStrings(Stream)
* @see URL#toFullString()
*/
SortedSet<String> getExportedURLs(String serviceInterface, String group, String version, String protocol);
default Set<URL> getExportedServiceURLs() {
return Collections.emptySet();
}
/**
* Interface definition.
*
* @return
*/
default String getServiceDefinition(String interfaceName, String version, String group) {
return getServiceDefinition(buildKey(interfaceName, group, version));
}
String getServiceDefinition(String serviceKey);
MetadataInfo getMetadataInfo(String revision);
List<MetadataInfo> getMetadataInfos();
/**
* Convert the specified {@link Iterable} of {@link URL URLs} to be the {@link URL#toFullString() strings} presenting
* the {@link URL URLs}
*
* @param iterable {@link Iterable} of {@link URL}
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting
* @see URL#toFullString()
*/
static SortedSet<String> toSortedStrings(Iterable<URL> iterable) {
return toSortedStrings(StreamSupport.stream(iterable.spliterator(), false));
}
/**
* Convert the specified {@link Stream} of {@link URL URLs} to be the {@link URL#toFullString() strings} presenting
* the {@link URL URLs}
*
* @param stream {@link Stream} of {@link URL}
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting
* @see URL#toFullString()
*/
static SortedSet<String> toSortedStrings(Stream<URL> stream) {
return unmodifiableSortedSet(stream.map(URL::toFullString).collect(TreeSet::new, Set::add, Set::addAll));
}
static boolean isMetadataService(String interfaceName) {
return interfaceName != null && interfaceName.equals(MetadataService.class.getName());
}
/**
* Export Metadata in Service Instance of Service Discovery
* <p>
* Used for consumer to get Service Instance Metadata
* if Registry is unsupported with publishing metadata
*
* @param instanceMetadata {@link Map} of provider Service Instance Metadata
* @since 3.0
*/
void exportInstanceMetadata(String instanceMetadata);
/**
* Get all Metadata listener from local
* <p>
* Used for consumer to get Service Instance Metadata
* if Registry is unsupported with publishing metadata
*
* @return {@link Map} of {@link InstanceMetadataChangedListener}
* @since 3.0
*/
Map<String, InstanceMetadataChangedListener> getInstanceMetadataChangedListenerMap();
/**
* 1. Fetch Metadata in Service Instance of Service Discovery
* 2. Add a metadata change listener
* <p>
* Used for consumer to get Service Instance Metadata
* if Registry is unsupported with publishing metadata
*
* @param consumerId consumerId
* @param listener {@link InstanceMetadataChangedListener} used to notify event
* @return {@link Map} of provider Service Instance Metadata
* @since 3.0
*/
String getAndListenInstanceMetadata(String consumerId, InstanceMetadataChangedListener listener);
}
| 7,229 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata;
public interface MappingListener {
void onEvent(MappingChangedEvent event);
void stop();
}
| 7,230 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataConstants.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata;
public interface MetadataConstants {
String KEY_SEPARATOR = ":";
String DEFAULT_PATH_TAG = "metadata";
String KEY_REVISON_PREFIX = "revision";
String META_DATA_STORE_TAG = ".metaData";
String METADATA_PUBLISH_DELAY_KEY = "dubbo.application.metadata.publish.delay";
int DEFAULT_METADATA_PUBLISH_DELAY = 1000;
String METADATA_PROXY_TIMEOUT_KEY = "dubbo.application.metadata.proxy.delay";
int DEFAULT_METADATA_TIMEOUT_VALUE = 5000;
String REPORT_CONSUMER_URL_KEY = "report-consumer-definition";
String PATH_SEPARATOR = "/";
}
| 7,231 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataServiceDetector.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata;
import org.apache.dubbo.rpc.model.BuiltinServiceDetector;
public class MetadataServiceDetector implements BuiltinServiceDetector {
@Override
public Class<?> getService() {
return MetadataService.class;
}
}
| 7,232 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/InstanceMetadataChangedListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata;
public interface InstanceMetadataChangedListener {
/**
* Call when metadata in provider side update <p/>
* Used to notify consumer to update metadata of ServiceInstance
*
* @param metadata latest metadata
*/
void onEvent(String metadata);
/**
* Echo test
* Used to check consumer still online
*/
default String echo(String msg) {
return msg;
}
}
| 7,233 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataParamsFilter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata;
import org.apache.dubbo.common.extension.SPI;
/**
* This filter applies an either 'include' or 'exclude' policy with 'include' having higher priority.
* That means if 'include' is specified then params specified in 'exclude' will be ignored
*
* If multiple Filter extensions are provided, then,
* 1. All params specified as should be included within different Filter extension instances will determine the params that will finally be used.
* 2. If none of the Filter extensions specified any params as should be included, then the final effective params would be those left after removed all the params specified as should be excluded.
*
* It is recommended for most users to use 'exclude' policy for service params and 'include' policy for instance params.
* Please use 'params-filter=-default, -filterName1, filterName2' to activate or deactivate filter extensions.
*/
@SPI
public interface MetadataParamsFilter {
/**
* params that need to be sent to metadata center
*
* @return arrays of keys
*/
default String[] serviceParamsIncluded() {
return new String[0];
}
/**
* params that need to be excluded before sending to metadata center
*
* @return arrays of keys
*/
default String[] serviceParamsExcluded() {
return new String[0];
}
/**
* params that need to be sent to registry center
*
* @return arrays of keys
*/
default String[] instanceParamsIncluded() {
return new String[0];
}
/**
* params that need to be excluded before sending to registry center
*
* @return arrays of keys
*/
default String[] instanceParamsExcluded() {
return new String[0];
}
}
| 7,234 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ParameterTypesComparator.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata;
import java.util.Arrays;
public class ParameterTypesComparator {
private Class[] parameterTypes;
public ParameterTypesComparator(Class[] parameterTypes) {
this.parameterTypes = parameterTypes;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ParameterTypesComparator that = (ParameterTypesComparator) o;
return Arrays.equals(parameterTypes, that.parameterTypes);
}
@Override
public int hashCode() {
return Arrays.hashCode(parameterTypes);
}
public static ParameterTypesComparator getInstance(Class[] parameterTypes) {
return new ParameterTypesComparator(parameterTypes);
}
}
| 7,235 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractCacheManager.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata;
import org.apache.dubbo.common.cache.FileCacheStore;
import org.apache.dubbo.common.cache.FileCacheStoreFactory;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.resource.Disposable;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.LRUCache;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_LOAD_MAPPING_CACHE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION;
public abstract class AbstractCacheManager<V> implements Disposable {
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private ScheduledExecutorService executorService;
protected FileCacheStore cacheStore;
protected LRUCache<String, V> cache;
protected void init(
boolean enableFileCache,
String filePath,
String fileName,
int entrySize,
long fileSize,
int interval,
ScheduledExecutorService executorService) {
this.cache = new LRUCache<>(entrySize);
try {
cacheStore = FileCacheStoreFactory.getInstance(filePath, fileName, enableFileCache);
Map<String, String> properties = cacheStore.loadCache(entrySize);
if (logger.isDebugEnabled()) {
logger.debug("Successfully loaded " + getName() + " cache from file " + fileName + ", entries "
+ properties.size());
}
for (Map.Entry<String, String> entry : properties.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
this.cache.put(key, toValueType(value));
}
// executorService can be empty if FileCacheStore fails
if (executorService == null) {
this.executorService = Executors.newSingleThreadScheduledExecutor(
new NamedThreadFactory("Dubbo-cache-refreshing-scheduler", true));
} else {
this.executorService = executorService;
}
this.executorService.scheduleWithFixedDelay(
new CacheRefreshTask<>(this.cacheStore, this.cache, this, fileSize),
10,
interval,
TimeUnit.MINUTES);
} catch (Exception e) {
logger.error(COMMON_FAILED_LOAD_MAPPING_CACHE, "", "", "Load mapping from local cache file error ", e);
}
}
protected abstract V toValueType(String value);
protected abstract String getName();
public V get(String key) {
return cache.get(key);
}
public void put(String key, V apps) {
cache.put(key, apps);
}
public V remove(String key) {
return cache.remove(key);
}
public Map<String, V> getAll() {
if (cache.isEmpty()) {
return Collections.emptyMap();
}
Map<String, V> copyMap = new HashMap<>();
cache.lock();
try {
for (Map.Entry<String, V> entry : cache.entrySet()) {
copyMap.put(entry.getKey(), entry.getValue());
}
} finally {
cache.releaseLock();
}
return Collections.unmodifiableMap(copyMap);
}
public void update(Map<String, V> newCache) {
for (Map.Entry<String, V> entry : newCache.entrySet()) {
cache.put(entry.getKey(), entry.getValue());
}
}
public void destroy() {
if (executorService != null) {
executorService.shutdownNow();
try {
if (!executorService.awaitTermination(
ConfigurationUtils.reCalShutdownTime(DEFAULT_SERVER_SHUTDOWN_TIMEOUT), TimeUnit.MILLISECONDS)) {
logger.warn(
COMMON_UNEXPECTED_EXCEPTION, "", "", "Wait global executor service terminated timeout.");
}
} catch (InterruptedException e) {
logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "destroy resources failed: " + e.getMessage(), e);
}
}
if (cacheStore != null) {
cacheStore.destroy();
}
if (cache != null) {
cache.clear();
}
}
public static class CacheRefreshTask<V> implements Runnable {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private static final String DEFAULT_COMMENT = "Dubbo cache";
private final FileCacheStore cacheStore;
private final LRUCache<String, V> cache;
private final AbstractCacheManager<V> cacheManager;
private final long maxFileSize;
public CacheRefreshTask(
FileCacheStore cacheStore,
LRUCache<String, V> cache,
AbstractCacheManager<V> cacheManager,
long maxFileSize) {
this.cacheStore = cacheStore;
this.cache = cache;
this.cacheManager = cacheManager;
this.maxFileSize = maxFileSize;
}
@Override
public void run() {
Map<String, String> properties = new HashMap<>();
cache.lock();
try {
for (Map.Entry<String, V> entry : cache.entrySet()) {
properties.put(entry.getKey(), JsonUtils.toJson(entry.getValue()));
}
} finally {
cache.releaseLock();
}
if (logger.isDebugEnabled()) {
logger.debug("Dumping " + cacheManager.getName() + " caches, latest entries " + properties.size());
}
cacheStore.refreshCache(properties, DEFAULT_COMMENT, maxFileSize);
}
}
// for test unit
public FileCacheStore getCacheStore() {
return cacheStore;
}
public LRUCache<String, V> getCache() {
return cache;
}
}
| 7,236 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReport.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.report;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.metadata.MappingListener;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
public interface MetadataReport {
/**
* Service Definition -- START
**/
void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition);
String getServiceDefinition(MetadataIdentifier metadataIdentifier);
/**
* Application Metadata -- START
**/
default void publishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) {}
default void unPublishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) {}
default MetadataInfo getAppMetadata(SubscriberMetadataIdentifier identifier, Map<String, String> instanceMetadata) {
return null;
}
/**
* deprecated or need triage
**/
void storeConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, Map<String, String> serviceParameterMap);
List<String> getExportedURLs(ServiceMetadataIdentifier metadataIdentifier);
void destroy();
void saveServiceMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url);
void removeServiceMetadata(ServiceMetadataIdentifier metadataIdentifier);
void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, Set<String> urls);
List<String> getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier);
default ConfigItem getConfigItem(String key, String group) {
return new ConfigItem();
}
default boolean registerServiceAppMapping(
String serviceInterface, String defaultMappingGroup, String newConfigContent, Object ticket) {
return false;
}
default boolean registerServiceAppMapping(String serviceKey, String application, URL url) {
return false;
}
default void removeServiceAppMappingListener(String serviceKey, MappingListener listener) {}
/**
* Service<-->Application Mapping -- START
**/
default Set<String> getServiceAppMapping(String serviceKey, MappingListener listener, URL url) {
return Collections.emptySet();
}
default Set<String> getServiceAppMapping(String serviceKey, URL url) {
return Collections.emptySet();
}
boolean shouldReportDefinition();
boolean shouldReportMetadata();
}
| 7,237 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.report;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.metadata.report.MetadataReportFactory.DEFAULT;
/**
*/
@SPI(DEFAULT)
public interface MetadataReportFactory {
String DEFAULT = "redis";
@Adaptive({PROTOCOL_KEY})
MetadataReport getMetadataReport(URL url);
default void destroy() {}
}
| 7,238 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataScopeModelInitializer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.report;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
public class MetadataScopeModelInitializer implements ScopeModelInitializer {
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {}
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {
ScopeBeanFactory beanFactory = applicationModel.getBeanFactory();
beanFactory.registerBean(MetadataReportInstance.class);
}
@Override
public void initializeModuleModel(ModuleModel moduleModel) {}
}
| 7,239 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.report;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.resource.Disposable;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.metadata.report.support.NopMetadataReport;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_DIRECTORY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.CommonConstants.PORT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_LOCAL_FILE_CACHE_ENABLED;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
import static org.apache.dubbo.metadata.report.support.Constants.METADATA_REPORT_KEY;
/**
* Repository of MetadataReport instances that can talk to remote metadata server.
*
* MetadataReport instances are initiated during the beginning of deployer.start() and used by components that
* need to interact with metadata server.
*
* If multiple metadata reports and registries need to be declared, it is recommended to group each two metadata report and registry together by giving them the same id:
* <dubbo:registry id=demo1 address="registry://"/>
* <dubbo:metadata id=demo1 address="metadata://"/>
*
* <dubbo:registry id=demo2 address="registry://"/>
* <dubbo:metadata id=demo2 address="metadata://"/>
*/
public class MetadataReportInstance implements Disposable {
private AtomicBoolean init = new AtomicBoolean(false);
private String metadataType;
// mapping of registry id to metadata report instance, registry instances will use this mapping to find related
// metadata reports
private final Map<String, MetadataReport> metadataReports = new HashMap<>();
private final ApplicationModel applicationModel;
private final NopMetadataReport nopMetadataReport;
public MetadataReportInstance(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
this.nopMetadataReport = new NopMetadataReport();
}
public void init(List<MetadataReportConfig> metadataReportConfigs) {
if (!init.compareAndSet(false, true)) {
return;
}
this.metadataType = applicationModel
.getApplicationConfigManager()
.getApplicationOrElseThrow()
.getMetadataType();
if (metadataType == null) {
this.metadataType = DEFAULT_METADATA_STORAGE_TYPE;
}
MetadataReportFactory metadataReportFactory =
applicationModel.getExtensionLoader(MetadataReportFactory.class).getAdaptiveExtension();
for (MetadataReportConfig metadataReportConfig : metadataReportConfigs) {
init(metadataReportConfig, metadataReportFactory);
}
}
private void init(MetadataReportConfig config, MetadataReportFactory metadataReportFactory) {
URL url = config.toUrl();
if (METADATA_REPORT_KEY.equals(url.getProtocol())) {
String protocol = url.getParameter(METADATA_REPORT_KEY, DEFAULT_DIRECTORY);
url = URLBuilder.from(url)
.setProtocol(protocol)
.setPort(url.getParameter(PORT_KEY, url.getPort()))
.setScopeModel(config.getScopeModel())
.removeParameter(METADATA_REPORT_KEY)
.build();
}
url = url.addParameterIfAbsent(
APPLICATION_KEY, applicationModel.getCurrentConfig().getName());
url = url.addParameterIfAbsent(
REGISTRY_LOCAL_FILE_CACHE_ENABLED,
String.valueOf(applicationModel.getCurrentConfig().getEnableFileCache()));
String relatedRegistryId = isEmpty(config.getRegistry())
? (isEmpty(config.getId()) ? DEFAULT_KEY : config.getId())
: config.getRegistry();
// RegistryConfig registryConfig = applicationModel.getConfigManager().getRegistry(relatedRegistryId)
// .orElseThrow(() -> new IllegalStateException("Registry id " + relatedRegistryId + " does not
// exist."));
MetadataReport metadataReport = metadataReportFactory.getMetadataReport(url);
if (metadataReport != null) {
metadataReports.put(relatedRegistryId, metadataReport);
}
}
public Map<String, MetadataReport> getMetadataReports(boolean checked) {
return metadataReports;
}
public MetadataReport getMetadataReport(String registryKey) {
MetadataReport metadataReport = metadataReports.get(registryKey);
if (metadataReport == null && metadataReports.size() > 0) {
metadataReport = metadataReports.values().iterator().next();
}
return metadataReport;
}
public MetadataReport getNopMetadataReport() {
return nopMetadataReport;
}
public String getMetadataType() {
return metadataType;
}
public boolean inited() {
return init.get();
}
@Override
public void destroy() {
metadataReports.forEach((_k, reporter) -> {
reporter.destroy();
});
metadataReports.clear();
}
}
| 7,240 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/SubscriberMetadataIdentifier.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.report.identifier;
import org.apache.dubbo.common.URL;
import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY;
/**
* 2019-08-12
*/
public class SubscriberMetadataIdentifier extends BaseApplicationMetadataIdentifier implements BaseMetadataIdentifier {
private String revision;
public SubscriberMetadataIdentifier() {}
public SubscriberMetadataIdentifier(String application, String revision) {
this.application = application;
this.revision = revision;
}
public SubscriberMetadataIdentifier(URL url) {
this.application = url.getApplication("");
this.revision = url.getParameter(REVISION_KEY, "");
}
public String getUniqueKey(KeyTypeEnum keyType) {
return super.getUniqueKey(keyType, revision);
}
public String getIdentifierKey() {
return super.getIdentifierKey(revision);
}
public String getApplication() {
return application;
}
public void setApplication(String application) {
this.application = application;
}
public String getRevision() {
return revision;
}
public void setRevision(String revision) {
this.revision = revision;
}
}
| 7,241 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseServiceMetadataIdentifier.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.report.identifier;
import org.apache.dubbo.common.URL;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
import static org.apache.dubbo.metadata.MetadataConstants.DEFAULT_PATH_TAG;
/**
* The Base class of MetadataIdentifier for service scope
* <p>
* 2019-08-09
*/
public class BaseServiceMetadataIdentifier {
protected String serviceInterface;
protected String version;
protected String group;
protected String side;
protected String getUniqueKey(KeyTypeEnum keyType, String... params) {
if (keyType == KeyTypeEnum.PATH) {
return getFilePathKey(params);
}
return getIdentifierKey(params);
}
protected String getIdentifierKey(String... params) {
String prefix = KeyTypeEnum.UNIQUE_KEY.build(serviceInterface, version, group, side);
return KeyTypeEnum.UNIQUE_KEY.build(prefix, params);
}
private String getFilePathKey(String... params) {
return getFilePathKey(DEFAULT_PATH_TAG, params);
}
private String getFilePathKey(String pathTag, String... params) {
String prefix = KeyTypeEnum.PATH.build(pathTag, toServicePath(), version, group, side);
return KeyTypeEnum.PATH.build(prefix, params);
}
private String toServicePath() {
if (ANY_VALUE.equals(serviceInterface)) {
return "";
}
return URL.encode(serviceInterface);
}
}
| 7,242 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifier.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.report.identifier;
import org.apache.dubbo.common.URL;
/**
* The MetadataIdentifier is used to store method descriptor.
* <p>
* The name of class is reserved because of it has been used in the previous version.
* <p>
* 2018/10/25
*/
public class MetadataIdentifier extends BaseServiceMetadataIdentifier implements BaseMetadataIdentifier {
private String application;
public MetadataIdentifier() {}
public MetadataIdentifier(String serviceInterface, String version, String group, String side, String application) {
this.serviceInterface = serviceInterface;
this.version = version;
this.group = group;
this.side = side;
this.application = application;
}
public MetadataIdentifier(URL url) {
this.serviceInterface = url.getServiceInterface();
this.version = url.getVersion();
this.group = url.getGroup();
this.side = url.getSide();
setApplication(url.getApplication());
}
public String getUniqueKey(KeyTypeEnum keyType) {
return super.getUniqueKey(keyType, application);
}
public String getIdentifierKey() {
return super.getIdentifierKey(application);
}
public String getServiceInterface() {
return serviceInterface;
}
public void setServiceInterface(String serviceInterface) {
this.serviceInterface = serviceInterface;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getSide() {
return side;
}
public void setSide(String side) {
this.side = side;
}
public String getApplication() {
return application;
}
public void setApplication(String application) {
this.application = application;
}
public String getUniqueServiceName() {
return serviceInterface != null ? URL.buildKey(serviceInterface, getGroup(), getVersion()) : null;
}
@Override
public String toString() {
return "MetadataIdentifier{" + "application='"
+ application + '\'' + ", serviceInterface='"
+ serviceInterface + '\'' + ", version='"
+ version + '\'' + ", group='"
+ group + '\'' + ", side='"
+ side + '\'' + '}';
}
}
| 7,243 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/KeyTypeEnum.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.report.identifier;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR;
import static org.apache.dubbo.common.utils.PathUtils.buildPath;
import static org.apache.dubbo.common.utils.StringUtils.EMPTY_STRING;
import static org.apache.dubbo.common.utils.StringUtils.isBlank;
import static org.apache.dubbo.metadata.MetadataConstants.KEY_SEPARATOR;
/**
* 2019-08-15
*/
public enum KeyTypeEnum {
PATH(PATH_SEPARATOR) {
public String build(String one, String... others) {
return buildPath(one, others);
}
},
UNIQUE_KEY(KEY_SEPARATOR) {
public String build(String one, String... others) {
StringBuilder keyBuilder = new StringBuilder(one);
for (String other : others) {
keyBuilder.append(separator).append(isBlank(other) ? EMPTY_STRING : other);
}
return keyBuilder.toString();
}
};
final String separator;
KeyTypeEnum(String separator) {
this.separator = separator;
}
/**
* Build Key
*
* @param one one
* @param others the others
* @return
* @since 2.7.8
*/
public abstract String build(String one, String... others);
}
| 7,244 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/ServiceMetadataIdentifier.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.report.identifier;
import org.apache.dubbo.common.URL;
import static org.apache.dubbo.metadata.MetadataConstants.KEY_REVISON_PREFIX;
/**
* The ServiceMetadataIdentifier is used to store the {@link org.apache.dubbo.common.URL}
* that are from provider and consumer
* <p>
* 2019-08-09
*/
public class ServiceMetadataIdentifier extends BaseServiceMetadataIdentifier implements BaseMetadataIdentifier {
private String revision;
private String protocol;
public ServiceMetadataIdentifier() {}
public ServiceMetadataIdentifier(
String serviceInterface, String version, String group, String side, String revision, String protocol) {
this.serviceInterface = serviceInterface;
this.version = version;
this.group = group;
this.side = side;
this.revision = revision;
this.protocol = protocol;
}
public ServiceMetadataIdentifier(URL url) {
this.serviceInterface = url.getServiceInterface();
this.version = url.getVersion();
this.group = url.getGroup();
this.side = url.getSide();
this.protocol = url.getProtocol();
}
public String getUniqueKey(KeyTypeEnum keyType) {
return super.getUniqueKey(keyType, protocol, KEY_REVISON_PREFIX + revision);
}
public String getIdentifierKey() {
return super.getIdentifierKey(protocol, KEY_REVISON_PREFIX + revision);
}
public void setRevision(String revision) {
this.revision = revision;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
@Override
public String toString() {
return "ServiceMetadataIdentifier{" + "revision='"
+ revision + '\'' + ", protocol='"
+ protocol + '\'' + ", serviceInterface='"
+ serviceInterface + '\'' + ", version='"
+ version + '\'' + ", group='"
+ group + '\'' + ", side='"
+ side + '\'' + "} "
+ super.toString();
}
}
| 7,245 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseMetadataIdentifier.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.report.identifier;
public interface BaseMetadataIdentifier {
String getUniqueKey(KeyTypeEnum keyType);
String getIdentifierKey();
}
| 7,246 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseApplicationMetadataIdentifier.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.report.identifier;
import static org.apache.dubbo.metadata.MetadataConstants.DEFAULT_PATH_TAG;
/**
* The Base class of MetadataIdentifier for application scope
* <p>
* 2019-08-09
*/
public class BaseApplicationMetadataIdentifier {
protected String application;
protected String getUniqueKey(KeyTypeEnum keyType, String... params) {
if (keyType == KeyTypeEnum.PATH) {
return getFilePathKey(params);
}
return getIdentifierKey(params);
}
protected String getIdentifierKey(String... params) {
return KeyTypeEnum.UNIQUE_KEY.build(application, params);
}
private String getFilePathKey(String... params) {
return getFilePathKey(DEFAULT_PATH_TAG, params);
}
private String getFilePathKey(String pathTag, String... params) {
String prefix = KeyTypeEnum.PATH.build(pathTag, application);
return KeyTypeEnum.PATH.build(prefix, params);
}
}
| 7,247 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.report.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.MetadataReportFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED_EXPORT_SERVICE;
public abstract class AbstractMetadataReportFactory implements MetadataReportFactory {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AbstractMetadataReportFactory.class);
private static final String EXPORT_KEY = "export";
private static final String REFER_KEY = "refer";
/**
* The lock for the acquisition process of the registry
*/
private final ReentrantLock lock = new ReentrantLock();
/**
* Registry Collection Map<metadataAddress, MetadataReport>
*/
private final Map<String, MetadataReport> serviceStoreMap = new ConcurrentHashMap<>();
@Override
public MetadataReport getMetadataReport(URL url) {
url = url.setPath(MetadataReport.class.getName()).removeParameters(EXPORT_KEY, REFER_KEY);
String key = url.toServiceString();
MetadataReport metadataReport = serviceStoreMap.get(key);
if (metadataReport != null) {
return metadataReport;
}
// Lock the metadata access process to ensure a single instance of the metadata instance
lock.lock();
try {
metadataReport = serviceStoreMap.get(key);
if (metadataReport != null) {
return metadataReport;
}
boolean check = url.getParameter(CHECK_KEY, true) && url.getPort() != 0;
try {
metadataReport = createMetadataReport(url);
} catch (Exception e) {
if (!check) {
logger.warn(PROXY_FAILED_EXPORT_SERVICE, "", "", "The metadata reporter failed to initialize", e);
} else {
throw e;
}
}
if (check && metadataReport == null) {
throw new IllegalStateException("Can not create metadata Report " + url);
}
if (metadataReport != null) {
serviceStoreMap.put(key, metadataReport);
}
return metadataReport;
} finally {
// Release the lock
lock.unlock();
}
}
@Override
public void destroy() {
lock.lock();
try {
for (MetadataReport metadataReport : serviceStoreMap.values()) {
try {
metadataReport.destroy();
} catch (Throwable ignored) {
// ignored
logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", ignored.getMessage(), ignored);
}
}
serviceStoreMap.clear();
} finally {
lock.unlock();
}
}
protected abstract MetadataReport createMetadataReport(URL url);
}
| 7,248 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.report.support;
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.CollectionUtils;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.metadata.definition.model.FullServiceDefinition;
import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.metadata.event.MetadataEvent;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.CYCLE_REPORT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_LOCAL_FILE_CACHE_ENABLED;
import static org.apache.dubbo.common.constants.CommonConstants.REPORT_DEFINITION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REPORT_METADATA_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.RETRY_PERIOD_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.RETRY_TIMES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SYNC_REPORT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED_EXPORT_SERVICE;
import static org.apache.dubbo.common.utils.StringUtils.replace;
import static org.apache.dubbo.metadata.report.support.Constants.CACHE;
import static org.apache.dubbo.metadata.report.support.Constants.DEFAULT_METADATA_REPORT_CYCLE_REPORT;
import static org.apache.dubbo.metadata.report.support.Constants.DEFAULT_METADATA_REPORT_RETRY_PERIOD;
import static org.apache.dubbo.metadata.report.support.Constants.DEFAULT_METADATA_REPORT_RETRY_TIMES;
import static org.apache.dubbo.metadata.report.support.Constants.DUBBO_METADATA;
import static org.apache.dubbo.metadata.report.support.Constants.USER_HOME;
public abstract class AbstractMetadataReport implements MetadataReport {
protected static final String DEFAULT_ROOT = "dubbo";
private static final int ONE_DAY_IN_MILLISECONDS = 60 * 24 * 60 * 1000;
private static final int FOUR_HOURS_IN_MILLISECONDS = 60 * 4 * 60 * 1000;
// Log output
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
// Local disk cache, where the special key value.registries records the list of metadata centers, and the others are
// the list of notified service providers
final Properties properties = new Properties();
private final ExecutorService reportCacheExecutor =
Executors.newFixedThreadPool(1, new NamedThreadFactory("DubboSaveMetadataReport", true));
final Map<MetadataIdentifier, Object> allMetadataReports = new ConcurrentHashMap<>(4);
private final AtomicLong lastCacheChanged = new AtomicLong();
final Map<MetadataIdentifier, Object> failedReports = new ConcurrentHashMap<>(4);
private URL reportURL;
boolean syncReport;
// Local disk cache file
File file;
private AtomicBoolean initialized = new AtomicBoolean(false);
public MetadataReportRetry metadataReportRetry;
private ScheduledExecutorService reportTimerScheduler;
private final boolean reportMetadata;
private final boolean reportDefinition;
protected ApplicationModel applicationModel;
public AbstractMetadataReport(URL reportServerURL) {
setUrl(reportServerURL);
applicationModel = reportServerURL.getOrDefaultApplicationModel();
boolean localCacheEnabled = reportServerURL.getParameter(REGISTRY_LOCAL_FILE_CACHE_ENABLED, true);
// Start file save timer
String defaultFilename = System.getProperty(USER_HOME) + DUBBO_METADATA + reportServerURL.getApplication()
+ "-" + replace(reportServerURL.getAddress(), ":", "-")
+ CACHE;
String filename = reportServerURL.getParameter(FILE_KEY, defaultFilename);
File file = null;
if (localCacheEnabled && ConfigUtils.isNotEmpty(filename)) {
file = new File(filename);
if (!file.exists()
&& file.getParentFile() != null
&& !file.getParentFile().exists()) {
if (!file.getParentFile().mkdirs()) {
throw new IllegalArgumentException("Invalid service store file " + file
+ ", cause: Failed to create directory " + file.getParentFile() + "!");
}
}
// if this file exists, firstly delete it.
if (!initialized.getAndSet(true) && file.exists()) {
file.delete();
}
}
this.file = file;
loadProperties();
syncReport = reportServerURL.getParameter(SYNC_REPORT_KEY, false);
metadataReportRetry = new MetadataReportRetry(
reportServerURL.getParameter(RETRY_TIMES_KEY, DEFAULT_METADATA_REPORT_RETRY_TIMES),
reportServerURL.getParameter(RETRY_PERIOD_KEY, DEFAULT_METADATA_REPORT_RETRY_PERIOD));
// cycle report the data switch
if (reportServerURL.getParameter(CYCLE_REPORT_KEY, DEFAULT_METADATA_REPORT_CYCLE_REPORT)) {
reportTimerScheduler = Executors.newSingleThreadScheduledExecutor(
new NamedThreadFactory("DubboMetadataReportTimer", true));
reportTimerScheduler.scheduleAtFixedRate(
this::publishAll, calculateStartTime(), ONE_DAY_IN_MILLISECONDS, TimeUnit.MILLISECONDS);
}
this.reportMetadata = reportServerURL.getParameter(REPORT_METADATA_KEY, false);
this.reportDefinition = reportServerURL.getParameter(REPORT_DEFINITION_KEY, true);
}
public URL getUrl() {
return reportURL;
}
protected void setUrl(URL url) {
if (url == null) {
throw new IllegalArgumentException("metadataReport url == null");
}
this.reportURL = url;
}
private void doSaveProperties(long version) {
if (version < lastCacheChanged.get()) {
return;
}
if (file == null) {
return;
}
// Save
try {
File lockfile = new File(file.getAbsolutePath() + ".lock");
if (!lockfile.exists()) {
lockfile.createNewFile();
}
try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw");
FileChannel channel = raf.getChannel()) {
FileLock lock = channel.tryLock();
if (lock == null) {
throw new IOException(
"Can not lock the metadataReport cache file " + file.getAbsolutePath()
+ ", ignore and retry later, maybe multi java process use the file, please config: dubbo.metadata.file=xxx.properties");
}
// Save
try {
if (!file.exists()) {
file.createNewFile();
}
Properties tmpProperties;
if (!syncReport) {
// When syncReport = false, properties.setProperty and properties.store are called from the same
// thread(reportCacheExecutor), so deep copy is not required
tmpProperties = properties;
} else {
// Using store method and setProperty method of the this.properties will cause lock contention
// under multi-threading, so deep copy a new container
tmpProperties = new Properties();
Set<Map.Entry<Object, Object>> entries = properties.entrySet();
for (Map.Entry<Object, Object> entry : entries) {
tmpProperties.setProperty((String) entry.getKey(), (String) entry.getValue());
}
}
try (FileOutputStream outputFile = new FileOutputStream(file)) {
tmpProperties.store(outputFile, "Dubbo metadataReport Cache");
}
} finally {
lock.release();
}
}
} catch (Throwable e) {
if (version < lastCacheChanged.get()) {
return;
} else {
reportCacheExecutor.execute(new SaveProperties(lastCacheChanged.incrementAndGet()));
}
logger.warn(
COMMON_UNEXPECTED_EXCEPTION,
"",
"",
"Failed to save service store file, cause: " + e.getMessage(),
e);
}
}
void loadProperties() {
if (file != null && file.exists()) {
try (InputStream in = new FileInputStream(file)) {
properties.load(in);
if (logger.isInfoEnabled()) {
logger.info("Load service store file " + file + ", data: " + properties);
}
} catch (Throwable e) {
logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to load service store file" + file, e);
}
}
}
private void saveProperties(MetadataIdentifier metadataIdentifier, String value, boolean add, boolean sync) {
if (file == null) {
return;
}
try {
if (add) {
properties.setProperty(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), value);
} else {
properties.remove(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY));
}
long version = lastCacheChanged.incrementAndGet();
if (sync) {
new SaveProperties(version).run();
} else {
reportCacheExecutor.execute(new SaveProperties(version));
}
} catch (Throwable t) {
logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t);
}
}
@Override
public String toString() {
return getUrl().toString();
}
private class SaveProperties implements Runnable {
private long version;
private SaveProperties(long version) {
this.version = version;
}
@Override
public void run() {
doSaveProperties(version);
}
}
@Override
public void storeProviderMetadata(
MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) {
if (syncReport) {
storeProviderMetadataTask(providerMetadataIdentifier, serviceDefinition);
} else {
reportCacheExecutor.execute(() -> storeProviderMetadataTask(providerMetadataIdentifier, serviceDefinition));
}
}
private void storeProviderMetadataTask(
MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) {
MetadataEvent metadataEvent = MetadataEvent.toServiceSubscribeEvent(
applicationModel, providerMetadataIdentifier.getUniqueServiceName());
MetricsEventBus.post(
metadataEvent,
() -> {
boolean result = true;
try {
if (logger.isInfoEnabled()) {
logger.info("store provider metadata. Identifier : " + providerMetadataIdentifier
+ "; definition: " + serviceDefinition);
}
allMetadataReports.put(providerMetadataIdentifier, serviceDefinition);
failedReports.remove(providerMetadataIdentifier);
String data = JsonUtils.toJson(serviceDefinition);
doStoreProviderMetadata(providerMetadataIdentifier, data);
saveProperties(providerMetadataIdentifier, data, true, !syncReport);
} catch (Exception e) {
// retry again. If failed again, throw exception.
failedReports.put(providerMetadataIdentifier, serviceDefinition);
metadataReportRetry.startRetryTask();
logger.error(
PROXY_FAILED_EXPORT_SERVICE,
"",
"",
"Failed to put provider metadata " + providerMetadataIdentifier + " in "
+ serviceDefinition + ", cause: " + e.getMessage(),
e);
result = false;
}
return result;
},
aBoolean -> aBoolean);
}
@Override
public void storeConsumerMetadata(
MetadataIdentifier consumerMetadataIdentifier, Map<String, String> serviceParameterMap) {
if (syncReport) {
storeConsumerMetadataTask(consumerMetadataIdentifier, serviceParameterMap);
} else {
reportCacheExecutor.execute(
() -> storeConsumerMetadataTask(consumerMetadataIdentifier, serviceParameterMap));
}
}
protected void storeConsumerMetadataTask(
MetadataIdentifier consumerMetadataIdentifier, Map<String, String> serviceParameterMap) {
try {
if (logger.isInfoEnabled()) {
logger.info("store consumer metadata. Identifier : " + consumerMetadataIdentifier + "; definition: "
+ serviceParameterMap);
}
allMetadataReports.put(consumerMetadataIdentifier, serviceParameterMap);
failedReports.remove(consumerMetadataIdentifier);
String data = JsonUtils.toJson(serviceParameterMap);
doStoreConsumerMetadata(consumerMetadataIdentifier, data);
saveProperties(consumerMetadataIdentifier, data, true, !syncReport);
} catch (Exception e) {
// retry again. If failed again, throw exception.
failedReports.put(consumerMetadataIdentifier, serviceParameterMap);
metadataReportRetry.startRetryTask();
logger.error(
PROXY_FAILED_EXPORT_SERVICE,
"",
"",
"Failed to put consumer metadata " + consumerMetadataIdentifier + "; " + serviceParameterMap
+ ", cause: " + e.getMessage(),
e);
}
}
@Override
public void destroy() {
if (reportCacheExecutor != null) {
reportCacheExecutor.shutdown();
}
if (reportTimerScheduler != null) {
reportTimerScheduler.shutdown();
}
if (metadataReportRetry != null) {
metadataReportRetry.destroy();
metadataReportRetry = null;
}
}
@Override
public void saveServiceMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) {
if (syncReport) {
doSaveMetadata(metadataIdentifier, url);
} else {
reportCacheExecutor.execute(() -> doSaveMetadata(metadataIdentifier, url));
}
}
@Override
public void removeServiceMetadata(ServiceMetadataIdentifier metadataIdentifier) {
if (syncReport) {
doRemoveMetadata(metadataIdentifier);
} else {
reportCacheExecutor.execute(() -> doRemoveMetadata(metadataIdentifier));
}
}
@Override
public List<String> getExportedURLs(ServiceMetadataIdentifier metadataIdentifier) {
// TODO, fallback to local cache
return doGetExportedURLs(metadataIdentifier);
}
@Override
public void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, Set<String> urls) {
if (syncReport) {
doSaveSubscriberData(subscriberMetadataIdentifier, JsonUtils.toJson(urls));
} else {
reportCacheExecutor.execute(
() -> doSaveSubscriberData(subscriberMetadataIdentifier, JsonUtils.toJson(urls)));
}
}
@Override
public List<String> getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) {
String content = doGetSubscribedURLs(subscriberMetadataIdentifier);
return JsonUtils.toJavaList(content, String.class);
}
String getProtocol(URL url) {
String protocol = url.getSide();
protocol = protocol == null ? url.getProtocol() : protocol;
return protocol;
}
/**
* @return if need to continue
*/
public boolean retry() {
return doHandleMetadataCollection(failedReports);
}
@Override
public boolean shouldReportDefinition() {
return reportDefinition;
}
@Override
public boolean shouldReportMetadata() {
return reportMetadata;
}
private boolean doHandleMetadataCollection(Map<MetadataIdentifier, Object> metadataMap) {
if (metadataMap.isEmpty()) {
return true;
}
Iterator<Map.Entry<MetadataIdentifier, Object>> iterable =
metadataMap.entrySet().iterator();
while (iterable.hasNext()) {
Map.Entry<MetadataIdentifier, Object> item = iterable.next();
if (PROVIDER_SIDE.equals(item.getKey().getSide())) {
this.storeProviderMetadata(item.getKey(), (FullServiceDefinition) item.getValue());
} else if (CONSUMER_SIDE.equals(item.getKey().getSide())) {
this.storeConsumerMetadata(item.getKey(), (Map) item.getValue());
}
}
return false;
}
/**
* not private. just for unittest.
*/
void publishAll() {
logger.info("start to publish all metadata.");
this.doHandleMetadataCollection(allMetadataReports);
}
/**
* between 2:00 am to 6:00 am, the time is random.
*
* @return
*/
long calculateStartTime() {
Calendar calendar = Calendar.getInstance();
long nowMill = calendar.getTimeInMillis();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long subtract = calendar.getTimeInMillis() + ONE_DAY_IN_MILLISECONDS - nowMill;
return subtract
+ (FOUR_HOURS_IN_MILLISECONDS / 2)
+ ThreadLocalRandom.current().nextInt(FOUR_HOURS_IN_MILLISECONDS);
}
class MetadataReportRetry {
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
final ScheduledExecutorService retryExecutor =
Executors.newScheduledThreadPool(0, new NamedThreadFactory("DubboMetadataReportRetryTimer", true));
volatile ScheduledFuture retryScheduledFuture;
final AtomicInteger retryCounter = new AtomicInteger(0);
// retry task schedule period
long retryPeriod;
// if no failed report, wait how many times to run retry task.
int retryTimesIfNonFail = 600;
int retryLimit;
public MetadataReportRetry(int retryTimes, int retryPeriod) {
this.retryPeriod = retryPeriod;
this.retryLimit = retryTimes;
}
void startRetryTask() {
if (retryScheduledFuture == null) {
synchronized (retryCounter) {
if (retryScheduledFuture == null) {
retryScheduledFuture = retryExecutor.scheduleWithFixedDelay(
() -> {
// Check and connect to the metadata
try {
int times = retryCounter.incrementAndGet();
logger.info("start to retry task for metadata report. retry times:" + times);
if (retry() && times > retryTimesIfNonFail) {
cancelRetryTask();
}
if (times > retryLimit) {
cancelRetryTask();
}
} catch (Throwable t) { // Defensive fault tolerance
logger.error(
COMMON_UNEXPECTED_EXCEPTION,
"",
"",
"Unexpected error occur at failed retry, cause: " + t.getMessage(),
t);
}
},
500,
retryPeriod,
TimeUnit.MILLISECONDS);
}
}
}
}
void cancelRetryTask() {
if (retryScheduledFuture != null) {
retryScheduledFuture.cancel(false);
}
retryExecutor.shutdown();
}
void destroy() {
cancelRetryTask();
}
/**
* @deprecated only for test
*/
@Deprecated
ScheduledExecutorService getRetryExecutor() {
return retryExecutor;
}
}
private void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, List<String> urls) {
if (CollectionUtils.isEmpty(urls)) {
return;
}
List<String> encodedUrlList = new ArrayList<>(urls.size());
for (String url : urls) {
encodedUrlList.add(URL.encode(url));
}
doSaveSubscriberData(subscriberMetadataIdentifier, encodedUrlList);
}
protected abstract void doStoreProviderMetadata(
MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions);
protected abstract void doStoreConsumerMetadata(
MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString);
protected abstract void doSaveMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url);
protected abstract void doRemoveMetadata(ServiceMetadataIdentifier metadataIdentifier);
protected abstract List<String> doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier);
protected abstract void doSaveSubscriberData(
SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urlListStr);
protected abstract String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier);
/**
* @deprecated only for unit test
*/
@Deprecated
protected ExecutorService getReportCacheExecutor() {
return reportCacheExecutor;
}
/**
* @deprecated only for unit test
*/
@Deprecated
protected MetadataReportRetry getMetadataReportRetry() {
return metadataReportRetry;
}
}
| 7,249 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/NopMetadataReport.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.report.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class NopMetadataReport implements MetadataReport {
public NopMetadataReport() {}
@Override
public void storeProviderMetadata(
MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) {}
@Override
public String getServiceDefinition(MetadataIdentifier metadataIdentifier) {
return null;
}
@Override
public void storeConsumerMetadata(
MetadataIdentifier consumerMetadataIdentifier, Map<String, String> serviceParameterMap) {}
@Override
public List<String> getExportedURLs(ServiceMetadataIdentifier metadataIdentifier) {
return null;
}
@Override
public void destroy() {}
@Override
public void saveServiceMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) {}
@Override
public void removeServiceMetadata(ServiceMetadataIdentifier metadataIdentifier) {}
@Override
public void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, Set<String> urls) {}
@Override
public List<String> getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) {
return null;
}
@Override
public boolean shouldReportDefinition() {
return true;
}
@Override
public boolean shouldReportMetadata() {
return false;
}
}
| 7,250 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/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.metadata.report.support;
public interface Constants {
String METADATA_REPORT_KEY = "metadata";
Integer DEFAULT_METADATA_REPORT_RETRY_TIMES = 100;
Integer DEFAULT_METADATA_REPORT_RETRY_PERIOD = 3000;
Boolean DEFAULT_METADATA_REPORT_CYCLE_REPORT = true;
String USER_HOME = "user.home";
String CACHE = ".cache";
String DUBBO_METADATA = "/.dubbo/dubbo-metadata-";
}
| 7,251 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractServiceRestMetadataResolver.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.common.compact.Dubbo2CompactUtils;
import org.apache.dubbo.common.utils.MethodComparator;
import org.apache.dubbo.common.utils.ServiceAnnotationResolver;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.metadata.definition.MethodDefinitionBuilder;
import org.apache.dubbo.metadata.definition.model.MethodDefinition;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import static java.util.Collections.emptyList;
import static java.util.Collections.sort;
import static java.util.Collections.unmodifiableMap;
import static org.apache.dubbo.common.function.ThrowableFunction.execute;
import static org.apache.dubbo.common.utils.AnnotationUtils.isAnnotationPresent;
import static org.apache.dubbo.common.utils.AnnotationUtils.isAnyAnnotationPresent;
import static org.apache.dubbo.common.utils.ClassUtils.forName;
import static org.apache.dubbo.common.utils.ClassUtils.getAllInterfaces;
import static org.apache.dubbo.common.utils.MemberUtils.isPrivate;
import static org.apache.dubbo.common.utils.MemberUtils.isStatic;
import static org.apache.dubbo.common.utils.MethodUtils.excludedDeclaredClass;
import static org.apache.dubbo.common.utils.MethodUtils.getAllMethods;
import static org.apache.dubbo.common.utils.MethodUtils.overrides;
/**
* The abstract {@link ServiceRestMetadataResolver} class to provider some template methods assemble the instance of
* {@link ServiceRestMetadata} will extended by the sub-classes.
*
* @since 2.7.6
*/
public abstract class AbstractServiceRestMetadataResolver implements ServiceRestMetadataResolver {
private final Map<String, List<AnnotatedMethodParameterProcessor>> parameterProcessorsMap;
private final Set<NoAnnotatedParameterRequestTagProcessor> noAnnotatedParameterRequestTagProcessors;
public AbstractServiceRestMetadataResolver(ApplicationModel applicationModel) {
this.parameterProcessorsMap = loadAnnotatedMethodParameterProcessors(applicationModel);
this.noAnnotatedParameterRequestTagProcessors = loadNoAnnotatedMethodParameterProcessors(applicationModel);
}
@Override
public final boolean supports(Class<?> serviceType) {
return supports(serviceType, false);
}
@Override
public final boolean supports(Class<?> serviceType, boolean consumer) {
if (serviceType == null) {
return false;
}
// for consumer
// it is possible serviceType is impl
// for provider
// for xml config bean && isServiceAnnotationPresent(serviceType)
// isImplementedInterface(serviceType) SpringController
return supports0(serviceType);
}
protected final boolean isImplementedInterface(Class<?> serviceType) {
return !getAllInterfaces(serviceType).isEmpty();
}
protected final boolean isServiceAnnotationPresent(Class<?> serviceType) {
if (Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isServiceClassLoaded()) {
return isAnyAnnotationPresent(
serviceType, DubboService.class, Service.class, Dubbo2CompactUtils.getServiceClass());
} else {
return isAnyAnnotationPresent(serviceType, DubboService.class, Service.class);
}
}
/**
* internal support method
*
* @param serviceType Dubbo Service interface or type
* @return If supports, return <code>true</code>, or <code>false</code>
*/
protected abstract boolean supports0(Class<?> serviceType);
@Override
public final ServiceRestMetadata resolve(Class<?> serviceType) {
ServiceRestMetadata serviceRestMetadata = new ServiceRestMetadata();
// Process ServiceRestMetadata
processServiceRestMetadata(serviceRestMetadata, serviceType);
return resolve(serviceType, serviceRestMetadata);
}
@Override
public final ServiceRestMetadata resolve(Class<?> serviceType, ServiceRestMetadata serviceRestMetadata) {
serviceRestMetadata.setCodeStyle(this.getClass());
// Process RestMethodMetadata
processAllRestMethodMetadata(serviceRestMetadata, serviceType);
return serviceRestMetadata;
}
/**
* Process the service type including the sub-routines:
* <ul>
* <li>{@link ServiceRestMetadata#setServiceInterface(String)}</li>
* <li>{@link ServiceRestMetadata#setVersion(String)}</li>
* <li>{@link ServiceRestMetadata#setGroup(String)}</li>
* </ul>
*
* @param serviceRestMetadata {@link ServiceRestMetadata}
* @param serviceType Dubbo Service interface or type
*/
protected void processServiceRestMetadata(ServiceRestMetadata serviceRestMetadata, Class<?> serviceType) {
ServiceAnnotationResolver resolver = new ServiceAnnotationResolver(serviceType);
serviceRestMetadata.setServiceInterface(resolver.resolveInterfaceClassName());
serviceRestMetadata.setVersion(resolver.resolveVersion());
serviceRestMetadata.setGroup(resolver.resolveGroup());
}
/**
* Process all {@link RestMethodMetadata}
*
* @param serviceRestMetadata {@link ServiceRestMetadata}
* @param serviceType Dubbo Service interface or type
*/
protected void processAllRestMethodMetadata(ServiceRestMetadata serviceRestMetadata, Class<?> serviceType) {
Class<?> serviceInterfaceClass = resolveServiceInterfaceClass(serviceRestMetadata, serviceType);
Map<Method, Method> serviceMethodsMap = resolveServiceMethodsMap(serviceType, serviceInterfaceClass);
for (Map.Entry<Method, Method> entry : serviceMethodsMap.entrySet()) {
// try the overrider method first
Method serviceMethod = entry.getKey();
// If failed, it indicates the overrider method does not contain metadata , then try the declared method
if (!processRestMethodMetadata(
serviceMethod,
serviceType,
serviceInterfaceClass,
serviceRestMetadata::addRestMethodMetadata,
serviceRestMetadata)) {
Method declaredServiceMethod = entry.getValue();
processRestMethodMetadata(
declaredServiceMethod,
serviceType,
serviceInterfaceClass,
serviceRestMetadata::addRestMethodMetadata,
serviceRestMetadata);
}
}
}
/**
* Resolve a map of all public services methods from the specified service type and its interface class, whose key is the
* declared method, and the value is the overrider method
*
* @param serviceType the service interface implementation class
* @param serviceInterfaceClass the service interface class
* @return non-null read-only {@link Map}
*/
protected Map<Method, Method> resolveServiceMethodsMap(Class<?> serviceType, Class<?> serviceInterfaceClass) {
Map<Method, Method> serviceMethodsMap = new LinkedHashMap<>();
// exclude the public methods declared in java.lang.Object.class
List<Method> declaredServiceMethods =
new ArrayList<>(getAllMethods(serviceInterfaceClass, excludedDeclaredClass(Object.class)));
// controller class
if (serviceType.equals(serviceInterfaceClass)) {
putServiceMethodToMap(serviceMethodsMap, declaredServiceMethods);
return unmodifiableMap(serviceMethodsMap);
}
// for interface , such as consumer interface
if (serviceType.isInterface()) {
putServiceMethodToMap(serviceMethodsMap, declaredServiceMethods);
return unmodifiableMap(serviceMethodsMap);
}
List<Method> serviceMethods = new ArrayList<>(getAllMethods(serviceType, excludedDeclaredClass(Object.class)));
// sort methods
sort(declaredServiceMethods, MethodComparator.INSTANCE);
sort(serviceMethods, MethodComparator.INSTANCE);
for (Method declaredServiceMethod : declaredServiceMethods) {
for (Method serviceMethod : serviceMethods) {
if (overrides(serviceMethod, declaredServiceMethod)) {
serviceMethodsMap.put(serviceMethod, declaredServiceMethod);
// override method count > 1
// // once method match ,break for decrease loop times
// break;
}
}
}
// make them to be read-only
return unmodifiableMap(serviceMethodsMap);
}
private void putServiceMethodToMap(Map<Method, Method> serviceMethodsMap, List<Method> declaredServiceMethods) {
declaredServiceMethods.stream().forEach(method -> {
// filter static private default
if (isStatic(method) || isPrivate(method) || method.isDefault()) {
return;
}
serviceMethodsMap.put(method, method);
});
}
/**
* Resolve the class of Dubbo Service interface
*
* @param serviceRestMetadata {@link ServiceRestMetadata}
* @param serviceType Dubbo Service interface or type
* @return non-null
* @throws RuntimeException If the class is not found, the {@link RuntimeException} wraps the cause will be thrown
*/
protected Class<?> resolveServiceInterfaceClass(ServiceRestMetadata serviceRestMetadata, Class<?> serviceType) {
return execute(serviceType.getClassLoader(), classLoader -> {
String serviceInterface = serviceRestMetadata.getServiceInterface();
return forName(serviceInterface, classLoader);
});
}
/**
* Process the single {@link RestMethodMetadata} by the specified {@link Consumer} if present
*
* @param serviceMethod Dubbo Service method
* @param serviceType Dubbo Service interface or type
* @param serviceInterfaceClass The type of Dubbo Service interface
* @param metadataToProcess {@link RestMethodMetadata} to process if present
* @return if processed successfully, return <code>true</code>, or <code>false</code>
*/
protected boolean processRestMethodMetadata(
Method serviceMethod,
Class<?> serviceType,
Class<?> serviceInterfaceClass,
Consumer<RestMethodMetadata> metadataToProcess,
ServiceRestMetadata serviceRestMetadata) {
if (!isRestCapableMethod(serviceMethod, serviceType, serviceInterfaceClass)) {
return false;
}
String requestPath =
resolveRequestPath(serviceMethod, serviceType, serviceInterfaceClass); // requestPath is required
if (requestPath == null) {
return false;
}
String requestMethod =
resolveRequestMethod(serviceMethod, serviceType, serviceInterfaceClass); // requestMethod is required
if (requestMethod == null) {
return false;
}
RestMethodMetadata metadata = new RestMethodMetadata();
metadata.setCodeStyle(this.getClass());
// to consumer service map
metadata.setReflectMethod(serviceMethod);
MethodDefinition methodDefinition = resolveMethodDefinition(serviceMethod, serviceType, serviceInterfaceClass);
// Set MethodDefinition
metadata.setMethod(methodDefinition);
// process produces
Set<String> produces = new LinkedHashSet<>();
processProduces(serviceMethod, serviceType, serviceInterfaceClass, produces);
// process consumes
Set<String> consumes = new LinkedHashSet<>();
processConsumes(serviceMethod, serviceType, serviceInterfaceClass, consumes);
// Initialize RequestMetadata
RequestMetadata request = metadata.getRequest();
request.setPath(requestPath);
request.appendContextPathFromUrl(serviceRestMetadata.getContextPathFromUrl());
request.setMethod(requestMethod);
request.setProduces(produces);
request.setConsumes(consumes);
// process the annotated method parameters
processAnnotatedMethodParameters(serviceMethod, serviceType, serviceInterfaceClass, metadata);
// Post-Process
postResolveRestMethodMetadata(serviceMethod, serviceType, serviceInterfaceClass, metadata);
// Accept RestMethodMetadata
metadataToProcess.accept(metadata);
return true;
}
/**
* Test the service method is capable of REST or not?
*
* @param serviceMethod Dubbo Service method
* @param serviceType Dubbo Service interface or type
* @param serviceInterfaceClass The type of Dubbo Service interface
* @return If capable, return <code>true</code>
*/
protected abstract boolean isRestCapableMethod(
Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass);
/**
* Resolve the request method
*
* @param serviceMethod Dubbo Service method
* @param serviceType Dubbo Service interface or type
* @param serviceInterfaceClass The type of Dubbo Service interface
* @return if can't be resolve, return <code>null</code>
*/
protected abstract String resolveRequestMethod(
Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass);
/**
* Resolve the request path
*
* @param serviceMethod Dubbo Service method
* @param serviceType Dubbo Service interface or type
* @param serviceInterfaceClass The type of Dubbo Service interface
* @return if can't be resolve, return <code>null</code>
*/
protected abstract String resolveRequestPath(
Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass);
/**
* Resolve the {@link MethodDefinition}
*
* @param serviceMethod Dubbo Service method
* @param serviceType Dubbo Service interface or type
* @param serviceInterfaceClass The type of Dubbo Service interface
* @return if can't be resolve, return <code>null</code>
* @see MethodDefinitionBuilder
*/
protected MethodDefinition resolveMethodDefinition(
Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass) {
MethodDefinitionBuilder builder = new MethodDefinitionBuilder();
return builder.build(serviceMethod);
}
private void processAnnotatedMethodParameters(
Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass, RestMethodMetadata metadata) {
int paramCount = serviceMethod.getParameterCount();
Parameter[] parameters = serviceMethod.getParameters();
for (int i = 0; i < paramCount; i++) {
Parameter parameter = parameters[i];
// Add indexed parameter name
metadata.addIndexToName(i, parameter.getName());
processAnnotatedMethodParameter(parameter, i, serviceMethod, serviceType, serviceInterfaceClass, metadata);
}
}
private void processAnnotatedMethodParameter(
Parameter parameter,
int parameterIndex,
Method serviceMethod,
Class<?> serviceType,
Class<?> serviceInterfaceClass,
RestMethodMetadata metadata) {
Annotation[] annotations = parameter.getAnnotations();
if (annotations == null || annotations.length == 0) {
for (NoAnnotatedParameterRequestTagProcessor processor : noAnnotatedParameterRequestTagProcessors) {
// no annotation only one default annotationType
if (processor.process(parameter, parameterIndex, metadata)) {
return;
}
}
}
for (Annotation annotation : annotations) {
String annotationType = annotation.annotationType().getName();
parameterProcessorsMap.getOrDefault(annotationType, emptyList()).forEach(processor -> {
processor.process(
annotation,
parameter,
parameterIndex,
serviceMethod,
serviceType,
serviceInterfaceClass,
metadata);
});
}
}
protected abstract void processProduces(
Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass, Set<String> produces);
protected abstract void processConsumes(
Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass, Set<String> consumes);
protected void postResolveRestMethodMetadata(
Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass, RestMethodMetadata metadata) {
// parse pathVariable index from url by annotation info
PathUtil.setArgInfoSplitIndex(metadata.getRequest().getPath(), metadata.getArgInfos());
}
private static Map<String, List<AnnotatedMethodParameterProcessor>> loadAnnotatedMethodParameterProcessors(
ApplicationModel applicationModel) {
Map<String, List<AnnotatedMethodParameterProcessor>> parameterProcessorsMap = new LinkedHashMap<>();
applicationModel
.getExtensionLoader(AnnotatedMethodParameterProcessor.class)
.getSupportedExtensionInstances()
.forEach(processor -> {
List<AnnotatedMethodParameterProcessor> processors = parameterProcessorsMap.computeIfAbsent(
processor.getAnnotationName(), k -> new LinkedList<>());
processors.add(processor);
});
return parameterProcessorsMap;
}
private static Set<NoAnnotatedParameterRequestTagProcessor> loadNoAnnotatedMethodParameterProcessors(
ApplicationModel applicationModel) {
Set<NoAnnotatedParameterRequestTagProcessor> supportedExtensionInstances = applicationModel
.getExtensionLoader(NoAnnotatedParameterRequestTagProcessor.class)
.getSupportedExtensionInstances();
return supportedExtensionInstances;
}
public static boolean isServiceMethodAnnotationPresent(Class<?> serviceImpl, String annotationClass) {
List<Method> allMethods = getAllMethods(serviceImpl, excludedDeclaredClass(Object.class));
for (Method method : allMethods) {
if (isAnnotationPresent(method, annotationClass)) {
return true;
}
}
return false;
}
}
| 7,252 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/ArgInfo.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
/**
* description of service method args info
*/
public class ArgInfo {
/**
* method arg index 0,1,2,3
*/
private int index;
/**
* method annotation name or name
*/
private String annotationNameAttribute;
/**
* param annotation type
*/
private Class paramAnnotationType;
/**
* param Type
*/
private Class paramType;
/**
* param actual Type(collection,map,array)
*/
private Type actualType;
/**
* param name
*/
private String paramName;
/**
* url split("/") String[n] index
*/
private int urlSplitIndex;
private Object defaultValue;
private boolean formContentType;
public ArgInfo(int index, String name, Class paramType) {
this.index = index;
this.paramName = name;
this.paramType = paramType;
}
public ArgInfo(int index, Parameter parameter) {
this(index, parameter.getName(), parameter.getType());
this.actualType = parameter.getParameterizedType();
}
public ArgInfo() {}
public int getIndex() {
return index;
}
public ArgInfo setIndex(int index) {
this.index = index;
return this;
}
public String getAnnotationNameAttribute() {
if (annotationNameAttribute == null) {
// such as String param no annotation
return paramName;
}
return annotationNameAttribute;
}
public ArgInfo setAnnotationNameAttribute(String annotationNameAttribute) {
this.annotationNameAttribute = annotationNameAttribute;
return this;
}
public Class getParamAnnotationType() {
return paramAnnotationType;
}
public ArgInfo setParamAnnotationType(Class paramAnnotationType) {
this.paramAnnotationType = paramAnnotationType;
return this;
}
public Class getParamType() {
return paramType;
}
public void setParamType(Class paramType) {
this.paramType = paramType;
}
public int getUrlSplitIndex() {
return urlSplitIndex;
}
public void setUrlSplitIndex(int urlSplitIndex) {
this.urlSplitIndex = urlSplitIndex;
}
public static ArgInfo build() {
return new ArgInfo();
}
public static ArgInfo build(int index, Parameter parameter) {
return new ArgInfo(index, parameter);
}
public String getParamName() {
return paramName;
}
public ArgInfo setParamName(String paramName) {
this.paramName = paramName;
return this;
}
public Object getDefaultValue() {
return defaultValue;
}
public ArgInfo setDefaultValue(Object defaultValue) {
this.defaultValue = defaultValue;
return this;
}
public boolean isFormContentType() {
return formContentType;
}
public ArgInfo setFormContentType(boolean isFormContentType) {
this.formContentType = isFormContentType;
return this;
}
public Type actualReflectType() {
return actualType;
}
@Override
public String toString() {
return "ArgInfo{" + "index="
+ index + ", annotationNameAttribute='"
+ annotationNameAttribute + '\'' + ", paramAnnotationType="
+ paramAnnotationType + ", paramType="
+ paramType + ", paramName='"
+ paramName + '\'' + ", urlSplitIndex="
+ urlSplitIndex + ", defaultValue="
+ defaultValue + ", formContentType="
+ formContentType + '}';
}
}
| 7,253 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/SpringMvcClassConstants.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import static org.apache.dubbo.common.utils.ClassUtils.getClassLoader;
import static org.apache.dubbo.common.utils.ClassUtils.resolveClass;
public interface SpringMvcClassConstants extends RestMetadataConstants.SPRING_MVC {
/**
* The annotation class of @RequestMapping
*/
Class REQUEST_MAPPING_ANNOTATION_CLASS = resolveClass(REQUEST_MAPPING_ANNOTATION_CLASS_NAME, getClassLoader());
/**
* The annotation class of @RequestHeader
*/
Class REQUEST_HEADER_ANNOTATION_CLASS = resolveClass(REQUEST_HEADER_ANNOTATION_CLASS_NAME, getClassLoader());
/**
* The annotation class of @RequestParam
*/
Class REQUEST_PARAM_ANNOTATION_CLASS = resolveClass(REQUEST_PARAM_ANNOTATION_CLASS_NAME, getClassLoader());
/**
* The annotation class of @RequestBody
*/
Class REQUEST_BODY_ANNOTATION_CLASS = resolveClass(REQUEST_BODY_ANNOTATION_CLASS_NAME, getClassLoader());
/**
* The annotation class of @RequestBody
*/
Class PATH_VARIABLE_ANNOTATION_CLASS = resolveClass(PATH_VARIABLE_ANNOTATION_CLASS_NAME, getClassLoader());
}
| 7,254 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/PathUtil.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.metadata.MetadataConstants;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* is used to parse url pathVariable
* <p>
* String[] splits= url.split("/")
* List<String> strings = Arrays.asList(split);
* strings.set(UrlSplitIndex, (String) args.get(argIndex));
*/
public class PathUtil {
private static final String SEPARATOR = MetadataConstants.PATH_SEPARATOR;
/**
* generate real path from rawPath according to argInfo and method args
*
* @param rawPath
* @param argInfos
* @param args
* @return
*/
public static String resolvePathVariable(String rawPath, List<ArgInfo> argInfos, List<Object> args) {
String[] split = rawPath.split(SEPARATOR);
List<String> strings = Arrays.asList(split);
List<ArgInfo> pathArgInfos = new ArrayList<>();
for (ArgInfo argInfo : argInfos) {
if (ParamType.PATH.supportAnno(argInfo.getParamAnnotationType())) {
pathArgInfos.add(argInfo);
}
}
for (ArgInfo pathArgInfo : pathArgInfos) {
strings.set(pathArgInfo.getUrlSplitIndex(), String.valueOf(args.get(pathArgInfo.getIndex())));
}
String pat = SEPARATOR;
for (String string : strings) {
if (string.length() == 0) {
continue;
}
pat = pat + string + SEPARATOR;
}
if (pat.endsWith(SEPARATOR)) {
pat = pat.substring(0, pat.lastIndexOf(SEPARATOR));
}
return pat;
}
/**
* parse pathVariable index from url by annotation info
*
* @param rawPath
* @param argInfos
*/
public static void setArgInfoSplitIndex(String rawPath, List<ArgInfo> argInfos) {
String[] split = rawPath.split(SEPARATOR);
List<PathPair> pathPairs = new ArrayList<>();
for (ArgInfo argInfo : argInfos) {
if (ParamType.PATH.supportAnno(argInfo.getParamAnnotationType())) {
pathPairs.add(new PathPair(argInfo));
}
}
for (int i = 0; i < split.length; i++) {
String s = split[i];
for (PathPair pathPair : pathPairs) {
boolean match = pathPair.match(s);
if (match) {
pathPair.setArgInfoSplitIndex(i);
}
}
}
}
public static class PathPair {
String value;
ArgInfo argInfo;
public PathPair(ArgInfo argInfo) {
this.argInfo = argInfo;
this.value = argInfo.getAnnotationNameAttribute();
}
public String getPatten() {
return "{" + value + "}";
}
public String getLeftPatten() {
return "{" + value;
}
public String getRightPatten() {
return "}";
}
public boolean match(String value) {
return getPatten().equals(value) // for : {id}
|| (value.startsWith(getLeftPatten()) && value.endsWith(getRightPatten())); // for : {id: \d+}
}
public String getValue() {
return value;
}
public void setArgInfo(ArgInfo argInfo) {
this.argInfo = argInfo;
}
public void setArgInfoSplitIndex(int urlSplitIndex) {
this.argInfo.setUrlSplitIndex(urlSplitIndex);
}
}
}
| 7,255 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AnnotatedMethodParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.lang.Prioritized;
import javax.lang.model.element.VariableElement;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
/**
* The interface to process the annotated method parameter
*
* @since 2.7.6
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface AnnotatedMethodParameterProcessor extends Prioritized {
/**
* The string presenting the annotation name
*
* @return non-null
*/
String getAnnotationName();
/**
* The string presenting the annotation type
*
* @return non-null
*/
Class getAnnotationClass();
/**
* Process the specified method {@link VariableElement parameter}
*
* @param annotation {@link Annotation the target annotation} whose type is {@link #getAnnotationName()}
* @param parameter the method parameter
* @param parameterIndex the index of method parameter
* @param method {@link Method method that parameter belongs to}
* @param serviceType Dubbo Service interface or type
* @param serviceInterfaceClass The type of Dubbo Service interface
* @param restMethodMetadata {@link RestMethodMetadata the metadata is used to update}
*/
void process(
Annotation annotation,
Parameter parameter,
int parameterIndex,
Method method,
Class<?> serviceType,
Class<?> serviceInterfaceClass,
RestMethodMetadata restMethodMetadata);
/**
* Build the default value
*
* @param parameterIndex the index of parameter
* @return the placeholder
*/
static String buildDefaultValue(int parameterIndex) {
return "{" + parameterIndex + "}";
}
}
| 7,256 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataResolver.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* The interface to resolve the {@link ServiceRestMetadata REST metadata} from the specified
* Dubbo Service interface or type.
*
* @since 2.7.6
*/
@SPI(scope = ExtensionScope.APPLICATION)
public interface ServiceRestMetadataResolver {
/**
* Support to resolve {@link ServiceRestMetadata REST metadata} or not
*
* @param serviceType Dubbo Service interface or type
* @return If supports, return <code>true</code>, or <code>false</code>
*/
boolean supports(Class<?> serviceType);
boolean supports(Class<?> serviceType, boolean consumer);
/**
* Resolve the {@link ServiceRestMetadata REST metadata} from the specified
* Dubbo Service interface or type
*
* @param serviceType Dubbo Service interface or type
* @return
*/
ServiceRestMetadata resolve(Class<?> serviceType);
ServiceRestMetadata resolve(Class<?> serviceType, ServiceRestMetadata serviceRestMetadata);
}
| 7,257 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/ParamType.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.metadata.rest.tag.BodyTag;
import org.apache.dubbo.metadata.rest.tag.ParamTag;
import java.util.ArrayList;
import java.util.List;
public enum ParamType {
HEADER(addSupportTypes(
JAXRSClassConstants.HEADER_PARAM_ANNOTATION_CLASS,
SpringMvcClassConstants.REQUEST_HEADER_ANNOTATION_CLASS)),
PARAM(addSupportTypes(
JAXRSClassConstants.QUERY_PARAM_ANNOTATION_CLASS,
SpringMvcClassConstants.REQUEST_PARAM_ANNOTATION_CLASS,
ParamTag.class)),
BODY(addSupportTypes(
JAXRSClassConstants.REST_EASY_BODY_ANNOTATION_CLASS,
SpringMvcClassConstants.REQUEST_BODY_ANNOTATION_CLASS,
BodyTag.class)),
PATH(addSupportTypes(
JAXRSClassConstants.PATH_PARAM_ANNOTATION_CLASS, SpringMvcClassConstants.PATH_VARIABLE_ANNOTATION_CLASS)),
FORM(addSupportTypes(
JAXRSClassConstants.FORM_PARAM_ANNOTATION_CLASS,
JAXRSClassConstants.FORM_BODY_ANNOTATION_CLASS,
SpringMvcClassConstants.REQUEST_BODY_ANNOTATION_CLASS)),
PROVIDER_BODY(addSupportTypes(
JAXRSClassConstants.REST_EASY_BODY_ANNOTATION_CLASS,
JAXRSClassConstants.FORM_PARAM_ANNOTATION_CLASS,
SpringMvcClassConstants.REQUEST_BODY_ANNOTATION_CLASS,
BodyTag.class,
JAXRSClassConstants.FORM_BODY_ANNOTATION_CLASS)),
EMPTY(addSupportTypes());
private List<Class> annotationClasses;
ParamType(List<Class> annotationClasses) {
this.annotationClasses = annotationClasses;
}
public boolean supportAnno(Class anno) {
if (anno == null) {
return false;
}
return this.annotationClasses.contains(anno);
}
/**
* exclude null types
*
* @param classes
* @return
*/
private static List<Class> addSupportTypes(Class... classes) {
ArrayList<Class> types = new ArrayList<>();
for (Class clazz : classes) {
if (clazz == null) {
continue;
}
types.add(clazz);
}
return types;
}
}
| 7,258 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/PathMatcher.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;
/**
* for http request path match
*/
public class PathMatcher {
private static final String SEPARATOR = "/";
private String path;
private String version; // service version
private String group; // service group
private Integer port; // service port
private String[] pathSplits;
private boolean hasPathVariable;
private String contextPath;
private String httpMethod;
// for provider http method compare,http 405
private boolean needCompareHttpMethod = true;
// compare method directly (for get Invoker by method)
private boolean needCompareServiceMethod = false;
// service method
private Method method;
public PathMatcher(String path) {
this(path, null, null, null);
}
public PathMatcher(String path, String version, String group, Integer port) {
this.path = path;
dealPathVariable(path);
this.version = version;
this.group = group;
this.port = (port == null || port == -1 || port == 0) ? null : port;
}
public PathMatcher(String path, String version, String group, Integer port, String httpMethod) {
this(path, version, group, port);
setHttpMethod(httpMethod);
}
public PathMatcher(Method method) {
this.method = method;
}
private void dealPathVariable(String path) {
if (path == null) {
return;
}
this.pathSplits = path.split(SEPARATOR);
for (String pathSplit : pathSplits) {
if (isPlaceHold(pathSplit)) {
hasPathVariable = true;
break;
}
}
}
private void setPath(String path) {
this.path = path;
}
public void setVersion(String version) {
this.version = version;
}
public void setGroup(String group) {
this.group = group;
}
public void setPort(Integer port) {
this.port = port;
}
public void setContextPath(String contextPath) {
contextPath = contextPathFormat(contextPath);
this.contextPath = contextPath;
setPath(contextPath + path);
dealPathVariable(path);
}
public static PathMatcher getInvokeCreatePathMatcher(
String path, String version, String group, Integer port, String method) {
return new PathMatcher(path, version, group, port, method).compareHttpMethod(false);
}
public static PathMatcher getInvokeCreatePathMatcher(Method serviceMethod) {
return new PathMatcher(serviceMethod).setNeedCompareServiceMethod(true);
}
public static PathMatcher convertPathMatcher(PathMatcher pathMatcher) {
return getInvokeCreatePathMatcher(
pathMatcher.path, pathMatcher.version, pathMatcher.group, pathMatcher.port, pathMatcher.httpMethod);
}
public boolean hasPathVariable() {
return hasPathVariable;
}
public Integer getPort() {
return port;
}
public String getHttpMethod() {
return httpMethod;
}
public PathMatcher setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
return this;
}
public PathMatcher compareHttpMethod(boolean needCompareHttpMethod) {
this.needCompareHttpMethod = needCompareHttpMethod;
return this;
}
public Method getMethod() {
return method;
}
public void setMethod(Method method) {
this.method = method;
}
private PathMatcher setNeedCompareServiceMethod(boolean needCompareServiceMethod) {
this.needCompareServiceMethod = needCompareServiceMethod;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PathMatcher that = (PathMatcher) o;
return serviceMethodEqual(that, this) || pathMatch(that);
}
private boolean pathMatch(PathMatcher that) {
return (!that.needCompareServiceMethod && !needCompareServiceMethod) // no need service method compare
&& pathEqual(that) // path compare
&& Objects.equals(version, that.version) // service version compare
&& httpMethodMatch(that) // http method compare
&& Objects.equals(group, that.group)
&& Objects.equals(port, that.port);
}
/**
* it is needed to compare http method when one of needCompareHttpMethod is true,and don`t compare when both needCompareHttpMethod are false
*
* @param that
* @return
*/
private boolean httpMethodMatch(PathMatcher that) {
return !that.needCompareHttpMethod || !this.needCompareHttpMethod
? true
: Objects.equals(this.httpMethod, that.httpMethod);
}
private boolean serviceMethodEqual(PathMatcher thatPathMatcher, PathMatcher thisPathMatcher) {
Method thatMethod = thatPathMatcher.method;
Method thisMethod = thisPathMatcher.method;
return thatMethod != null
&& thisMethod != null
&& (thatPathMatcher.needCompareServiceMethod || thisPathMatcher.needCompareServiceMethod)
&& thisMethod.getName().equals(thatMethod.getName())
&& Arrays.equals(thisMethod.getParameterTypes(), thatMethod.getParameterTypes());
}
@Override
public int hashCode() {
return Objects.hash(version, group, port);
}
private boolean pathEqual(PathMatcher pathMatcher) {
// path is null return false directly
if (this.path == null || pathMatcher.path == null) {
return false;
}
// no place hold
if (!pathMatcher.hasPathVariable) {
return this.path.equals(pathMatcher.path);
}
String[] pathSplits = pathMatcher.pathSplits;
String[] thisPathSplits = this.pathSplits;
if (thisPathSplits.length != pathSplits.length) {
return false;
}
for (int i = 0; i < pathSplits.length; i++) {
boolean equals = thisPathSplits[i].equals(pathSplits[i]);
if (equals) {
continue;
} else {
if (placeHoldCompare(pathSplits[i], thisPathSplits[i])) {
continue;
} else {
return false;
}
}
}
return true;
}
private boolean placeHoldCompare(String pathSplit, String pathToCompare) {
boolean startAndEndEqual = isPlaceHold(pathSplit) || isPlaceHold(pathToCompare);
// start { end }
if (!startAndEndEqual) {
return false;
}
// exclude {}
boolean lengthCondition = pathSplit.length() >= 3 || pathToCompare.length() >= 3;
if (!lengthCondition) {
return false;
}
return true;
}
private boolean isPlaceHold(String pathSplit) {
return pathSplit.startsWith("{") && pathSplit.endsWith("}");
}
private String contextPathFormat(String contextPath) {
if (contextPath == null || contextPath.equals(SEPARATOR) || contextPath.length() == 0) {
return "";
}
return pathFormat(contextPath);
}
private String pathFormat(String path) {
if (path.startsWith(SEPARATOR)) {
return path;
} else {
return SEPARATOR + path;
}
}
@Override
public String toString() {
return "PathMatcher{" + "path='"
+ path + '\'' + ", version='"
+ version + '\'' + ", group='"
+ group + '\'' + ", port="
+ port + ", hasPathVariable="
+ hasPathVariable + ", contextPath='"
+ contextPath + '\'' + ", httpMethod='"
+ httpMethod + '\'' + '}';
}
}
| 7,259 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/RestMetadataConstants.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import java.lang.annotation.Annotation;
import static org.apache.dubbo.common.utils.ClassUtils.getClassLoader;
import static org.apache.dubbo.common.utils.ClassUtils.resolveClass;
/**
* The REST Metadata Constants definition interface
*
* @since 2.7.6
*/
public interface RestMetadataConstants {
/**
* The encoding of metadata
*/
String METADATA_ENCODING = "UTF-8";
/**
* {@link ServiceRestMetadata} Resource PATH
*/
String SERVICE_REST_METADATA_RESOURCE_PATH = "META-INF/dubbo/service-rest-metadata.json";
/**
* JAX-RS
*/
interface JAX_RS {
/**
* The annotation class name of @Path
*/
String PATH_ANNOTATION_CLASS_NAME = "javax.ws.rs.Path";
/**
* The annotation class name of @HttpMethod
*/
String HTTP_METHOD_ANNOTATION_CLASS_NAME = "javax.ws.rs.HttpMethod";
/**
* The annotation class name of @Produces
*/
String PRODUCES_ANNOTATION_CLASS_NAME = "javax.ws.rs.Produces";
/**
* The annotation class name of @Consumes
*/
String CONSUMES_ANNOTATION_CLASS_NAME = "javax.ws.rs.Consumes";
/**
* The annotation class name of @DefaultValue
*/
String DEFAULT_VALUE_ANNOTATION_CLASS_NAME = "javax.ws.rs.DefaultValue";
/**
* The annotation class name of @FormParam
*/
String FORM_PARAM_ANNOTATION_CLASS_NAME = "javax.ws.rs.FormParam";
/**
* The annotation class name of @HeaderParam
*/
String HEADER_PARAM_ANNOTATION_CLASS_NAME = "javax.ws.rs.HeaderParam";
/**
* The annotation class name of @MatrixParam
*/
String MATRIX_PARAM_ANNOTATION_CLASS_NAME = "javax.ws.rs.MatrixParam";
/**
* The annotation class name of @QueryParam
*/
String QUERY_PARAM_ANNOTATION_CLASS_NAME = "javax.ws.rs.QueryParam";
/**
* The annotation class name of @Body
*/
String REST_EASY_BODY_ANNOTATION_CLASS_NAME = "org.jboss.resteasy.annotations.Body";
/**
* The annotation class name of @Form
*/
String REST_EASY_FORM_BODY_ANNOTATION_CLASS_NAME = "org.jboss.resteasy.annotations.Form";
/**
* The annotation class name of @PathParam
*/
String PATH_PARAM_ANNOTATION_CLASS_NAME = "javax.ws.rs.PathParam";
}
/**
* Spring MVC
*/
interface SPRING_MVC {
/**
* The annotation class name of @Controller
*/
String CONTROLLER_ANNOTATION_CLASS_NAME = "org.springframework.stereotype.Controller";
/**
* The annotation class name of @RequestMapping
*/
String REQUEST_MAPPING_ANNOTATION_CLASS_NAME = "org.springframework.web.bind.annotation.RequestMapping";
/**
* The annotation class name of @RequestHeader
*/
String REQUEST_HEADER_ANNOTATION_CLASS_NAME = "org.springframework.web.bind.annotation.RequestHeader";
/**
* The annotation class name of @RequestParam
*/
String REQUEST_PARAM_ANNOTATION_CLASS_NAME = "org.springframework.web.bind.annotation.RequestParam";
/**
* The annotation class name of @RequestBody
*/
String REQUEST_BODY_ANNOTATION_CLASS_NAME = "org.springframework.web.bind.annotation.RequestBody";
/**
* The annotation class name of @PathVariable
*/
String PATH_VARIABLE_ANNOTATION_CLASS_NAME = "org.springframework.web.bind.annotation.PathVariable";
/**
* The class of @Controller
*
* @since 2.7.9
*/
Class<? extends Annotation> CONTROLLER_ANNOTATION_CLASS =
(Class<? extends Annotation>) resolveClass(CONTROLLER_ANNOTATION_CLASS_NAME, getClassLoader());
/**
* The class of @RequestMapping
*
* @since 2.7.9
*/
Class<? extends Annotation> REQUEST_MAPPING_ANNOTATION_CLASS =
(Class<? extends Annotation>) resolveClass(REQUEST_MAPPING_ANNOTATION_CLASS_NAME, getClassLoader());
/**
* The annotation class name of AnnotatedElementUtils
*
* @since 2.7.9
*/
String ANNOTATED_ELEMENT_UTILS_CLASS_NAME = "org.springframework.core.annotation.AnnotatedElementUtils";
/**
* The class of AnnotatedElementUtils
*
* @since 2.7.9
*/
Class<?> ANNOTATED_ELEMENT_UTILS_CLASS = resolveClass(ANNOTATED_ELEMENT_UTILS_CLASS_NAME, getClassLoader());
}
}
| 7,260 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractNoAnnotatedParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver;
import org.apache.dubbo.metadata.rest.media.MediaType;
import java.lang.reflect.Parameter;
import java.util.Set;
import static org.apache.dubbo.common.utils.ClassUtils.getClassLoader;
import static org.apache.dubbo.common.utils.ClassUtils.resolveClass;
public abstract class AbstractNoAnnotatedParameterProcessor implements NoAnnotatedParameterRequestTagProcessor {
public boolean process(Parameter parameter, int parameterIndex, RestMethodMetadata restMethodMetadata) {
MediaType mediaType = consumerContentType();
if (!contentTypeSupport(restMethodMetadata, mediaType, parameter.getType())) {
return false;
}
boolean isFormBody = isFormContentType(restMethodMetadata);
addArgInfo(parameter, parameterIndex, restMethodMetadata, isFormBody);
return true;
}
private boolean contentTypeSupport(RestMethodMetadata restMethodMetadata, MediaType mediaType, Class paramType) {
// @RequestParam String,number param
if (mediaType.equals(MediaType.ALL_VALUE)) {
// jaxrs no annotation param is from http body
if (JAXRSServiceRestMetadataResolver.class.equals(restMethodMetadata.getCodeStyle())) {
return true;
}
// spring mvc no annotation param only is used by text data(string,number)
if (String.class == paramType || paramType.isPrimitive() || Number.class.isAssignableFrom(paramType)) {
return true;
}
}
Set<String> consumes = restMethodMetadata.getRequest().getConsumes();
for (String consume : consumes) {
if (consume.contains(mediaType.value)) {
return true;
}
}
return false;
}
protected boolean isFormContentType(RestMethodMetadata restMethodMetadata) {
return false;
}
protected void addArgInfo(
Parameter parameter, int parameterIndex, RestMethodMetadata restMethodMetadata, boolean isFormBody) {
ArgInfo argInfo = ArgInfo.build(parameterIndex, parameter)
.setParamAnnotationType(resolveClass(defaultAnnotationClassName(restMethodMetadata), getClassLoader()))
.setAnnotationNameAttribute(parameter.getName())
.setFormContentType(isFormBody);
restMethodMetadata.addArgInfo(argInfo);
}
}
| 7,261 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/RestMethodMetadata.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.metadata.definition.model.MethodDefinition;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static java.util.Collections.emptyList;
/**
* The metadata class for {@link RequestMetadata HTTP(REST) request} and
* its binding {@link MethodDefinition method definition}
*
* @since 2.7.6
*/
public class RestMethodMetadata implements Serializable {
private static final long serialVersionUID = 2935252016200830694L;
private MethodDefinition method;
private RequestMetadata request;
private Integer urlIndex;
private Integer bodyIndex;
private Integer headerMapIndex;
private String bodyType;
private Map<Integer, Collection<String>> indexToName;
private List<String> formParams;
private Map<Integer, Boolean> indexToEncoded;
private List<ArgInfo> argInfos;
private Method reflectMethod;
/**
* make a distinction between mvc & resteasy
*/
private Class codeStyle;
public MethodDefinition getMethod() {
if (method == null) {
method = new MethodDefinition();
}
return method;
}
public void setMethod(MethodDefinition method) {
this.method = method;
}
public RequestMetadata getRequest() {
if (request == null) {
request = new RequestMetadata();
}
return request;
}
public void setRequest(RequestMetadata request) {
this.request = request;
}
public Integer getUrlIndex() {
return urlIndex;
}
public void setUrlIndex(Integer urlIndex) {
this.urlIndex = urlIndex;
}
public Integer getBodyIndex() {
return bodyIndex;
}
public void setBodyIndex(Integer bodyIndex) {
this.bodyIndex = bodyIndex;
}
public Integer getHeaderMapIndex() {
return headerMapIndex;
}
public void setHeaderMapIndex(Integer headerMapIndex) {
this.headerMapIndex = headerMapIndex;
}
public String getBodyType() {
return bodyType;
}
public void setBodyType(String bodyType) {
this.bodyType = bodyType;
}
public Map<Integer, Collection<String>> getIndexToName() {
if (indexToName == null) {
indexToName = new LinkedHashMap<>();
}
return indexToName;
}
public void setIndexToName(Map<Integer, Collection<String>> indexToName) {
this.indexToName = indexToName;
}
public void addIndexToName(Integer index, String name) {
if (index == null) {
return;
}
if (name.startsWith("arg") && name.endsWith(index.toString())) {
// Ignore this value because of the Java byte-code without the metadata of method parameters
return;
}
Map<Integer, Collection<String>> indexToName = getIndexToName();
Collection<String> parameterNames = indexToName.computeIfAbsent(index, i -> new ArrayList<>(1));
parameterNames.add(name);
}
public boolean hasIndexedName(Integer index, String name) {
Map<Integer, Collection<String>> indexToName = getIndexToName();
return indexToName.getOrDefault(index, emptyList()).contains(name);
}
public List<String> getFormParams() {
return formParams;
}
public void setFormParams(List<String> formParams) {
this.formParams = formParams;
}
public Map<Integer, Boolean> getIndexToEncoded() {
return indexToEncoded;
}
public void setIndexToEncoded(Map<Integer, Boolean> indexToEncoded) {
this.indexToEncoded = indexToEncoded;
}
public List<ArgInfo> getArgInfos() {
if (argInfos == null) {
argInfos = new ArrayList<>();
}
return argInfos;
}
public void addArgInfo(ArgInfo argInfo) {
getArgInfos().add(argInfo);
}
public Method getReflectMethod() {
return reflectMethod;
}
public void setReflectMethod(Method reflectMethod) {
this.reflectMethod = reflectMethod;
}
public Class getCodeStyle() {
return codeStyle;
}
public void setCodeStyle(Class codeStyle) {
this.codeStyle = codeStyle;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof RestMethodMetadata)) {
return false;
}
RestMethodMetadata that = (RestMethodMetadata) o;
return Objects.equals(getMethod(), that.getMethod())
&& Objects.equals(getRequest(), that.getRequest())
&& Objects.equals(getUrlIndex(), that.getUrlIndex())
&& Objects.equals(getBodyIndex(), that.getBodyIndex())
&& Objects.equals(getHeaderMapIndex(), that.getHeaderMapIndex())
&& Objects.equals(getBodyType(), that.getBodyType())
&& Objects.equals(getFormParams(), that.getFormParams())
&& Objects.equals(getIndexToEncoded(), that.getIndexToEncoded());
}
@Override
public int hashCode() {
return Objects.hash(
getMethod(),
getRequest(),
getUrlIndex(),
getBodyIndex(),
getHeaderMapIndex(),
getBodyType(),
getFormParams(),
getIndexToEncoded());
}
@Override
public String toString() {
return "RestMethodMetadata{" + "method="
+ method + ", request="
+ request + ", urlIndex="
+ urlIndex + ", bodyIndex="
+ bodyIndex + ", headerMapIndex="
+ headerMapIndex + ", bodyType='"
+ bodyType + '\'' + ", indexToName="
+ indexToName + ", formParams="
+ formParams + ", indexToEncoded="
+ indexToEncoded + ", argInfos="
+ argInfos + ", reflectMethod="
+ reflectMethod + ", codeStyle="
+ codeStyle + '}';
}
}
| 7,262 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/JAXRSClassConstants.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import static org.apache.dubbo.common.utils.ClassUtils.getClassLoader;
import static org.apache.dubbo.common.utils.ClassUtils.resolveClass;
public interface JAXRSClassConstants extends RestMetadataConstants.JAX_RS {
/**
* The annotation class of @Path
*/
Class PATH_ANNOTATION_CLASS = resolveClass(PATH_ANNOTATION_CLASS_NAME, getClassLoader());
/**
* The annotation class of @FormParam
*/
Class FORM_PARAM_ANNOTATION_CLASS = resolveClass(FORM_PARAM_ANNOTATION_CLASS_NAME, getClassLoader());
/**
* The annotation class of @Form
*/
Class FORM_BODY_ANNOTATION_CLASS = resolveClass(REST_EASY_FORM_BODY_ANNOTATION_CLASS_NAME, getClassLoader());
/**
* The annotation class of @HeaderParam
*/
Class HEADER_PARAM_ANNOTATION_CLASS = resolveClass(HEADER_PARAM_ANNOTATION_CLASS_NAME, getClassLoader());
/**
* The annotation class of @MatrixParam
*/
Class MATRIX_PARAM_ANNOTATION_CLASS = resolveClass(MATRIX_PARAM_ANNOTATION_CLASS_NAME, getClassLoader());
/**
* The annotation class of @QueryParam
*/
Class QUERY_PARAM_ANNOTATION_CLASS = resolveClass(QUERY_PARAM_ANNOTATION_CLASS_NAME, getClassLoader());
/**
* The annotation class of @Body
*/
Class REST_EASY_BODY_ANNOTATION_CLASS = resolveClass(REST_EASY_BODY_ANNOTATION_CLASS_NAME, getClassLoader());
/**
* The annotation class of @PathParam
*/
Class PATH_PARAM_ANNOTATION_CLASS = resolveClass(PATH_PARAM_ANNOTATION_CLASS_NAME, getClassLoader());
}
| 7,263 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/RequestMetadata.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.common.utils.CollectionUtils;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import static java.util.Collections.unmodifiableMap;
import static org.apache.dubbo.common.utils.PathUtils.normalize;
import static org.apache.dubbo.common.utils.StringUtils.SLASH;
import static org.apache.dubbo.common.utils.StringUtils.isBlank;
/**
* The metadata class for REST request
*
* @since 2.7.6
*/
public class RequestMetadata implements Serializable {
private static final long serialVersionUID = -240099840085329958L;
private String method;
private String path;
private Map<String, List<String>> params = new LinkedHashMap<>();
private Map<String, List<String>> headers = new LinkedHashMap<>();
private Set<String> consumes = new LinkedHashSet<>();
private Set<String> produces = new LinkedHashSet<>();
/**
* Default Constructor
*/
public RequestMetadata() {}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method == null ? null : method.toUpperCase();
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = normalize(path);
if (!path.startsWith(SLASH)) {
this.path = SLASH + path;
}
}
public Map<String, List<String>> getParams() {
return unmodifiableMap(params);
}
public void setParams(Map<String, List<String>> params) {
params(params);
}
private static void add(Map<String, List<String>> multiValueMap, String key, String value) {
if (isBlank(key)) {
return;
}
List<String> values = get(multiValueMap, key, true);
values.add(value);
}
private static <T extends Collection<String>> void addAll(
Map<String, List<String>> multiValueMap, Map<String, T> source) {
for (Map.Entry<String, T> entry : source.entrySet()) {
String key = entry.getKey();
for (String value : entry.getValue()) {
add(multiValueMap, key, value);
}
}
}
private static String getFirst(Map<String, List<String>> multiValueMap, String key) {
List<String> values = get(multiValueMap, key);
return CollectionUtils.isNotEmpty(values) ? values.get(0) : null;
}
private static List<String> get(Map<String, List<String>> multiValueMap, String key) {
return get(multiValueMap, key, false);
}
private static List<String> get(Map<String, List<String>> multiValueMap, String key, boolean createIfAbsent) {
return createIfAbsent ? multiValueMap.computeIfAbsent(key, k -> new LinkedList<>()) : multiValueMap.get(key);
}
public Map<String, List<String>> getHeaders() {
return unmodifiableMap(headers);
}
public void setHeaders(Map<String, List<String>> headers) {
headers(headers);
}
public Set<String> getConsumes() {
return consumes;
}
public void setConsumes(Set<String> consumes) {
this.consumes = consumes;
}
public Set<String> getProduces() {
return produces;
}
public void setProduces(Set<String> produces) {
this.produces = produces;
}
public Set<String> getParamNames() {
return new HashSet<>(params.keySet());
}
public Set<String> getHeaderNames() {
return new HashSet<>(headers.keySet());
}
// public List<MediaType> getConsumeMediaTypes() {
// return toMediaTypes(consumes);
// }
//
// public List<MediaType> getProduceMediaTypes() {
// return toMediaTypes(produces);
// }
public String getParameter(String name) {
return getFirst(params, name);
}
public String getHeader(String name) {
return getFirst(headers, name);
}
public RequestMetadata addParam(String name, String value) {
add(params, name, value);
return this;
}
public RequestMetadata addHeader(String name, String value) {
add(headers, name, value);
return this;
}
private <T extends Collection<String>> RequestMetadata params(Map<String, T> params) {
addAll(this.params, params);
return this;
}
private <T extends Collection<String>> RequestMetadata headers(Map<String, List<String>> headers) {
if (headers != null && !headers.isEmpty()) {
Map<String, List<String>> httpHeaders = new LinkedHashMap<>();
// Add all headers
addAll(httpHeaders, headers);
// Handles "Content-Type" and "Accept" headers if present
// mediaTypes(httpHeaders, HttpHeaders.CONTENT_TYPE, this.consumes);
// mediaTypes(httpHeaders, HttpHeaders.ACCEPT, this.produces);
this.headers.putAll(httpHeaders);
}
return this;
}
public void appendContextPathFromUrl(String contextPathFromUrl) {
if (contextPathFromUrl == null) {
return;
}
setPath(contextPathFromUrl + path);
}
public boolean methodAllowed(String method) {
return method != null && method.equals(this.method);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof RequestMetadata)) {
return false;
}
RequestMetadata that = (RequestMetadata) o;
return Objects.equals(method, that.method)
&& Objects.equals(path, that.path)
&& Objects.equals(consumes, that.consumes)
&& Objects.equals(produces, that.produces)
&&
// Metadata should not compare the values
Objects.equals(getParamNames(), that.getParamNames())
&& Objects.equals(getHeaderNames(), that.getHeaderNames());
}
@Override
public int hashCode() {
// The values of metadata should not use for the hashCode() method
return Objects.hash(method, path, consumes, produces, getParamNames(), getHeaderNames());
}
@Override
public String toString() {
return "RequestMetadata{" + "method='" + method + '\'' + ", path='" + path + '\''
+ ", params=" + params + ", headers=" + headers + ", consumes=" + consumes
+ ", produces=" + produces + '}';
}
}
| 7,264 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/NoAnnotatedParameterRequestTagProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.metadata.rest.media.MediaType;
import java.lang.reflect.Parameter;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface NoAnnotatedParameterRequestTagProcessor {
MediaType consumerContentType();
String defaultAnnotationClassName(RestMethodMetadata restMethodMetadata);
boolean process(Parameter parameter, int parameterIndex, RestMethodMetadata restMethodMetadata);
}
| 7,265 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/DefaultServiceRestMetadataResolver.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.lang.reflect.Method;
import java.util.Set;
/**
* The default implementation {@link ServiceRestMetadataResolver}
*
* @since 2.7.6
*/
public class DefaultServiceRestMetadataResolver extends AbstractServiceRestMetadataResolver {
public DefaultServiceRestMetadataResolver(ApplicationModel applicationModel) {
super(applicationModel);
}
@Override
protected boolean supports0(Class<?> serviceType) {
return false;
}
@Override
protected boolean isRestCapableMethod(Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass) {
return false;
}
@Override
protected String resolveRequestMethod(Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass) {
return null;
}
@Override
protected String resolveRequestPath(Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass) {
return null;
}
@Override
protected void processProduces(
Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass, Set<String> produces) {}
@Override
protected void processConsumes(
Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass, Set<String> consumes) {}
}
| 7,266 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataReader.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.common.extension.SPI;
import java.util.List;
/**
* An interface to read {@link ServiceRestMetadata}
*
* @see ServiceRestMetadata
* @since 2.7.6
*/
@SPI
public interface ServiceRestMetadataReader {
/**
* Read the instances of {@link ServiceRestMetadata}
*
* @return non-null
*/
List<ServiceRestMetadata> read();
}
| 7,267 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/AbstractAnnotatedMethodParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import static org.apache.dubbo.common.utils.AnnotationUtils.getValue;
import static org.apache.dubbo.common.utils.ClassUtils.getClassLoader;
import static org.apache.dubbo.common.utils.ClassUtils.resolveClass;
/**
* The abstract {@link AnnotatedMethodParameterProcessor} implementation
*
* @since 2.7.6
*/
public abstract class AbstractAnnotatedMethodParameterProcessor implements AnnotatedMethodParameterProcessor {
@Override
public void process(
Annotation annotation,
Parameter parameter,
int parameterIndex,
Method method,
Class<?> serviceType,
Class<?> serviceInterfaceClass,
RestMethodMetadata restMethodMetadata) {
String annotationValue = getAnnotationValue(annotation, parameter, parameterIndex);
String defaultValue = getDefaultValue(annotation, parameter, parameterIndex);
addArgInfo(parameter, parameterIndex, restMethodMetadata, annotationValue, defaultValue);
process(annotationValue, defaultValue, annotation, parameter, parameterIndex, method, restMethodMetadata);
}
protected void process(
String annotationValue,
String defaultValue,
Annotation annotation,
Parameter parameter,
int parameterIndex,
Method method,
RestMethodMetadata restMethodMetadata) {}
@Override
public Class getAnnotationClass() {
return resolveClass(getAnnotationName(), getClassLoader());
}
protected void addArgInfo(
Parameter parameter,
int parameterIndex,
RestMethodMetadata restMethodMetadata,
String annotationValue,
Object defaultValue) {
ArgInfo argInfo = ArgInfo.build(parameterIndex, parameter)
.setParamAnnotationType(getAnnotationClass())
.setAnnotationNameAttribute(annotationValue)
.setDefaultValue(defaultValue);
restMethodMetadata.addArgInfo(argInfo);
}
protected String getAnnotationValue(Annotation annotation, Parameter parameter, int parameterIndex) {
return getValue(annotation);
}
protected String getDefaultValue(Annotation annotation, Parameter parameter, int parameterIndex) {
return AnnotatedMethodParameterProcessor.buildDefaultValue(parameterIndex);
}
}
| 7,268 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/ClassPathServiceRestMetadataReader.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.common.utils.IOUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import static java.util.Collections.unmodifiableList;
import static org.apache.dubbo.common.function.ThrowableAction.execute;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.METADATA_ENCODING;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SERVICE_REST_METADATA_RESOURCE_PATH;
/**
* Class-Path based {@link ServiceRestMetadataReader} implementation
*
* @see ServiceRestMetadataReader
* @since 2.7.6
*/
public class ClassPathServiceRestMetadataReader implements ServiceRestMetadataReader {
private final String serviceRestMetadataJsonResourcePath;
public ClassPathServiceRestMetadataReader() {
this(SERVICE_REST_METADATA_RESOURCE_PATH);
}
public ClassPathServiceRestMetadataReader(String serviceRestMetadataJsonResourcePath) {
this.serviceRestMetadataJsonResourcePath = serviceRestMetadataJsonResourcePath;
}
@Override
public List<ServiceRestMetadata> read() {
List<ServiceRestMetadata> serviceRestMetadataList = new LinkedList<>();
ClassLoader classLoader = getClass().getClassLoader();
execute(() -> {
Enumeration<URL> resources = classLoader.getResources(serviceRestMetadataJsonResourcePath);
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
InputStream inputStream = resource.openStream();
String json = IOUtils.read(inputStream, METADATA_ENCODING);
serviceRestMetadataList.addAll(JsonUtils.toJavaList(json, ServiceRestMetadata.class));
}
});
return unmodifiableList(serviceRestMetadataList);
}
}
| 7,269 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadata.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest;
import org.apache.dubbo.common.utils.PathUtils;
import org.apache.dubbo.metadata.ParameterTypesComparator;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* The metadata class for {@link RequestMetadata HTTP(REST) request} and
* its binding Dubbo service metadata
*
* @since 2.7.6
*/
public class ServiceRestMetadata implements Serializable {
private static final long serialVersionUID = -4549723140727443569L;
private String serviceInterface;
private String version;
private String group;
private Set<RestMethodMetadata> meta;
private Integer port;
private boolean consumer;
private String contextPathFromUrl;
/**
* make a distinction between mvc & resteasy
*/
private Class codeStyle;
private Map<PathMatcher, RestMethodMetadata> pathToServiceMapContainPathVariable = new HashMap<>();
private Map<PathMatcher, RestMethodMetadata> pathToServiceMapUnContainPathVariable = new HashMap<>();
private Map<String, Map<ParameterTypesComparator, RestMethodMetadata>> methodToServiceMap = new HashMap<>();
public ServiceRestMetadata(String serviceInterface, String version, String group, boolean consumer) {
this.serviceInterface = serviceInterface;
this.version = version;
this.group = group;
this.consumer = consumer;
}
public ServiceRestMetadata() {}
public ServiceRestMetadata(String serviceInterface, String version, String group) {
this(serviceInterface, version, group, false);
}
public String getServiceInterface() {
return serviceInterface;
}
public void setServiceInterface(String serviceInterface) {
this.serviceInterface = serviceInterface;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public Set<RestMethodMetadata> getMeta() {
if (meta == null) {
meta = new LinkedHashSet<>();
}
return meta;
}
public void setMeta(Set<RestMethodMetadata> meta) {
this.meta = meta;
}
public void addRestMethodMetadata(RestMethodMetadata restMethodMetadata) {
PathMatcher pathMather = new PathMatcher(
restMethodMetadata.getRequest().getPath(),
this.getVersion(),
this.getGroup(),
this.getPort(),
restMethodMetadata.getRequest().getMethod());
pathMather.setMethod(restMethodMetadata.getReflectMethod());
addPathToServiceMap(pathMather, restMethodMetadata);
addMethodToServiceMap(restMethodMetadata);
getMeta().add(restMethodMetadata);
}
public Map<PathMatcher, RestMethodMetadata> getPathContainPathVariableToServiceMap() {
return pathToServiceMapContainPathVariable;
}
public Map<PathMatcher, RestMethodMetadata> getPathUnContainPathVariableToServiceMap() {
return pathToServiceMapUnContainPathVariable;
}
public void addPathToServiceMap(PathMatcher pathMather, RestMethodMetadata restMethodMetadata) {
if (pathMather.hasPathVariable()) {
doublePathCheck(pathToServiceMapContainPathVariable, pathMather, restMethodMetadata, true);
} else {
doublePathCheck(pathToServiceMapUnContainPathVariable, pathMather, restMethodMetadata, false);
}
}
private void doublePathCheck(
Map<PathMatcher, RestMethodMetadata> pathMatcherRestMethodMetadataMap,
PathMatcher pathMather,
RestMethodMetadata restMethodMetadata,
boolean containPathVariable) {
if (pathMatcherRestMethodMetadataMap.containsKey(pathMather)) {
if (containPathVariable) {
throw new IllegalArgumentException(
"dubbo rest metadata resolve double path error,and contain path variable is: " + pathMather
+ ", rest method metadata is: " + restMethodMetadata);
} else {
throw new IllegalArgumentException(
"dubbo rest metadata resolve double path error,and do not contain path variable is: "
+ pathMather + ", rest method metadata is: " + restMethodMetadata);
}
}
pathMatcherRestMethodMetadataMap.put(pathMather, restMethodMetadata);
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
setPort(port, getPathContainPathVariableToServiceMap());
setPort(port, getPathUnContainPathVariableToServiceMap());
}
private void setPort(Integer port, Map<PathMatcher, RestMethodMetadata> pathToServiceMapContainPathVariable) {
for (PathMatcher pathMather : pathToServiceMapContainPathVariable.keySet()) {
pathMather.setPort(port);
}
}
public boolean isConsumer() {
return consumer;
}
public void setConsumer(boolean consumer) {
this.consumer = consumer;
}
public Map<String, Map<ParameterTypesComparator, RestMethodMetadata>> getMethodToServiceMap() {
return methodToServiceMap;
}
public void addMethodToServiceMap(RestMethodMetadata restMethodMetadata) {
if (this.methodToServiceMap == null) {
this.methodToServiceMap = new HashMap<>();
}
this.methodToServiceMap
.computeIfAbsent(restMethodMetadata.getReflectMethod().getName(), k -> new HashMap<>())
.put(
ParameterTypesComparator.getInstance(
restMethodMetadata.getReflectMethod().getParameterTypes()),
restMethodMetadata);
}
public Class getCodeStyle() {
return codeStyle;
}
public void setCodeStyle(Class codeStyle) {
this.codeStyle = codeStyle;
}
public String getContextPathFromUrl() {
return contextPathFromUrl == null ? "" : contextPathFromUrl;
}
public void setContextPathFromUrl(String contextPathFromUrl) {
this.contextPathFromUrl = PathUtils.normalize(contextPathFromUrl);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ServiceRestMetadata)) {
return false;
}
ServiceRestMetadata that = (ServiceRestMetadata) o;
return Objects.equals(getServiceInterface(), that.getServiceInterface())
&& Objects.equals(getVersion(), that.getVersion())
&& Objects.equals(getGroup(), that.getGroup())
&& Objects.equals(getMeta(), that.getMeta())
&& Objects.equals(getPort(), that.getPort());
}
@Override
public int hashCode() {
return Objects.hash(getServiceInterface(), getVersion(), getGroup(), getMeta(), getPort());
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ServiceRestMetadata{");
sb.append("serviceInterface='").append(serviceInterface).append('\'');
sb.append(", version='").append(version).append('\'');
sb.append(", group='").append(group).append('\'');
sb.append(", meta=").append(meta);
sb.append(", port=").append(port);
sb.append('}');
return sb.toString();
}
}
| 7,270 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/FormParamParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.jaxrs;
import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.FORM_PARAM_ANNOTATION_CLASS_NAME;
/**
* The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @FormParam
*
* @since 2.7.6
*/
public class FormParamParameterProcessor extends ParamAnnotationParameterProcessor {
@Override
public String getAnnotationName() {
return FORM_PARAM_ANNOTATION_CLASS_NAME;
}
}
| 7,271 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolver.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.jaxrs;
import org.apache.dubbo.metadata.rest.AbstractServiceRestMetadataResolver;
import org.apache.dubbo.metadata.rest.ServiceRestMetadataResolver;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.stream.Stream;
import static org.apache.dubbo.common.utils.AnnotationUtils.findAnnotation;
import static org.apache.dubbo.common.utils.AnnotationUtils.findMetaAnnotation;
import static org.apache.dubbo.common.utils.AnnotationUtils.getValue;
import static org.apache.dubbo.common.utils.AnnotationUtils.isAnnotationPresent;
import static org.apache.dubbo.common.utils.PathUtils.buildPath;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.CONSUMES_ANNOTATION_CLASS_NAME;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.HTTP_METHOD_ANNOTATION_CLASS_NAME;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.PATH_ANNOTATION_CLASS_NAME;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.PRODUCES_ANNOTATION_CLASS_NAME;
/**
* JAX-RS {@link ServiceRestMetadataResolver} implementation
*
* @since 2.7.6
*/
public class JAXRSServiceRestMetadataResolver extends AbstractServiceRestMetadataResolver {
public JAXRSServiceRestMetadataResolver(ApplicationModel applicationModel) {
super(applicationModel);
}
@Override
protected boolean supports0(Class<?> serviceType) {
return isAnnotationPresent(serviceType, PATH_ANNOTATION_CLASS_NAME)
// method @Path
|| isServiceMethodAnnotationPresent(serviceType, PATH_ANNOTATION_CLASS_NAME);
}
@Override
protected boolean isRestCapableMethod(Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass) {
return isAnnotationPresent(serviceMethod, HTTP_METHOD_ANNOTATION_CLASS_NAME);
}
@Override
protected String resolveRequestMethod(Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass) {
Annotation httpMethod = findMetaAnnotation(serviceMethod, HTTP_METHOD_ANNOTATION_CLASS_NAME);
return getValue(httpMethod);
}
@Override
protected String resolveRequestPath(Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass) {
String requestBasePath = resolveRequestPathFromType(serviceType, serviceInterfaceClass);
String requestRelativePath = resolveRequestPathFromMethod(serviceMethod);
return buildPath(requestBasePath, requestRelativePath);
}
private String resolveRequestPathFromType(Class<?> serviceType, Class<?> serviceInterfaceClass) {
Annotation path = findAnnotation(serviceType, PATH_ANNOTATION_CLASS_NAME);
if (path == null) {
path = findAnnotation(serviceInterfaceClass, PATH_ANNOTATION_CLASS_NAME);
}
return getValue(path);
}
private String resolveRequestPathFromMethod(Method serviceMethod) {
Annotation path = findAnnotation(serviceMethod, PATH_ANNOTATION_CLASS_NAME);
return getValue(path);
}
@Override
protected void processProduces(
Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass, Set<String> produces) {
addAnnotationValues(serviceMethod, PRODUCES_ANNOTATION_CLASS_NAME, produces);
addAnnotationValues(serviceType, PRODUCES_ANNOTATION_CLASS_NAME, produces);
addAnnotationValues(serviceInterfaceClass, PRODUCES_ANNOTATION_CLASS_NAME, produces);
}
@Override
protected void processConsumes(
Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass, Set<String> consumes) {
addAnnotationValues(serviceMethod, CONSUMES_ANNOTATION_CLASS_NAME, consumes);
addAnnotationValues(serviceType, CONSUMES_ANNOTATION_CLASS_NAME, consumes);
addAnnotationValues(serviceInterfaceClass, CONSUMES_ANNOTATION_CLASS_NAME, consumes);
}
private void addAnnotationValues(Method serviceMethod, String annotationAttributeName, Set<String> result) {
Annotation annotation = findAnnotation(serviceMethod, annotationAttributeName);
String[] value = getValue(annotation);
if (value != null) {
Stream.of(value).forEach(result::add);
}
}
private void addAnnotationValues(Class serviceType, String annotationAttributeName, Set<String> result) {
Annotation annotation = findAnnotation(serviceType, annotationAttributeName);
String[] value = getValue(annotation);
if (value != null) {
Stream.of(value).forEach(result::add);
}
}
}
| 7,272 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/DefaultValueParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.jaxrs;
import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor;
import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor;
import org.apache.dubbo.metadata.rest.RequestMetadata;
import org.apache.dubbo.metadata.rest.RestMethodMetadata;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.List;
import java.util.Map;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.DEFAULT_VALUE_ANNOTATION_CLASS_NAME;
/**
* The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @DefaultValue
* *
*
* @since 2.7.6
*/
public class DefaultValueParameterProcessor extends AbstractAnnotatedMethodParameterProcessor {
@Override
public String getAnnotationName() {
return DEFAULT_VALUE_ANNOTATION_CLASS_NAME;
}
@Override
protected void process(
String annotationValue,
String defaultValue,
Annotation annotation,
Parameter parameter,
int parameterIndex,
Method method,
RestMethodMetadata restMethodMetadata) {
RequestMetadata requestMetadata = restMethodMetadata.getRequest();
// process the request parameters
setDefaultValue(requestMetadata.getParams(), defaultValue, annotationValue);
// process the request headers
setDefaultValue(requestMetadata.getHeaders(), defaultValue, annotationValue);
}
private void setDefaultValue(Map<String, List<String>> source, String placeholderValue, String defaultValue) {
OUTTER:
for (Map.Entry<String, List<String>> entry : source.entrySet()) {
List<String> values = entry.getValue();
int size = values.size();
for (int i = 0; i < size; i++) {
String value = values.get(i);
if (placeholderValue.equals(value)) {
values.set(i, defaultValue);
break OUTTER;
}
}
}
}
@Override
public int getPriority() {
return MIN_PRIORITY;
}
}
| 7,273 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/PathParamParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.jaxrs;
import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor;
import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.PATH_PARAM_ANNOTATION_CLASS_NAME;
/**
* The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @PathParam
*
* @since 2.7.6
*/
public class PathParamParameterProcessor extends AbstractAnnotatedMethodParameterProcessor {
@Override
public String getAnnotationName() {
return PATH_PARAM_ANNOTATION_CLASS_NAME;
}
}
| 7,274 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/QueryParamParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.jaxrs;
import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.QUERY_PARAM_ANNOTATION_CLASS_NAME;
/**
* The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @QueryParam
*
* @since 2.7.6
*/
public class QueryParamParameterProcessor extends ParamAnnotationParameterProcessor {
@Override
public String getAnnotationName() {
return QUERY_PARAM_ANNOTATION_CLASS_NAME;
}
}
| 7,275 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/MatrixParamParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.jaxrs;
import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.MATRIX_PARAM_ANNOTATION_CLASS_NAME;
/**
* The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @MatrixParam
*
* @since 2.7.6
*/
public class MatrixParamParameterProcessor extends ParamAnnotationParameterProcessor {
@Override
public String getAnnotationName() {
return MATRIX_PARAM_ANNOTATION_CLASS_NAME;
}
}
| 7,276 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/FormBodyParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.jaxrs;
import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor;
import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor;
import org.apache.dubbo.metadata.rest.RestMethodMetadata;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.REST_EASY_FORM_BODY_ANNOTATION_CLASS_NAME;
import static org.apache.dubbo.metadata.rest.media.MediaType.APPLICATION_FORM_URLENCODED_VALUE;
/**
* The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @FormParam
*
* @since 2.7.6
*/
public class FormBodyParameterProcessor extends AbstractAnnotatedMethodParameterProcessor {
@Override
public String getAnnotationName() {
return REST_EASY_FORM_BODY_ANNOTATION_CLASS_NAME;
}
@Override
public void process(
Annotation annotation,
Parameter parameter,
int parameterIndex,
Method method,
Class<?> serviceType,
Class<?> serviceInterfaceClass,
RestMethodMetadata restMethodMetadata) {
super.process(
annotation, parameter, parameterIndex, method, serviceType, serviceInterfaceClass, restMethodMetadata);
restMethodMetadata.getRequest().getConsumes().add(APPLICATION_FORM_URLENCODED_VALUE.value);
}
@Override
protected String getAnnotationValue(Annotation annotation, Parameter parameter, int parameterIndex) {
return null;
}
}
| 7,277 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/HeaderParamParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.jaxrs;
import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor;
import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor;
import org.apache.dubbo.metadata.rest.RequestMetadata;
import org.apache.dubbo.metadata.rest.RestMethodMetadata;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import static org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor.buildDefaultValue;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.HEADER_PARAM_ANNOTATION_CLASS_NAME;
/**
* The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @HeaderParam
*
* @since 2.7.6
*/
public class HeaderParamParameterProcessor extends AbstractAnnotatedMethodParameterProcessor {
@Override
public String getAnnotationName() {
return HEADER_PARAM_ANNOTATION_CLASS_NAME;
}
@Override
protected void process(
String headerName,
String defaultValue,
Annotation annotation,
Parameter parameter,
int parameterIndex,
Method method,
RestMethodMetadata restMethodMetadata) {
RequestMetadata requestMetadata = restMethodMetadata.getRequest();
// Add the placeholder as header value
requestMetadata.addHeader(headerName, buildDefaultValue(parameterIndex));
}
}
| 7,278 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/ParamAnnotationParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.jaxrs;
import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor;
import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor;
import org.apache.dubbo.metadata.rest.RequestMetadata;
import org.apache.dubbo.metadata.rest.RestMethodMetadata;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
/**
* The abstract {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @*Param
*/
public abstract class ParamAnnotationParameterProcessor extends AbstractAnnotatedMethodParameterProcessor {
@Override
protected void process(
String name,
String defaultValue,
Annotation annotation,
Parameter parameter,
int parameterIndex,
Method method,
RestMethodMetadata restMethodMetadata) {
RequestMetadata requestMetadata = restMethodMetadata.getRequest();
requestMetadata.addParam(name, defaultValue);
}
}
| 7,279 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/BodyParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.jaxrs;
import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor;
import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor;
import org.apache.dubbo.metadata.rest.ArgInfo;
import org.apache.dubbo.metadata.rest.RestMethodMetadata;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.REST_EASY_BODY_ANNOTATION_CLASS_NAME;
/**
* The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @FormParam
*
* @since 2.7.6
*/
public class BodyParameterProcessor extends AbstractAnnotatedMethodParameterProcessor {
@Override
public String getAnnotationName() {
return REST_EASY_BODY_ANNOTATION_CLASS_NAME;
}
@Override
public void process(
Annotation annotation,
Parameter parameter,
int parameterIndex,
Method method,
Class<?> serviceType,
Class<?> serviceInterfaceClass,
RestMethodMetadata restMethodMetadata) {
ArgInfo argInfo = ArgInfo.build(parameterIndex, parameter).setParamAnnotationType(getAnnotationClass());
restMethodMetadata.addArgInfo(argInfo);
}
}
| 7,280 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/tag/BodyTag.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.tag;
/**
* for @RequestBody class no found
*/
public interface BodyTag {}
| 7,281 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/tag/ParamTag.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.tag;
/**
* for @RequestParam or @QueryParam class no found
*/
public interface ParamTag {}
| 7,282 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/AbstractRequestAnnotationParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.springmvc;
import org.apache.dubbo.common.utils.AnnotationUtils;
import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor;
import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Parameter;
import java.util.Objects;
import static org.apache.dubbo.common.utils.AnnotationUtils.getAttribute;
/**
* The abstract {@link AnnotatedMethodParameterProcessor} implementation for Spring Web MVC's @Request*
*/
public abstract class AbstractRequestAnnotationParameterProcessor extends AbstractAnnotatedMethodParameterProcessor {
@Override
protected String getAnnotationValue(Annotation annotation, Parameter parameter, int parameterIndex) {
// try to get "value" attribute first
String name = super.getAnnotationValue(annotation, parameter, parameterIndex);
// try to get "name" attribute if required
if (isEmpty(name)) {
name = getAttribute(annotation, "name");
}
// finally , try to the name of parameter
if (isEmpty(name)) {
name = parameter.getName();
}
return name;
}
@Override
protected String getDefaultValue(Annotation annotation, Parameter parameter, int parameterIndex) {
String attributeName = "defaultValue";
String attributeValue = getAttribute(annotation, attributeName);
if (isEmpty(attributeValue) || isDefaultValue(annotation, attributeName, attributeValue)) {
attributeValue = super.getDefaultValue(annotation, parameter, parameterIndex);
}
return attributeValue;
}
private boolean isDefaultValue(Annotation annotation, String attributeName, Object attributeValue) {
String defaultValue = AnnotationUtils.getDefaultValue(annotation, attributeName);
return Objects.deepEquals(attributeValue, defaultValue);
}
protected boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
}
| 7,283 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/ParamNoAnnotatedProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.springmvc;
import org.apache.dubbo.metadata.rest.AbstractNoAnnotatedParameterProcessor;
import org.apache.dubbo.metadata.rest.RestMethodMetadata;
import org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver;
import org.apache.dubbo.metadata.rest.media.MediaType;
import org.apache.dubbo.metadata.rest.tag.BodyTag;
import org.apache.dubbo.metadata.rest.tag.ParamTag;
import static org.apache.dubbo.metadata.rest.media.MediaType.ALL_VALUE;
public class ParamNoAnnotatedProcessor extends AbstractNoAnnotatedParameterProcessor {
@Override
public MediaType consumerContentType() {
return ALL_VALUE;
}
@Override
public String defaultAnnotationClassName(RestMethodMetadata restMethodMetadata) {
if (JAXRSServiceRestMetadataResolver.class.equals(restMethodMetadata.getCodeStyle())) {
return BodyTag.class.getName();
}
return ParamTag.class.getName();
}
}
| 7,284 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestParamParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.springmvc;
import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor;
import org.apache.dubbo.metadata.rest.RestMethodMetadata;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.REQUEST_PARAM_ANNOTATION_CLASS_NAME;
/**
* The {@link AnnotatedMethodParameterProcessor} implementation for Spring Web MVC's @RequestParam
*/
public class RequestParamParameterProcessor extends AbstractRequestAnnotationParameterProcessor {
@Override
public String getAnnotationName() {
return REQUEST_PARAM_ANNOTATION_CLASS_NAME;
}
@Override
protected void process(
String name,
String defaultValue,
Annotation annotation,
Parameter parameter,
int parameterIndex,
Method method,
RestMethodMetadata restMethodMetadata) {
restMethodMetadata.getRequest().addParam(name, defaultValue);
}
}
| 7,285 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/JsonBodyNoAnnotatedProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.springmvc;
import org.apache.dubbo.metadata.rest.AbstractNoAnnotatedParameterProcessor;
import org.apache.dubbo.metadata.rest.RestMethodMetadata;
import org.apache.dubbo.metadata.rest.media.MediaType;
import org.apache.dubbo.metadata.rest.tag.BodyTag;
import static org.apache.dubbo.metadata.rest.media.MediaType.APPLICATION_JSON_VALUE;
public class JsonBodyNoAnnotatedProcessor extends AbstractNoAnnotatedParameterProcessor {
@Override
public MediaType consumerContentType() {
return APPLICATION_JSON_VALUE;
}
@Override
public String defaultAnnotationClassName(RestMethodMetadata restMethodMetadata) {
return BodyTag.class.getName();
}
}
| 7,286 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestHeaderParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.springmvc;
import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor;
import org.apache.dubbo.metadata.rest.RestMethodMetadata;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.REQUEST_HEADER_ANNOTATION_CLASS_NAME;
/**
* The {@link AnnotatedMethodParameterProcessor} implementation for Spring Web MVC's @RequestHeader
*/
public class RequestHeaderParameterProcessor extends AbstractRequestAnnotationParameterProcessor {
@Override
public String getAnnotationName() {
return REQUEST_HEADER_ANNOTATION_CLASS_NAME;
}
@Override
protected void process(
String name,
String defaultValue,
Annotation annotation,
Parameter parameter,
int parameterIndex,
Method method,
RestMethodMetadata restMethodMetadata) {
restMethodMetadata.getRequest().addHeader(name, defaultValue);
}
}
| 7,287 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/FormBodyNoAnnotatedProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.springmvc;
import org.apache.dubbo.metadata.rest.AbstractNoAnnotatedParameterProcessor;
import org.apache.dubbo.metadata.rest.RestMethodMetadata;
import org.apache.dubbo.metadata.rest.media.MediaType;
import org.apache.dubbo.metadata.rest.tag.BodyTag;
import static org.apache.dubbo.metadata.rest.media.MediaType.APPLICATION_FORM_URLENCODED_VALUE;
public class FormBodyNoAnnotatedProcessor extends AbstractNoAnnotatedParameterProcessor {
@Override
public MediaType consumerContentType() {
return APPLICATION_FORM_URLENCODED_VALUE;
}
@Override
public String defaultAnnotationClassName(RestMethodMetadata restMethodMetadata) {
return BodyTag.class.getName();
}
@Override
protected boolean isFormContentType(RestMethodMetadata restMethodMetadata) {
return true;
}
}
| 7,288 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestBodyParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.springmvc;
import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor;
import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Parameter;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.REQUEST_BODY_ANNOTATION_CLASS_NAME;
/**
* The {@link AnnotatedMethodParameterProcessor} implementation for Spring Web MVC's @RequestBody
*/
public class RequestBodyParameterProcessor extends AbstractAnnotatedMethodParameterProcessor {
@Override
public String getAnnotationName() {
return REQUEST_BODY_ANNOTATION_CLASS_NAME;
}
@Override
protected String getAnnotationValue(Annotation annotation, Parameter parameter, int parameterIndex) {
return null;
}
@Override
protected String getDefaultValue(Annotation annotation, Parameter parameter, int parameterIndex) {
return null;
}
}
| 7,289 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolver.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.springmvc;
import org.apache.dubbo.metadata.rest.AbstractServiceRestMetadataResolver;
import org.apache.dubbo.metadata.rest.ServiceRestMetadataResolver;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.Set;
import static java.lang.String.valueOf;
import static java.lang.reflect.Array.getLength;
import static java.util.stream.Stream.of;
import static org.apache.dubbo.common.utils.AnnotationUtils.findAnnotation;
import static org.apache.dubbo.common.utils.AnnotationUtils.getAttribute;
import static org.apache.dubbo.common.utils.AnnotationUtils.isAnnotationPresent;
import static org.apache.dubbo.common.utils.ArrayUtils.isEmpty;
import static org.apache.dubbo.common.utils.ArrayUtils.isNotEmpty;
import static org.apache.dubbo.common.utils.MethodUtils.findMethod;
import static org.apache.dubbo.common.utils.PathUtils.buildPath;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.ANNOTATED_ELEMENT_UTILS_CLASS;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.CONTROLLER_ANNOTATION_CLASS;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.REQUEST_MAPPING_ANNOTATION_CLASS;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.REQUEST_MAPPING_ANNOTATION_CLASS_NAME;
/**
* {@link ServiceRestMetadataResolver}
*
* @since 2.7.6
*/
public class SpringMvcServiceRestMetadataResolver extends AbstractServiceRestMetadataResolver {
private static final int FIRST_ELEMENT_INDEX = 0;
public SpringMvcServiceRestMetadataResolver(ApplicationModel applicationModel) {
super(applicationModel);
}
@Override
protected boolean supports0(Class<?> serviceType) {
// class @Controller or @RequestMapping
return isAnnotationPresent(serviceType, CONTROLLER_ANNOTATION_CLASS)
|| isAnnotationPresent(serviceType, REQUEST_MAPPING_ANNOTATION_CLASS)
// method @RequestMapping
|| isServiceMethodAnnotationPresent(serviceType, REQUEST_MAPPING_ANNOTATION_CLASS_NAME);
}
@Override
protected boolean isRestCapableMethod(Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass) {
// method only match @RequestMapping
return isAnnotationPresent(serviceMethod, REQUEST_MAPPING_ANNOTATION_CLASS);
}
@Override
protected String resolveRequestMethod(Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass) {
Annotation requestMapping = getRequestMapping(serviceMethod);
// httpMethod is an array of RequestMethod
Object httpMethod = getAttribute(requestMapping, "method");
if (httpMethod == null || getLength(httpMethod) < 1) {
return null;
}
// TODO Is is required to support more request methods?
return valueOf(Array.get(httpMethod, FIRST_ELEMENT_INDEX));
}
@Override
protected String resolveRequestPath(Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass) {
String requestBasePath = resolveRequestPath(serviceType);
String requestRelativePath = resolveRequestPath(serviceMethod);
return buildPath(requestBasePath, requestRelativePath);
}
@Override
protected void processProduces(
Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass, Set<String> produces) {
addMediaTypes(serviceMethod, "produces", produces);
addMediaTypes(serviceType, "produces", produces);
addMediaTypes(serviceInterfaceClass, "produces", produces);
}
@Override
protected void processConsumes(
Method serviceMethod, Class<?> serviceType, Class<?> serviceInterfaceClass, Set<String> consumes) {
addMediaTypes(serviceMethod, "consumes", consumes);
addMediaTypes(serviceType, "consumes", consumes);
addMediaTypes(serviceInterfaceClass, "consumes", consumes);
}
private String resolveRequestPath(AnnotatedElement annotatedElement) {
Annotation mappingAnnotation = getRequestMapping(annotatedElement);
// try "value" first
String[] value = getAttribute(mappingAnnotation, "value");
if (isEmpty(value)) { // try "path" later
value = getAttribute(mappingAnnotation, "path");
}
if (isEmpty(value)) {
return "";
}
// TODO Is is required to support more request paths?
return value[FIRST_ELEMENT_INDEX];
}
private void addMediaTypes(Method serviceMethod, String annotationAttributeName, Set<String> mediaTypesSet) {
Annotation mappingAnnotation = getRequestMapping(serviceMethod);
String[] mediaTypes = getAttribute(mappingAnnotation, annotationAttributeName);
if (isNotEmpty(mediaTypes)) {
of(mediaTypes).forEach(mediaTypesSet::add);
}
}
private void addMediaTypes(Class serviceType, String annotationAttributeName, Set<String> mediaTypesSet) {
Annotation mappingAnnotation = getRequestMapping(serviceType);
String[] mediaTypes = getAttribute(mappingAnnotation, annotationAttributeName);
if (isNotEmpty(mediaTypes)) {
of(mediaTypes).forEach(mediaTypesSet::add);
}
}
private Annotation getRequestMapping(AnnotatedElement annotatedElement) {
// try "@RequestMapping" first
Annotation requestMapping = findAnnotation(annotatedElement, REQUEST_MAPPING_ANNOTATION_CLASS);
if (requestMapping == null) {
// To try the meta-annotated annotation if can't be found.
// For example, if the annotation "@GetMapping" is used in the Spring Framework is 4.2 or above,
// because of "@GetMapping" alias for ("@AliasFor") "@RequestMapping" , both of them belongs to
// the artifact "spring-web" which depends on "spring-core", thus Spring core's
// AnnotatedElementUtils.findMergedAnnotation(AnnotatedElement, Class) must be involved.
Method method = findMethod(
ANNOTATED_ELEMENT_UTILS_CLASS, "findMergedAnnotation", AnnotatedElement.class, Class.class);
if (method != null) {
try {
requestMapping =
(Annotation) method.invoke(null, annotatedElement, REQUEST_MAPPING_ANNOTATION_CLASS);
} catch (Exception ignored) {
}
}
}
return requestMapping;
}
}
| 7,290 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/springmvc/PathVariableParameterProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.springmvc;
import org.apache.dubbo.metadata.rest.AbstractAnnotatedMethodParameterProcessor;
import org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Parameter;
import static org.apache.dubbo.metadata.rest.RestMetadataConstants.SPRING_MVC.PATH_VARIABLE_ANNOTATION_CLASS_NAME;
/**
* The {@link AnnotatedMethodParameterProcessor} implementation for Spring Web MVC's @PathVariable
*/
public class PathVariableParameterProcessor extends AbstractAnnotatedMethodParameterProcessor {
@Override
public String getAnnotationName() {
return PATH_VARIABLE_ANNOTATION_CLASS_NAME;
}
@Override
protected String getDefaultValue(Annotation annotation, Parameter parameter, int parameterIndex) {
return null;
}
}
| 7,291 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/rest/media/MediaType.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.rest.media;
import java.util.Arrays;
import java.util.List;
public enum MediaType {
ALL_VALUE("*/*"),
APPLICATION_JSON_VALUE("application/json"),
APPLICATION_FORM_URLENCODED_VALUE("application/x-www-form-urlencoded"),
TEXT_PLAIN("text/plain"),
TEXT_XML("text/xml"),
OCTET_STREAM("application/octet-stream"),
;
MediaType(String value) {
this.value = value;
}
public String value;
public static String getAllContentType() {
MediaType[] values = MediaType.values();
StringBuilder stringBuilder = new StringBuilder();
for (MediaType mediaType : values) {
stringBuilder.append(mediaType.value + " ");
}
return stringBuilder.toString();
}
public static List<MediaType> getSupportMediaTypes() {
return Arrays.asList(
APPLICATION_JSON_VALUE, APPLICATION_FORM_URLENCODED_VALUE, TEXT_PLAIN, TEXT_XML, OCTET_STREAM);
}
}
| 7,292 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadata4TstService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store.redis;
/**
* 2018/10/26
*/
public interface RedisMetadata4TstService {
int getCounter();
void printResult(String var);
}
| 7,293 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store.redis;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder;
import org.apache.dubbo.metadata.definition.model.FullServiceDefinition;
import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.rpc.RpcException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.apache.commons.lang3.SystemUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.embedded.RedisServer;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.SYNC_REPORT_KEY;
import static redis.embedded.RedisServer.newRedisServer;
class RedisMetadataReportTest {
private static final String REDIS_URL_TEMPLATE = "redis://%slocalhost:%d",
REDIS_PASSWORD = "チェリー",
REDIS_URL_AUTH_SECTION = "username:" + REDIS_PASSWORD + "@";
RedisMetadataReport redisMetadataReport;
RedisMetadataReport syncRedisMetadataReport;
RedisServer redisServer;
URL registryUrl;
@BeforeEach
public void constructor(final TestInfo testInfo) {
final boolean usesAuthentication = usesAuthentication(testInfo);
int redisPort = 0;
IOException exception = null;
for (int i = 0; i < 10; i++) {
try {
redisPort = NetUtils.getAvailablePort(30000 + new Random().nextInt(10000));
redisServer = newRedisServer()
.port(redisPort)
// set maxheap to fix Windows error 0x70 while starting redis
.settingIf(SystemUtils.IS_OS_WINDOWS, "maxheap 128mb")
.settingIf(usesAuthentication, "requirepass " + REDIS_PASSWORD)
.build();
this.redisServer.start();
exception = null;
} catch (IOException e) {
e.printStackTrace();
exception = e;
}
if (exception == null) {
break;
}
}
Assertions.assertNull(exception);
registryUrl = newRedisUrl(usesAuthentication, redisPort);
redisMetadataReport = (RedisMetadataReport) new RedisMetadataReportFactory().createMetadataReport(registryUrl);
URL syncRegistryUrl = registryUrl.addParameter(SYNC_REPORT_KEY, "true");
syncRedisMetadataReport =
(RedisMetadataReport) new RedisMetadataReportFactory().createMetadataReport(syncRegistryUrl);
}
private static boolean usesAuthentication(final TestInfo testInfo) {
final String methodName = testInfo.getTestMethod().get().getName();
return "testAuthRedisMetadata".equals(methodName) || "testWrongAuthRedisMetadata".equals(methodName);
}
private static URL newRedisUrl(final boolean usesAuthentication, final int redisPort) {
final String urlAuthSection = usesAuthentication ? REDIS_URL_AUTH_SECTION : "";
return URL.valueOf(String.format(REDIS_URL_TEMPLATE, urlAuthSection, redisPort));
}
@AfterEach
public void tearDown() throws Exception {
this.redisServer.stop();
}
@Test
void testAsyncStoreProvider() throws ClassNotFoundException {
testStoreProvider(redisMetadataReport, "1.0.0.redis.md.p1", 3000);
}
@Test
void testSyncStoreProvider() throws ClassNotFoundException {
testStoreProvider(syncRedisMetadataReport, "1.0.0.redis.md.p2", 3);
}
private void testStoreProvider(RedisMetadataReport redisMetadataReport, String version, long moreTime)
throws ClassNotFoundException {
String interfaceName = "org.apache.dubbo.metadata.store.redis.RedisMetadata4TstService";
String group = null;
String application = "vic.redis.md";
MetadataIdentifier providerMetadataIdentifier =
storePrivider(redisMetadataReport, interfaceName, version, group, application);
Jedis jedis = null;
try {
jedis = redisMetadataReport.pool.getResource();
String keyTmp = providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY);
String value = jedis.get(keyTmp);
if (value == null) {
Thread.sleep(moreTime);
value = jedis.get(keyTmp);
}
Assertions.assertNotNull(value);
FullServiceDefinition fullServiceDefinition = JsonUtils.toJavaObject(value, FullServiceDefinition.class);
Assertions.assertEquals(fullServiceDefinition.getParameters().get("paramTest"), "redisTest");
} catch (Throwable e) {
throw new RpcException("Failed to put to redis . cause: " + e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.del(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY));
}
redisMetadataReport.pool.close();
}
}
@Test
void testAsyncStoreConsumer() throws ClassNotFoundException {
testStoreConsumer(redisMetadataReport, "1.0.0.redis.md.c1", 3000);
}
@Test
void testSyncStoreConsumer() throws ClassNotFoundException {
testStoreConsumer(syncRedisMetadataReport, "1.0.0.redis.md.c2", 3);
}
private void testStoreConsumer(RedisMetadataReport redisMetadataReport, String version, long moreTime)
throws ClassNotFoundException {
String interfaceName = "org.apache.dubbo.metadata.store.redis.RedisMetadata4TstService";
String group = null;
String application = "vic.redis.md";
MetadataIdentifier consumerMetadataIdentifier =
storeConsumer(redisMetadataReport, interfaceName, version, group, application);
Jedis jedis = null;
try {
jedis = redisMetadataReport.pool.getResource();
String keyTmp = consumerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY);
String value = jedis.get(keyTmp);
if (value == null) {
Thread.sleep(moreTime);
value = jedis.get(keyTmp);
}
Assertions.assertEquals(value, "{\"paramConsumerTest\":\"redisCm\"}");
} catch (Throwable e) {
throw new RpcException("Failed to put to redis . cause: " + e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.del(consumerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY));
}
redisMetadataReport.pool.close();
}
}
private MetadataIdentifier storePrivider(
RedisMetadataReport redisMetadataReport,
String interfaceName,
String version,
String group,
String application)
throws ClassNotFoundException {
URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName
+ "?paramTest=redisTest&version=" + version + "&application=" + application
+ (group == null ? "" : "&group=" + group));
MetadataIdentifier providerMetadataIdentifier =
new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application);
Class interfaceClass = Class.forName(interfaceName);
FullServiceDefinition fullServiceDefinition =
ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters());
redisMetadataReport.storeProviderMetadata(providerMetadataIdentifier, fullServiceDefinition);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
return providerMetadataIdentifier;
}
private MetadataIdentifier storeConsumer(
RedisMetadataReport redisMetadataReport,
String interfaceName,
String version,
String group,
String application)
throws ClassNotFoundException {
URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName
+ "?version=" + version + "&application=" + application + (group == null ? "" : "&group=" + group));
MetadataIdentifier consumerMetadataIdentifier =
new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application);
Class interfaceClass = Class.forName(interfaceName);
Map<String, String> tmp = new HashMap<>();
tmp.put("paramConsumerTest", "redisCm");
redisMetadataReport.storeConsumerMetadata(consumerMetadataIdentifier, tmp);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
return consumerMetadataIdentifier;
}
@Test
void testAuthRedisMetadata() throws ClassNotFoundException {
testStoreProvider(redisMetadataReport, "1.0.0.redis.md.p1", 3000);
}
@Test
void testWrongAuthRedisMetadata() throws ClassNotFoundException {
registryUrl = registryUrl.setPassword("123456");
redisMetadataReport = (RedisMetadataReport) new RedisMetadataReportFactory().createMetadataReport(registryUrl);
try {
testStoreProvider(redisMetadataReport, "1.0.0.redis.md.p1", 3000);
} catch (RpcException e) {
if (e.getCause() instanceof JedisConnectionException
&& e.getCause().getCause() instanceof JedisDataException) {
Assertions.assertEquals(
"ERR invalid password", e.getCause().getCause().getMessage());
} else {
Assertions.fail("no invalid password exception!");
}
}
}
}
| 7,294 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store.redis;
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.StringUtils;
import org.apache.dubbo.metadata.report.identifier.BaseMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import org.apache.dubbo.metadata.report.support.AbstractMetadataReport;
import org.apache.dubbo.rpc.RpcException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RESPONSE;
import static org.apache.dubbo.metadata.MetadataConstants.META_DATA_STORE_TAG;
/**
* RedisMetadataReport
*/
public class RedisMetadataReport extends AbstractMetadataReport {
private static final String REDIS_DATABASE_KEY = "database";
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RedisMetadataReport.class);
// protected , for test
protected JedisPool pool;
private Set<HostAndPort> jedisClusterNodes;
private int timeout;
private String password;
public RedisMetadataReport(URL url) {
super(url);
timeout = url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT);
password = url.getPassword();
if (url.getParameter(CLUSTER_KEY, false)) {
jedisClusterNodes = new HashSet<>();
List<URL> urls = url.getBackupUrls();
for (URL tmpUrl : urls) {
jedisClusterNodes.add(new HostAndPort(tmpUrl.getHost(), tmpUrl.getPort()));
}
} else {
int database = url.getParameter(REDIS_DATABASE_KEY, 0);
pool = new JedisPool(new JedisPoolConfig(), url.getHost(), url.getPort(), timeout, password, database);
}
}
@Override
protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) {
this.storeMetadata(providerMetadataIdentifier, serviceDefinitions);
}
@Override
protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String value) {
this.storeMetadata(consumerMetadataIdentifier, value);
}
@Override
protected void doSaveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier, URL url) {
this.storeMetadata(serviceMetadataIdentifier, URL.encode(url.toFullString()));
}
@Override
protected void doRemoveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier) {
this.deleteMetadata(serviceMetadataIdentifier);
}
@Override
protected List<String> doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) {
String content = getMetadata(metadataIdentifier);
if (StringUtils.isEmpty(content)) {
return Collections.emptyList();
}
return new ArrayList<>(Arrays.asList(URL.decode(content)));
}
@Override
protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urlListStr) {
this.storeMetadata(subscriberMetadataIdentifier, urlListStr);
}
@Override
protected String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) {
return this.getMetadata(subscriberMetadataIdentifier);
}
@Override
public String getServiceDefinition(MetadataIdentifier metadataIdentifier) {
return this.getMetadata(metadataIdentifier);
}
private void storeMetadata(BaseMetadataIdentifier metadataIdentifier, String v) {
if (pool != null) {
storeMetadataStandalone(metadataIdentifier, v);
} else {
storeMetadataInCluster(metadataIdentifier, v);
}
}
private void storeMetadataInCluster(BaseMetadataIdentifier metadataIdentifier, String v) {
try (JedisCluster jedisCluster =
new JedisCluster(jedisClusterNodes, timeout, timeout, 2, password, new GenericObjectPoolConfig<>())) {
jedisCluster.set(metadataIdentifier.getIdentifierKey() + META_DATA_STORE_TAG, v);
} catch (Throwable e) {
String msg =
"Failed to put " + metadataIdentifier + " to redis cluster " + v + ", cause: " + e.getMessage();
logger.error(TRANSPORT_FAILED_RESPONSE, "", "", msg, e);
throw new RpcException(msg, e);
}
}
private void storeMetadataStandalone(BaseMetadataIdentifier metadataIdentifier, String v) {
try (Jedis jedis = pool.getResource()) {
jedis.set(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), v);
} catch (Throwable e) {
String msg = "Failed to put " + metadataIdentifier + " to redis " + v + ", cause: " + e.getMessage();
logger.error(TRANSPORT_FAILED_RESPONSE, "", "", msg, e);
throw new RpcException(msg, e);
}
}
private void deleteMetadata(BaseMetadataIdentifier metadataIdentifier) {
if (pool != null) {
deleteMetadataStandalone(metadataIdentifier);
} else {
deleteMetadataInCluster(metadataIdentifier);
}
}
private void deleteMetadataInCluster(BaseMetadataIdentifier metadataIdentifier) {
try (JedisCluster jedisCluster =
new JedisCluster(jedisClusterNodes, timeout, timeout, 2, password, new GenericObjectPoolConfig<>())) {
jedisCluster.del(metadataIdentifier.getIdentifierKey() + META_DATA_STORE_TAG);
} catch (Throwable e) {
String msg = "Failed to delete " + metadataIdentifier + " from redis cluster , cause: " + e.getMessage();
logger.error(TRANSPORT_FAILED_RESPONSE, "", "", msg, e);
throw new RpcException(msg, e);
}
}
private void deleteMetadataStandalone(BaseMetadataIdentifier metadataIdentifier) {
try (Jedis jedis = pool.getResource()) {
jedis.del(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY));
} catch (Throwable e) {
String msg = "Failed to delete " + metadataIdentifier + " from redis , cause: " + e.getMessage();
logger.error(TRANSPORT_FAILED_RESPONSE, "", "", msg, e);
throw new RpcException(msg, e);
}
}
private String getMetadata(BaseMetadataIdentifier metadataIdentifier) {
if (pool != null) {
return getMetadataStandalone(metadataIdentifier);
} else {
return getMetadataInCluster(metadataIdentifier);
}
}
private String getMetadataInCluster(BaseMetadataIdentifier metadataIdentifier) {
try (JedisCluster jedisCluster =
new JedisCluster(jedisClusterNodes, timeout, timeout, 2, password, new GenericObjectPoolConfig<>())) {
return jedisCluster.get(metadataIdentifier.getIdentifierKey() + META_DATA_STORE_TAG);
} catch (Throwable e) {
String msg = "Failed to get " + metadataIdentifier + " from redis cluster , cause: " + e.getMessage();
logger.error(TRANSPORT_FAILED_RESPONSE, "", "", msg, e);
throw new RpcException(msg, e);
}
}
private String getMetadataStandalone(BaseMetadataIdentifier metadataIdentifier) {
try (Jedis jedis = pool.getResource()) {
return jedis.get(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY));
} catch (Throwable e) {
String msg = "Failed to get " + metadataIdentifier + " from redis , cause: " + e.getMessage();
logger.error(TRANSPORT_FAILED_RESPONSE, "", "", msg, e);
throw new RpcException(msg, e);
}
}
}
| 7,295 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store.redis;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory;
/**
* RedisMetadataReportFactory.
*/
public class RedisMetadataReportFactory extends AbstractMetadataReportFactory {
@Override
public MetadataReport createMetadataReport(URL url) {
return new RedisMetadataReport(url);
}
}
| 7,296 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/MockConfigService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store.nacos;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
public class MockConfigService implements ConfigService {
@Override
public String getConfig(String dataId, String group, long timeoutMs) throws NacosException {
return null;
}
@Override
public String getConfigAndSignListener(String dataId, String group, long timeoutMs, Listener listener) {
return null;
}
@Override
public void addListener(String dataId, String group, Listener listener) {}
@Override
public boolean publishConfig(String dataId, String group, String content) {
return false;
}
@Override
public boolean publishConfig(String dataId, String group, String content, String type) {
return false;
}
@Override
public boolean publishConfigCas(String dataId, String group, String content, String casMd5) {
return false;
}
@Override
public boolean publishConfigCas(String dataId, String group, String content, String casMd5, String type) {
return false;
}
@Override
public boolean removeConfig(String dataId, String group) {
return false;
}
@Override
public void removeListener(String dataId, String group, Listener listener) {}
@Override
public String getServerStatus() {
return null;
}
@Override
public void shutDown() {}
}
| 7,297 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/RetryTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store.nacos;
import org.apache.dubbo.common.URL;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static com.alibaba.nacos.client.constant.Constants.HealthCheck.DOWN;
import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP;
import static org.mockito.ArgumentMatchers.any;
class RetryTest {
@Test
void testRetryCreate() {
try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) {
AtomicInteger atomicInteger = new AtomicInteger(0);
ConfigService mock = new MockConfigService() {
@Override
public String getServerStatus() {
return atomicInteger.incrementAndGet() > 10 ? UP : DOWN;
}
};
nacosFactoryMockedStatic
.when(() -> NacosFactory.createConfigService((Properties) any()))
.thenReturn(mock);
URL url = URL.valueOf("nacos://127.0.0.1:8848")
.addParameter("nacos.retry", 5)
.addParameter("nacos.retry-wait", 10);
Assertions.assertThrows(IllegalStateException.class, () -> new NacosMetadataReport(url));
try {
new NacosMetadataReport(url);
} catch (Throwable t) {
Assertions.fail(t);
}
}
}
@Test
void testDisable() {
try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) {
ConfigService mock = new MockConfigService() {
@Override
public String getServerStatus() {
return DOWN;
}
};
nacosFactoryMockedStatic
.when(() -> NacosFactory.createConfigService((Properties) any()))
.thenReturn(mock);
URL url = URL.valueOf("nacos://127.0.0.1:8848")
.addParameter("nacos.retry", 5)
.addParameter("nacos.retry-wait", 10)
.addParameter("nacos.check", "false");
try {
new NacosMetadataReport(url);
} catch (Throwable t) {
Assertions.fail(t);
}
}
}
@Test
void testRequest() {
try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) {
AtomicInteger atomicInteger = new AtomicInteger(0);
ConfigService mock = new MockConfigService() {
@Override
public String getConfig(String dataId, String group, long timeoutMs) throws NacosException {
if (atomicInteger.incrementAndGet() > 10) {
return "";
} else {
throw new NacosException();
}
}
@Override
public String getServerStatus() {
return UP;
}
};
nacosFactoryMockedStatic
.when(() -> NacosFactory.createConfigService((Properties) any()))
.thenReturn(mock);
URL url = URL.valueOf("nacos://127.0.0.1:8848")
.addParameter("nacos.retry", 5)
.addParameter("nacos.retry-wait", 10);
Assertions.assertThrows(IllegalStateException.class, () -> new NacosMetadataReport(url));
try {
new NacosMetadataReport(url);
} catch (Throwable t) {
Assertions.fail(t);
}
}
}
}
| 7,298 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store.nacos;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.MD5Utils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MappingChangedEvent;
import org.apache.dubbo.metadata.MappingListener;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.ServiceNameMapping;
import org.apache.dubbo.metadata.report.identifier.BaseMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import org.apache.dubbo.metadata.report.support.AbstractMetadataReport;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executor;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.AbstractSharedListener;
import com.alibaba.nacos.api.exception.NacosException;
import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR;
import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_ERROR_NACOS;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_INTERRUPTED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION;
import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY;
import static org.apache.dubbo.common.utils.StringConstantFieldValuePredicate.of;
import static org.apache.dubbo.common.utils.StringUtils.HYPHEN_CHAR;
import static org.apache.dubbo.metadata.MetadataConstants.REPORT_CONSUMER_URL_KEY;
import static org.apache.dubbo.metadata.ServiceNameMapping.DEFAULT_MAPPING_GROUP;
import static org.apache.dubbo.metadata.ServiceNameMapping.getAppNames;
/**
* metadata report impl for nacos
*/
public class NacosMetadataReport extends AbstractMetadataReport {
private NacosConfigServiceWrapper configService;
/**
* The group used to store metadata in Nacos
*/
private String group;
private Map<String, NacosConfigListener> watchListenerMap = new ConcurrentHashMap<>();
private Map<String, MappingDataListener> casListenerMap = new ConcurrentHashMap<>();
private MD5Utils md5Utils = new MD5Utils();
private static final String NACOS_RETRY_KEY = "nacos.retry";
private static final String NACOS_RETRY_WAIT_KEY = "nacos.retry-wait";
private static final String NACOS_CHECK_KEY = "nacos.check";
public NacosMetadataReport(URL url) {
super(url);
this.configService = buildConfigService(url);
group = url.getParameter(GROUP_KEY, DEFAULT_ROOT);
}
private NacosConfigServiceWrapper buildConfigService(URL url) {
Properties nacosProperties = buildNacosProperties(url);
int retryTimes = url.getPositiveParameter(NACOS_RETRY_KEY, 10);
int sleepMsBetweenRetries = url.getPositiveParameter(NACOS_RETRY_WAIT_KEY, 1000);
boolean check = url.getParameter(NACOS_CHECK_KEY, true);
ConfigService tmpConfigServices = null;
try {
for (int i = 0; i < retryTimes + 1; i++) {
tmpConfigServices = NacosFactory.createConfigService(nacosProperties);
if (!check
|| (UP.equals(tmpConfigServices.getServerStatus()) && testConfigService(tmpConfigServices))) {
break;
} else {
logger.warn(
LoggerCodeConstants.CONFIG_ERROR_NACOS,
"",
"",
"Failed to connect to nacos config server. "
+ (i < retryTimes
? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". "
: "Exceed retry max times.")
+ "Try times: "
+ (i + 1));
}
tmpConfigServices.shutDown();
tmpConfigServices = null;
Thread.sleep(sleepMsBetweenRetries);
}
} catch (NacosException e) {
logger.error(CONFIG_ERROR_NACOS, "", "", e.getErrMsg(), e);
throw new IllegalStateException(e);
} catch (InterruptedException e) {
logger.error(INTERNAL_INTERRUPTED, "", "", "Interrupted when creating nacos config service client.", e);
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
if (tmpConfigServices == null) {
logger.error(
CONFIG_ERROR_NACOS,
"",
"",
"Failed to create nacos config service client. Reason: server status check failed.");
throw new IllegalStateException(
"Failed to create nacos config service client. Reason: server status check failed.");
}
return new NacosConfigServiceWrapper(tmpConfigServices);
}
private boolean testConfigService(ConfigService configService) {
try {
configService.getConfig("Dubbo-Nacos-Test", "Dubbo-Nacos-Test", 3000L);
return true;
} catch (NacosException e) {
return false;
}
}
private Properties buildNacosProperties(URL url) {
Properties properties = new Properties();
setServerAddr(url, properties);
setProperties(url, properties);
return properties;
}
private void setServerAddr(URL url, Properties properties) {
StringBuilder serverAddrBuilder = new StringBuilder(url.getHost()) // Host
.append(':')
.append(url.getPort()); // Port
// Append backup parameter as other servers
String backup = url.getParameter(BACKUP_KEY);
if (backup != null) {
serverAddrBuilder.append(',').append(backup);
}
String serverAddr = serverAddrBuilder.toString();
properties.put(SERVER_ADDR, serverAddr);
}
private static void setProperties(URL url, Properties properties) {
// Get the parameters from constants
Map<String, String> parameters = url.getParameters(of(PropertyKeyConst.class));
// Put all parameters
properties.putAll(parameters);
}
private static void putPropertyIfAbsent(URL url, Properties properties, String propertyName) {
String propertyValue = url.getParameter(propertyName);
if (StringUtils.isNotEmpty(propertyValue)) {
properties.setProperty(propertyName, propertyValue);
}
}
private static void putPropertyIfAbsent(URL url, Properties properties, String propertyName, String defaultValue) {
String propertyValue = url.getParameter(propertyName);
if (StringUtils.isNotEmpty(propertyValue)) {
properties.setProperty(propertyName, propertyValue);
} else {
properties.setProperty(propertyName, defaultValue);
}
}
@Override
public void publishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) {
try {
if (metadataInfo.getContent() != null) {
configService.publishConfig(
identifier.getApplication(), identifier.getRevision(), metadataInfo.getContent());
}
} catch (NacosException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
public void unPublishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) {
try {
configService.removeConfig(identifier.getApplication(), identifier.getRevision());
} catch (NacosException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
public MetadataInfo getAppMetadata(SubscriberMetadataIdentifier identifier, Map<String, String> instanceMetadata) {
try {
String content = configService.getConfig(identifier.getApplication(), identifier.getRevision(), 3000L);
return JsonUtils.toJavaObject(content, MetadataInfo.class);
} catch (NacosException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) {
this.storeMetadata(providerMetadataIdentifier, serviceDefinitions);
}
@Override
protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String value) {
if (getUrl().getParameter(REPORT_CONSUMER_URL_KEY, false)) {
this.storeMetadata(consumerMetadataIdentifier, value);
}
}
@Override
protected void doSaveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier, URL url) {
storeMetadata(serviceMetadataIdentifier, URL.encode(url.toFullString()));
}
@Override
protected void doRemoveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier) {
deleteMetadata(serviceMetadataIdentifier);
}
@Override
protected List<String> doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) {
String content = getConfig(metadataIdentifier);
if (StringUtils.isEmpty(content)) {
return Collections.emptyList();
}
return new ArrayList<String>(Arrays.asList(URL.decode(content)));
}
@Override
protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urlListStr) {
storeMetadata(subscriberMetadataIdentifier, urlListStr);
}
@Override
protected String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) {
return getConfig(subscriberMetadataIdentifier);
}
@Override
public String getServiceDefinition(MetadataIdentifier metadataIdentifier) {
return getConfig(metadataIdentifier);
}
@Override
public boolean registerServiceAppMapping(String key, String group, String content, Object ticket) {
try {
if (!(ticket instanceof String)) {
throw new IllegalArgumentException("nacos publishConfigCas requires string type ticket");
}
return configService.publishConfigCas(key, group, content, (String) ticket);
} catch (NacosException e) {
logger.warn(REGISTRY_NACOS_EXCEPTION, "", "", "nacos publishConfigCas failed.", e);
return false;
}
}
@Override
public ConfigItem getConfigItem(String key, String group) {
String content = getConfig(key, group);
String casMd5 = "0";
if (StringUtils.isNotEmpty(content)) {
casMd5 = md5Utils.getMd5(content);
}
return new ConfigItem(content, casMd5);
}
@Override
public Set<String> getServiceAppMapping(String serviceKey, MappingListener listener, URL url) {
String group = DEFAULT_MAPPING_GROUP;
if (null == casListenerMap.get(buildListenerKey(serviceKey, group))) {
addCasServiceMappingListener(serviceKey, group, listener);
}
String content = getConfig(serviceKey, group);
return ServiceNameMapping.getAppNames(content);
}
@Override
public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) {
String group = DEFAULT_MAPPING_GROUP;
MappingDataListener mappingDataListener = casListenerMap.get(buildListenerKey(serviceKey, group));
if (null != mappingDataListener) {
removeCasServiceMappingListener(serviceKey, group, listener);
}
}
@Override
public Set<String> getServiceAppMapping(String serviceKey, URL url) {
String content = getConfig(serviceKey, DEFAULT_MAPPING_GROUP);
return ServiceNameMapping.getAppNames(content);
}
private String getConfig(String dataId, String group) {
try {
return configService.getConfig(dataId, group);
} catch (NacosException e) {
logger.error(REGISTRY_NACOS_EXCEPTION, "", "", e.getMessage());
}
return null;
}
private void addCasServiceMappingListener(String serviceKey, String group, MappingListener listener) {
MappingDataListener mappingDataListener = casListenerMap.computeIfAbsent(
buildListenerKey(serviceKey, group), k -> new MappingDataListener(serviceKey, group));
mappingDataListener.addListeners(listener);
addListener(serviceKey, DEFAULT_MAPPING_GROUP, mappingDataListener);
}
private void removeCasServiceMappingListener(String serviceKey, String group, MappingListener listener) {
MappingDataListener mappingDataListener = casListenerMap.get(buildListenerKey(serviceKey, group));
if (mappingDataListener != null) {
mappingDataListener.removeListeners(listener);
if (mappingDataListener.isEmpty()) {
removeListener(serviceKey, DEFAULT_MAPPING_GROUP, mappingDataListener);
casListenerMap.remove(buildListenerKey(serviceKey, group), mappingDataListener);
}
}
}
public void addListener(String key, String group, ConfigurationListener listener) {
String listenerKey = buildListenerKey(key, group);
NacosConfigListener nacosConfigListener =
watchListenerMap.computeIfAbsent(listenerKey, k -> createTargetListener(key, group));
nacosConfigListener.addListener(listener);
try {
configService.addListener(key, group, nacosConfigListener);
} catch (NacosException e) {
logger.error(REGISTRY_NACOS_EXCEPTION, "", "", e.getMessage());
}
}
public void removeListener(String key, String group, ConfigurationListener listener) {
String listenerKey = buildListenerKey(key, group);
NacosConfigListener nacosConfigListener = watchListenerMap.get(listenerKey);
try {
if (nacosConfigListener != null) {
nacosConfigListener.removeListener(listener);
if (nacosConfigListener.isEmpty()) {
configService.removeListener(key, group, nacosConfigListener);
watchListenerMap.remove(listenerKey);
}
}
} catch (NacosException e) {
logger.error(REGISTRY_NACOS_EXCEPTION, "", "", e.getMessage());
}
}
private NacosConfigListener createTargetListener(String key, String group) {
NacosConfigListener configListener = new NacosConfigListener();
configListener.fillContext(key, group);
return configListener;
}
private String buildListenerKey(String key, String group) {
return key + HYPHEN_CHAR + group;
}
private void storeMetadata(BaseMetadataIdentifier identifier, String value) {
try {
boolean publishResult =
configService.publishConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group, value);
if (!publishResult) {
throw new RuntimeException("publish nacos metadata failed");
}
} catch (Throwable t) {
logger.error(
REGISTRY_NACOS_EXCEPTION,
"",
"",
"Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(),
t);
throw new RuntimeException(
"Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(), t);
}
}
private void deleteMetadata(BaseMetadataIdentifier identifier) {
try {
boolean publishResult = configService.removeConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group);
if (!publishResult) {
throw new RuntimeException("remove nacos metadata failed");
}
} catch (Throwable t) {
logger.error(
REGISTRY_NACOS_EXCEPTION,
"",
"",
"Failed to remove " + identifier + " from nacos , cause: " + t.getMessage(),
t);
throw new RuntimeException("Failed to remove " + identifier + " from nacos , cause: " + t.getMessage(), t);
}
}
private String getConfig(BaseMetadataIdentifier identifier) {
try {
return configService.getConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group, 3000L);
} catch (Throwable t) {
logger.error(
REGISTRY_NACOS_EXCEPTION,
"",
"",
"Failed to get " + identifier + " from nacos , cause: " + t.getMessage(),
t);
throw new RuntimeException("Failed to get " + identifier + " from nacos , cause: " + t.getMessage(), t);
}
}
public class NacosConfigListener extends AbstractSharedListener {
private Set<ConfigurationListener> listeners = new CopyOnWriteArraySet<>();
/**
* cache data to store old value
*/
private Map<String, String> cacheData = new ConcurrentHashMap<>();
@Override
public Executor getExecutor() {
return null;
}
/**
* receive
*
* @param dataId data ID
* @param group group
* @param configInfo content
*/
@Override
public void innerReceive(String dataId, String group, String configInfo) {
String oldValue = cacheData.get(dataId);
ConfigChangedEvent event =
new ConfigChangedEvent(dataId, group, configInfo, getChangeType(configInfo, oldValue));
if (configInfo == null) {
cacheData.remove(dataId);
} else {
cacheData.put(dataId, configInfo);
}
listeners.forEach(listener -> listener.process(event));
}
void addListener(ConfigurationListener configurationListener) {
this.listeners.add(configurationListener);
}
void removeListener(ConfigurationListener configurationListener) {
this.listeners.remove(configurationListener);
}
boolean isEmpty() {
return this.listeners.isEmpty();
}
private ConfigChangeType getChangeType(String configInfo, String oldValue) {
if (StringUtils.isBlank(configInfo)) {
return ConfigChangeType.DELETED;
}
if (StringUtils.isBlank(oldValue)) {
return ConfigChangeType.ADDED;
}
return ConfigChangeType.MODIFIED;
}
}
static class MappingDataListener implements ConfigurationListener {
private String dataId;
private String groupId;
private String serviceKey;
private Set<MappingListener> listeners;
public MappingDataListener(String dataId, String groupId) {
this.serviceKey = dataId;
this.dataId = dataId;
this.groupId = groupId;
this.listeners = new HashSet<>();
}
public void addListeners(MappingListener mappingListener) {
listeners.add(mappingListener);
}
public void removeListeners(MappingListener mappingListener) {
listeners.remove(mappingListener);
}
public boolean isEmpty() {
return listeners.isEmpty();
}
@Override
public void process(ConfigChangedEvent event) {
if (ConfigChangeType.DELETED == event.getChangeType()) {
return;
}
if (!dataId.equals(event.getKey()) || !groupId.equals(event.getGroup())) {
return;
}
Set<String> apps = getAppNames(event.getContent());
MappingChangedEvent mappingChangedEvent = new MappingChangedEvent(serviceKey, apps);
listeners.forEach(listener -> listener.onEvent(mappingChangedEvent));
}
}
}
| 7,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.