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-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ArgumentConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.config; @Deprecated public class ArgumentConfig extends org.apache.dubbo.config.ArgumentConfig {}
5,300
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.config; @Deprecated public class ProtocolConfig extends org.apache.dubbo.config.ProtocolConfig { public ProtocolConfig() {} public ProtocolConfig(String name) { super(name); } public ProtocolConfig(String name, int port) { super(name, port); } public void mergeProtocol(ProtocolConfig sourceConfig) { super.mergeProtocol(sourceConfig); } }
5,301
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/MethodConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.config; @Deprecated public class MethodConfig extends org.apache.dubbo.config.MethodConfig { public void addArgument(com.alibaba.dubbo.config.ArgumentConfig argumentConfig) { super.addArgument(argumentConfig); } public void setMock(Boolean mock) { if (mock == null) { setMock((String) null); } else { setMock(String.valueOf(mock)); } } }
5,302
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ConsumerConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.config; @Deprecated public class ConsumerConfig extends org.apache.dubbo.config.ConsumerConfig { public void setApplication(com.alibaba.dubbo.config.ApplicationConfig application) { super.setApplication(application); } public void setModule(com.alibaba.dubbo.config.ModuleConfig module) { super.setModule(module); } public void setRegistry(com.alibaba.dubbo.config.RegistryConfig registry) { super.setRegistry(registry); } public void addMethod(com.alibaba.dubbo.config.MethodConfig methodConfig) { super.addMethod(methodConfig); } public void setMonitor(com.alibaba.dubbo.config.MonitorConfig monitor) { super.setMonitor(monitor); } public void setMock(Boolean mock) { if (mock == null) { setMock((String) null); } else { setMock(String.valueOf(mock)); } } }
5,303
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/config
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.config.annotation; import org.apache.dubbo.config.annotation.DubboReference; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Reference * <p> * * @see DubboReference * @deprecated Recommend {@link DubboReference} as the substitute */ @Deprecated @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface Reference { Class<?> interfaceClass() default void.class; String interfaceName() default ""; String version() default ""; String group() default ""; String url() default ""; String client() default ""; /** * Whether to enable generic invocation, default value is false * @deprecated Do not need specify generic value, judge by injection type and interface class */ @Deprecated boolean generic() default false; boolean injvm() default true; boolean check() default true; boolean init() default true; boolean lazy() default false; boolean stubevent() default false; String reconnect() default ""; boolean sticky() default false; String proxy() default ""; String stub() default ""; String cluster() default ""; int connections() default -1; int callbacks() default -1; String onconnect() default ""; String ondisconnect() default ""; String owner() default ""; String layer() default ""; int retries() default -1; String loadbalance() default ""; boolean async() default false; int actives() default -1; boolean sent() default false; String mock() default ""; String validation() default ""; int timeout() default -1; String cache() default ""; String[] filter() default {}; String[] listener() default {}; String[] parameters() default {}; /** * Application associated name * @deprecated Do not set it and use the global Application Config */ @Deprecated String application() default ""; String module() default ""; String consumer() default ""; String monitor() default ""; String[] registry() default {}; }
5,304
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/config
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/annotation/Service.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.config.annotation; import org.apache.dubbo.config.annotation.DubboService; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Service annotation * * @see DubboService * @deprecated Recommend {@link DubboService} as the substitute */ @Deprecated @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) @Inherited public @interface Service { Class<?> interfaceClass() default void.class; String interfaceName() default ""; String version() default ""; String group() default ""; String path() default ""; boolean export() default false; String token() default ""; boolean deprecated() default false; boolean dynamic() default true; String accesslog() default ""; int executes() default -1; boolean register() default false; int weight() default -1; String document() default ""; int delay() default -1; String local() default ""; String stub() default ""; String cluster() default ""; String proxy() default ""; int connections() default -1; int callbacks() default -1; String onconnect() default ""; String ondisconnect() default ""; String owner() default ""; String layer() default ""; int retries() default -1; String loadbalance() default ""; boolean async() default false; int actives() default -1; boolean sent() default false; String mock() default ""; String validation() default ""; int timeout() default -1; String cache() default ""; String[] filter() default {}; String[] listener() default {}; String[] parameters() default {}; /** * Application associated name * @deprecated Do not set it and use the global Application Config */ @Deprecated String application() default ""; String module() default ""; String provider() default ""; String[] protocol() default {}; String monitor() default ""; String[] registry() default {}; }
5,305
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/spring/context
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubbo.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.config.spring.context.annotation; import org.apache.dubbo.config.AbstractConfig; import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor; @Deprecated @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented @EnableDubboConfig @DubboComponentScan public @interface EnableDubbo { /** * Base packages to scan for annotated @Service classes. * <p> * Use {@link #scanBasePackageClasses()} for a type-safe alternative to String-based * package names. * * @return the base packages to scan * @see DubboComponentScan#basePackages() */ @AliasFor(annotation = DubboComponentScan.class, attribute = "basePackages") String[] scanBasePackages() default {}; /** * Type-safe alternative to {@link #scanBasePackages()} for specifying the packages to * scan for annotated @Service classes. The package of each class specified will be * scanned. * * @return classes from the base packages to scan * @see DubboComponentScan#basePackageClasses */ @AliasFor(annotation = DubboComponentScan.class, attribute = "basePackageClasses") Class<?>[] scanBasePackageClasses() default {}; /** * It indicates whether {@link AbstractConfig} binding to multiple Spring Beans. * * @return the default value is <code>false</code> * @see EnableDubboConfig#multiple() */ @AliasFor(annotation = EnableDubboConfig.class, attribute = "multiple") boolean multipleConfig() default false; }
5,306
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/qos
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/qos/command/BaseCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.qos.command; import org.apache.dubbo.qos.api.CommandContext; @Deprecated public interface BaseCommand extends org.apache.dubbo.qos.api.BaseCommand { String execute(com.alibaba.dubbo.qos.command.CommandContext commandContext, String[] args); @Override default String execute(CommandContext commandContext, String[] args) { return this.execute(new com.alibaba.dubbo.qos.command.CommandContext(commandContext), args); } }
5,307
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/qos
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/qos/command/CommandContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.qos.command; @Deprecated public class CommandContext extends org.apache.dubbo.qos.api.CommandContext { public CommandContext(org.apache.dubbo.qos.api.CommandContext context) { super(context.getCommandName(), context.getArgs(), context.isHttp()); setRemote(context.getRemote()); setOriginRequest(context.getOriginRequest()); } public CommandContext(String commandName) { super(commandName); } public CommandContext(String commandName, String[] args, boolean isHttp) { super(commandName, args, isHttp); } }
5,308
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/Container.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.container; @Deprecated public interface Container extends org.apache.dubbo.container.Container {}
5,309
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/Page.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.container.page; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Page */ public class Page { private final String navigation; private final String title; private final List<String> columns; private final List<List<String>> rows; public Page(String navigation) { this(navigation, (String) null, (String[]) null, (List<List<String>>) null); } public Page(String navigation, String title, String column, String row) { this( navigation, title, column == null ? null : Arrays.asList(new String[] {column}), row == null ? null : stringToList(row)); } public Page(String navigation, String title, String[] columns, List<List<String>> rows) { this(navigation, title, columns == null ? null : Arrays.asList(columns), rows); } public Page(String navigation, String title, List<String> columns, List<List<String>> rows) { this.navigation = navigation; this.title = title; this.columns = columns; this.rows = rows; } private static List<List<String>> stringToList(String str) { List<List<String>> rows = new ArrayList<List<String>>(); List<String> row = new ArrayList<String>(); row.add(str); rows.add(row); return rows; } public String getNavigation() { return navigation; } public String getTitle() { return title; } public List<String> getColumns() { return columns; } public List<List<String>> getRows() { return rows; } }
5,310
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/Menu.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.container.page; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Menu */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface Menu { String name(); String desc() default ""; int order() default 0; }
5,311
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/PageServlet.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.container.page; 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.utils.StringUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; /** * PageServlet */ public class PageServlet extends HttpServlet { protected static final Logger logger = LoggerFactory.getLogger(PageServlet.class); private static final long serialVersionUID = -8370312705453328501L; private static PageServlet INSTANCE; protected final Random random = new Random(); protected final Map<String, PageHandler> pages = new ConcurrentHashMap<String, PageHandler>(); protected final List<PageHandler> menus = new ArrayList<PageHandler>(); public static PageServlet getInstance() { return INSTANCE; } public List<PageHandler> getMenus() { return Collections.unmodifiableList(menus); } @Override public void init() throws ServletException { super.init(); INSTANCE = this; String config = getServletConfig().getInitParameter("pages"); Collection<String> names; if (config != null && config.length() > 0) { names = Arrays.asList(Constants.COMMA_SPLIT_PATTERN.split(config)); } else { names = ExtensionLoader.getExtensionLoader(PageHandler.class).getSupportedExtensions(); } for (String name : names) { PageHandler handler = ExtensionLoader.getExtensionLoader(PageHandler.class).getExtension(name); pages.put(ExtensionLoader.getExtensionLoader(PageHandler.class).getExtensionName(handler), handler); Menu menu = handler.getClass().getAnnotation(Menu.class); if (menu != null) { menus.add(handler); } } Collections.sort(menus, new MenuComparator()); } @Override protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!response.isCommitted()) { PrintWriter writer = response.getWriter(); String uri = request.getRequestURI(); boolean isHtml = false; if (uri == null || uri.length() == 0 || "/".equals(uri)) { uri = "index"; isHtml = true; } else { if (uri.startsWith("/")) { uri = uri.substring(1); } if (uri.endsWith(".html")) { uri = uri.substring(0, uri.length() - ".html".length()); isHtml = true; } } if (uri.endsWith("favicon.ico")) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } ExtensionLoader<PageHandler> pageHandlerLoader = ExtensionLoader.getExtensionLoader(PageHandler.class); PageHandler pageHandler = pageHandlerLoader.hasExtension(uri) ? pageHandlerLoader.getExtension(uri) : null; if (isHtml) { writer.println("<html><head><title>Dubbo</title>"); writer.println( "<style type=\"text/css\">html, body {margin: 10;padding: 0;background-color: #6D838C;font-family: Arial, Verdana;font-size: 12px;color: #FFFFFF;text-align: center;vertical-align: middle;word-break: break-all; } table {width: 90%; margin: 0px auto;border-collapse: collapse;border: 8px solid #FFFFFF; } thead tr {background-color: #253c46; } tbody tr {background-color: #8da5af; } th {padding-top: 4px;padding-bottom: 4px;font-size: 14px;height: 20px; } td {margin: 3px;padding: 3px;border: 2px solid #FFFFFF;font-size: 14px;height: 25px; } a {color: #FFFFFF;cursor: pointer;text-decoration: underline; } a:hover {text-decoration: none; }</style>"); writer.println("</head><body>"); } if (pageHandler != null) { Page page = null; try { String query = request.getQueryString(); page = pageHandler.handle( URL.valueOf(request.getRequestURL().toString() + (query == null || query.length() == 0 ? "" : "?" + query))); } catch (Throwable t) { logger.warn(t.getMessage(), t); String msg = t.getMessage(); if (msg == null) { msg = StringUtils.toString(t); } if (isHtml) { writer.println("<table>"); writer.println("<thead>"); writer.println(" <tr>"); writer.println(" <th>Error</th>"); writer.println(" </tr>"); writer.println("</thead>"); writer.println("<tbody>"); writer.println(" <tr>"); writer.println(" <td>"); writer.println(" " + msg.replace("<", "&lt;").replace(">", "&lt;").replace("\n", "<br/>")); writer.println(" </td>"); writer.println(" </tr>"); writer.println("</tbody>"); writer.println("</table>"); writer.println("<br/>"); } else { writer.println(msg); } } if (page != null) { if (isHtml) { String nav = page.getNavigation(); if (nav == null || nav.length() == 0) { nav = ExtensionLoader.getExtensionLoader(PageHandler.class) .getExtensionName(pageHandler); nav = nav.substring(0, 1).toUpperCase() + nav.substring(1); } if (!"index".equals(uri)) { nav = "<a href=\"/\">Home</a> &gt; " + nav; } writeMenu(request, writer, nav); writeTable(writer, page.getTitle(), page.getColumns(), page.getRows()); } else { if (page.getRows().size() > 0 && page.getRows().get(0).size() > 0) { writer.println(page.getRows().get(0).get(0)); } } } } else { if (isHtml) { writer.println("<table>"); writer.println("<thead>"); writer.println(" <tr>"); writer.println(" <th>Error</th>"); writer.println(" </tr>"); writer.println("</thead>"); writer.println("<tbody>"); writer.println(" <tr>"); writer.println(" <td>"); writer.println(" Not found " + uri + " page. Please goto <a href=\"/\">Home</a> page."); writer.println(" </td>"); writer.println(" </tr>"); writer.println("</tbody>"); writer.println("</table>"); writer.println("<br/>"); } else { writer.println("Not found " + uri + " page."); } } if (isHtml) { writer.println("</body></html>"); } writer.flush(); } } protected final void writeMenu(HttpServletRequest request, PrintWriter writer, String nav) { writer.println("<table>"); writer.println("<thead>"); writer.println(" <tr>"); for (PageHandler handler : menus) { String uri = ExtensionLoader.getExtensionLoader(PageHandler.class).getExtensionName(handler); Menu menu = handler.getClass().getAnnotation(Menu.class); writer.println(" <th><a href=\"" + uri + ".html\">" + menu.name() + "</a></th>"); } writer.println(" </tr>"); writer.println("</thead>"); writer.println("<tbody>"); writer.println(" <tr>"); writer.println(" <td style=\"text-align: left\" colspan=\"" + menus.size() + "\">"); writer.println(nav); writer.println(" </td>"); writer.println(" </tr>"); writer.println("</tbody>"); writer.println("</table>"); writer.println("<br/>"); } protected final void writeTable(PrintWriter writer, String title, List<String> columns, List<List<String>> rows) { int n = random.nextInt(); int c = (columns == null ? (rows == null || rows.size() == 0 ? 0 : rows.get(0).size()) : columns.size()); int r = (rows == null ? 0 : rows.size()); writer.println("<table>"); writer.println("<thead>"); writer.println(" <tr>"); writer.println(" <th colspan=\"" + c + "\">" + title + "</th>"); writer.println(" </tr>"); if (columns != null && columns.size() > 0) { writer.println(" <tr>"); for (int i = 0; i < columns.size(); i++) { String col = columns.get(i); if (col.endsWith(":")) { col += " <input type=\"text\" id=\"in_" + n + "_" + i + "\" onkeyup=\"for (var i = 0; i < " + r + "; i ++) { var m = true; for (var j = 0; j < " + columns.size() + "; j ++) { if (document.getElementById('in_" + n + "_' + j)) { var iv = document.getElementById('in_" + n + "_' + j).value; var tv = document.getElementById('td_" + n + "_' + i + '_' + j).innerHTML; if (iv.length > 0 && (tv.length < iv.length || tv.indexOf(iv) == -1)) { m = false; break; } } } document.getElementById('tr_" + n + "_' + i).style.display = (m ? '' : 'none');}\" style=\"width: 100%\" />"; } writer.println(" <td>" + col + "</td>"); } writer.println(" </tr>"); } writer.println("</thead>"); if (rows != null && rows.size() > 0) { writer.println("<tbody>"); int i = 0; for (Collection<String> row : rows) { writer.println(" <tr id=\"tr_" + n + "_" + i + "\">"); int j = 0; for (String col : row) { writer.println(" <td id=\"td_" + n + "_" + i + "_" + j + "\" style=\"display: ;\">" + col + "</td>"); j++; } writer.println(" </tr>"); i++; } writer.println("</tbody>"); } writer.println("</table>"); writer.println("<br/>"); } }
5,312
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.container.page; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import com.alibaba.dubbo.common.Constants; /** * ResourceServlet */ public class ResourceFilter implements Filter { private static final String CLASSPATH_PREFIX = "classpath:"; private final long start = System.currentTimeMillis(); private final List<String> resources = new ArrayList<String>(); public void init(FilterConfig filterConfig) throws ServletException { String config = filterConfig.getInitParameter("resources"); if (config != null && config.length() > 0) { String[] configs = Constants.COMMA_SPLIT_PATTERN.split(config); for (String c : configs) { if (c != null && c.length() > 0) { c = c.replace('\\', '/'); if (c.endsWith("/")) { c = c.substring(0, c.length() - 1); } resources.add(c); } } } } public void destroy() {} public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if (response.isCommitted()) { return; } String uri = request.getRequestURI(); String context = request.getContextPath(); if (uri.endsWith("/favicon.ico")) { uri = "/favicon.ico"; } else if (context != null && !"/".equals(context)) { uri = uri.substring(context.length()); } if (!uri.startsWith("/")) { uri = "/" + uri; } long lastModified = getLastModified(uri); long since = request.getDateHeader("If-Modified-Since"); if (since >= lastModified) { response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } byte[] data; InputStream input = getInputStream(uri); if (input == null) { chain.doFilter(req, res); return; } try { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } data = output.toByteArray(); } finally { input.close(); } response.setDateHeader("Last-Modified", lastModified); OutputStream output = response.getOutputStream(); output.write(data); output.flush(); } private boolean isFile(String path) { return path.startsWith("/") || path.indexOf(":") <= 1; } private long getLastModified(String uri) { for (String resource : resources) { if (resource != null && resource.length() > 0) { String path = resource + uri; if (isFile(path)) { File file = new File(path); if (file.exists()) { return file.lastModified(); } } } } return start; } private InputStream getInputStream(String uri) { for (String resource : resources) { String path = resource + uri; try { if (isFile(path)) { return new FileInputStream(path); } else if (path.startsWith(CLASSPATH_PREFIX)) { return Thread.currentThread() .getContextClassLoader() .getResourceAsStream(path.substring(CLASSPATH_PREFIX.length())); } else { return new URL(path).openStream(); } } catch (IOException e) { } } return null; } }
5,313
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/PageHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.container.page; import org.apache.dubbo.common.extension.SPI; import com.alibaba.dubbo.common.URL; /** * PageHandler */ @SPI public interface PageHandler { /** * Handle the page. * * @param url * @return the page. */ Page handle(URL url); }
5,314
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/MenuComparator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.container.page; import java.io.Serializable; import java.util.Comparator; /** * MenuComparator */ public class MenuComparator implements Comparator<PageHandler>, Serializable { private static final long serialVersionUID = -3161526932904414029L; @Override public int compare(PageHandler o1, PageHandler o2) { if (o1 == null && o2 == null) { return 0; } if (o1 == null) { return -1; } if (o2 == null) { return 1; } return o1.equals(o2) ? 0 : (o1.getClass().getAnnotation(Menu.class).order() > o2.getClass().getAnnotation(Menu.class).order() ? 1 : -1); } }
5,315
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/LogPageHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.container.page.pages; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.List; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.container.page.Menu; import com.alibaba.dubbo.container.page.Page; import com.alibaba.dubbo.container.page.PageHandler; import org.apache.log4j.Appender; import org.apache.log4j.FileAppender; import org.apache.log4j.Level; import org.apache.log4j.LogManager; /** * LogPageHandler */ @Menu(name = "Log", desc = "Show system log.", order = Integer.MAX_VALUE - 11000) public class LogPageHandler implements PageHandler { private static final int SHOW_LOG_LENGTH = 30000; private File file; @SuppressWarnings("unchecked") public LogPageHandler() { try { org.apache.log4j.Logger logger = LogManager.getRootLogger(); if (logger != null) { Enumeration<Appender> appenders = logger.getAllAppenders(); if (appenders != null) { while (appenders.hasMoreElements()) { Appender appender = appenders.nextElement(); if (appender instanceof FileAppender) { FileAppender fileAppender = (FileAppender) appender; String filename = fileAppender.getFile(); file = new File(filename); break; } } } } } catch (Throwable t) { } } @Override public Page handle(URL url) { long size = 0; String content = ""; String modified = "Not exist"; if (file != null && file.exists()) { try { FileInputStream fis = new FileInputStream(file); FileChannel channel = fis.getChannel(); size = channel.size(); ByteBuffer bb; if (size <= SHOW_LOG_LENGTH) { bb = ByteBuffer.allocate((int) size); channel.read(bb, 0); } else { int pos = (int) (size - SHOW_LOG_LENGTH); bb = ByteBuffer.allocate(SHOW_LOG_LENGTH); channel.read(bb, pos); } bb.flip(); content = new String(bb.array()) .replace("<", "&lt;") .replace(">", "&gt;") .replace("\n", "<br/><br/>"); modified = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(file.lastModified())); } catch (IOException e) { } } Level level = LogManager.getRootLogger().getLevel(); List<List<String>> rows = new ArrayList<List<String>>(); List<String> row = new ArrayList<String>(); row.add(content); rows.add(row); return new Page( "Log", "Log", new String[] {(file == null ? "" : file.getName()) + ", " + size + " bytes, " + modified + ", " + level }, rows); } }
5,316
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/StatusPageHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.container.page.pages; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.common.status.support.StatusUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.status.StatusChecker; import com.alibaba.dubbo.container.page.Menu; import com.alibaba.dubbo.container.page.Page; import com.alibaba.dubbo.container.page.PageHandler; /** * StatusPageHandler */ @Menu(name = "Status", desc = "Show system status.", order = Integer.MAX_VALUE - 12000) public class StatusPageHandler implements PageHandler { @Override public Page handle(URL url) { List<List<String>> rows = new ArrayList<List<String>>(); Set<String> names = ExtensionLoader.getExtensionLoader(StatusChecker.class).getSupportedExtensions(); Map<String, Status> statuses = new HashMap<String, Status>(); for (String name : names) { StatusChecker checker = ExtensionLoader.getExtensionLoader(StatusChecker.class).getExtension(name); List<String> row = new ArrayList<String>(); row.add(name); Status status = checker.check(); if (status != null && !Status.Level.UNKNOWN.equals(status.getLevel())) { statuses.put(name, status); row.add(getLevelHtml(status.getLevel())); row.add(status.getMessage()); rows.add(row); } } Status status = StatusUtils.getSummaryStatus(statuses); if ("status".equals(url.getPath())) { return new Page("", "", "", status.getLevel().toString()); } else { List<String> row = new ArrayList<String>(); row.add("summary"); row.add(getLevelHtml(status.getLevel())); row.add("<a href=\"/status\" target=\"_blank\">summary</a>"); rows.add(row); return new Page( "Status (<a href=\"/status\" target=\"_blank\">summary</a>)", "Status", new String[] {"Name", "Status", "Description"}, rows); } } private String getLevelHtml(Status.Level level) { return "<font color=\"" + getLevelColor(level) + "\">" + level.name() + "</font>"; } private String getLevelColor(Status.Level level) { if (level == Status.Level.OK) { return "green"; } else if (level == Status.Level.ERROR) { return "red"; } else if (level == Status.Level.WARN) { return "yellow"; } return "gray"; } }
5,317
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/SystemPageHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.container.page.pages; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.utils.NetUtils; import java.lang.management.ManagementFactory; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.container.page.Menu; import com.alibaba.dubbo.container.page.Page; import com.alibaba.dubbo.container.page.PageHandler; /** * SystemPageHandler */ @Menu(name = "System", desc = "Show system environment information.", order = Integer.MAX_VALUE - 10000) public class SystemPageHandler implements PageHandler { private static final long SECOND = 1000; private static final long MINUTE = 60 * SECOND; private static final long HOUR = 60 * MINUTE; private static final long DAY = 24 * HOUR; @Override public Page handle(URL url) { List<List<String>> rows = new ArrayList<List<String>>(); List<String> row; row = new ArrayList<String>(); row.add("Version"); row.add(Version.getVersion(SystemPageHandler.class, "2.0.0")); rows.add(row); row = new ArrayList<String>(); row.add("Host"); String address = NetUtils.getLocalHost(); row.add(NetUtils.getHostName(address) + "/" + address); rows.add(row); row = new ArrayList<String>(); row.add("OS"); row.add(System.getProperty("os.name") + " " + System.getProperty("os.version")); rows.add(row); row = new ArrayList<String>(); row.add("JVM"); row.add(System.getProperty("java.runtime.name") + " " + System.getProperty("java.runtime.version") + ",<br/>" + System.getProperty("java.vm.name") + " " + System.getProperty("java.vm.version") + " " + System.getProperty("java.vm.info", "")); rows.add(row); row = new ArrayList<String>(); row.add("CPU"); row.add(System.getProperty("os.arch", "") + ", " + String.valueOf(Runtime.getRuntime().availableProcessors()) + " cores"); rows.add(row); row = new ArrayList<String>(); row.add("Locale"); row.add(Locale.getDefault().toString() + "/" + System.getProperty("file.encoding")); rows.add(row); row = new ArrayList<String>(); row.add("Uptime"); row.add(formatUptime(ManagementFactory.getRuntimeMXBean().getUptime())); rows.add(row); row = new ArrayList<String>(); row.add("Time"); row.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z").format(new Date())); rows.add(row); return new Page("System", "System", new String[] {"Property", "Value"}, rows); } private String formatUptime(long uptime) { StringBuilder buf = new StringBuilder(); if (uptime > DAY) { long days = (uptime - uptime % DAY) / DAY; buf.append(days); buf.append(" Days"); uptime = uptime % DAY; } if (uptime > HOUR) { long hours = (uptime - uptime % HOUR) / HOUR; if (buf.length() > 0) { buf.append(", "); } buf.append(hours); buf.append(" Hours"); uptime = uptime % HOUR; } if (uptime > MINUTE) { long minutes = (uptime - uptime % MINUTE) / MINUTE; if (buf.length() > 0) { buf.append(", "); } buf.append(minutes); buf.append(" Minutes"); uptime = uptime % MINUTE; } if (uptime > SECOND) { long seconds = (uptime - uptime % SECOND) / SECOND; if (buf.length() > 0) { buf.append(", "); } buf.append(seconds); buf.append(" Seconds"); uptime = uptime % SECOND; } if (uptime > 0) { if (buf.length() > 0) { buf.append(", "); } buf.append(uptime); buf.append(" Milliseconds"); } return buf.toString(); } }
5,318
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/HomePageHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.container.page.pages; import org.apache.dubbo.common.extension.ExtensionLoader; import java.util.ArrayList; import java.util.List; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.container.page.Menu; import com.alibaba.dubbo.container.page.Page; import com.alibaba.dubbo.container.page.PageHandler; import com.alibaba.dubbo.container.page.PageServlet; /** * HomePageHandler */ @Menu(name = "Home", desc = "Home page.", order = Integer.MIN_VALUE) public class HomePageHandler implements PageHandler { @Override public Page handle(URL url) { List<List<String>> rows = new ArrayList<List<String>>(); for (PageHandler handler : PageServlet.getInstance().getMenus()) { String uri = ExtensionLoader.getExtensionLoader(PageHandler.class).getExtensionName(handler); Menu menu = handler.getClass().getAnnotation(Menu.class); List<String> row = new ArrayList<String>(); row.add("<a href=\"" + uri + ".html\">" + menu.name() + "</a>"); row.add(menu.desc()); rows.add(row); } return new Page("Home", "Menus", new String[] {"Menu Name", "Menu Desc"}, rows); } }
5,319
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/URL.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import java.net.InetSocketAddress; import java.util.Collection; import java.util.Map; @Deprecated public class URL extends org.apache.dubbo.common.URL { protected URL() { super(); } public URL(org.apache.dubbo.common.URL url) { super( url.getProtocol(), url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), url.getPath(), url.getParameters()); } public URL(String protocol, String host, int port) { super(protocol, null, null, host, port, null, (Map<String, String>) null); } public URL(String protocol, String host, int port, String[] pairs) { super(protocol, null, null, host, port, null, CollectionUtils.toStringMap(pairs)); } public URL(String protocol, String host, int port, Map<String, String> parameters) { super(protocol, null, null, host, port, null, parameters); } public URL(String protocol, String host, int port, String path) { super(protocol, null, null, host, port, path, (Map<String, String>) null); } public URL(String protocol, String host, int port, String path, String... pairs) { super(protocol, null, null, host, port, path, CollectionUtils.toStringMap(pairs)); } public URL(String protocol, String host, int port, String path, Map<String, String> parameters) { super(protocol, null, null, host, port, path, parameters); } public URL(String protocol, String username, String password, String host, int port, String path) { super(protocol, username, password, host, port, path, (Map<String, String>) null); } public URL(String protocol, String username, String password, String host, int port, String path, String... pairs) { super(protocol, username, password, host, port, path, CollectionUtils.toStringMap(pairs)); } public URL( String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters) { super(protocol, username, password, host, port, path, parameters); } public static URL valueOf(String url) { org.apache.dubbo.common.URL result = org.apache.dubbo.common.URL.valueOf(url); return new DelegateURL(result); } public static String encode(String value) { return org.apache.dubbo.common.URL.encode(value); } public static String decode(String value) { return org.apache.dubbo.common.URL.decode(value); } @Override public String getProtocol() { return super.getProtocol(); } @Override public URL setProtocol(String protocol) { return new URL( protocol, super.getUsername(), super.getPassword(), super.getHost(), super.getPort(), super.getPath(), super.getParameters()); } @Override public String getUsername() { return super.getUsername(); } @Override public URL setUsername(String username) { return new URL( super.getProtocol(), username, super.getPassword(), super.getHost(), super.getPort(), super.getPath(), super.getParameters()); } @Override public String getPassword() { return super.getPassword(); } @Override public URL setPassword(String password) { return new URL( super.getProtocol(), super.getUsername(), password, super.getHost(), super.getPort(), super.getPath(), super.getParameters()); } @Override public String getAuthority() { // Compatible with old version logic:The previous Authority only contained username and password information. return super.getUserInformation(); } @Override public String getHost() { return super.getHost(); } @Override public URL setHost(String host) { return new URL( super.getProtocol(), super.getUsername(), super.getPassword(), host, super.getPort(), super.getPath(), super.getParameters()); } @Override public String getIp() { return super.getIp(); } @Override public int getPort() { return super.getPort(); } @Override public URL setPort(int port) { return new URL( super.getProtocol(), super.getUsername(), super.getPassword(), super.getHost(), port, super.getPath(), super.getParameters()); } @Override public int getPort(int defaultPort) { return super.getPort(); } @Override public String getAddress() { return super.getAddress(); } @Override public URL setAddress(String address) { org.apache.dubbo.common.URL result = super.setAddress(address); return new URL(result); } @Override public String getBackupAddress() { return super.getBackupAddress(); } @Override public String getBackupAddress(int defaultPort) { return super.getBackupAddress(defaultPort); } // public List<URL> getBackupUrls() { // List<org.apache.dubbo.common.URL> res = super.getBackupUrls(); // return res.stream().map(url -> new URL(url)).collect(Collectors.toList()); // } @Override public String getPath() { return super.getPath(); } @Override public URL setPath(String path) { return new URL( super.getProtocol(), super.getUsername(), super.getPassword(), super.getHost(), super.getPort(), path, super.getParameters()); } @Override public String getAbsolutePath() { return super.getAbsolutePath(); } @Override public Map<String, String> getParameters() { return super.getParameters(); } @Override public String getParameterAndDecoded(String key) { return super.getParameterAndDecoded(key); } @Override public String getParameterAndDecoded(String key, String defaultValue) { return org.apache.dubbo.common.URL.decode(getParameter(key, defaultValue)); } @Override public String getParameter(String key) { return super.getParameter(key); } @Override public String getParameter(String key, String defaultValue) { return super.getParameter(key, defaultValue); } @Override public String[] getParameter(String key, String[] defaultValue) { return super.getParameter(key, defaultValue); } @Override public URL getUrlParameter(String key) { org.apache.dubbo.common.URL result = super.getUrlParameter(key); return new URL(result); } @Override public double getParameter(String key, double defaultValue) { return super.getParameter(key, defaultValue); } @Override public float getParameter(String key, float defaultValue) { return super.getParameter(key, defaultValue); } @Override public long getParameter(String key, long defaultValue) { return super.getParameter(key, defaultValue); } @Override public int getParameter(String key, int defaultValue) { return super.getParameter(key, defaultValue); } @Override public short getParameter(String key, short defaultValue) { return super.getParameter(key, defaultValue); } @Override public byte getParameter(String key, byte defaultValue) { return super.getParameter(key, defaultValue); } @Override public float getPositiveParameter(String key, float defaultValue) { return super.getPositiveParameter(key, defaultValue); } @Override public double getPositiveParameter(String key, double defaultValue) { return super.getPositiveParameter(key, defaultValue); } @Override public long getPositiveParameter(String key, long defaultValue) { return super.getPositiveParameter(key, defaultValue); } @Override public int getPositiveParameter(String key, int defaultValue) { return super.getPositiveParameter(key, defaultValue); } @Override public short getPositiveParameter(String key, short defaultValue) { return super.getPositiveParameter(key, defaultValue); } @Override public byte getPositiveParameter(String key, byte defaultValue) { return super.getPositiveParameter(key, defaultValue); } @Override public char getParameter(String key, char defaultValue) { return super.getParameter(key, defaultValue); } @Override public boolean getParameter(String key, boolean defaultValue) { return super.getParameter(key, defaultValue); } @Override public boolean hasParameter(String key) { return super.hasParameter(key); } @Override public String getMethodParameterAndDecoded(String method, String key) { return super.getMethodParameterAndDecoded(method, key); } @Override public String getMethodParameterAndDecoded(String method, String key, String defaultValue) { return super.getMethodParameterAndDecoded(method, key, defaultValue); } @Override public String getMethodParameter(String method, String key) { return super.getMethodParameter(method, key); } @Override public String getMethodParameter(String method, String key, String defaultValue) { return super.getMethodParameter(method, key, defaultValue); } @Override public double getMethodParameter(String method, String key, double defaultValue) { return super.getMethodParameter(method, key, defaultValue); } @Override public float getMethodParameter(String method, String key, float defaultValue) { return super.getMethodParameter(method, key, defaultValue); } @Override public long getMethodParameter(String method, String key, long defaultValue) { return super.getMethodParameter(method, key, defaultValue); } @Override public int getMethodParameter(String method, String key, int defaultValue) { return super.getMethodParameter(method, key, defaultValue); } @Override public short getMethodParameter(String method, String key, short defaultValue) { return super.getMethodParameter(method, key, defaultValue); } @Override public byte getMethodParameter(String method, String key, byte defaultValue) { return super.getMethodParameter(method, key, defaultValue); } @Override public double getMethodPositiveParameter(String method, String key, double defaultValue) { return super.getMethodPositiveParameter(method, key, defaultValue); } @Override public float getMethodPositiveParameter(String method, String key, float defaultValue) { return super.getMethodPositiveParameter(method, key, defaultValue); } @Override public long getMethodPositiveParameter(String method, String key, long defaultValue) { return super.getMethodPositiveParameter(method, key, defaultValue); } @Override public int getMethodPositiveParameter(String method, String key, int defaultValue) { return super.getMethodPositiveParameter(method, key, defaultValue); } @Override public short getMethodPositiveParameter(String method, String key, short defaultValue) { return super.getMethodPositiveParameter(method, key, defaultValue); } @Override public byte getMethodPositiveParameter(String method, String key, byte defaultValue) { return super.getMethodPositiveParameter(method, key, defaultValue); } @Override public char getMethodParameter(String method, String key, char defaultValue) { return super.getMethodParameter(method, key, defaultValue); } @Override public boolean getMethodParameter(String method, String key, boolean defaultValue) { return super.getMethodParameter(method, key, defaultValue); } @Override public boolean hasMethodParameter(String method, String key) { return super.hasMethodParameter(method, key); } @Override public boolean isLocalHost() { return super.isLocalHost(); } @Override public boolean isAnyHost() { return super.isAnyHost(); } @Override public URL addParameterAndEncoded(String key, String value) { if (StringUtils.isEmpty(value)) { return this; } return addParameter(key, encode(value)); } @Override public URL addParameter(String key, boolean value) { return addParameter(key, String.valueOf(value)); } @Override public URL addParameter(String key, char value) { return addParameter(key, String.valueOf(value)); } @Override public URL addParameter(String key, byte value) { return addParameter(key, String.valueOf(value)); } @Override public URL addParameter(String key, short value) { return addParameter(key, String.valueOf(value)); } @Override public URL addParameter(String key, int value) { return addParameter(key, String.valueOf(value)); } @Override public URL addParameter(String key, long value) { return addParameter(key, String.valueOf(value)); } @Override public URL addParameter(String key, float value) { return addParameter(key, String.valueOf(value)); } @Override public URL addParameter(String key, double value) { return addParameter(key, String.valueOf(value)); } @Override public URL addParameter(String key, Enum<?> value) { if (value == null) { return this; } return addParameter(key, String.valueOf(value)); } @Override public URL addParameter(String key, Number value) { if (value == null) { return this; } return addParameter(key, String.valueOf(value)); } @Override public URL addParameter(String key, CharSequence value) { if (value == null || value.length() == 0) { return this; } return addParameter(key, String.valueOf(value)); } @Override public URL addParameter(String key, String value) { org.apache.dubbo.common.URL result = super.addParameter(key, value); return new URL(result); } @Override public URL addParameterIfAbsent(String key, String value) { org.apache.dubbo.common.URL result = super.addParameterIfAbsent(key, value); return new URL(result); } @Override public URL addParameters(Map<String, String> parameters) { org.apache.dubbo.common.URL result = super.addParameters(parameters); return new URL(result); } @Override public URL addParametersIfAbsent(Map<String, String> parameters) { org.apache.dubbo.common.URL result = super.addParametersIfAbsent(parameters); return new URL(result); } @Override public URL addParameters(String... pairs) { org.apache.dubbo.common.URL result = super.addParameters(pairs); return new URL(result); } @Override public URL addParameterString(String query) { org.apache.dubbo.common.URL result = super.addParameterString(query); return new URL(result); } @Override public URL removeParameter(String key) { org.apache.dubbo.common.URL result = super.removeParameter(key); return new URL(result); } @Override public URL removeParameters(Collection<String> keys) { org.apache.dubbo.common.URL result = super.removeParameters(keys); return new URL(result); } @Override public URL removeParameters(String... keys) { org.apache.dubbo.common.URL result = super.removeParameters(keys); return new URL(result); } @Override public URL clearParameters() { org.apache.dubbo.common.URL result = super.clearParameters(); return new URL(result); } @Override public String getRawParameter(String key) { return super.getRawParameter(key); } @Override public Map<String, String> toMap() { return super.toMap(); } @Override public String toString() { return super.toString(); } @Override public String toString(String... parameters) { return super.toString(parameters); } @Override public String toIdentityString() { return super.toIdentityString(); } @Override public String toIdentityString(String... parameters) { return super.toIdentityString(parameters); } @Override public String toFullString() { return super.toFullString(); } @Override public String toFullString(String... parameters) { return super.toFullString(parameters); } @Override public String toParameterString() { return super.toParameterString(); } @Override public String toParameterString(String... parameters) { return super.toParameterString(parameters); } @Override public java.net.URL toJavaURL() { return super.toJavaURL(); } @Override public InetSocketAddress toInetSocketAddress() { return super.toInetSocketAddress(); } @Override public String getServiceKey() { return super.getServiceKey(); } @Override public String toServiceStringWithoutResolving() { return super.toServiceStringWithoutResolving(); } @Override public String toServiceString() { return super.toServiceString(); } @Override public String getServiceInterface() { return super.getServiceInterface(); } @Override public URL setServiceInterface(String service) { org.apache.dubbo.common.URL result = super.setServiceInterface(service); return new URL(result); } public org.apache.dubbo.common.URL getOriginalURL() { return new org.apache.dubbo.common.URL( super.getProtocol(), super.getUsername(), super.getPassword(), super.getHost(), super.getPort(), super.getPath(), super.getParameters()); } }
5,320
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/DelegateURL.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common; import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.url.component.URLAddress; import org.apache.dubbo.common.url.component.URLParam; 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.ScopeModel; import org.apache.dubbo.rpc.model.ServiceModel; import java.net.InetSocketAddress; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.function.Predicate; @Deprecated public class DelegateURL extends com.alibaba.dubbo.common.URL { protected final org.apache.dubbo.common.URL apacheUrl; public DelegateURL(org.apache.dubbo.common.URL apacheUrl) { this.apacheUrl = apacheUrl; } public static com.alibaba.dubbo.common.URL valueOf(String url) { return new DelegateURL(org.apache.dubbo.common.URL.valueOf(url)); } @Override public String getProtocol() { return apacheUrl.getProtocol(); } @Override public com.alibaba.dubbo.common.URL setProtocol(String protocol) { return new DelegateURL(apacheUrl.setProtocol(protocol)); } @Override public String getUsername() { return apacheUrl.getUsername(); } @Override public com.alibaba.dubbo.common.URL setUsername(String username) { return new DelegateURL(apacheUrl.setUsername(username)); } @Override public String getPassword() { return apacheUrl.getPassword(); } @Override public com.alibaba.dubbo.common.URL setPassword(String password) { return new DelegateURL(apacheUrl.setPassword(password)); } @Override public String getAuthority() { return apacheUrl.getAuthority(); } @Override public String getHost() { return apacheUrl.getHost(); } @Override public com.alibaba.dubbo.common.URL setHost(String host) { return new DelegateURL(apacheUrl.setHost(host)); } @Override public String getIp() { return apacheUrl.getIp(); } @Override public int getPort() { return apacheUrl.getPort(); } @Override public com.alibaba.dubbo.common.URL setPort(int port) { return new DelegateURL(apacheUrl.setPort(port)); } @Override public int getPort(int defaultPort) { return apacheUrl.getPort(defaultPort); } @Override public String getAddress() { return apacheUrl.getAddress(); } @Override public com.alibaba.dubbo.common.URL setAddress(String address) { return new DelegateURL(apacheUrl.setAddress(address)); } @Override public String getBackupAddress() { return apacheUrl.getBackupAddress(); } @Override public String getBackupAddress(int defaultPort) { return apacheUrl.getBackupAddress(defaultPort); } @Override public String getPath() { return apacheUrl.getPath(); } @Override public com.alibaba.dubbo.common.URL setPath(String path) { return new DelegateURL(apacheUrl.setPath(path)); } @Override public String getAbsolutePath() { return apacheUrl.getAbsolutePath(); } @Override public Map<String, String> getParameters() { return apacheUrl.getParameters(); } @Override public String getParameterAndDecoded(String key) { return apacheUrl.getParameterAndDecoded(key); } @Override public String getParameterAndDecoded(String key, String defaultValue) { return apacheUrl.getParameterAndDecoded(key, defaultValue); } @Override public String getParameter(String key) { return apacheUrl.getParameter(key); } @Override public String getParameter(String key, String defaultValue) { return apacheUrl.getParameter(key, defaultValue); } @Override public String[] getParameter(String key, String[] defaultValue) { return apacheUrl.getParameter(key, defaultValue); } @Override public com.alibaba.dubbo.common.URL getUrlParameter(String key) { return new DelegateURL(apacheUrl.getUrlParameter(key)); } @Override public double getParameter(String key, double defaultValue) { return apacheUrl.getParameter(key, defaultValue); } @Override public float getParameter(String key, float defaultValue) { return apacheUrl.getParameter(key, defaultValue); } @Override public long getParameter(String key, long defaultValue) { return apacheUrl.getParameter(key, defaultValue); } @Override public int getParameter(String key, int defaultValue) { return apacheUrl.getParameter(key, defaultValue); } @Override public short getParameter(String key, short defaultValue) { return apacheUrl.getParameter(key, defaultValue); } @Override public byte getParameter(String key, byte defaultValue) { return apacheUrl.getParameter(key, defaultValue); } @Override public float getPositiveParameter(String key, float defaultValue) { return apacheUrl.getPositiveParameter(key, defaultValue); } @Override public double getPositiveParameter(String key, double defaultValue) { return apacheUrl.getPositiveParameter(key, defaultValue); } @Override public long getPositiveParameter(String key, long defaultValue) { return apacheUrl.getPositiveParameter(key, defaultValue); } @Override public int getPositiveParameter(String key, int defaultValue) { return apacheUrl.getPositiveParameter(key, defaultValue); } @Override public short getPositiveParameter(String key, short defaultValue) { return apacheUrl.getPositiveParameter(key, defaultValue); } @Override public byte getPositiveParameter(String key, byte defaultValue) { return apacheUrl.getPositiveParameter(key, defaultValue); } @Override public char getParameter(String key, char defaultValue) { return apacheUrl.getParameter(key, defaultValue); } @Override public boolean getParameter(String key, boolean defaultValue) { return apacheUrl.getParameter(key, defaultValue); } @Override public boolean hasParameter(String key) { return apacheUrl.hasParameter(key); } @Override public String getMethodParameterAndDecoded(String method, String key) { return apacheUrl.getMethodParameterAndDecoded(method, key); } @Override public String getMethodParameterAndDecoded(String method, String key, String defaultValue) { return apacheUrl.getMethodParameterAndDecoded(method, key, defaultValue); } @Override public String getMethodParameter(String method, String key) { return apacheUrl.getMethodParameter(method, key); } @Override public String getMethodParameter(String method, String key, String defaultValue) { return apacheUrl.getMethodParameter(method, key, defaultValue); } @Override public double getMethodParameter(String method, String key, double defaultValue) { return apacheUrl.getMethodParameter(method, key, defaultValue); } @Override public float getMethodParameter(String method, String key, float defaultValue) { return apacheUrl.getMethodParameter(method, key, defaultValue); } @Override public long getMethodParameter(String method, String key, long defaultValue) { return apacheUrl.getMethodParameter(method, key, defaultValue); } @Override public int getMethodParameter(String method, String key, int defaultValue) { return apacheUrl.getMethodParameter(method, key, defaultValue); } @Override public short getMethodParameter(String method, String key, short defaultValue) { return apacheUrl.getMethodParameter(method, key, defaultValue); } @Override public byte getMethodParameter(String method, String key, byte defaultValue) { return apacheUrl.getMethodParameter(method, key, defaultValue); } @Override public double getMethodPositiveParameter(String method, String key, double defaultValue) { return apacheUrl.getMethodPositiveParameter(method, key, defaultValue); } @Override public float getMethodPositiveParameter(String method, String key, float defaultValue) { return apacheUrl.getMethodPositiveParameter(method, key, defaultValue); } @Override public long getMethodPositiveParameter(String method, String key, long defaultValue) { return apacheUrl.getMethodPositiveParameter(method, key, defaultValue); } @Override public int getMethodPositiveParameter(String method, String key, int defaultValue) { return apacheUrl.getMethodPositiveParameter(method, key, defaultValue); } @Override public short getMethodPositiveParameter(String method, String key, short defaultValue) { return apacheUrl.getMethodPositiveParameter(method, key, defaultValue); } @Override public byte getMethodPositiveParameter(String method, String key, byte defaultValue) { return apacheUrl.getMethodPositiveParameter(method, key, defaultValue); } @Override public char getMethodParameter(String method, String key, char defaultValue) { return apacheUrl.getMethodParameter(method, key, defaultValue); } @Override public boolean getMethodParameter(String method, String key, boolean defaultValue) { return apacheUrl.getMethodParameter(method, key, defaultValue); } @Override public boolean hasMethodParameter(String method, String key) { return apacheUrl.hasMethodParameter(method, key); } @Override public boolean isLocalHost() { return apacheUrl.isLocalHost(); } @Override public boolean isAnyHost() { return apacheUrl.isAnyHost(); } @Override public com.alibaba.dubbo.common.URL addParameterAndEncoded(String key, String value) { return new DelegateURL(apacheUrl.addParameterAndEncoded(key, value)); } @Override public com.alibaba.dubbo.common.URL addParameter(String key, boolean value) { return new DelegateURL(apacheUrl.addParameter(key, value)); } @Override public com.alibaba.dubbo.common.URL addParameter(String key, char value) { return new DelegateURL(apacheUrl.addParameter(key, value)); } @Override public com.alibaba.dubbo.common.URL addParameter(String key, byte value) { return new DelegateURL(apacheUrl.addParameter(key, value)); } @Override public com.alibaba.dubbo.common.URL addParameter(String key, short value) { return new DelegateURL(apacheUrl.addParameter(key, value)); } @Override public com.alibaba.dubbo.common.URL addParameter(String key, int value) { return new DelegateURL(apacheUrl.addParameter(key, value)); } @Override public com.alibaba.dubbo.common.URL addParameter(String key, long value) { return new DelegateURL(apacheUrl.addParameter(key, value)); } @Override public com.alibaba.dubbo.common.URL addParameter(String key, float value) { return new DelegateURL(apacheUrl.addParameter(key, value)); } @Override public com.alibaba.dubbo.common.URL addParameter(String key, double value) { return new DelegateURL(apacheUrl.addParameter(key, value)); } @Override public com.alibaba.dubbo.common.URL addParameter(String key, Enum<?> value) { return new DelegateURL(apacheUrl.addParameter(key, value)); } @Override public com.alibaba.dubbo.common.URL addParameter(String key, Number value) { return new DelegateURL(apacheUrl.addParameter(key, value)); } @Override public com.alibaba.dubbo.common.URL addParameter(String key, CharSequence value) { return new DelegateURL(apacheUrl.addParameter(key, value)); } @Override public com.alibaba.dubbo.common.URL addParameter(String key, String value) { return new DelegateURL(apacheUrl.addParameter(key, value)); } @Override public com.alibaba.dubbo.common.URL addParameterIfAbsent(String key, String value) { return new DelegateURL(apacheUrl.addParameterIfAbsent(key, value)); } @Override public com.alibaba.dubbo.common.URL addParameters(Map<String, String> parameters) { return new DelegateURL(apacheUrl.addParameters(parameters)); } @Override public com.alibaba.dubbo.common.URL addParametersIfAbsent(Map<String, String> parameters) { return new DelegateURL(apacheUrl.addParametersIfAbsent(parameters)); } @Override public com.alibaba.dubbo.common.URL addParameters(String... pairs) { return new DelegateURL(apacheUrl.addParameters(pairs)); } @Override public com.alibaba.dubbo.common.URL addParameterString(String query) { return new DelegateURL(apacheUrl.addParameterString(query)); } @Override public com.alibaba.dubbo.common.URL removeParameter(String key) { return new DelegateURL(apacheUrl.removeParameter(key)); } @Override public com.alibaba.dubbo.common.URL removeParameters(Collection<String> keys) { return new DelegateURL(apacheUrl.removeParameters(keys)); } @Override public com.alibaba.dubbo.common.URL removeParameters(String... keys) { return new DelegateURL(apacheUrl.removeParameters(keys)); } @Override public com.alibaba.dubbo.common.URL clearParameters() { return new DelegateURL(apacheUrl.clearParameters()); } @Override public String getRawParameter(String key) { return apacheUrl.getRawParameter(key); } @Override public Map<String, String> toMap() { return apacheUrl.toMap(); } @Override public String toString() { return apacheUrl.toString(); } @Override public String toString(String... parameters) { return apacheUrl.toString(parameters); } @Override public String toIdentityString() { return apacheUrl.toIdentityString(); } @Override public String toIdentityString(String... parameters) { return apacheUrl.toIdentityString(parameters); } @Override public String toFullString() { return apacheUrl.toFullString(); } @Override public String toFullString(String... parameters) { return apacheUrl.toFullString(parameters); } @Override public String toParameterString() { return apacheUrl.toParameterString(); } @Override public String toParameterString(String... parameters) { return apacheUrl.toParameterString(parameters); } @Override public java.net.URL toJavaURL() { return apacheUrl.toJavaURL(); } @Override public InetSocketAddress toInetSocketAddress() { return apacheUrl.toInetSocketAddress(); } @Override public String getServiceKey() { return apacheUrl.getServiceKey(); } @Override public String toServiceStringWithoutResolving() { return apacheUrl.toServiceStringWithoutResolving(); } @Override public String toServiceString() { return apacheUrl.toServiceString(); } @Override public String getServiceInterface() { return apacheUrl.getServiceInterface(); } @Override public com.alibaba.dubbo.common.URL setServiceInterface(String service) { return new DelegateURL(apacheUrl.setServiceInterface(service)); } @Override public org.apache.dubbo.common.URL getOriginalURL() { return apacheUrl; } @Override public URLAddress getUrlAddress() { return apacheUrl.getUrlAddress(); } @Override public URLParam getUrlParam() { return apacheUrl.getUrlParam(); } @Override public String getUserInformation() { return apacheUrl.getUserInformation(); } @Override public List<org.apache.dubbo.common.URL> getBackupUrls() { return apacheUrl.getBackupUrls(); } @Override public Map<String, String> getOriginalParameters() { return apacheUrl.getOriginalParameters(); } @Override public Map<String, String> getAllParameters() { return apacheUrl.getAllParameters(); } @Override public Map<String, String> getParameters(Predicate<String> nameToSelect) { return apacheUrl.getParameters(nameToSelect); } @Override public String getOriginalParameter(String key) { return apacheUrl.getOriginalParameter(key); } @Override public List<String> getParameter(String key, List<String> defaultValue) { return apacheUrl.getParameter(key, defaultValue); } @Override public <T> T getParameter(String key, Class<T> valueType) { return apacheUrl.getParameter(key, valueType); } @Override public <T> T getParameter(String key, Class<T> valueType, T defaultValue) { return apacheUrl.getParameter(key, valueType, defaultValue); } @Override public org.apache.dubbo.common.URL setScopeModel(ScopeModel scopeModel) { return apacheUrl.setScopeModel(scopeModel); } @Override public ScopeModel getScopeModel() { return apacheUrl.getScopeModel(); } @Override public FrameworkModel getOrDefaultFrameworkModel() { return apacheUrl.getOrDefaultFrameworkModel(); } @Override public ApplicationModel getOrDefaultApplicationModel() { return apacheUrl.getOrDefaultApplicationModel(); } @Override public ApplicationModel getApplicationModel() { return apacheUrl.getApplicationModel(); } @Override public ModuleModel getOrDefaultModuleModel() { return apacheUrl.getOrDefaultModuleModel(); } @Override public org.apache.dubbo.common.URL setServiceModel(ServiceModel serviceModel) { return apacheUrl.setServiceModel(serviceModel); } @Override public ServiceModel getServiceModel() { return apacheUrl.getServiceModel(); } @Override public String getMethodParameterStrict(String method, String key) { return apacheUrl.getMethodParameterStrict(method, key); } @Override public String getAnyMethodParameter(String key) { return apacheUrl.getAnyMethodParameter(key); } @Override public boolean hasMethodParameter(String method) { return apacheUrl.hasMethodParameter(method); } @Override public Map<String, String> toOriginalMap() { return apacheUrl.toOriginalMap(); } @Override public String getColonSeparatedKey() { return apacheUrl.getColonSeparatedKey(); } @Override public String getDisplayServiceKey() { return apacheUrl.getDisplayServiceKey(); } @Override public String getPathKey() { return apacheUrl.getPathKey(); } public static String buildKey(String path, String group, String version) { return org.apache.dubbo.common.URL.buildKey(path, group, version); } @Override public String getProtocolServiceKey() { return apacheUrl.getProtocolServiceKey(); } @Override @Deprecated public String getServiceName() { return apacheUrl.getServiceName(); } @Override @Deprecated public int getIntParameter(String key) { return apacheUrl.getIntParameter(key); } @Override @Deprecated public int getIntParameter(String key, int defaultValue) { return apacheUrl.getIntParameter(key, defaultValue); } @Override @Deprecated public int getPositiveIntParameter(String key, int defaultValue) { return apacheUrl.getPositiveIntParameter(key, defaultValue); } @Override @Deprecated public boolean getBooleanParameter(String key) { return apacheUrl.getBooleanParameter(key); } @Override @Deprecated public boolean getBooleanParameter(String key, boolean defaultValue) { return apacheUrl.getBooleanParameter(key, defaultValue); } @Override @Deprecated public int getMethodIntParameter(String method, String key) { return apacheUrl.getMethodIntParameter(method, key); } @Override @Deprecated public int getMethodIntParameter(String method, String key, int defaultValue) { return apacheUrl.getMethodIntParameter(method, key, defaultValue); } @Override @Deprecated public int getMethodPositiveIntParameter(String method, String key, int defaultValue) { return apacheUrl.getMethodPositiveIntParameter(method, key, defaultValue); } @Override @Deprecated public boolean getMethodBooleanParameter(String method, String key) { return apacheUrl.getMethodBooleanParameter(method, key); } @Override @Deprecated public boolean getMethodBooleanParameter(String method, String key, boolean defaultValue) { return apacheUrl.getMethodBooleanParameter(method, key, defaultValue); } @Override public Configuration toConfiguration() { return apacheUrl.toConfiguration(); } @Override public int hashCode() { return apacheUrl.hashCode(); } @Override public boolean equals(Object obj) { return apacheUrl.equals(obj); } public static void putMethodParameter( String method, String key, String value, Map<String, Map<String, String>> methodParameters) { org.apache.dubbo.common.URL.putMethodParameter(method, key, value, methodParameters); } @Override public String getApplication(String defaultValue) { return apacheUrl.getApplication(defaultValue); } @Override public String getApplication() { return apacheUrl.getApplication(); } @Override public String getRemoteApplication() { return apacheUrl.getRemoteApplication(); } @Override public String getGroup() { return apacheUrl.getGroup(); } @Override public String getGroup(String defaultValue) { return apacheUrl.getGroup(defaultValue); } @Override public String getVersion() { return apacheUrl.getVersion(); } @Override public String getVersion(String defaultValue) { return apacheUrl.getVersion(defaultValue); } @Override public String getConcatenatedParameter(String key) { return apacheUrl.getConcatenatedParameter(key); } @Override public String getCategory(String defaultValue) { return apacheUrl.getCategory(defaultValue); } @Override public String[] getCategory(String[] defaultValue) { return apacheUrl.getCategory(defaultValue); } @Override public String getCategory() { return apacheUrl.getCategory(); } @Override public String getSide(String defaultValue) { return apacheUrl.getSide(defaultValue); } @Override public String getSide() { return apacheUrl.getSide(); } @Override public Map<String, Object> getAttributes() { return apacheUrl.getAttributes(); } @Override public org.apache.dubbo.common.URL addAttributes(Map<String, Object> attributes) { return apacheUrl.addAttributes(attributes); } @Override public Object getAttribute(String key) { return apacheUrl.getAttribute(key); } @Override public Object getAttribute(String key, Object defaultValue) { return apacheUrl.getAttribute(key, defaultValue); } @Override public org.apache.dubbo.common.URL putAttribute(String key, Object obj) { return apacheUrl.putAttribute(key, obj); } @Override public org.apache.dubbo.common.URL removeAttribute(String key) { return apacheUrl.removeAttribute(key); } @Override public boolean hasAttribute(String key) { return apacheUrl.hasAttribute(key); } @Override public Map<String, String> getOriginalServiceParameters(String service) { return apacheUrl.getOriginalServiceParameters(service); } @Override public Map<String, String> getServiceParameters(String service) { return apacheUrl.getServiceParameters(service); } @Override public String getOriginalServiceParameter(String service, String key) { return apacheUrl.getOriginalServiceParameter(service, key); } @Override public String getServiceParameter(String service, String key) { return apacheUrl.getServiceParameter(service, key); } @Override public String getServiceParameter(String service, String key, String defaultValue) { return apacheUrl.getServiceParameter(service, key, defaultValue); } @Override public int getServiceParameter(String service, String key, int defaultValue) { return apacheUrl.getServiceParameter(service, key, defaultValue); } @Override public double getServiceParameter(String service, String key, double defaultValue) { return apacheUrl.getServiceParameter(service, key, defaultValue); } @Override public float getServiceParameter(String service, String key, float defaultValue) { return apacheUrl.getServiceParameter(service, key, defaultValue); } @Override public long getServiceParameter(String service, String key, long defaultValue) { return apacheUrl.getServiceParameter(service, key, defaultValue); } @Override public short getServiceParameter(String service, String key, short defaultValue) { return apacheUrl.getServiceParameter(service, key, defaultValue); } @Override public byte getServiceParameter(String service, String key, byte defaultValue) { return apacheUrl.getServiceParameter(service, key, defaultValue); } @Override public char getServiceParameter(String service, String key, char defaultValue) { return apacheUrl.getServiceParameter(service, key, defaultValue); } @Override public boolean getServiceParameter(String service, String key, boolean defaultValue) { return apacheUrl.getServiceParameter(service, key, defaultValue); } @Override public boolean hasServiceParameter(String service, String key) { return apacheUrl.hasServiceParameter(service, key); } @Override public float getPositiveServiceParameter(String service, String key, float defaultValue) { return apacheUrl.getPositiveServiceParameter(service, key, defaultValue); } @Override public double getPositiveServiceParameter(String service, String key, double defaultValue) { return apacheUrl.getPositiveServiceParameter(service, key, defaultValue); } @Override public long getPositiveServiceParameter(String service, String key, long defaultValue) { return apacheUrl.getPositiveServiceParameter(service, key, defaultValue); } @Override public int getPositiveServiceParameter(String service, String key, int defaultValue) { return apacheUrl.getPositiveServiceParameter(service, key, defaultValue); } @Override public short getPositiveServiceParameter(String service, String key, short defaultValue) { return apacheUrl.getPositiveServiceParameter(service, key, defaultValue); } @Override public byte getPositiveServiceParameter(String service, String key, byte defaultValue) { return apacheUrl.getPositiveServiceParameter(service, key, defaultValue); } @Override public String getServiceMethodParameterAndDecoded(String service, String method, String key) { return apacheUrl.getServiceMethodParameterAndDecoded(service, method, key); } @Override public String getServiceMethodParameterAndDecoded(String service, String method, String key, String defaultValue) { return apacheUrl.getServiceMethodParameterAndDecoded(service, method, key, defaultValue); } @Override public String getServiceMethodParameterStrict(String service, String method, String key) { return apacheUrl.getServiceMethodParameterStrict(service, method, key); } @Override public String getServiceMethodParameter(String service, String method, String key) { return apacheUrl.getServiceMethodParameter(service, method, key); } @Override public String getServiceMethodParameter(String service, String method, String key, String defaultValue) { return apacheUrl.getServiceMethodParameter(service, method, key, defaultValue); } @Override public double getServiceMethodParameter(String service, String method, String key, double defaultValue) { return apacheUrl.getServiceMethodParameter(service, method, key, defaultValue); } @Override public float getServiceMethodParameter(String service, String method, String key, float defaultValue) { return apacheUrl.getServiceMethodParameter(service, method, key, defaultValue); } @Override public long getServiceMethodParameter(String service, String method, String key, long defaultValue) { return apacheUrl.getServiceMethodParameter(service, method, key, defaultValue); } @Override public int getServiceMethodParameter(String service, String method, String key, int defaultValue) { return apacheUrl.getServiceMethodParameter(service, method, key, defaultValue); } @Override public short getServiceMethodParameter(String service, String method, String key, short defaultValue) { return apacheUrl.getServiceMethodParameter(service, method, key, defaultValue); } @Override public byte getServiceMethodParameter(String service, String method, String key, byte defaultValue) { return apacheUrl.getServiceMethodParameter(service, method, key, defaultValue); } @Override public boolean hasServiceMethodParameter(String service, String method, String key) { return apacheUrl.hasServiceMethodParameter(service, method, key); } @Override public boolean hasServiceMethodParameter(String service, String method) { return apacheUrl.hasServiceMethodParameter(service, method); } @Override public org.apache.dubbo.common.URL toSerializableURL() { return apacheUrl.toSerializableURL(); } }
5,321
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/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 com.alibaba.dubbo.common; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.constants.FilterConstants; import org.apache.dubbo.common.constants.QosConstants; import org.apache.dubbo.common.constants.RegistryConstants; import org.apache.dubbo.common.constants.RemotingConstants; import java.util.concurrent.ExecutorService; import java.util.regex.Pattern; @Deprecated public class Constants implements CommonConstants, QosConstants, FilterConstants, RegistryConstants, RemotingConstants, org.apache.dubbo.config.Constants, org.apache.dubbo.remoting.Constants, org.apache.dubbo.rpc.cluster.Constants, org.apache.dubbo.monitor.Constants, org.apache.dubbo.rpc.Constants, org.apache.dubbo.rpc.protocol.dubbo.Constants, org.apache.dubbo.common.serialize.Constants, org.apache.dubbo.common.config.configcenter.Constants, org.apache.dubbo.metadata.report.support.Constants, org.apache.dubbo.rpc.protocol.rest.Constants, org.apache.dubbo.registry.Constants { public static final String PROVIDER = "provider"; public static final String CONSUMER = "consumer"; public static final String REGISTER = "register"; public static final String UNREGISTER = "unregister"; public static final String SUBSCRIBE = "subscribe"; public static final String UNSUBSCRIBE = "unsubscribe"; public static final String CATEGORY_KEY = "category"; public static final String PROVIDERS_CATEGORY = "providers"; public static final String CONSUMERS_CATEGORY = "consumers"; public static final String ROUTERS_CATEGORY = "routers"; public static final String CONFIGURATORS_CATEGORY = "configurators"; public static final String DEFAULT_CATEGORY = PROVIDERS_CATEGORY; public static final String ENABLED_KEY = "enabled"; public static final String DISABLED_KEY = "disabled"; public static final String VALIDATION_KEY = "validation"; public static final String CACHE_KEY = "cache"; public static final String DYNAMIC_KEY = "dynamic"; public static final String DUBBO_PROPERTIES_KEY = "dubbo.properties.file"; public static final String DEFAULT_DUBBO_PROPERTIES = "dubbo.properties"; public static final String SENT_KEY = "sent"; public static final boolean DEFAULT_SENT = false; public static final String REGISTRY_PROTOCOL = "registry"; public static final String $INVOKE = "$invoke"; public static final String $ECHO = "$echo"; public static final int DEFAULT_IO_THREADS = Runtime.getRuntime().availableProcessors() + 1; public static final String DEFAULT_PROXY = "javassist"; public static final int DEFAULT_PAYLOAD = 8 * 1024 * 1024; public static final String DEFAULT_CLUSTER = "failover"; public static final String DEFAULT_DIRECTORY = "dubbo"; public static final String DEFAULT_LOADBALANCE = "random"; public static final String DEFAULT_PROTOCOL = "dubbo"; public static final String DEFAULT_EXCHANGER = "header"; public static final String DEFAULT_TRANSPORTER = "netty"; public static final String DEFAULT_REMOTING_SERVER = "netty"; public static final String DEFAULT_REMOTING_CLIENT = "netty"; public static final String DEFAULT_REMOTING_CODEC = "dubbo"; public static final String DEFAULT_REMOTING_SERIALIZATION = "hessian2"; public static final String DEFAULT_HTTP_SERVER = "servlet"; public static final String DEFAULT_HTTP_CLIENT = "jdk"; public static final String DEFAULT_HTTP_SERIALIZATION = "json"; public static final String DEFAULT_CHARSET = "UTF-8"; public static final int DEFAULT_WEIGHT = 100; public static final int DEFAULT_FORKS = 2; public static final String DEFAULT_THREAD_NAME = "Dubbo"; public static final int DEFAULT_CORE_THREADS = 0; public static final int DEFAULT_THREADS = 200; public static final int DEFAULT_QUEUES = 0; public static final int DEFAULT_ALIVE = 60 * 1000; public static final int DEFAULT_CONNECTIONS = 0; public static final int DEFAULT_ACCEPTS = 0; public static final int DEFAULT_IDLE_TIMEOUT = 600 * 1000; public static final int DEFAULT_HEARTBEAT = 60 * 1000; public static final int DEFAULT_TIMEOUT = 1000; public static final int DEFAULT_CONNECT_TIMEOUT = 3000; public static final int DEFAULT_RETRIES = 2; public static final int DEFAULT_BUFFER_SIZE = 8 * 1024; public static final int MAX_BUFFER_SIZE = 16 * 1024; public static final int MIN_BUFFER_SIZE = 1 * 1024; public static final String REMOVE_VALUE_PREFIX = "-"; public static final String HIDE_KEY_PREFIX = "."; public static final String DEFAULT_KEY_PREFIX = "default."; public static final String DEFAULT_KEY = "default"; public static final String LOADBALANCE_KEY = "loadbalance"; public static final String ROUTER_KEY = "router"; public static final String CLUSTER_KEY = "cluster"; public static final String REGISTRY_KEY = "registry"; public static final String MONITOR_KEY = "monitor"; public static final String SIDE_KEY = "side"; public static final String PROVIDER_SIDE = "provider"; public static final String CONSUMER_SIDE = "consumer"; public static final String DEFAULT_REGISTRY = "dubbo"; public static final String BACKUP_KEY = "backup"; public static final String DIRECTORY_KEY = "directory"; public static final String DEPRECATED_KEY = "deprecated"; public static final String ANYHOST_KEY = "anyhost"; public static final String ANYHOST_VALUE = "0.0.0.0"; public static final String LOCALHOST_KEY = "localhost"; public static final String LOCALHOST_VALUE = "127.0.0.1"; public static final String APPLICATION_KEY = "application"; public static final String LOCAL_KEY = "local"; public static final String STUB_KEY = "stub"; public static final String MOCK_KEY = "mock"; public static final String PROTOCOL_KEY = "protocol"; public static final String PROXY_KEY = "proxy"; public static final String WEIGHT_KEY = "weight"; public static final String FORKS_KEY = "forks"; public static final String DEFAULT_THREADPOOL = "limited"; public static final String DEFAULT_CLIENT_THREADPOOL = "cached"; public static final String THREADPOOL_KEY = "threadpool"; public static final String THREAD_NAME_KEY = "threadname"; public static final String IO_THREADS_KEY = "iothreads"; public static final String CORE_THREADS_KEY = "corethreads"; public static final String THREADS_KEY = "threads"; public static final String QUEUES_KEY = "queues"; public static final String ALIVE_KEY = "alive"; public static final String EXECUTES_KEY = "executes"; public static final String BUFFER_KEY = "buffer"; public static final String PAYLOAD_KEY = "payload"; public static final String REFERENCE_FILTER_KEY = "reference.filter"; public static final String INVOKER_LISTENER_KEY = "invoker.listener"; public static final String SERVICE_FILTER_KEY = "service.filter"; public static final String EXPORTER_LISTENER_KEY = "exporter.listener"; public static final String ACCESS_LOG_KEY = "accesslog"; public static final String ACTIVES_KEY = "actives"; public static final String CONNECTIONS_KEY = "connections"; public static final String ACCEPTS_KEY = "accepts"; public static final String IDLE_TIMEOUT_KEY = "idle.timeout"; public static final String HEARTBEAT_KEY = "heartbeat"; public static final String HEARTBEAT_TIMEOUT_KEY = "heartbeat.timeout"; public static final String CONNECT_TIMEOUT_KEY = "connect.timeout"; public static final String TIMEOUT_KEY = "timeout"; public static final String RETRIES_KEY = "retries"; public static final String PROMPT_KEY = "prompt"; public static final String DEFAULT_PROMPT = "dubbo>"; public static final String CODEC_KEY = "codec"; public static final String SERIALIZATION_KEY = "serialization"; public static final String EXCHANGER_KEY = "exchanger"; public static final String TRANSPORTER_KEY = "transporter"; public static final String SERVER_KEY = "server"; public static final String CLIENT_KEY = "client"; public static final String ID_KEY = "id"; public static final String ASYNC_KEY = "async"; public static final String RETURN_KEY = "return"; public static final String TOKEN_KEY = "token"; public static final String METHOD_KEY = "method"; public static final String METHODS_KEY = "methods"; public static final String CHARSET_KEY = "charset"; public static final String RECONNECT_KEY = "reconnect"; public static final String SEND_RECONNECT_KEY = "send.reconnect"; public static final int DEFAULT_RECONNECT_PERIOD = 2000; public static final String SHUTDOWN_TIMEOUT_KEY = "shutdown.timeout"; public static final int DEFAULT_SHUTDOWN_TIMEOUT = 1000 * 60 * 15; public static final String PID_KEY = "pid"; public static final String TIMESTAMP_KEY = "timestamp"; public static final String WARMUP_KEY = "warmup"; public static final int DEFAULT_WARMUP = 10 * 60 * 1000; public static final String CHECK_KEY = "check"; public static final String REGISTER_KEY = "register"; public static final String SUBSCRIBE_KEY = "subscribe"; public static final String GROUP_KEY = "group"; public static final String PATH_KEY = "path"; public static final String INTERFACE_KEY = "interface"; public static final String GENERIC_KEY = "generic"; public static final String FILE_KEY = "file"; public static final String WAIT_KEY = "wait"; public static final String CLASSIFIER_KEY = "classifier"; public static final String VERSION_KEY = "version"; public static final String REVISION_KEY = "revision"; public static final String DUBBO_VERSION_KEY = "dubbo"; public static final String HESSIAN_VERSION_KEY = "hessian.version"; public static final String DISPATCHER_KEY = "dispatcher"; public static final String CHANNEL_HANDLER_KEY = "channel.handler"; public static final String DEFAULT_CHANNEL_HANDLER = "default"; public static final String ANY_VALUE = "*"; public static final String COMMA_SEPARATOR = ","; public static final Pattern COMMA_SPLIT_PATTERN = Pattern.compile("\\s*[,]+\\s*"); public static final String PATH_SEPARATOR = "/"; public static final String REGISTRY_SEPARATOR = "|"; public static final Pattern REGISTRY_SPLIT_PATTERN = Pattern.compile("\\s*[|;]+\\s*"); public static final String SEMICOLON_SEPARATOR = ";"; public static final Pattern SEMICOLON_SPLIT_PATTERN = Pattern.compile("\\s*[;]+\\s*"); public static final String CONNECT_QUEUE_CAPACITY = "connect.queue.capacity"; public static final String CONNECT_QUEUE_WARNING_SIZE = "connect.queue.warning.size"; public static final int DEFAULT_CONNECT_QUEUE_WARNING_SIZE = 1000; public static final String CHANNEL_ATTRIBUTE_READONLY_KEY = "channel.readonly"; public static final String CHANNEL_READONLYEVENT_SENT_KEY = "channel.readonly.sent"; public static final String CHANNEL_SEND_READONLYEVENT_KEY = "channel.readonly.send"; public static final String COUNT_PROTOCOL = "count"; public static final String TRACE_PROTOCOL = "trace"; public static final String EMPTY_PROTOCOL = "empty"; public static final String ADMIN_PROTOCOL = "admin"; public static final String PROVIDER_PROTOCOL = "provider"; public static final String CONSUMER_PROTOCOL = "consumer"; public static final String ROUTE_PROTOCOL = "route"; public static final String SCRIPT_PROTOCOL = "script"; public static final String CONDITION_PROTOCOL = "condition"; public static final String MOCK_PROTOCOL = "mock"; public static final String RETURN_PREFIX = "return "; public static final String THROW_PREFIX = "throw"; public static final String FAIL_PREFIX = "fail:"; public static final String FORCE_PREFIX = "force:"; public static final String FORCE_KEY = "force"; public static final String MERGER_KEY = "merger"; public static final String CLUSTER_AVAILABLE_CHECK_KEY = "cluster.availablecheck"; public static final boolean DEFAULT_CLUSTER_AVAILABLE_CHECK = true; public static final String CLUSTER_STICKY_KEY = "sticky"; public static final boolean DEFAULT_CLUSTER_STICKY = false; public static final String LAZY_CONNECT_KEY = "lazy"; public static final String LAZY_CONNECT_INITIAL_STATE_KEY = "connect.lazy.initial.state"; public static final boolean DEFAULT_LAZY_CONNECT_INITIAL_STATE = true; public static final String REGISTRY_FILESAVE_SYNC_KEY = "save.file"; public static final String REGISTRY_RETRY_PERIOD_KEY = "retry.period"; public static final int DEFAULT_REGISTRY_RETRY_PERIOD = 5 * 1000; public static final String REGISTRY_RECONNECT_PERIOD_KEY = "reconnect.period"; public static final int DEFAULT_REGISTRY_RECONNECT_PERIOD = 3 * 1000; public static final String SESSION_TIMEOUT_KEY = "session"; public static final int DEFAULT_SESSION_TIMEOUT = 60 * 1000; public static final String EXPORT_KEY = "export"; public static final String REFER_KEY = "refer"; public static final String CALLBACK_SERVICE_KEY = "callback.service.instid"; public static final String CALLBACK_INSTANCES_LIMIT_KEY = "callbacks"; public static final int DEFAULT_CALLBACK_INSTANCES = 1; public static final String CALLBACK_SERVICE_PROXY_KEY = "callback.service.proxy"; public static final String IS_CALLBACK_SERVICE = "is_callback_service"; public static final String CHANNEL_CALLBACK_KEY = "channel.callback.invokers.key"; @Deprecated public static final String SHUTDOWN_WAIT_SECONDS_KEY = "dubbo.service.shutdown.wait.seconds"; public static final String SHUTDOWN_WAIT_KEY = "dubbo.service.shutdown.wait"; public static final String IS_SERVER_KEY = "isserver"; public static final int DEFAULT_SERVER_SHUTDOWN_TIMEOUT = 10000; public static final String ON_CONNECT_KEY = "onconnect"; public static final String ON_DISCONNECT_KEY = "ondisconnect"; public static final String ON_INVOKE_METHOD_KEY = "oninvoke.method"; public static final String ON_RETURN_METHOD_KEY = "onreturn.method"; public static final String ON_THROW_METHOD_KEY = "onthrow.method"; public static final String ON_INVOKE_INSTANCE_KEY = "oninvoke.instance"; public static final String ON_RETURN_INSTANCE_KEY = "onreturn.instance"; public static final String ON_THROW_INSTANCE_KEY = "onthrow.instance"; public static final String OVERRIDE_PROTOCOL = "override"; public static final String PRIORITY_KEY = "priority"; public static final String RULE_KEY = "rule"; public static final String TYPE_KEY = "type"; public static final String RUNTIME_KEY = "runtime"; public static final String ROUTER_TYPE_CLEAR = "clean"; public static final String DEFAULT_SCRIPT_TYPE_KEY = "javascript"; public static final String STUB_EVENT_KEY = "dubbo.stub.event"; public static final boolean DEFAULT_STUB_EVENT = false; public static final String STUB_EVENT_METHODS_KEY = "dubbo.stub.event.methods"; public static final String INVOCATION_NEED_MOCK = "invocation.need.mock"; public static final String LOCAL_PROTOCOL = "injvm"; public static final String AUTO_ATTACH_INVOCATIONID_KEY = "invocationid.autoattach"; public static final String SCOPE_KEY = "scope"; public static final String SCOPE_LOCAL = "local"; public static final String SCOPE_REMOTE = "remote"; public static final String SCOPE_NONE = "none"; public static final String RELIABLE_PROTOCOL = "napoli"; public static final String TPS_LIMIT_RATE_KEY = "tps"; public static final String TPS_LIMIT_INTERVAL_KEY = "tps.interval"; public static final long DEFAULT_TPS_LIMIT_INTERVAL = 60 * 1000; public static final String DECODE_IN_IO_THREAD_KEY = "decode.in.io"; public static final boolean DEFAULT_DECODE_IN_IO_THREAD = true; public static final String INPUT_KEY = "input"; public static final String OUTPUT_KEY = "output"; public static final String EXECUTOR_SERVICE_COMPONENT_KEY = ExecutorService.class.getName(); public static final String GENERIC_SERIALIZATION_NATIVE_JAVA = "nativejava"; public static final String GENERIC_SERIALIZATION_DEFAULT = "true"; public static final String INVOKER_CONNECTED_KEY = "connected"; public static final String INVOKER_INSIDE_INVOKERS_KEY = "inside.invokers"; public static final String INVOKER_INSIDE_INVOKER_COUNT_KEY = "inside.invoker.count"; public static final String CLUSTER_SWITCH_FACTOR = "cluster.switch.factor"; public static final String CLUSTER_SWITCH_LOG_ERROR = "cluster.switch.log.error"; public static final double DEFAULT_CLUSTER_SWITCH_FACTOR = 2; public static final String DISPATHER_KEY = "dispather"; }
5,322
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/extension/ExtensionFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common.extension; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; @Deprecated @SPI(scope = ExtensionScope.FRAMEWORK) public interface ExtensionFactory extends org.apache.dubbo.common.extension.ExtensionFactory {}
5,323
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/extension/Activate.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common.extension; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * See @org.apache.dubbo.common.extension.Activate */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) @Deprecated public @interface Activate { String[] group() default {}; String[] value() default {}; @Deprecated String[] before() default {}; @Deprecated String[] after() default {}; int order() default 0; /** * Activate loadClass when the current extension when the specified className all match * @return className names to all match */ String[] onClass() default {}; }
5,324
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/logger/LoggerAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common.logger; @Deprecated public interface LoggerAdapter extends org.apache.dubbo.common.logger.LoggerAdapter {}
5,325
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/serialize/ObjectInput.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common.serialize; @Deprecated public interface ObjectInput extends org.apache.dubbo.common.serialize.ObjectInput {}
5,326
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/serialize/Serialization.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common.serialize; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import com.alibaba.dubbo.common.DelegateURL; import com.alibaba.dubbo.common.URL; @Deprecated public interface Serialization extends org.apache.dubbo.common.serialize.Serialization { ObjectOutput serialize(URL url, OutputStream output) throws IOException; ObjectInput deserialize(URL url, InputStream input) throws IOException; @Override default org.apache.dubbo.common.serialize.ObjectOutput serialize( org.apache.dubbo.common.URL url, OutputStream output) throws IOException { return this.serialize(new DelegateURL(url), output); } @Override default org.apache.dubbo.common.serialize.ObjectInput deserialize( org.apache.dubbo.common.URL url, InputStream input) throws IOException { return this.deserialize(new DelegateURL(url), input); } }
5,327
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/serialize/ObjectOutput.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common.serialize; @Deprecated public interface ObjectOutput extends org.apache.dubbo.common.serialize.ObjectOutput {}
5,328
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common.utils; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import com.alibaba.dubbo.common.DelegateURL; import com.alibaba.dubbo.common.URL; /** * 2019-04-17 */ @Deprecated public class UrlUtils { public static URL parseURL(String address, Map<String, String> defaults) { return new DelegateURL(org.apache.dubbo.common.utils.UrlUtils.parseURL(address, defaults)); } public static List<URL> parseURLs(String address, Map<String, String> defaults) { return org.apache.dubbo.common.utils.UrlUtils.parseURLs(address, defaults).stream() .map(e -> new DelegateURL(e)) .collect(Collectors.toList()); } public static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register) { return org.apache.dubbo.common.utils.UrlUtils.convertRegister(register); } public static Map<String, String> convertSubscribe(Map<String, String> subscribe) { return org.apache.dubbo.common.utils.UrlUtils.convertSubscribe(subscribe); } public static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register) { return org.apache.dubbo.common.utils.UrlUtils.revertRegister(register); } public static Map<String, String> revertSubscribe(Map<String, String> subscribe) { return org.apache.dubbo.common.utils.UrlUtils.revertSubscribe(subscribe); } public static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify) { return org.apache.dubbo.common.utils.UrlUtils.revertNotify(notify); } // compatible for dubbo-2.0.0 public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { Set<org.apache.dubbo.common.URL> urls = subscribed.stream().map(e -> e.getOriginalURL()).collect(Collectors.toSet()); return org.apache.dubbo.common.utils.UrlUtils.revertForbid(forbid, urls); } public static URL getEmptyUrl(String service, String category) { return new DelegateURL(org.apache.dubbo.common.utils.UrlUtils.getEmptyUrl(service, category)); } public static boolean isMatchCategory(String category, String categories) { return org.apache.dubbo.common.utils.UrlUtils.isMatchCategory(category, categories); } public static boolean isMatch(URL consumerUrl, URL providerUrl) { return org.apache.dubbo.common.utils.UrlUtils.isMatch( consumerUrl.getOriginalURL(), providerUrl.getOriginalURL()); } public static boolean isMatchGlobPattern(String pattern, String value, URL param) { return org.apache.dubbo.common.utils.UrlUtils.isMatchGlobPattern(pattern, value, param.getOriginalURL()); } public static boolean isMatchGlobPattern(String pattern, String value) { return org.apache.dubbo.common.utils.UrlUtils.isMatchGlobPattern(pattern, value); } public static boolean isServiceKeyMatch(URL pattern, URL value) { return org.apache.dubbo.common.utils.UrlUtils.isServiceKeyMatch( pattern.getOriginalURL(), value.getOriginalURL()); } public static boolean isConfigurator(URL url) { return org.apache.dubbo.common.utils.UrlUtils.isConfigurator(url.getOriginalURL()); } public static boolean isRoute(URL url) { return org.apache.dubbo.common.utils.UrlUtils.isRoute(url.getOriginalURL()); } public static boolean isProvider(URL url) { return org.apache.dubbo.common.utils.UrlUtils.isProvider(url.getOriginalURL()); } public static int getHeartbeat(URL url) { return org.apache.dubbo.remoting.utils.UrlUtils.getHeartbeat(url.getOriginalURL()); } public static int getIdleTimeout(URL url) { return org.apache.dubbo.remoting.utils.UrlUtils.getIdleTimeout(url.getOriginalURL()); } }
5,329
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/status/Status.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common.status; @Deprecated public class Status extends org.apache.dubbo.common.status.Status { public Status(Level level) { super(level); } public Status(Level level, String message) { super(level, message); } public Status(Level level, String message, String description) { super(level, message, description); } }
5,330
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/status/StatusChecker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common.status; @Deprecated public interface StatusChecker extends org.apache.dubbo.common.status.StatusChecker { @Override Status check(); }
5,331
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/threadpool/ThreadPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common.threadpool; import org.apache.dubbo.common.URL; import java.util.concurrent.Executor; @Deprecated public interface ThreadPool extends org.apache.dubbo.common.threadpool.ThreadPool { Executor getExecutor(com.alibaba.dubbo.common.URL url); @Override default Executor getExecutor(URL url) { return getExecutor(new com.alibaba.dubbo.common.DelegateURL(url)); } }
5,332
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/compiler/Compiler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common.compiler; @Deprecated public interface Compiler extends org.apache.dubbo.common.compiler.Compiler {}
5,333
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/store/DataStore.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common.store; @Deprecated public interface DataStore extends org.apache.dubbo.common.store.DataStore {}
5,334
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/RegistryFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.registry; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.Registry; @Deprecated public interface RegistryFactory extends org.apache.dubbo.registry.RegistryFactory { com.alibaba.dubbo.registry.Registry getRegistry(com.alibaba.dubbo.common.URL url); @Override default Registry getRegistry(URL url) { return this.getRegistry(new com.alibaba.dubbo.common.DelegateURL(url)); } }
5,335
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/NotifyListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.registry; import java.util.List; import java.util.stream.Collectors; import com.alibaba.dubbo.common.DelegateURL; import com.alibaba.dubbo.common.URL; @Deprecated public interface NotifyListener { void notify(List<URL> urls); class CompatibleNotifyListener implements NotifyListener { private org.apache.dubbo.registry.NotifyListener listener; public CompatibleNotifyListener(org.apache.dubbo.registry.NotifyListener listener) { this.listener = listener; } @Override public void notify(List<URL> urls) { if (listener != null) { listener.notify(urls.stream().map(url -> url.getOriginalURL()).collect(Collectors.toList())); } } } class ReverseCompatibleNotifyListener implements org.apache.dubbo.registry.NotifyListener { private NotifyListener listener; public ReverseCompatibleNotifyListener(NotifyListener listener) { this.listener = listener; } @Override public void notify(List<org.apache.dubbo.common.URL> urls) { if (listener != null) { listener.notify(urls.stream().map(url -> new DelegateURL(url)).collect(Collectors.toList())); } } } }
5,336
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/Registry.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.registry; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.NotifyListener; import java.util.List; import java.util.stream.Collectors; @Deprecated public interface Registry extends org.apache.dubbo.registry.Registry { @Override com.alibaba.dubbo.common.URL getUrl(); void register(com.alibaba.dubbo.common.URL url); void unregister(com.alibaba.dubbo.common.URL url); void subscribe(com.alibaba.dubbo.common.URL url, com.alibaba.dubbo.registry.NotifyListener listener); void unsubscribe(com.alibaba.dubbo.common.URL url, com.alibaba.dubbo.registry.NotifyListener listener); List<com.alibaba.dubbo.common.URL> lookup(com.alibaba.dubbo.common.URL url); @Override default void register(URL url) { this.register(new com.alibaba.dubbo.common.DelegateURL(url)); } @Override default void unregister(URL url) { this.unregister(new com.alibaba.dubbo.common.DelegateURL(url)); } @Override default void subscribe(URL url, NotifyListener listener) { this.subscribe( new com.alibaba.dubbo.common.DelegateURL(url), new com.alibaba.dubbo.registry.NotifyListener.CompatibleNotifyListener(listener)); } @Override default void unsubscribe(URL url, NotifyListener listener) { this.unsubscribe( new com.alibaba.dubbo.common.DelegateURL(url), new com.alibaba.dubbo.registry.NotifyListener.CompatibleNotifyListener(listener)); } @Override default List<URL> lookup(URL url) { return this.lookup(new com.alibaba.dubbo.common.DelegateURL(url)).stream() .map(u -> u.getOriginalURL()) .collect(Collectors.toList()); } }
5,337
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistryFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.registry.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.Registry; import com.alibaba.dubbo.registry.RegistryFactory; /** * 2019-04-16 */ @Deprecated public abstract class AbstractRegistryFactory extends org.apache.dubbo.registry.support.AbstractRegistryFactory implements RegistryFactory { @Override public com.alibaba.dubbo.registry.Registry getRegistry(com.alibaba.dubbo.common.URL url) { return (com.alibaba.dubbo.registry.Registry) super.getRegistry(url.getOriginalURL()); } protected abstract com.alibaba.dubbo.registry.Registry createRegistry(com.alibaba.dubbo.common.URL url); @Override protected Registry createRegistry(URL url) { return createRegistry(new com.alibaba.dubbo.common.DelegateURL(url)); } }
5,338
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.registry.support; import java.util.List; import java.util.stream.Collectors; import com.alibaba.dubbo.common.DelegateURL; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.registry.NotifyListener; import com.alibaba.dubbo.registry.Registry; /** * 2019-04-17 */ @Deprecated public abstract class FailbackRegistry implements org.apache.dubbo.registry.Registry, Registry { private CompatibleFailbackRegistry failbackRegistry; public FailbackRegistry(URL url) { failbackRegistry = new CompatibleFailbackRegistry(url.getOriginalURL(), this); } public void removeFailedRegisteredTask(URL url) { failbackRegistry.removeFailedRegisteredTask(url.getOriginalURL()); } public void removeFailedUnregisteredTask(URL url) { failbackRegistry.removeFailedUnregisteredTask(url.getOriginalURL()); } public void removeFailedSubscribedTask(URL url, NotifyListener listener) { failbackRegistry.removeFailedSubscribedTask( url.getOriginalURL(), new NotifyListener.ReverseCompatibleNotifyListener(listener)); } public void removeFailedUnsubscribedTask(URL url, NotifyListener listener) { failbackRegistry.removeFailedUnsubscribedTask( url.getOriginalURL(), new NotifyListener.ReverseCompatibleNotifyListener(listener)); } @Override public void register(URL url) { failbackRegistry.register(url.getOriginalURL()); } @Override public void unregister(URL url) { failbackRegistry.unregister(url.getOriginalURL()); } @Override public void subscribe(URL url, NotifyListener listener) { failbackRegistry.subscribe( url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); } @Override public void unsubscribe(URL url, NotifyListener listener) { failbackRegistry.unsubscribe( url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); } protected void notify(URL url, NotifyListener listener, List<URL> urls) { List<org.apache.dubbo.common.URL> urlResult = urls.stream().map(URL::getOriginalURL).collect(Collectors.toList()); failbackRegistry.notify( url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener), urlResult); } protected void doNotify(URL url, NotifyListener listener, List<URL> urls) { List<org.apache.dubbo.common.URL> urlResult = urls.stream().map(URL::getOriginalURL).collect(Collectors.toList()); failbackRegistry.doNotify( url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener), urlResult); } protected void recover() throws Exception { failbackRegistry.recover(); } @Override public List<URL> lookup(URL url) { return failbackRegistry.lookup(url.getOriginalURL()).stream() .map(e -> new DelegateURL(e)) .collect(Collectors.toList()); } @Override public URL getUrl() { return new DelegateURL(failbackRegistry.getUrl()); } @Override public void destroy() { failbackRegistry.destroy(); } // ==== Template method ==== public abstract void doRegister(URL url); public abstract void doUnregister(URL url); public abstract void doSubscribe(URL url, NotifyListener listener); public abstract void doUnsubscribe(URL url, NotifyListener listener); @Override public void register(org.apache.dubbo.common.URL url) { this.register(new DelegateURL(url)); } @Override public void unregister(org.apache.dubbo.common.URL url) { this.unregister(new DelegateURL(url)); } @Override public void subscribe(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener) { this.subscribe(new DelegateURL(url), new NotifyListener.CompatibleNotifyListener(listener)); } @Override public void unsubscribe(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener) { this.unsubscribe(new DelegateURL(url), new NotifyListener.CompatibleNotifyListener(listener)); } @Override public List<org.apache.dubbo.common.URL> lookup(org.apache.dubbo.common.URL url) { return failbackRegistry.lookup(url); } static class CompatibleFailbackRegistry extends org.apache.dubbo.registry.support.FailbackRegistry { private FailbackRegistry compatibleFailbackRegistry; public CompatibleFailbackRegistry( org.apache.dubbo.common.URL url, FailbackRegistry compatibleFailbackRegistry) { super(url); this.compatibleFailbackRegistry = compatibleFailbackRegistry; } @Override public void doRegister(org.apache.dubbo.common.URL url) { this.compatibleFailbackRegistry.doRegister(new DelegateURL(url)); } @Override public void doUnregister(org.apache.dubbo.common.URL url) { this.compatibleFailbackRegistry.doUnregister(new DelegateURL(url)); } @Override public void doSubscribe(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener) { this.compatibleFailbackRegistry.doSubscribe( new DelegateURL(url), new NotifyListener.CompatibleNotifyListener(listener)); } @Override public void doUnsubscribe(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener) { this.compatibleFailbackRegistry.doUnsubscribe( new DelegateURL(url), new NotifyListener.CompatibleNotifyListener(listener)); } @Override public void notify( org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener, List<org.apache.dubbo.common.URL> urls) { super.notify(url, listener, urls); } @Override public void doNotify( org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener, List<org.apache.dubbo.common.URL> urls) { super.doNotify(url, listener, urls); } @Override public boolean isAvailable() { return false; } @Override public void recover() throws Exception { super.recover(); } } }
5,339
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.registry.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.Registry; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * 2019-04-16 */ @Deprecated public abstract class AbstractRegistry implements Registry { private CompatibleAbstractRegistry abstractRegistry; public AbstractRegistry(com.alibaba.dubbo.common.URL url) { abstractRegistry = new CompatibleAbstractRegistry(url.getOriginalURL()); } @Override public com.alibaba.dubbo.common.URL getUrl() { return new com.alibaba.dubbo.common.DelegateURL(abstractRegistry.getUrl()); } protected void setUrl(com.alibaba.dubbo.common.URL url) { abstractRegistry.setUrl(url.getOriginalURL()); } public Set<com.alibaba.dubbo.common.URL> getRegistered() { return abstractRegistry.getRegistered().stream() .map(url -> new com.alibaba.dubbo.common.DelegateURL(url)) .collect(Collectors.toSet()); } public Map<com.alibaba.dubbo.common.URL, Set<com.alibaba.dubbo.registry.NotifyListener>> getSubscribed() { return abstractRegistry.getSubscribed().entrySet().stream() .collect(Collectors.toMap( entry -> new com.alibaba.dubbo.common.DelegateURL(entry.getKey()), entry -> convertToNotifyListeners(entry.getValue()))); } public Map<com.alibaba.dubbo.common.URL, Map<String, List<com.alibaba.dubbo.common.URL>>> getNotified() { return abstractRegistry.getNotified().entrySet().stream() .collect(Collectors.toMap(entry -> new com.alibaba.dubbo.common.DelegateURL(entry.getKey()), entry -> { return entry.getValue().entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> { return e.getValue().stream() .map(url -> new com.alibaba.dubbo.common.DelegateURL(url)) .collect(Collectors.toList()); })); })); } public List<com.alibaba.dubbo.common.URL> getCacheUrls(com.alibaba.dubbo.common.URL url) { return abstractRegistry.lookup(url.getOriginalURL()).stream() .map(tmpUrl -> new com.alibaba.dubbo.common.DelegateURL(tmpUrl)) .collect(Collectors.toList()); } public List<com.alibaba.dubbo.common.URL> lookup(com.alibaba.dubbo.common.URL url) { return abstractRegistry.lookup(url.getOriginalURL()).stream() .map(tmpUrl -> new com.alibaba.dubbo.common.DelegateURL(tmpUrl)) .collect(Collectors.toList()); } protected void notify( com.alibaba.dubbo.common.URL url, com.alibaba.dubbo.registry.NotifyListener listener, List<com.alibaba.dubbo.common.URL> urls) { abstractRegistry.notify( url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener), urls.stream().map(tmpUrl -> tmpUrl.getOriginalURL()).collect(Collectors.toList())); } public void register(com.alibaba.dubbo.common.URL url) { abstractRegistry.register(url.getOriginalURL()); } public void unregister(com.alibaba.dubbo.common.URL url) { abstractRegistry.unregister(url.getOriginalURL()); } public void subscribe(com.alibaba.dubbo.common.URL url, com.alibaba.dubbo.registry.NotifyListener listener) { abstractRegistry.subscribe( url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); } public void unsubscribe(com.alibaba.dubbo.common.URL url, com.alibaba.dubbo.registry.NotifyListener listener) { abstractRegistry.unsubscribe( url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); } @Override public void register(URL url) { this.register(new com.alibaba.dubbo.common.DelegateURL(url)); } @Override public void unregister(URL url) { this.unregister(new com.alibaba.dubbo.common.DelegateURL(url)); } @Override public void subscribe(URL url, NotifyListener listener) { this.subscribe( new com.alibaba.dubbo.common.DelegateURL(url), new com.alibaba.dubbo.registry.NotifyListener.CompatibleNotifyListener(listener)); } @Override public void unsubscribe(URL url, NotifyListener listener) { this.unsubscribe( new com.alibaba.dubbo.common.DelegateURL(url), new com.alibaba.dubbo.registry.NotifyListener.CompatibleNotifyListener(listener)); } final Set<com.alibaba.dubbo.registry.NotifyListener> convertToNotifyListeners(Set<NotifyListener> notifyListeners) { return notifyListeners.stream() .map(listener -> new com.alibaba.dubbo.registry.NotifyListener.CompatibleNotifyListener(listener)) .collect(Collectors.toSet()); } static class CompatibleAbstractRegistry extends org.apache.dubbo.registry.support.AbstractRegistry { public CompatibleAbstractRegistry(URL url) { super(url); } @Override public boolean isAvailable() { return false; } @Override public void notify(URL url, NotifyListener listener, List<URL> urls) { super.notify(url, listener, urls); } @Override public void setUrl(URL url) { super.setUrl(url); } } }
5,340
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/ProxyFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; @Deprecated public interface ProxyFactory extends org.apache.dubbo.rpc.ProxyFactory { <T> T getProxy(com.alibaba.dubbo.rpc.Invoker<T> invoker) throws com.alibaba.dubbo.rpc.RpcException; <T> T getProxy(com.alibaba.dubbo.rpc.Invoker<T> invoker, boolean generic) throws com.alibaba.dubbo.rpc.RpcException; <T> com.alibaba.dubbo.rpc.Invoker<T> getInvoker(T proxy, Class<T> type, com.alibaba.dubbo.common.URL url) throws com.alibaba.dubbo.rpc.RpcException; @Override default <T> T getProxy(Invoker<T> invoker) throws RpcException { return getProxy(new com.alibaba.dubbo.rpc.Invoker.CompatibleInvoker<>(invoker)); } @Override default <T> T getProxy(Invoker<T> invoker, boolean generic) throws RpcException { return getProxy(new com.alibaba.dubbo.rpc.Invoker.CompatibleInvoker<>(invoker), generic); } @Override default <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) throws RpcException { return getInvoker(proxy, type, new com.alibaba.dubbo.common.DelegateURL(url)); } }
5,341
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.FutureContext; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.DelegateURL; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.rpc.protocol.dubbo.FutureAdapter; @Deprecated public class RpcContext { public static RpcContext getContext() { return new RpcContext(org.apache.dubbo.rpc.RpcContext.getContext()); } public static RpcContext getServerContext() { return new RpcContext(org.apache.dubbo.rpc.RpcContext.getServerContext()); } public static RpcContext getClientResponseContext() { return new RpcContext(org.apache.dubbo.rpc.RpcContext.getClientResponseContext()); } public static RpcContext getServerResponseContext() { return new RpcContext(org.apache.dubbo.rpc.RpcContext.getServerResponseContext()); } public static void removeClientResponseContext() { org.apache.dubbo.rpc.RpcContext.removeClientResponseContext(); } public static void removeServerResponseContext() { org.apache.dubbo.rpc.RpcContext.removeServerResponseContext(); } public static void removeServerContext() { org.apache.dubbo.rpc.RpcContext.removeServerContext(); } public static void removeContext() { org.apache.dubbo.rpc.RpcContext.removeContext(); } private org.apache.dubbo.rpc.RpcContext newRpcContext; public RpcContext(org.apache.dubbo.rpc.RpcContext newRpcContext) { this.newRpcContext = newRpcContext; } public Object getRequest() { return newRpcContext.getRequest(); } public <T> T getRequest(Class<T> clazz) { return newRpcContext.getRequest(clazz); } public void setRequest(Object request) { newRpcContext.setRequest(request); } /** * Get the response object of the underlying RPC protocol, e.g. HttpServletResponse * * @return null if the underlying protocol doesn't provide support for getting response */ public Object getResponse() { return newRpcContext.getResponse(); } /** * Get the response object of the underlying RPC protocol, e.g. HttpServletResponse * * @return null if the underlying protocol doesn't provide support for getting response or the response is not of the specified type */ @SuppressWarnings("unchecked") public <T> T getResponse(Class<T> clazz) { return newRpcContext.getResponse(clazz); } public void setResponse(Object response) { newRpcContext.setResponse(response); } /** * is provider side. * * @return provider side. */ public boolean isProviderSide() { return newRpcContext.isProviderSide(); } /** * is consumer side. * * @return consumer side. */ public boolean isConsumerSide() { return newRpcContext.isConsumerSide(); } public List<URL> getUrls() { List<org.apache.dubbo.common.URL> newUrls = newRpcContext.getUrls(); if (CollectionUtils.isNotEmpty(newUrls)) { List<URL> urls = new ArrayList<>(newUrls.size()); for (org.apache.dubbo.common.URL newUrl : newUrls) { urls.add(new DelegateURL(newUrl)); } return urls; } return Collections.emptyList(); } public void setUrls(List<URL> urls) { if (CollectionUtils.isNotEmpty(urls)) { List<org.apache.dubbo.common.URL> newUrls = new ArrayList<>(urls.size()); for (URL url : urls) { newUrls.add(url.getOriginalURL()); } newRpcContext.setUrls(newUrls); } } public URL getUrl() { return new DelegateURL(newRpcContext.getUrl()); } public void setUrl(URL url) { newRpcContext.setUrl(url.getOriginalURL()); } public String getMethodName() { return newRpcContext.getMethodName(); } public void setMethodName(String methodName) { newRpcContext.setMethodName(methodName); } public Class<?>[] getParameterTypes() { return newRpcContext.getParameterTypes(); } public void setParameterTypes(Class<?>[] parameterTypes) { newRpcContext.setParameterTypes(parameterTypes); } public Object[] getArguments() { return newRpcContext.getArguments(); } public void setArguments(Object[] arguments) { newRpcContext.setArguments(arguments); } public RpcContext setLocalAddress(String host, int port) { newRpcContext.setLocalAddress(host, port); return this; } /** * get local address. * * @return local address */ public InetSocketAddress getLocalAddress() { return newRpcContext.getLocalAddress(); } public RpcContext setLocalAddress(InetSocketAddress address) { newRpcContext.setLocalAddress(address); return this; } public String getLocalAddressString() { return newRpcContext.getLocalAddressString(); } public String getLocalHostName() { return newRpcContext.getLocalHostName(); } public RpcContext setRemoteAddress(String host, int port) { newRpcContext.setRemoteAddress(host, port); return this; } public InetSocketAddress getRemoteAddress() { return newRpcContext.getRemoteAddress(); } public RpcContext setRemoteAddress(InetSocketAddress address) { newRpcContext.setRemoteAddress(address); return this; } public String getRemoteAddressString() { return newRpcContext.getRemoteAddressString(); } public String getRemoteHostName() { return newRpcContext.getRemoteHostName(); } public String getLocalHost() { return newRpcContext.getLocalHost(); } public int getLocalPort() { return newRpcContext.getLocalPort(); } public String getRemoteHost() { return newRpcContext.getRemoteHost(); } public int getRemotePort() { return newRpcContext.getRemotePort(); } public String getAttachment(String key) { return newRpcContext.getAttachment(key); } public RpcContext setAttachment(String key, String value) { newRpcContext.setAttachment(key, value); return this; } public RpcContext removeAttachment(String key) { newRpcContext.removeAttachment(key); return this; } public Map<String, String> getAttachments() { return newRpcContext.getAttachments(); } public RpcContext setAttachments(Map<String, String> attachment) { newRpcContext.setAttachments(attachment); return this; } public void clearAttachments() { newRpcContext.clearAttachments(); } /** * get values. * * @return values */ public Map<String, Object> get() { return newRpcContext.get(); } /** * set value. * * @param key * @param value * @return context */ public RpcContext set(String key, Object value) { newRpcContext.set(key, value); return this; } public RpcContext remove(String key) { newRpcContext.remove(key); return this; } public Object get(String key) { return newRpcContext.get(key); } public Invocation getInvocation() { return new Invocation.CompatibleInvocation(newRpcContext.getInvocation()); } @Deprecated public boolean isServerSide() { return isProviderSide(); } @Deprecated public boolean isClientSide() { return isConsumerSide(); } @Deprecated public Invoker<?> getInvoker() { org.apache.dubbo.rpc.Invoker<?> invoker = newRpcContext.getInvoker(); if (invoker == null) { return null; } return new Invoker.CompatibleInvoker<>(invoker); } @Deprecated public List<Invoker<?>> getInvokers() { List<org.apache.dubbo.rpc.Invoker<?>> invokers = newRpcContext.getInvokers(); if (CollectionUtils.isEmpty(invokers)) { return Collections.emptyList(); } return invokers.stream().map(Invoker.CompatibleInvoker::new).collect(Collectors.toList()); } /** * Async invocation. Timeout will be handled even if <code>Future.get()</code> is not called. * * @param callable * @return get the return result from <code>future.get()</code> */ @SuppressWarnings("unchecked") public <T> Future<T> asyncCall(Callable<T> callable) { try { try { setAttachment(Constants.ASYNC_KEY, Boolean.TRUE.toString()); final T o = callable.call(); // local invoke will return directly if (o != null) { FutureTask<T> f = new FutureTask<T>(new Callable<T>() { @Override public T call() throws Exception { return o; } }); f.run(); return f; } else { } } catch (Exception e) { throw new RpcException(e); } finally { removeAttachment(Constants.ASYNC_KEY); } } catch (final RpcException e) { return new Future<T>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } @Override public T get() throws InterruptedException, ExecutionException { throw new ExecutionException(e.getCause()); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return get(); } }; } return ((Future<T>) getContext().getFuture()); } /** * one way async call, send request only, and result is not required * * @param runnable */ public void asyncCall(Runnable runnable) { try { setAttachment(Constants.RETURN_KEY, Boolean.FALSE.toString()); runnable.run(); } catch (Throwable e) { // FIXME should put exception in future? throw new RpcException("oneway call error ." + e.getMessage(), e); } finally { removeAttachment(Constants.RETURN_KEY); } } public <T> Future<T> getFuture() { CompletableFuture completableFuture = FutureContext.getContext().getCompatibleCompletableFuture(); if (completableFuture == null) { return null; } return new FutureAdapter(completableFuture); } public void setFuture(CompletableFuture<?> future) { FutureContext.getContext().setCompatibleFuture(future); } }
5,342
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc; import org.apache.dubbo.rpc.model.ServiceModel; import java.beans.Transient; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; @Deprecated public interface Invocation extends org.apache.dubbo.rpc.Invocation { @Override Invoker<?> getInvoker(); default org.apache.dubbo.rpc.Invocation getOriginal() { return null; } @Override default void setAttachment(String key, String value) { setObjectAttachment(key, value); } @Override default void setAttachmentIfAbsent(String key, String value) { setObjectAttachmentIfAbsent(key, value); } @Override default void setObjectAttachmentIfAbsent(String key, Object value) {} @Override default void setObjectAttachment(String key, Object value) {} @Override default void setAttachment(String key, Object value) { setObjectAttachment(key, value); } @Override default void setAttachmentIfAbsent(String key, Object value) { setObjectAttachmentIfAbsent(key, value); } @Override default String getServiceName() { return null; } @Override default String getTargetServiceUniqueName() { return null; } @Override default String getAttachment(String key, String defaultValue) { return null; } @Override default void setServiceModel(ServiceModel serviceModel) {} @Override default ServiceModel getServiceModel() { return null; } @Override default Object put(Object key, Object value) { return null; } @Override default Object get(Object key) { return null; } @Override default Map<Object, Object> getAttributes() { return null; } @Override default Map<String, Object> getObjectAttachments() { return Collections.emptyMap(); } @Override default Map<String, Object> copyObjectAttachments() { return new HashMap<>(getObjectAttachments()); } @Override default void foreachAttachment(Consumer<Map.Entry<String, Object>> consumer) { getObjectAttachments().entrySet().forEach(consumer); } @Override default Object getObjectAttachment(String key) { return null; } @Override default Object getObjectAttachment(String key, Object defaultValue) { return null; } class CompatibleInvocation implements Invocation { private org.apache.dubbo.rpc.Invocation delegate; public CompatibleInvocation(org.apache.dubbo.rpc.Invocation invocation) { this.delegate = invocation; } @Override public String getTargetServiceUniqueName() { return delegate.getTargetServiceUniqueName(); } @Override public String getProtocolServiceKey() { return delegate.getProtocolServiceKey(); } @Override public String getMethodName() { return delegate.getMethodName(); } @Override public String getServiceName() { return null; } @Override public Class<?>[] getParameterTypes() { return delegate.getParameterTypes(); } @Override public Object[] getArguments() { return delegate.getArguments(); } @Override public Map<String, String> getAttachments() { return delegate.getAttachments(); } @Override public String getAttachment(String key) { return delegate.getAttachment(key); } @Override public String getAttachment(String key, String defaultValue) { return delegate.getAttachment(key, defaultValue); } @Override @Transient public Invoker<?> getInvoker() { return new Invoker.CompatibleInvoker(delegate.getInvoker()); } @Override public void setServiceModel(ServiceModel serviceModel) { delegate.setServiceModel(serviceModel); } @Override public ServiceModel getServiceModel() { return delegate.getServiceModel(); } @Override public Object put(Object key, Object value) { return delegate.put(key, value); } @Override public Object get(Object key) { return delegate.get(key); } @Override public Map<Object, Object> getAttributes() { return delegate.getAttributes(); } @Override public org.apache.dubbo.rpc.Invocation getOriginal() { return delegate; } @Override public void addInvokedInvoker(org.apache.dubbo.rpc.Invoker<?> invoker) { delegate.addInvokedInvoker(invoker); } @Override public List<org.apache.dubbo.rpc.Invoker<?>> getInvokedInvokers() { return delegate.getInvokedInvokers(); } } }
5,343
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc; @Deprecated public class RpcException extends org.apache.dubbo.rpc.RpcException { public RpcException() { super(); } public RpcException(String message, Throwable cause) { super(message, cause); } public RpcException(String message) { super(message); } public RpcException(Throwable cause) { super(cause); } public RpcException(int code) { super(code); } public RpcException(int code, String message, Throwable cause) { super(code, message, cause); } public RpcException(int code, String message) { super(code, message); } public RpcException(int code, Throwable cause) { super(code, cause); } public boolean isForbidded() { return isForbidden(); } }
5,344
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/InvokerListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; @Deprecated public interface InvokerListener extends org.apache.dubbo.rpc.InvokerListener { void referred(com.alibaba.dubbo.rpc.Invoker<?> invoker) throws com.alibaba.dubbo.rpc.RpcException; void destroyed(com.alibaba.dubbo.rpc.Invoker<?> invoker); @Override default void referred(Invoker<?> invoker) throws RpcException { this.referred(new com.alibaba.dubbo.rpc.Invoker.CompatibleInvoker<>(invoker)); } @Override default void destroyed(Invoker<?> invoker) { this.destroyed(new com.alibaba.dubbo.rpc.Invoker.CompatibleInvoker<>(invoker)); } }
5,345
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Protocol.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc; import org.apache.dubbo.rpc.ProtocolServer; import java.util.Collections; import java.util.List; import com.alibaba.dubbo.common.DelegateURL; import com.alibaba.dubbo.common.URL; @Deprecated public interface Protocol extends org.apache.dubbo.rpc.Protocol { <T> Exporter<T> export(Invoker<T> invoker) throws RpcException; <T> Invoker<T> refer(Class<T> aClass, URL url) throws RpcException; @Override default <T> org.apache.dubbo.rpc.Exporter<T> export(org.apache.dubbo.rpc.Invoker<T> invoker) throws RpcException { return this.export(new Invoker.CompatibleInvoker<>(invoker)); } @Override default <T> org.apache.dubbo.rpc.Invoker<T> refer(Class<T> aClass, org.apache.dubbo.common.URL url) throws RpcException { return this.refer(aClass, new DelegateURL(url)); } @Override default List<ProtocolServer> getServers() { return Collections.emptyList(); } }
5,346
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Result.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc; import java.util.Collections; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.BiConsumer; import java.util.function.Function; @Deprecated public interface Result extends org.apache.dubbo.rpc.Result { @Override default void setValue(Object value) {} @Override default void setException(Throwable t) {} @Override default Map<String, Object> getObjectAttachments() { return Collections.emptyMap(); } @Override default void addObjectAttachments(Map<String, Object> map) {} @Override default void setObjectAttachments(Map<String, Object> map) {} @Override default Object getObjectAttachment(String key) { return null; } @Override default Object getObjectAttachment(String key, Object defaultValue) { return null; } /** * @see com.alibaba.dubbo.rpc.Result#getValue() * @deprecated Replace to getValue() */ @Deprecated default Object getResult() { return getValue(); } class CompatibleResult implements Result { private org.apache.dubbo.rpc.Result delegate; public CompatibleResult(org.apache.dubbo.rpc.Result result) { this.delegate = result; } public org.apache.dubbo.rpc.Result getDelegate() { return delegate; } @Override public org.apache.dubbo.rpc.Result whenCompleteWithContext( BiConsumer<org.apache.dubbo.rpc.Result, Throwable> fn) { return delegate.whenCompleteWithContext(fn); } @Override public Object getValue() { return delegate.getValue(); } @Override public void setValue(Object value) { delegate.setValue(value); } @Override public Throwable getException() { return delegate.getException(); } @Override public void setException(Throwable t) { delegate.setException(t); } @Override public boolean hasException() { return delegate.hasException(); } @Override public Object recreate() throws Throwable { return delegate.recreate(); } @Override public Map<String, String> getAttachments() { return delegate.getAttachments(); } @Override public void addAttachments(Map<String, String> map) { delegate.addAttachments(map); } @Override public void setAttachments(Map<String, String> map) { delegate.setAttachments(map); } @Override public String getAttachment(String key) { return delegate.getAttachment(key); } @Override public String getAttachment(String key, String defaultValue) { return delegate.getAttachment(key, defaultValue); } @Override public void setAttachment(String key, String value) { delegate.setAttachment(key, value); } @Override public void setAttachment(String key, Object value) { delegate.setAttachment(key, value); } @Override public void setObjectAttachment(String key, Object value) { delegate.setObjectAttachment(key, value); } @Override public <U> CompletableFuture<U> thenApply(Function<org.apache.dubbo.rpc.Result, ? extends U> fn) { return delegate.thenApply(fn); } @Override public org.apache.dubbo.rpc.Result get() throws InterruptedException, ExecutionException { return delegate.get(); } @Override public org.apache.dubbo.rpc.Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return delegate.get(timeout, unit); } } }
5,347
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc; import java.beans.Transient; import java.io.Serializable; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; @Deprecated public class RpcInvocation implements Invocation, Serializable { private static final long serialVersionUID = -4355285085441097045L; private String methodName; private Class<?>[] parameterTypes; private Object[] arguments; private Map<String, String> attachments; private transient Invoker<?> invoker; public RpcInvocation() {} public RpcInvocation(Invocation invocation, Invoker<?> invoker) { this( invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments(), new HashMap<String, String>(invocation.getAttachments()), invocation.getInvoker()); if (invoker != null) { URL url = invoker.getUrl(); setAttachment(Constants.PATH_KEY, url.getPath()); if (url.hasParameter(Constants.INTERFACE_KEY)) { setAttachment(Constants.INTERFACE_KEY, url.getParameter(Constants.INTERFACE_KEY)); } if (url.hasParameter(Constants.GROUP_KEY)) { setAttachment(Constants.GROUP_KEY, url.getParameter(Constants.GROUP_KEY)); } if (url.hasParameter(Constants.VERSION_KEY)) { setAttachment(Constants.VERSION_KEY, url.getParameter(Constants.VERSION_KEY, "0.0.0")); } if (url.hasParameter(Constants.TIMEOUT_KEY)) { setAttachment(Constants.TIMEOUT_KEY, url.getParameter(Constants.TIMEOUT_KEY)); } if (url.hasParameter(Constants.TOKEN_KEY)) { setAttachment(Constants.TOKEN_KEY, url.getParameter(Constants.TOKEN_KEY)); } if (url.hasParameter(Constants.APPLICATION_KEY)) { setAttachment(Constants.APPLICATION_KEY, url.getParameter(Constants.APPLICATION_KEY)); } } } public RpcInvocation(Invocation invocation) { this( invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments(), invocation.getAttachments(), invocation.getInvoker()); } public RpcInvocation(Method method, Object[] arguments) { this(method.getName(), method.getParameterTypes(), arguments, null, null); } public RpcInvocation(Method method, Object[] arguments, Map<String, String> attachment) { this(method.getName(), method.getParameterTypes(), arguments, attachment, null); } public RpcInvocation(String methodName, Class<?>[] parameterTypes, Object[] arguments) { this(methodName, parameterTypes, arguments, null, null); } public RpcInvocation( String methodName, Class<?>[] parameterTypes, Object[] arguments, Map<String, String> attachments) { this(methodName, parameterTypes, arguments, attachments, null); } public RpcInvocation( String methodName, Class<?>[] parameterTypes, Object[] arguments, Map<String, String> attachments, Invoker<?> invoker) { this.methodName = methodName; this.parameterTypes = parameterTypes == null ? new Class<?>[0] : parameterTypes; this.arguments = arguments == null ? new Object[0] : arguments; this.attachments = attachments == null ? new HashMap<String, String>() : attachments; this.invoker = invoker; } @Transient public Invoker<?> getInvoker() { return invoker; } public void setInvoker(Invoker<?> invoker) { this.invoker = invoker; } @Override public String getProtocolServiceKey() { return null; } public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } public Class<?>[] getParameterTypes() { return parameterTypes; } public void setParameterTypes(Class<?>[] parameterTypes) { this.parameterTypes = parameterTypes == null ? new Class<?>[0] : parameterTypes; } public Object[] getArguments() { return arguments; } public void setArguments(Object[] arguments) { this.arguments = arguments == null ? new Object[0] : arguments; } public Map<String, String> getAttachments() { return attachments; } public void setAttachments(Map<String, String> attachments) { this.attachments = attachments == null ? new HashMap<String, String>() : attachments; } public void setAttachment(String key, String value) { if (attachments == null) { attachments = new HashMap<String, String>(); } attachments.put(key, value); } public void setAttachmentIfAbsent(String key, String value) { if (attachments == null) { attachments = new HashMap<String, String>(); } if (!attachments.containsKey(key)) { attachments.put(key, value); } } public void addAttachments(Map<String, String> attachments) { if (attachments == null) { return; } if (this.attachments == null) { this.attachments = new HashMap<String, String>(); } this.attachments.putAll(attachments); } public void addAttachmentsIfAbsent(Map<String, String> attachments) { if (attachments == null) { return; } for (Map.Entry<String, String> entry : attachments.entrySet()) { setAttachmentIfAbsent(entry.getKey(), entry.getValue()); } } public String getAttachment(String key) { if (attachments == null) { return null; } return (String) attachments.get(key); } public String getAttachment(String key, String defaultValue) { if (attachments == null) { return defaultValue; } String value = (String) attachments.get(key); if (value == null || value.length() == 0) { return defaultValue; } return value; } @Override public void addInvokedInvoker(org.apache.dubbo.rpc.Invoker<?> invoker) { throw new UnsupportedOperationException(); } @Override public List<org.apache.dubbo.rpc.Invoker<?>> getInvokedInvokers() { throw new UnsupportedOperationException(); } @Override public String toString() { return "RpcInvocation [methodName=" + methodName + ", parameterTypes=" + Arrays.toString(parameterTypes) + ", arguments=" + Arrays.toString(arguments) + ", attachments=" + attachments + "]"; } }
5,348
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcResult.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc; import org.apache.dubbo.rpc.AppResponse; @Deprecated public class RpcResult extends AppResponse implements com.alibaba.dubbo.rpc.Result { public RpcResult() {} public RpcResult(Object result) { super(result); } public RpcResult(Throwable exception) { super(exception); } }
5,349
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc; import org.apache.dubbo.rpc.AsyncRpcResult; import com.alibaba.dubbo.common.DelegateURL; import com.alibaba.dubbo.common.URL; @Deprecated public interface Invoker<T> extends org.apache.dubbo.rpc.Invoker<T> { Result invoke(Invocation invocation) throws RpcException; @Override URL getUrl(); default org.apache.dubbo.rpc.Invoker<T> getOriginal() { return null; } // This method will never be called for a legacy invoker. @Override default org.apache.dubbo.rpc.Result invoke(org.apache.dubbo.rpc.Invocation invocation) throws org.apache.dubbo.rpc.RpcException { return null; } class CompatibleInvoker<T> implements Invoker<T> { private org.apache.dubbo.rpc.Invoker<T> invoker; public CompatibleInvoker(org.apache.dubbo.rpc.Invoker<T> invoker) { this.invoker = invoker; } @Override public Class<T> getInterface() { return invoker.getInterface(); } @Override public org.apache.dubbo.rpc.Result invoke(org.apache.dubbo.rpc.Invocation invocation) throws org.apache.dubbo.rpc.RpcException { return new Result.CompatibleResult(invoker.invoke(invocation)); } @Override public Result invoke(Invocation invocation) throws RpcException { if (invoker instanceof Invoker) { Result result = ((Invoker) invoker).invoke(invocation); if (result instanceof Result.CompatibleResult) { return result; } else { AsyncRpcResult asyncRpcResult = AsyncRpcResult.newDefaultAsyncResult(invocation.getOriginal()); asyncRpcResult.setValue(result.getValue()); asyncRpcResult.setException(result.getException()); asyncRpcResult.setObjectAttachments(result.getObjectAttachments()); return new Result.CompatibleResult(asyncRpcResult); } } return new Result.CompatibleResult(invoker.invoke(invocation.getOriginal())); } @Override public URL getUrl() { return new DelegateURL(invoker.getUrl()); } @Override public boolean isAvailable() { return invoker.isAvailable(); } @Override public void destroy() { invoker.destroy(); } @Override public org.apache.dubbo.rpc.Invoker<T> getOriginal() { return invoker; } @Override public int hashCode() { return invoker.hashCode(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof CompatibleInvoker)) { return false; } return invoker.equals(o); } } }
5,350
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Filter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.AttachmentsAdapter; import java.util.Map; @Deprecated public interface Filter extends org.apache.dubbo.rpc.Filter { Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException; @Override default org.apache.dubbo.rpc.Result invoke( org.apache.dubbo.rpc.Invoker<?> invoker, org.apache.dubbo.rpc.Invocation invocation) throws org.apache.dubbo.rpc.RpcException { Result invokeResult = invoke(new Invoker.CompatibleInvoker<>(invoker), new Invocation.CompatibleInvocation(invocation)); if (invokeResult instanceof Result.CompatibleResult) { return ((Result.CompatibleResult) invokeResult).getDelegate(); } AsyncRpcResult asyncRpcResult = AsyncRpcResult.newDefaultAsyncResult(invocation); asyncRpcResult.setValue(invokeResult.getValue()); asyncRpcResult.setException(invokeResult.getException()); Map<String, String> attachments = invokeResult.getAttachments(); if (!(attachments instanceof AttachmentsAdapter.ObjectToStringMap)) { asyncRpcResult.setAttachments(attachments); } asyncRpcResult.setObjectAttachments(invokeResult.getObjectAttachments()); return asyncRpcResult; } }
5,351
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Exporter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc; @Deprecated public interface Exporter<T> extends org.apache.dubbo.rpc.Exporter<T> { @Override Invoker<T> getInvoker(); default void register() {} default void unregister() {} class CompatibleExporter<T> implements Exporter<T> { private org.apache.dubbo.rpc.Exporter<T> delegate; public CompatibleExporter(org.apache.dubbo.rpc.Exporter<T> delegate) { this.delegate = delegate; } @Override public Invoker<T> getInvoker() { return new Invoker.CompatibleInvoker<>(delegate.getInvoker()); } @Override public void unexport() { delegate.unexport(); } @Override public void register() { delegate.register(); } @Override public void unregister() { delegate.unregister(); } } }
5,352
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Merger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.cluster; @Deprecated public interface Merger extends org.apache.dubbo.rpc.cluster.Merger {}
5,353
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Router.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.cluster; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; @Deprecated public interface Router extends org.apache.dubbo.rpc.cluster.Router { @Override com.alibaba.dubbo.common.URL getUrl(); <T> List<com.alibaba.dubbo.rpc.Invoker<T>> route( List<com.alibaba.dubbo.rpc.Invoker<T>> invokers, com.alibaba.dubbo.common.URL url, com.alibaba.dubbo.rpc.Invocation invocation) throws com.alibaba.dubbo.rpc.RpcException; int compareTo(Router o); // Add since 2.7.0 @Override default <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException { List<com.alibaba.dubbo.rpc.Invoker<T>> invs = invokers.stream() .map(invoker -> new com.alibaba.dubbo.rpc.Invoker.CompatibleInvoker<T>(invoker)) .collect(Collectors.toList()); List<com.alibaba.dubbo.rpc.Invoker<T>> res = this.route( invs, new com.alibaba.dubbo.common.DelegateURL(url), new com.alibaba.dubbo.rpc.Invocation.CompatibleInvocation(invocation)); return res.stream() .map(inv -> inv.getOriginal()) .filter(Objects::nonNull) .collect(Collectors.toList()); } @Override default boolean isRuntime() { return true; } @Override default boolean isForce() { return false; } @Override default int getPriority() { return 1; } @Override default int compareTo(org.apache.dubbo.rpc.cluster.Router o) { if (!(o instanceof Router)) { return 1; } return this.compareTo((Router) o); } }
5,354
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Directory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.cluster; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; import java.util.List; import java.util.stream.Collectors; import com.alibaba.dubbo.common.URL; @Deprecated public interface Directory<T> extends org.apache.dubbo.rpc.cluster.Directory<T> { @Override URL getUrl(); List<com.alibaba.dubbo.rpc.Invoker<T>> list(com.alibaba.dubbo.rpc.Invocation invocation) throws com.alibaba.dubbo.rpc.RpcException; @Override default List<Invoker<T>> list(Invocation invocation) throws RpcException { List<com.alibaba.dubbo.rpc.Invoker<T>> res = this.list(new com.alibaba.dubbo.rpc.Invocation.CompatibleInvocation(invocation)); return res.stream().map(com.alibaba.dubbo.rpc.Invoker::getOriginal).collect(Collectors.toList()); } }
5,355
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/LoadBalance.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.cluster; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; import java.util.List; import java.util.stream.Collectors; import com.alibaba.dubbo.common.DelegateURL; @Deprecated public interface LoadBalance extends org.apache.dubbo.rpc.cluster.LoadBalance { <T> com.alibaba.dubbo.rpc.Invoker<T> select( List<com.alibaba.dubbo.rpc.Invoker<T>> invokers, com.alibaba.dubbo.common.URL url, com.alibaba.dubbo.rpc.Invocation invocation) throws RpcException; @Override default <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException { List<com.alibaba.dubbo.rpc.Invoker<T>> invs = invokers.stream() .map(invoker -> new com.alibaba.dubbo.rpc.Invoker.CompatibleInvoker<T>(invoker)) .collect(Collectors.toList()); com.alibaba.dubbo.rpc.Invoker<T> selected = select( invs, new DelegateURL(url), new com.alibaba.dubbo.rpc.Invocation.CompatibleInvocation(invocation)); return selected == null ? null : selected.getOriginal(); } }
5,356
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Cluster.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.cluster; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.cluster.Directory; @Deprecated public interface Cluster extends org.apache.dubbo.rpc.cluster.Cluster { <T> com.alibaba.dubbo.rpc.Invoker<T> join(com.alibaba.dubbo.rpc.cluster.Directory<T> directory) throws com.alibaba.dubbo.rpc.RpcException; @Override default <T> Invoker<T> join(Directory<T> directory, boolean buildFilterChain) throws RpcException { return null; } }
5,357
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/RuleConverter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.cluster; import org.apache.dubbo.common.URL; import java.util.List; import java.util.stream.Collectors; @Deprecated public interface RuleConverter extends org.apache.dubbo.rpc.cluster.RuleConverter { List<com.alibaba.dubbo.common.URL> convert(com.alibaba.dubbo.common.URL subscribeUrl, Object source); @Override default List<URL> convert(URL subscribeUrl, Object source) { return this.convert(new com.alibaba.dubbo.common.DelegateURL(subscribeUrl), source).stream() .map(url -> url.getOriginalURL()) .collect(Collectors.toList()); } }
5,358
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/RouterFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.cluster; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.cluster.Router; @Deprecated public interface RouterFactory extends org.apache.dubbo.rpc.cluster.RouterFactory { com.alibaba.dubbo.rpc.cluster.Router getRouter(com.alibaba.dubbo.common.URL url); @Override default Router getRouter(URL url) { return this.getRouter(new com.alibaba.dubbo.common.DelegateURL(url)); } }
5,359
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Configurator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.cluster; import org.apache.dubbo.common.URL; @Deprecated public interface Configurator extends org.apache.dubbo.rpc.cluster.Configurator { /** * Get the configurator url. * * @return configurator url. */ com.alibaba.dubbo.common.URL getUrl(); /** * Configure the provider url. * * @param url - old provider url. * @return new provider url. */ com.alibaba.dubbo.common.URL configure(com.alibaba.dubbo.common.URL url); @Override default URL configure(URL url) { return this.configure(new com.alibaba.dubbo.common.DelegateURL(url)); } }
5,360
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/ConfiguratorFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.cluster; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.rpc.cluster.Configurator; @Deprecated public interface ConfiguratorFactory extends org.apache.dubbo.rpc.cluster.ConfiguratorFactory { @Adaptive(CommonConstants.PROTOCOL_KEY) com.alibaba.dubbo.rpc.cluster.Configurator getConfigurator(com.alibaba.dubbo.common.URL url); @Override default Configurator getConfigurator(URL url) { return this.getConfigurator(new com.alibaba.dubbo.common.DelegateURL(url)); } }
5,361
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.cluster.loadbalance; import org.apache.dubbo.rpc.support.RpcUtils; import java.util.List; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.cluster.LoadBalance; @Deprecated public abstract class AbstractLoadBalance implements LoadBalance { @Override public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) { if (invokers == null || invokers.size() == 0) return null; if (invokers.size() == 1) return invokers.get(0); return doSelect(invokers, url, invocation); } protected abstract <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation); protected int getWeight(Invoker<?> invoker, Invocation invocation) { int weight = invoker.getUrl() .getMethodParameter(RpcUtils.getMethodName(invocation), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT); if (weight > 0) { long timestamp = invoker.getUrl().getParameter(Constants.TIMESTAMP_KEY, 0L); if (timestamp > 0L) { int uptime = (int) (System.currentTimeMillis() - timestamp); int warmup = invoker.getUrl().getParameter(Constants.WARMUP_KEY, Constants.DEFAULT_WARMUP); if (uptime > 0 && uptime < warmup) { weight = calculateWarmupWeight(uptime, warmup, weight); } } } return weight; } static int calculateWarmupWeight(int uptime, int warmup, int weight) { int ww = (int) ((float) uptime / ((float) warmup / (float) weight)); return ww < 1 ? 1 : (ww > weight ? weight : ww); } }
5,362
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.protocol.dubbo; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Result; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.BiConsumer; import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.exchange.ResponseCallback; import com.alibaba.dubbo.remoting.exchange.ResponseFuture; import com.alibaba.dubbo.rpc.RpcException; /** * 2019-06-20 */ @Deprecated public class FutureAdapter<V> implements Future<V> { private CompletableFuture<Object> future; public FutureAdapter(CompletableFuture<Object> future) { this.future = future; } public FutureAdapter(ResponseFuture responseFuture) { this.future = new CompletableFuture<>(); responseFuture.setCallback(new ResponseCallback() { @Override public void done(Object response) { future.complete(response); } @Override public void caught(Throwable exception) { future.completeExceptionally(exception); } }); } public ResponseFuture getFuture() { return new ResponseFuture() { @Override public Object get() throws RemotingException { try { return future.get(); } catch (InterruptedException | ExecutionException e) { throw new RemotingException(e); } } @Override public Object get(int timeoutInMillis) throws RemotingException { try { return future.get(timeoutInMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException | TimeoutException | ExecutionException e) { throw new RemotingException(e); } } @Override public void setCallback(ResponseCallback callback) { FutureAdapter.this.setCallback(callback); } @Override public boolean isDone() { return future.isDone(); } }; } void setCallback(ResponseCallback callback) { BiConsumer<Object, ? super Throwable> biConsumer = new BiConsumer<Object, Throwable>() { @Override public void accept(Object obj, Throwable t) { if (t != null) { if (t instanceof CompletionException) { t = t.getCause(); } callback.caught(t); } else { AppResponse appResponse = (AppResponse) obj; if (appResponse.hasException()) { callback.caught(appResponse.getException()); } else { callback.done((V) appResponse.getValue()); } } } }; future.whenComplete(biConsumer); } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return future.isDone(); } @Override @SuppressWarnings("unchecked") public V get() throws InterruptedException, ExecutionException { try { return (V) (((Result) future.get()).recreate()); } catch (InterruptedException | ExecutionException e) { throw e; } catch (Throwable e) { throw new RpcException(e); } } @Override @SuppressWarnings("unchecked") public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { try { return (V) (((Result) future.get(timeout, unit)).recreate()); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw e; } catch (Throwable e) { throw new RpcException(e); } } }
5,363
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/ContentType.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.protocol.rest.support; @Deprecated public class ContentType extends org.apache.dubbo.rpc.protocol.rest.support.ContentType {}
5,364
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.support; import java.lang.reflect.Type; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.rpc.Invocation; /** * 2019-04-18 */ public class RpcUtils extends org.apache.dubbo.rpc.support.RpcUtils { public static Class<?> getReturnType(Invocation invocation) { return org.apache.dubbo.rpc.support.RpcUtils.getReturnType(invocation); } // TODO why not get return type when initialize Invocation? public static Type[] getReturnTypes(Invocation invocation) { return org.apache.dubbo.rpc.support.RpcUtils.getReturnTypes(invocation); } public static Long getInvocationId(Invocation inv) { return org.apache.dubbo.rpc.support.RpcUtils.getInvocationId(inv); } /** * Idempotent operation: invocation id will be added in async operation by default * * @param url * @param inv */ public static void attachInvocationIdIfAsync(URL url, Invocation inv) { org.apache.dubbo.rpc.support.RpcUtils.attachInvocationIdIfAsync(url.getOriginalURL(), inv); } public static String getMethodName(Invocation invocation) { return org.apache.dubbo.rpc.support.RpcUtils.getMethodName(invocation); } public static Object[] getArguments(Invocation invocation) { return org.apache.dubbo.rpc.support.RpcUtils.getArguments(invocation); } public static Class<?>[] getParameterTypes(Invocation invocation) { return org.apache.dubbo.rpc.support.RpcUtils.getParameterTypes(invocation); } public static boolean isAsync(URL url, Invocation inv) { return org.apache.dubbo.rpc.support.RpcUtils.isAsync(url.getOriginalURL(), inv); } public static boolean isReturnTypeFuture(Invocation inv) { return org.apache.dubbo.rpc.support.RpcUtils.isReturnTypeFuture(inv); } public static boolean isOneway(URL url, Invocation inv) { return org.apache.dubbo.rpc.support.RpcUtils.isOneway(url.getOriginalURL(), inv); } }
5,365
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/GenericException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.service; @Deprecated public class GenericException extends org.apache.dubbo.rpc.service.GenericException { private static final long serialVersionUID = -1182299763306599962L; public GenericException() {} public GenericException(String exceptionMessage) { super(exceptionMessage); } public GenericException(String exceptionClass, String exceptionMessage) { super(exceptionClass, exceptionMessage); } public GenericException(Throwable cause) { super(cause); } public GenericException(String message, Throwable cause, String exceptionClass, String exceptionMessage) { super(message, cause, exceptionClass, exceptionMessage); } }
5,366
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/GenericService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.service; @Deprecated public interface GenericService extends org.apache.dubbo.rpc.service.GenericService { @Override Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException; }
5,367
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/EchoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.rpc.service; @Deprecated public interface EchoService extends org.apache.dubbo.rpc.service.EchoService {}
5,368
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/validation/Validation.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.validation; @Deprecated public interface Validation extends org.apache.dubbo.validation.Validation {}
5,369
0
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo
Create_ds/dubbo/dubbo-compatible/src/main/java/com/alibaba/dubbo/validation/Validator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.validation; @Deprecated public interface Validator extends org.apache.dubbo.validation.Validator {}
5,370
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistryTestUtil.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multiple; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.registry.ListenerRegistryWrapper; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.zookeeper.ZookeeperRegistry; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.COMPATIBLE_CONFIG_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; /** * 2019-05-13 */ public class MultipleRegistryTestUtil { public static ZookeeperRegistry getZookeeperRegistry(Collection<Registry> registryCollection) { for (Registry registry : registryCollection) { if (registry instanceof ListenerRegistryWrapper) { registry = ((ListenerRegistryWrapper) registry).getRegistry(); } if (registry instanceof ZookeeperRegistry) { return (ZookeeperRegistry) registry; } } return null; } /** * copy from @org.apache.dubbo.registry.integration.RegistryDirectory#notify(java.util.List) * * @param urls * @return */ public static List<URL> getProviderURLsFromNotifyURLS(List<URL> urls) { Map<String, List<URL>> categoryUrls = urls.stream() .filter(Objects::nonNull) .filter(MultipleRegistryTestUtil::isValidCategory) .filter(MultipleRegistryTestUtil::isNotCompatibleFor26x) .collect(Collectors.groupingBy(url -> { if (UrlUtils.isConfigurator(url)) { return CONFIGURATORS_CATEGORY; } else if (UrlUtils.isRoute(url)) { return ROUTERS_CATEGORY; } else if (UrlUtils.isProvider(url)) { return PROVIDERS_CATEGORY; } return ""; })); // providers List<URL> providerURLs = categoryUrls.getOrDefault(PROVIDERS_CATEGORY, Collections.emptyList()); return providerURLs; } private static boolean isValidCategory(URL url) { String category = url.getCategory(DEFAULT_CATEGORY); if ((ROUTERS_CATEGORY.equals(category) || ROUTE_PROTOCOL.equals(url.getProtocol())) || PROVIDERS_CATEGORY.equals(category) || CONFIGURATORS_CATEGORY.equals(category) || DYNAMIC_CONFIGURATORS_CATEGORY.equals(category) || APP_DYNAMIC_CONFIGURATORS_CATEGORY.equals(category)) { return true; } return false; } private static boolean isNotCompatibleFor26x(URL url) { return StringUtils.isEmpty(url.getParameter(COMPATIBLE_CONFIG_KEY)); } }
5,371
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistry2S2RTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multiple; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.zookeeper.ZookeeperRegistry; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.curator5.Curator5ZookeeperClient; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; /** * 2019-04-30 */ class MultipleRegistry2S2RTest { private static final String SERVICE_NAME = "org.apache.dubbo.registry.MultipleService2S2R"; private static final String SERVICE2_NAME = "org.apache.dubbo.registry.MultipleService2S2R2"; private static MultipleRegistry multipleRegistry; // for test content private static ZookeeperClient zookeeperClient; private static ZookeeperClient zookeeperClient2; private static ZookeeperRegistry zookeeperRegistry; private static ZookeeperRegistry zookeeperRegistry2; private static String zookeeperConnectionAddress1, zookeeperConnectionAddress2; @BeforeAll public static void beforeAll() { zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1"); zookeeperConnectionAddress2 = System.getProperty("zookeeper.connection.address.2"); URL url = URL.valueOf("multiple://127.0.0.1?application=vic&enable-empty-protection=false&" + MultipleRegistry.REGISTRY_FOR_SERVICE + "=" + zookeeperConnectionAddress1 + "," + zookeeperConnectionAddress2 + "&" + MultipleRegistry.REGISTRY_FOR_REFERENCE + "=" + zookeeperConnectionAddress1 + "," + zookeeperConnectionAddress2); multipleRegistry = (MultipleRegistry) new MultipleRegistryFactory().createRegistry(url); // for test validation zookeeperClient = new Curator5ZookeeperClient(URL.valueOf(zookeeperConnectionAddress1)); zookeeperRegistry = MultipleRegistryTestUtil.getZookeeperRegistry( multipleRegistry.getServiceRegistries().values()); zookeeperClient2 = new Curator5ZookeeperClient(URL.valueOf(zookeeperConnectionAddress2)); zookeeperRegistry2 = MultipleRegistryTestUtil.getZookeeperRegistry( multipleRegistry.getServiceRegistries().values()); } @Test void testParamConfig() { Assertions.assertEquals(2, multipleRegistry.origReferenceRegistryURLs.size()); Assertions.assertTrue(multipleRegistry.origReferenceRegistryURLs.contains(zookeeperConnectionAddress1)); Assertions.assertTrue(multipleRegistry.origReferenceRegistryURLs.contains(zookeeperConnectionAddress2)); Assertions.assertEquals(2, multipleRegistry.origServiceRegistryURLs.size()); Assertions.assertTrue(multipleRegistry.origServiceRegistryURLs.contains(zookeeperConnectionAddress1)); Assertions.assertTrue(multipleRegistry.origServiceRegistryURLs.contains(zookeeperConnectionAddress2)); Assertions.assertEquals(2, multipleRegistry.effectReferenceRegistryURLs.size()); Assertions.assertTrue(multipleRegistry.effectReferenceRegistryURLs.contains(zookeeperConnectionAddress1)); Assertions.assertTrue(multipleRegistry.effectReferenceRegistryURLs.contains(zookeeperConnectionAddress2)); Assertions.assertEquals(2, multipleRegistry.effectServiceRegistryURLs.size()); Assertions.assertTrue(multipleRegistry.effectServiceRegistryURLs.contains(zookeeperConnectionAddress1)); Assertions.assertTrue(multipleRegistry.effectServiceRegistryURLs.contains(zookeeperConnectionAddress2)); Assertions.assertTrue(multipleRegistry.getServiceRegistries().containsKey(zookeeperConnectionAddress1)); Assertions.assertTrue(multipleRegistry.getServiceRegistries().containsKey(zookeeperConnectionAddress2)); Assertions.assertEquals( 2, multipleRegistry.getServiceRegistries().values().size()); // java.util.Iterator<Registry> registryIterable = // multipleRegistry.getServiceRegistries().values().iterator(); // Registry firstRegistry = registryIterable.next(); // Registry secondRegistry = registryIterable.next(); Assertions.assertNotNull(MultipleRegistryTestUtil.getZookeeperRegistry( multipleRegistry.getServiceRegistries().values())); Assertions.assertNotNull(MultipleRegistryTestUtil.getZookeeperRegistry( multipleRegistry.getReferenceRegistries().values())); Assertions.assertEquals( MultipleRegistryTestUtil.getZookeeperRegistry( multipleRegistry.getServiceRegistries().values()), MultipleRegistryTestUtil.getZookeeperRegistry( multipleRegistry.getReferenceRegistries().values())); Assertions.assertEquals( MultipleRegistryTestUtil.getZookeeperRegistry( multipleRegistry.getServiceRegistries().values()), MultipleRegistryTestUtil.getZookeeperRegistry( multipleRegistry.getReferenceRegistries().values())); Assertions.assertEquals(multipleRegistry.getApplicationName(), "vic"); Assertions.assertTrue(multipleRegistry.isAvailable()); } @Test void testRegistryAndUnRegistry() throws InterruptedException { URL serviceUrl = URL.valueOf( "http2://multiple/" + SERVICE_NAME + "?notify=false&methods=test1,test2&category=providers"); // URL serviceUrl2 = URL.valueOf("http2://multiple2/" + SERVICE_NAME + // "?notify=false&methods=test1,test2&category=providers"); multipleRegistry.register(serviceUrl); String path = "/dubbo/" + SERVICE_NAME + "/providers"; List<String> providerList = zookeeperClient.getChildren(path); Assertions.assertTrue(!providerList.isEmpty()); System.out.println(providerList.get(0)); final List<URL> list = new ArrayList<URL>(); multipleRegistry.subscribe(serviceUrl, new NotifyListener() { @Override public void notify(List<URL> urls) { System.out.println("invoke notify: " + urls); list.clear(); list.addAll(urls); } }); Thread.sleep(1500); Assertions.assertEquals(2, list.size()); multipleRegistry.unregister(serviceUrl); Thread.sleep(1500); Assertions.assertEquals(1, list.size()); List<URL> urls = MultipleRegistryTestUtil.getProviderURLsFromNotifyURLS(list); Assertions.assertEquals(1, list.size()); Assertions.assertEquals("empty", list.get(0).getProtocol()); } @Test void testSubscription() throws InterruptedException { URL serviceUrl = URL.valueOf( "http2://multiple/" + SERVICE2_NAME + "?notify=false&methods=test1,test2&category=providers"); // URL serviceUrl2 = URL.valueOf("http2://multiple2/" + SERVICE_NAME + // "?notify=false&methods=test1,test2&category=providers"); multipleRegistry.register(serviceUrl); String path = "/dubbo/" + SERVICE2_NAME + "/providers"; List<String> providerList = zookeeperClient.getChildren(path); Assumptions.assumeTrue(!providerList.isEmpty()); final List<URL> list = new ArrayList<URL>(); multipleRegistry.subscribe(serviceUrl, new NotifyListener() { @Override public void notify(List<URL> urls) { System.out.println("invoke notify: " + urls); list.clear(); list.addAll(urls); } }); Thread.sleep(1500); Assertions.assertEquals(2, list.size()); List<Registry> serviceRegistries = new ArrayList<Registry>(multipleRegistry.getServiceRegistries().values()); serviceRegistries.get(0).unregister(serviceUrl); Thread.sleep(1500); Assertions.assertEquals(1, list.size()); List<URL> urls = MultipleRegistryTestUtil.getProviderURLsFromNotifyURLS(list); Assertions.assertEquals(1, list.size()); Assertions.assertTrue(!"empty".equals(list.get(0).getProtocol())); serviceRegistries.get(1).unregister(serviceUrl); Thread.sleep(1500); Assertions.assertEquals(1, list.size()); urls = MultipleRegistryTestUtil.getProviderURLsFromNotifyURLS(list); Assertions.assertEquals(1, list.size()); Assertions.assertEquals("empty", list.get(0).getProtocol()); } @Test void testAggregation() { List<URL> result = new ArrayList<URL>(); List<URL> listToAggregate = new ArrayList<URL>(); URL url1 = URL.valueOf("dubbo://127.0.0.1:20880/service1"); URL url2 = URL.valueOf("dubbo://127.0.0.1:20880/service1"); listToAggregate.add(url1); listToAggregate.add(url2); URL registryURL = URL.valueOf( "mock://127.0.0.1/RegistryService?attachments=zone=hangzhou,tag=middleware&enable-empty-protection=false"); MultipleRegistry.MultipleNotifyListenerWrapper.aggregateRegistryUrls(result, listToAggregate, registryURL); Assertions.assertEquals(2, result.size()); Assertions.assertEquals(2, result.get(0).getParameters().size()); Assertions.assertEquals("hangzhou", result.get(0).getParameter("zone")); Assertions.assertEquals("middleware", result.get(1).getParameter("tag")); } }
5,372
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscoveryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multiple; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metadata.MetadataInfo; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.rpc.model.ApplicationModel; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.common.collect.Sets; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME; /** * MultipleServiceDiscoveryTest */ public class MultipleServiceDiscoveryTest { private static String zookeeperConnectionAddress1, zookeeperConnectionAddress2; @Test public void testOnEvent() { try { String metadata_111 = "{\"app\":\"app1\",\"revision\":\"111\",\"services\":{" + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app1\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" + "}}"; MetadataInfo metadataInfo = JsonUtils.toJavaObject(metadata_111, MetadataInfo.class); ApplicationModel applicationModel = ApplicationModel.defaultModel(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("app2")); zookeeperConnectionAddress1 = "multiple://127.0.0.1:2181?reference-registry=127.0.0.1:2181?enableEmptyProtection=false&child.a1=zookeeper://127.0.0.1:2181"; List<Object> urlsSameRevision = new ArrayList<>(); urlsSameRevision.add("127.0.0.1:20880?revision=111"); urlsSameRevision.add("127.0.0.2:20880?revision=111"); urlsSameRevision.add("127.0.0.3:20880?revision=111"); URL url = URL.valueOf(zookeeperConnectionAddress1); url.setScopeModel(applicationModel); MultipleServiceDiscovery multipleServiceDiscovery = new MultipleServiceDiscovery(url); Class<MultipleServiceDiscovery> multipleServiceDiscoveryClass = MultipleServiceDiscovery.class; Field serviceDiscoveries = multipleServiceDiscoveryClass.getDeclaredField("serviceDiscoveries"); serviceDiscoveries.setAccessible(true); ServiceDiscovery serviceDiscoveryMock = Mockito.mock(ServiceDiscovery.class); Mockito.when(serviceDiscoveryMock.getRemoteMetadata(Mockito.anyString(), Mockito.anyList())) .thenReturn(metadataInfo); serviceDiscoveries.set( multipleServiceDiscovery, Collections.singletonMap("child.a1", serviceDiscoveryMock)); MultipleServiceDiscovery.MultiServiceInstancesChangedListener listener = (MultipleServiceDiscovery.MultiServiceInstancesChangedListener) multipleServiceDiscovery.createListener(Sets.newHashSet("app1")); multipleServiceDiscovery.addServiceInstancesChangedListener(listener); MultipleServiceDiscovery.SingleServiceInstancesChangedListener singleServiceInstancesChangedListener = listener.getAndComputeIfAbsent("child.a1", (a1) -> null); Assert.notNull( singleServiceInstancesChangedListener, "singleServiceInstancesChangedListener can not be null"); singleServiceInstancesChangedListener.onEvent( new ServiceInstancesChangedEvent("app1", buildInstances(urlsSameRevision))); Mockito.verify(serviceDiscoveryMock, Mockito.times(1)) .getRemoteMetadata(Mockito.anyString(), Mockito.anyList()); Field serviceUrlsField = ServiceInstancesChangedListener.class.getDeclaredField("serviceUrls"); serviceUrlsField.setAccessible(true); Map<String, List<ServiceInstancesChangedListener.ProtocolServiceKeyWithUrls>> map = (Map<String, List<ServiceInstancesChangedListener.ProtocolServiceKeyWithUrls>>) serviceUrlsField.get(listener); Assert.assertTrue(!CollectionUtils.isEmptyMap(map), "url can not be empty"); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } static List<ServiceInstance> buildInstances(List<Object> rawURls) { List<ServiceInstance> instances = new ArrayList<>(); for (Object obj : rawURls) { String rawURL = (String) obj; DefaultServiceInstance instance = new DefaultServiceInstance(); final URL dubboUrl = URL.valueOf(rawURL); instance.setRawAddress(rawURL); instance.setHost(dubboUrl.getHost()); instance.setEnabled(true); instance.setHealthy(true); instance.setPort(dubboUrl.getPort()); instance.setRegistryCluster("default"); instance.setApplicationModel(ApplicationModel.defaultModel()); Map<String, String> metadata = new HashMap<>(); if (StringUtils.isNotEmpty(dubboUrl.getParameter(REVISION_KEY))) { metadata.put(EXPORTED_SERVICES_REVISION_PROPERTY_NAME, dubboUrl.getParameter(REVISION_KEY)); } instance.setMetadata(metadata); instances.add(instance); } return instances; } }
5,373
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistry.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multiple; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; import org.apache.dubbo.registry.support.AbstractRegistry; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; /** * MultipleRegistry */ public class MultipleRegistry extends AbstractRegistry { public static final Logger LOGGER = LoggerFactory.getLogger(MultipleRegistry.class); public static final String REGISTRY_FOR_SERVICE = "service-registry"; public static final String REGISTRY_FOR_REFERENCE = "reference-registry"; public static final String REGISTRY_SEPARATOR = "separator"; private final Map<String, Registry> serviceRegistries = new ConcurrentHashMap<>(4); private final Map<String, Registry> referenceRegistries = new ConcurrentHashMap<>(4); private final Map<NotifyListener, MultipleNotifyListenerWrapper> multipleNotifyListenerMap = new ConcurrentHashMap<>(32); private final URL registryUrl; private final String applicationName; protected RegistryFactory registryFactory; protected List<String> origServiceRegistryURLs; protected List<String> origReferenceRegistryURLs; protected List<String> effectServiceRegistryURLs; protected List<String> effectReferenceRegistryURLs; public MultipleRegistry(URL url) { this(url, true, true); this.registryFactory = url.getOrDefaultApplicationModel() .getExtensionLoader(RegistryFactory.class) .getAdaptiveExtension(); boolean defaultRegistry = url.getParameter(CommonConstants.DEFAULT_KEY, true); if (defaultRegistry && effectServiceRegistryURLs.isEmpty() && effectReferenceRegistryURLs.isEmpty()) { throw new IllegalArgumentException("Illegal registry url. You need to configure parameter " + REGISTRY_FOR_SERVICE + " or " + REGISTRY_FOR_REFERENCE); } } public MultipleRegistry(URL url, boolean initServiceRegistry, boolean initReferenceRegistry) { super(url); this.registryUrl = url; this.applicationName = url.getApplication(); this.registryFactory = url.getOrDefaultApplicationModel() .getExtensionLoader(RegistryFactory.class) .getAdaptiveExtension(); init(); checkApplicationName(this.applicationName); // This urls contain parameter, and it does not inherit from the parameter of url in MultipleRegistry Map<String, Registry> registryMap = new HashMap<>(); if (initServiceRegistry) { initServiceRegistry(url, registryMap); } if (initReferenceRegistry) { initReferenceRegistry(url, registryMap); } } protected void initServiceRegistry(URL url, Map<String, Registry> registryMap) { String serviceRegistryString = url.getParameter(REGISTRY_FOR_SERVICE); char separator = url.getParameter(REGISTRY_SEPARATOR, COMMA_SEPARATOR).charAt(0); origServiceRegistryURLs = StringUtils.splitToList(serviceRegistryString, separator); effectServiceRegistryURLs = this.filterServiceRegistry(origServiceRegistryURLs); for (String tmpUrl : effectServiceRegistryURLs) { if (registryMap.get(tmpUrl) != null) { serviceRegistries.put(tmpUrl, registryMap.get(tmpUrl)); continue; } final URL registryUrl = URL.valueOf(tmpUrl) .addParametersIfAbsent(url.getParameters()) .addParameterIfAbsent(CHECK_KEY, url.getParameter(CHECK_KEY, "true")); Registry registry = registryFactory.getRegistry(registryUrl); registryMap.put(tmpUrl, registry); serviceRegistries.put(tmpUrl, registry); } } protected void initReferenceRegistry(URL url, Map<String, Registry> registryMap) { String serviceRegistryString = url.getParameter(REGISTRY_FOR_REFERENCE); char separator = url.getParameter(REGISTRY_SEPARATOR, COMMA_SEPARATOR).charAt(0); origReferenceRegistryURLs = StringUtils.splitToList(serviceRegistryString, separator); effectReferenceRegistryURLs = this.filterReferenceRegistry(origReferenceRegistryURLs); for (String tmpUrl : effectReferenceRegistryURLs) { if (registryMap.get(tmpUrl) != null) { referenceRegistries.put(tmpUrl, registryMap.get(tmpUrl)); continue; } final URL registryUrl = URL.valueOf(tmpUrl).addParameterIfAbsent(CHECK_KEY, url.getParameter(CHECK_KEY, "true")); Registry registry = registryFactory.getRegistry(registryUrl); registryMap.put(tmpUrl, registry); referenceRegistries.put(tmpUrl, registry); } } @Override public URL getUrl() { return registryUrl; } @Override public boolean isAvailable() { boolean available = serviceRegistries.isEmpty(); for (Registry serviceRegistry : serviceRegistries.values()) { if (serviceRegistry.isAvailable()) { available = true; } } if (!available) { return false; } available = referenceRegistries.isEmpty(); for (Registry referenceRegistry : referenceRegistries.values()) { if (referenceRegistry.isAvailable()) { available = true; } } if (!available) { return false; } return true; } @Override public void destroy() { Set<Registry> registries = new HashSet<>(serviceRegistries.values()); registries.addAll(referenceRegistries.values()); for (Registry registry : registries) { registry.destroy(); } } @Override public void register(URL url) { super.register(url); for (Registry registry : serviceRegistries.values()) { registry.register(url); } } @Override public void unregister(URL url) { super.unregister(url); for (Registry registry : serviceRegistries.values()) { registry.unregister(url); } } @Override public void subscribe(URL url, NotifyListener listener) { MultipleNotifyListenerWrapper multipleNotifyListenerWrapper = new MultipleNotifyListenerWrapper(listener); multipleNotifyListenerMap.put(listener, multipleNotifyListenerWrapper); for (Registry registry : referenceRegistries.values()) { SingleNotifyListener singleNotifyListener = new SingleNotifyListener(multipleNotifyListenerWrapper, registry); multipleNotifyListenerWrapper.putRegistryMap(registry.getUrl(), singleNotifyListener); registry.subscribe(url, singleNotifyListener); } super.subscribe(url, multipleNotifyListenerWrapper); } @Override public void unsubscribe(URL url, NotifyListener listener) { MultipleNotifyListenerWrapper notifyListener = multipleNotifyListenerMap.remove(listener); for (Registry registry : referenceRegistries.values()) { SingleNotifyListener singleNotifyListener = notifyListener.registryMap.get(registry.getUrl()); registry.unsubscribe(url, singleNotifyListener); } if (notifyListener != null) { super.unsubscribe(url, notifyListener); notifyListener.destroy(); } } @Override public List<URL> lookup(URL url) { List<URL> urls = new ArrayList<>(); for (Registry registry : referenceRegistries.values()) { List<URL> tmpUrls = registry.lookup(url); if (!CollectionUtils.isEmpty(tmpUrls)) { urls.addAll(tmpUrls); } } return urls.stream().distinct().collect(Collectors.toList()); } protected void init() {} protected List<String> filterServiceRegistry(List<String> serviceRegistryURLs) { return serviceRegistryURLs; } protected List<String> filterReferenceRegistry(List<String> referenceRegistryURLs) { return referenceRegistryURLs; } protected void checkApplicationName(String applicationName) {} protected String getApplicationName() { return applicationName; } public Map<String, Registry> getServiceRegistries() { return serviceRegistries; } public Map<String, Registry> getReferenceRegistries() { return referenceRegistries; } public List<String> getOrigServiceRegistryURLs() { return origServiceRegistryURLs; } public List<String> getOrigReferenceRegistryURLs() { return origReferenceRegistryURLs; } public List<String> getEffectServiceRegistryURLs() { return effectServiceRegistryURLs; } public List<String> getEffectReferenceRegistryURLs() { return effectReferenceRegistryURLs; } protected static class MultipleNotifyListenerWrapper implements NotifyListener { Map<URL, SingleNotifyListener> registryMap = new ConcurrentHashMap<URL, SingleNotifyListener>(4); NotifyListener sourceNotifyListener; public MultipleNotifyListenerWrapper(NotifyListener sourceNotifyListener) { this.sourceNotifyListener = sourceNotifyListener; } public void putRegistryMap(URL registryURL, SingleNotifyListener singleNotifyListener) { this.registryMap.put(registryURL, singleNotifyListener); } public void destroy() { for (SingleNotifyListener singleNotifyListener : registryMap.values()) { if (singleNotifyListener != null) { singleNotifyListener.destroy(); } } registryMap.clear(); sourceNotifyListener = null; } public synchronized void notifySourceListener() { List<URL> notifyURLs = new ArrayList<>(); URL emptyURL = null; for (SingleNotifyListener singleNotifyListener : registryMap.values()) { List<URL> tmpUrls = singleNotifyListener.getUrlList(); if (CollectionUtils.isEmpty(tmpUrls)) { continue; } // empty protocol if (tmpUrls.size() == 1 && tmpUrls.get(0) != null && EMPTY_PROTOCOL.equals(tmpUrls.get(0).getProtocol())) { // if only one empty if (emptyURL == null) { emptyURL = tmpUrls.get(0); } continue; } URL registryURL = singleNotifyListener.getRegistry().getUrl(); aggregateRegistryUrls(notifyURLs, tmpUrls, registryURL); } // if no notify URL, add empty protocol URL if (emptyURL != null && notifyURLs.isEmpty()) { notifyURLs.add(emptyURL); LOGGER.info("No provider after aggregation, notify url with EMPTY protocol."); } else { LOGGER.info("Aggregated provider url size " + notifyURLs.size()); } this.notify(notifyURLs); } /** * Aggregate urls from different registries into one unified list while appending registry specific 'attachments' into each url. * * These 'attachments' can be very useful for traffic management among registries. * * @param notifyURLs unified url list * @param singleURLs single registry url list * @param registryURL single registry configuration url */ public static void aggregateRegistryUrls(List<URL> notifyURLs, List<URL> singleURLs, URL registryURL) { String registryAttachments = registryURL.getParameter("attachments"); if (StringUtils.isNotBlank(registryAttachments)) { LOGGER.info("Registry attachments " + registryAttachments + " found, will append to provider urls, urls size " + singleURLs.size()); String[] pairs = registryAttachments.split(COMMA_SEPARATOR); Map<String, String> attachments = new HashMap<>(pairs.length); for (String rawPair : pairs) { String[] keyValuePair = rawPair.split("="); if (keyValuePair.length == 2) { String key = keyValuePair[0]; String value = keyValuePair[1]; attachments.put(key, value); } } for (URL tmpUrl : singleURLs) { for (Map.Entry<String, String> entry : attachments.entrySet()) { tmpUrl = tmpUrl.addParameterIfAbsent(entry.getKey(), entry.getValue()); } notifyURLs.add(tmpUrl); } } else { LOGGER.info("Single registry " + registryURL + " has url size " + singleURLs.size()); notifyURLs.addAll(singleURLs); } } @Override public void notify(List<URL> urls) { sourceNotifyListener.notify(urls); } public Map<URL, SingleNotifyListener> getRegistryMap() { return registryMap; } } protected static class SingleNotifyListener implements NotifyListener { MultipleNotifyListenerWrapper multipleNotifyListenerWrapper; Registry registry; volatile List<URL> urlList; public SingleNotifyListener(MultipleNotifyListenerWrapper multipleNotifyListenerWrapper, Registry registry) { this.registry = registry; this.multipleNotifyListenerWrapper = multipleNotifyListenerWrapper; } @Override public synchronized void notify(List<URL> urls) { this.urlList = urls; if (multipleNotifyListenerWrapper != null) { this.multipleNotifyListenerWrapper.notifySourceListener(); } } public void destroy() { this.multipleNotifyListenerWrapper = null; this.registry = null; } public List<URL> getUrlList() { return urlList; } public Registry getRegistry() { return registry; } } }
5,374
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscovery.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multiple; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.metadata.MetadataInfo; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.registry.client.ServiceDiscoveryFactory; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Function; public class MultipleServiceDiscovery implements ServiceDiscovery { public static final String REGISTRY_PREFIX_KEY = "child."; private static final String REGISTRY_TYPE = "registry-type"; private static final String SERVICE = "service"; private final Map<String, ServiceDiscovery> serviceDiscoveries = new ConcurrentHashMap<>(); private URL registryURL; private String applicationName; private volatile boolean isDestroy; public MultipleServiceDiscovery(URL registryURL) { this.registryURL = registryURL; this.applicationName = registryURL.getApplication(); Map<String, String> parameters = registryURL.getParameters(); for (String key : parameters.keySet()) { if (key.startsWith(REGISTRY_PREFIX_KEY)) { URL url = URL.valueOf(registryURL.getParameter(key)) .addParameter(CommonConstants.APPLICATION_KEY, applicationName) .addParameter(REGISTRY_TYPE, SERVICE); ServiceDiscovery serviceDiscovery = ServiceDiscoveryFactory.getExtension(url).getServiceDiscovery(url); serviceDiscoveries.put(key, serviceDiscovery); } } } @Override public URL getUrl() { return registryURL; } @Override public void destroy() throws Exception { this.isDestroy = true; for (ServiceDiscovery serviceDiscovery : serviceDiscoveries.values()) { serviceDiscovery.destroy(); } } @Override public boolean isDestroy() { return isDestroy; } @Override public void register() throws RuntimeException { serviceDiscoveries.values().forEach(serviceDiscovery -> serviceDiscovery.register()); } @Override public void update() throws RuntimeException { serviceDiscoveries.values().forEach(serviceDiscovery -> serviceDiscovery.update()); } @Override public void unregister() throws RuntimeException { serviceDiscoveries.values().forEach(serviceDiscovery -> serviceDiscovery.unregister()); } @Override public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener) throws NullPointerException, IllegalArgumentException { MultiServiceInstancesChangedListener multiListener = (MultiServiceInstancesChangedListener) listener; for (String registryKey : serviceDiscoveries.keySet()) { ServiceDiscovery serviceDiscovery = serviceDiscoveries.get(registryKey); SingleServiceInstancesChangedListener singleListener = multiListener.getAndComputeIfAbsent( registryKey, k -> new SingleServiceInstancesChangedListener( listener.getServiceNames(), serviceDiscovery, multiListener)); serviceDiscovery.addServiceInstancesChangedListener(singleListener); } } @Override public ServiceInstancesChangedListener createListener(Set<String> serviceNames) { return new MultiServiceInstancesChangedListener(serviceNames, this); } @Override public List<ServiceInstance> getInstances(String serviceName) { List<ServiceInstance> serviceInstanceList = new ArrayList<>(); for (ServiceDiscovery serviceDiscovery : serviceDiscoveries.values()) { serviceInstanceList.addAll(serviceDiscovery.getInstances(serviceName)); } return serviceInstanceList; } @Override public Set<String> getServices() { Set<String> services = new HashSet<>(); for (ServiceDiscovery serviceDiscovery : serviceDiscoveries.values()) { services.addAll(serviceDiscovery.getServices()); } return services; } @Override public ServiceInstance getLocalInstance() { return null; } @Override public MetadataInfo getLocalMetadata() { throw new UnsupportedOperationException( "Multiple registry implementation does not support getMetadata() method."); } @Override public MetadataInfo getLocalMetadata(String revision) { MetadataInfo metadataInfo = MetadataInfo.EMPTY; for (ServiceDiscovery serviceDiscovery : serviceDiscoveries.values()) { MetadataInfo remoteMetadata = serviceDiscovery.getLocalMetadata(revision); if (!Objects.equals(MetadataInfo.EMPTY, remoteMetadata)) { metadataInfo = remoteMetadata; break; } } return metadataInfo; } @Override public MetadataInfo getRemoteMetadata(String revision) { throw new UnsupportedOperationException( "Multiple registry implementation does not support getMetadata() method."); } @Override public MetadataInfo getRemoteMetadata(String revision, List<ServiceInstance> instances) { MetadataInfo metadataInfo = MetadataInfo.EMPTY; for (ServiceDiscovery serviceDiscovery : serviceDiscoveries.values()) { MetadataInfo remoteMetadata = serviceDiscovery.getRemoteMetadata(revision, instances); if (!Objects.equals(MetadataInfo.EMPTY, remoteMetadata)) { metadataInfo = remoteMetadata; break; } } return metadataInfo; } @Override public void register(URL url) { serviceDiscoveries.values().forEach(serviceDiscovery -> serviceDiscovery.register(url)); } @Override public void unregister(URL url) { serviceDiscoveries.values().forEach(serviceDiscovery -> serviceDiscovery.unregister(url)); } @Override public void subscribe(URL url, NotifyListener listener) { serviceDiscoveries.values().forEach(serviceDiscovery -> serviceDiscovery.subscribe(url, listener)); } @Override public void unsubscribe(URL url, NotifyListener listener) { serviceDiscoveries.values().forEach(serviceDiscovery -> serviceDiscovery.unsubscribe(url, listener)); } @Override public List<URL> lookup(URL url) { throw new UnsupportedOperationException("Multiple registry implementation does not support lookup() method."); } protected static class MultiServiceInstancesChangedListener extends ServiceInstancesChangedListener { private final ConcurrentMap<String, SingleServiceInstancesChangedListener> singleListenerMap; public MultiServiceInstancesChangedListener(Set<String> serviceNames, ServiceDiscovery serviceDiscovery) { super(serviceNames, serviceDiscovery); this.singleListenerMap = new ConcurrentHashMap<>(); } @Override public void onEvent(ServiceInstancesChangedEvent event) { List<ServiceInstance> serviceInstances = new ArrayList<>(); for (SingleServiceInstancesChangedListener singleListener : singleListenerMap.values()) { if (null != singleListener.event && null != singleListener.event.getServiceInstances()) { for (ServiceInstance serviceInstance : singleListener.event.getServiceInstances()) { if (!serviceInstances.contains(serviceInstance)) { serviceInstances.add(serviceInstance); } } } } super.onEvent(new ServiceInstancesChangedEvent(event.getServiceName(), serviceInstances)); } public void putSingleListener(String registryKey, SingleServiceInstancesChangedListener singleListener) { singleListenerMap.put(registryKey, singleListener); } public SingleServiceInstancesChangedListener getAndComputeIfAbsent( String registryKey, Function<String, SingleServiceInstancesChangedListener> func) { return ConcurrentHashMapUtils.computeIfAbsent(singleListenerMap, registryKey, func); } } protected static class SingleServiceInstancesChangedListener extends ServiceInstancesChangedListener { private final MultiServiceInstancesChangedListener multiListener; volatile ServiceInstancesChangedEvent event; public SingleServiceInstancesChangedListener( Set<String> serviceNames, ServiceDiscovery serviceDiscovery, MultiServiceInstancesChangedListener multiListener) { super(serviceNames, serviceDiscovery); this.multiListener = multiListener; } @Override public void onEvent(ServiceInstancesChangedEvent event) { this.event = event; if (multiListener != null) { multiListener.onEvent(event); } } } }
5,375
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistryFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multiple; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.support.AbstractRegistryFactory; /** * MultipleRegistryFactory */ public class MultipleRegistryFactory extends AbstractRegistryFactory { @Override protected Registry createRegistry(URL url) { return new MultipleRegistry(url); } }
5,376
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscoveryFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multiple; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.client.AbstractServiceDiscoveryFactory; import org.apache.dubbo.registry.client.ServiceDiscovery; public class MultipleServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory { @Override protected ServiceDiscovery createDiscovery(URL registryURL) { return new MultipleServiceDiscovery(registryURL); } }
5,377
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-multicast/src/test/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-multicast/src/test/java/org/apache/dubbo/registry/multicast/MulticastRegistryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multicast; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.registry.NotifyListener; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.UnknownHostException; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class MulticastRegistryTest { private String service = "org.apache.dubbo.test.injvmServie"; private URL registryUrl = URL.valueOf("multicast://239.239.239.239/"); private URL serviceUrl = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + "/" + service + "?methods=test1,test2"); private URL adminUrl = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + "/*"); private URL consumerUrl = URL.valueOf("subscribe://" + NetUtils.getLocalHost() + "/" + service + "?arg1=1&arg2=2"); private MulticastRegistry registry = new MulticastRegistry(registryUrl); @BeforeEach void setUp() { registry.register(serviceUrl); } /** * Test method for {@link org.apache.dubbo.registry.multicast.MulticastRegistry#MulticastRegistry(URL)}. */ @Test void testUrlError() { Assertions.assertThrows(UnknownHostException.class, () -> { try { URL errorUrl = URL.valueOf("multicast://mullticast.local/"); new MulticastRegistry(errorUrl); } catch (IllegalStateException e) { throw e.getCause(); } }); } /** * Test method for {@link org.apache.dubbo.registry.multicast.MulticastRegistry#MulticastRegistry(URL)}. */ @Test void testAnyHost() { Assertions.assertThrows(IllegalStateException.class, () -> { URL errorUrl = URL.valueOf("multicast://0.0.0.0/"); new MulticastRegistry(errorUrl); }); } /** * Test method for {@link org.apache.dubbo.registry.multicast.MulticastRegistry#MulticastRegistry(URL)}. */ @Test void testGetCustomPort() { int port = NetUtils.getAvailablePort(20880 + new Random().nextInt(10000)); URL customPortUrl = URL.valueOf("multicast://239.239.239.239:" + port); MulticastRegistry multicastRegistry = new MulticastRegistry(customPortUrl); assertThat(multicastRegistry.getUrl().getPort(), is(port)); } /** * Test method for {@link org.apache.dubbo.registry.multicast.MulticastRegistry#getRegistered()}. */ @Test void testRegister() { Set<URL> registered; // clear first registered = registry.getRegistered(); for (URL url : registered) { registry.unregister(url); } for (int i = 0; i < 2; i++) { registry.register(serviceUrl); registered = registry.getRegistered(); assertTrue(registered.contains(serviceUrl)); } // confirm only 1 register success registered = registry.getRegistered(); assertEquals(1, registered.size()); } /** * Test method for {@link org.apache.dubbo.registry.multicast.MulticastRegistry#unregister(URL)}. */ @Test void testUnregister() { Set<URL> registered; // register first registry.register(serviceUrl); registered = registry.getRegistered(); assertTrue(registered.contains(serviceUrl)); // then unregister registered = registry.getRegistered(); registry.unregister(serviceUrl); assertFalse(registered.contains(serviceUrl)); } /** * Test method for * {@link org.apache.dubbo.registry.multicast.MulticastRegistry#subscribe(URL url, org.apache.dubbo.registry.NotifyListener)} * . */ @Test void testSubscribe() { // verify listener final URL[] notifyUrl = new URL[1]; for (int i = 0; i < 10; i++) { registry.register(serviceUrl); registry.subscribe(consumerUrl, urls -> { notifyUrl[0] = urls.get(0); Map<URL, Set<NotifyListener>> subscribed = registry.getSubscribed(); assertEquals(consumerUrl, subscribed.keySet().iterator().next()); }); if (!EMPTY_PROTOCOL.equalsIgnoreCase(notifyUrl[0].getProtocol())) { break; } } assertEquals(serviceUrl.toFullString(), notifyUrl[0].toFullString()); } /** * Test method for {@link org.apache.dubbo.registry.multicast.MulticastRegistry#unsubscribe(URL, NotifyListener)} */ @Test void testUnsubscribe() { // subscribe first registry.subscribe(consumerUrl, new NotifyListener() { @Override public void notify(List<URL> urls) { // do nothing } }); // then unsubscribe registry.unsubscribe(consumerUrl, new NotifyListener() { @Override public void notify(List<URL> urls) { Map<URL, Set<NotifyListener>> subscribed = registry.getSubscribed(); Set<NotifyListener> listeners = subscribed.get(consumerUrl); assertTrue(listeners.isEmpty()); Map<URL, Set<URL>> received = registry.getReceived(); assertTrue(received.get(consumerUrl).isEmpty()); } }); } /** * Test method for {@link MulticastRegistry#isAvailable()} */ @Test void testAvailability() { int port = NetUtils.getAvailablePort(20880 + new Random().nextInt(10000)); MulticastRegistry registry = new MulticastRegistry(URL.valueOf("multicast://224.5.6.8:" + port)); assertTrue(registry.isAvailable()); } /** * Test method for {@link MulticastRegistry#destroy()} */ @Test void testDestroy() { MulticastSocket socket = registry.getMulticastSocket(); assertFalse(socket.isClosed()); // then destroy, the multicast socket will be closed registry.destroy(); socket = registry.getMulticastSocket(); assertTrue(socket.isClosed()); } /** * Test method for {@link org.apache.dubbo.registry.multicast.MulticastRegistry#MulticastRegistry(URL)} */ @Test void testDefaultPort() { MulticastRegistry multicastRegistry = new MulticastRegistry(URL.valueOf("multicast://224.5.6.7")); try { MulticastSocket multicastSocket = multicastRegistry.getMulticastSocket(); Assertions.assertEquals(1234, multicastSocket.getLocalPort()); } finally { multicastRegistry.destroy(); } } /** * Test method for {@link org.apache.dubbo.registry.multicast.MulticastRegistry#MulticastRegistry(URL)} */ @Test void testCustomedPort() { int port = NetUtils.getAvailablePort(20880 + new Random().nextInt(10000)); MulticastRegistry multicastRegistry = new MulticastRegistry(URL.valueOf("multicast://224.5.6.7:" + port)); try { MulticastSocket multicastSocket = multicastRegistry.getMulticastSocket(); assertEquals(port, multicastSocket.getLocalPort()); } finally { multicastRegistry.destroy(); } } @Test void testMulticastAddress() { InetAddress multicastAddress = null; MulticastSocket multicastSocket = null; try { // ipv4 multicast address multicastAddress = InetAddress.getByName("224.55.66.77"); multicastSocket = new MulticastSocket(2345); multicastSocket.setLoopbackMode(false); NetUtils.setInterface(multicastSocket, false); multicastSocket.joinGroup(multicastAddress); } catch (Exception e) { Assertions.fail(e); } finally { if (multicastSocket != null) { multicastSocket.close(); } } // multicast ipv6 address, try { multicastAddress = InetAddress.getByName("ff01::1"); multicastSocket = new MulticastSocket(); multicastSocket.setLoopbackMode(false); NetUtils.setInterface(multicastSocket, true); multicastSocket.joinGroup(multicastAddress); } catch (Throwable t) { t.printStackTrace(); } finally { if (multicastSocket != null) { multicastSocket.close(); } } } }
5,378
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-multicast/src/test/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-multicast/src/test/java/org/apache/dubbo/registry/multicast/MulticastRegistryFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multicast; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.Registry; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; class MulticastRegistryFactoryTest { @Test void shouldCreateRegistry() { Registry registry = new MulticastRegistryFactory().createRegistry(URL.valueOf("multicast://239.255.255.255/")); assertThat(registry, not(nullValue())); assertThat(registry.isAvailable(), is(true)); } }
5,379
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastServiceDiscoveryFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multicast; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.client.AbstractServiceDiscoveryFactory; import org.apache.dubbo.registry.client.ServiceDiscovery; public class MulticastServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory { @Override protected ServiceDiscovery createDiscovery(URL registryURL) { return new MulticastServiceDiscovery(applicationModel, registryURL); } }
5,380
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistryFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multicast; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.support.AbstractRegistryFactory; /** * MulticastRegistryLocator * */ public class MulticastRegistryFactory extends AbstractRegistryFactory { @Override public Registry createRegistry(URL url) { return new MulticastRegistry(url, applicationModel); } }
5,381
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastServiceDiscovery.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multicast; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.client.AbstractServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collections; import java.util.List; import java.util.Set; /** * TODO: make multicast protocol support Service Discovery */ public class MulticastServiceDiscovery extends AbstractServiceDiscovery { public MulticastServiceDiscovery(ApplicationModel applicationModel, URL registryURL) { super(applicationModel, registryURL); } public MulticastServiceDiscovery(String serviceName, URL registryURL) { super(serviceName, registryURL); } @Override public void doDestroy() throws Exception {} @Override public void doRegister(ServiceInstance serviceInstance) throws RuntimeException {} @Override public void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) throws RuntimeException {} @Override public void doUnregister(ServiceInstance serviceInstance) throws RuntimeException { this.serviceInstance = null; } @Override public Set<String> getServices() { return Collections.singleton("Unsupported Operation"); } @Override public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException { return null; } @Override public URL getUrl() { return registryURL; } }
5,382
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.multicast; 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.ConcurrentHashSet; import org.apache.dubbo.common.utils.ExecutorUtil; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.support.FailbackRegistry; import org.apache.dubbo.rpc.model.ApplicationModel; import java.io.IOException; import java.net.DatagramPacket; import java.net.Inet4Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; 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.REGISTRY_SOCKET_EXCEPTION; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.OVERRIDE_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; import static org.apache.dubbo.registry.Constants.DEFAULT_SESSION_TIMEOUT; import static org.apache.dubbo.registry.Constants.REGISTER; import static org.apache.dubbo.registry.Constants.REGISTER_KEY; import static org.apache.dubbo.registry.Constants.SESSION_TIMEOUT_KEY; import static org.apache.dubbo.registry.Constants.SUBSCRIBE; import static org.apache.dubbo.registry.Constants.UNREGISTER; import static org.apache.dubbo.registry.Constants.UNSUBSCRIBE; /** * MulticastRegistry */ public class MulticastRegistry extends FailbackRegistry { // logging output private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MulticastRegistry.class); private static final int DEFAULT_MULTICAST_PORT = 1234; private final InetAddress multicastAddress; private final MulticastSocket multicastSocket; private final int multicastPort; private final ConcurrentMap<URL, Set<URL>> received = new ConcurrentHashMap<URL, Set<URL>>(); private final ScheduledExecutorService cleanExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("DubboMulticastRegistryCleanTimer", true)); private final ScheduledFuture<?> cleanFuture; private final int cleanPeriod; private volatile boolean admin = false; public MulticastRegistry(URL url, ApplicationModel applicationModel) { this(url); } public MulticastRegistry(URL url) { super(url); if (url.isAnyHost()) { throw new IllegalStateException("registry address == null"); } try { multicastAddress = InetAddress.getByName(url.getHost()); checkMulticastAddress(multicastAddress); multicastPort = url.getPort() <= 0 ? DEFAULT_MULTICAST_PORT : url.getPort(); multicastSocket = new MulticastSocket(multicastPort); NetUtils.joinMulticastGroup(multicastSocket, multicastAddress); Thread thread = new Thread( () -> { byte[] buf = new byte[2048]; DatagramPacket recv = new DatagramPacket(buf, buf.length); while (!multicastSocket.isClosed()) { try { multicastSocket.receive(recv); String msg = new String(recv.getData()).trim(); int i = msg.indexOf('\n'); if (i > 0) { msg = msg.substring(0, i).trim(); } MulticastRegistry.this.receive(msg, (InetSocketAddress) recv.getSocketAddress()); Arrays.fill(buf, (byte) 0); } catch (Throwable e) { if (!multicastSocket.isClosed()) { logger.error(REGISTRY_SOCKET_EXCEPTION, "", "", e.getMessage(), e); } } } }, "DubboMulticastRegistryReceiver"); thread.setDaemon(true); thread.start(); } catch (IOException e) { throw new IllegalStateException(e.getMessage(), e); } this.cleanPeriod = url.getParameter(SESSION_TIMEOUT_KEY, DEFAULT_SESSION_TIMEOUT); if (url.getParameter("clean", true)) { this.cleanFuture = cleanExecutor.scheduleWithFixedDelay( () -> { try { clean(); // Remove the expired } catch (Throwable t) { // Defensive fault tolerance logger.error( REGISTRY_SOCKET_EXCEPTION, "", "", "Unexpected exception occur at clean expired provider, cause: " + t.getMessage(), t); } }, cleanPeriod, cleanPeriod, TimeUnit.MILLISECONDS); } else { this.cleanFuture = null; } } private void checkMulticastAddress(InetAddress multicastAddress) { if (!multicastAddress.isMulticastAddress()) { String message = "Invalid multicast address " + multicastAddress; if (multicastAddress instanceof Inet4Address) { throw new IllegalArgumentException( message + ", " + "ipv4 multicast address scope: 224.0.0.0 - 239.255.255.255."); } else { throw new IllegalArgumentException( message + ", " + "ipv6 multicast address must start with ff, " + "for example: ff01::1"); } } } /** * Remove the expired providers, only when "clean" parameter is true. */ private void clean() { if (admin) { for (Set<URL> providers : new HashSet<Set<URL>>(received.values())) { for (URL url : new HashSet<URL>(providers)) { if (isExpired(url)) { if (logger.isWarnEnabled()) { logger.warn(REGISTRY_SOCKET_EXCEPTION, "", "", "Clean expired provider " + url); } doUnregister(url); } } } } } private boolean isExpired(URL url) { if (!url.getParameter(DYNAMIC_KEY, true) || url.getPort() <= 0 || CONSUMER_PROTOCOL.equals(url.getProtocol()) || ROUTE_PROTOCOL.equals(url.getProtocol()) || OVERRIDE_PROTOCOL.equals(url.getProtocol())) { return false; } try (Socket socket = new Socket(url.getHost(), url.getPort())) { } catch (Throwable e) { try { Thread.sleep(100); } catch (Throwable e2) { } try (Socket socket2 = new Socket(url.getHost(), url.getPort())) { } catch (Throwable e2) { return true; } } return false; } private void receive(String msg, InetSocketAddress remoteAddress) { if (logger.isInfoEnabled()) { logger.info("Receive multicast message: " + msg + " from " + remoteAddress); } if (msg.startsWith(REGISTER)) { URL url = URL.valueOf(msg.substring(REGISTER.length()).trim()); registered(url); } else if (msg.startsWith(UNREGISTER)) { URL url = URL.valueOf(msg.substring(UNREGISTER.length()).trim()); unregistered(url); } else if (msg.startsWith(SUBSCRIBE)) { URL url = URL.valueOf(msg.substring(SUBSCRIBE.length()).trim()); Set<URL> urls = getRegistered(); if (CollectionUtils.isNotEmpty(urls)) { for (URL u : urls) { if (UrlUtils.isMatch(url, u)) { String host = remoteAddress != null && remoteAddress.getAddress() != null ? remoteAddress.getAddress().getHostAddress() : url.getIp(); if (url.getParameter("unicast", true) // Whether the consumer's machine has only one process && !NetUtils.getLocalHost() .equals(host)) { // Multiple processes in the same machine cannot be unicast // with unicast or there will be only one process receiving // information unicast(REGISTER + " " + u.toFullString(), host); } else { multicast(REGISTER + " " + u.toFullString()); } } } } } /* else if (msg.startsWith(UNSUBSCRIBE)) { }*/ } private void multicast(String msg) { if (logger.isInfoEnabled()) { logger.info("Send multicast message: " + msg + " to " + multicastAddress + ":" + multicastPort); } try { byte[] data = (msg + "\n").getBytes(); DatagramPacket hi = new DatagramPacket(data, data.length, multicastAddress, multicastPort); multicastSocket.send(hi); } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } private void unicast(String msg, String host) { if (logger.isInfoEnabled()) { logger.info("Send unicast message: " + msg + " to " + host + ":" + multicastPort); } try { byte[] data = (msg + "\n").getBytes(); DatagramPacket hi = new DatagramPacket(data, data.length, InetAddress.getByName(host), multicastPort); multicastSocket.send(hi); } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override public void doRegister(URL url) { multicast(REGISTER + " " + url.toFullString()); } @Override public void doUnregister(URL url) { multicast(UNREGISTER + " " + url.toFullString()); } @Override public void doSubscribe(URL url, final NotifyListener listener) { if (ANY_VALUE.equals(url.getServiceInterface())) { admin = true; } multicast(SUBSCRIBE + " " + url.toFullString()); synchronized (listener) { try { listener.wait(url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT)); } catch (InterruptedException e) { } } } @Override public void doUnsubscribe(URL url, NotifyListener listener) { if (!ANY_VALUE.equals(url.getServiceInterface()) && url.getParameter(REGISTER_KEY, true)) { unregister(url); } multicast(UNSUBSCRIBE + " " + url.toFullString()); } @Override public boolean isAvailable() { try { return multicastSocket != null; } catch (Throwable t) { return false; } } /** * Remove the expired providers(if clean is true), leave the multicast group and close the multicast socket. */ @Override public void destroy() { super.destroy(); try { ExecutorUtil.cancelScheduledFuture(cleanFuture); } catch (Throwable t) { logger.warn(REGISTRY_SOCKET_EXCEPTION, "", "", t.getMessage(), t); } try { multicastSocket.leaveGroup(multicastAddress); multicastSocket.close(); } catch (Throwable t) { logger.warn(REGISTRY_SOCKET_EXCEPTION, "", "", t.getMessage(), t); } ExecutorUtil.gracefulShutdown(cleanExecutor, cleanPeriod); } protected void registered(URL url) { for (Map.Entry<URL, Set<NotifyListener>> entry : getSubscribed().entrySet()) { URL key = entry.getKey(); if (UrlUtils.isMatch(key, url)) { Set<URL> urls = received.computeIfAbsent(key, k -> new ConcurrentHashSet<>()); urls.add(url); List<URL> list = toList(urls); for (final NotifyListener listener : entry.getValue()) { notify(key, listener, list); synchronized (listener) { listener.notify(); } } } } } protected void unregistered(URL url) { for (Map.Entry<URL, Set<NotifyListener>> entry : getSubscribed().entrySet()) { URL key = entry.getKey(); if (UrlUtils.isMatch(key, url)) { Set<URL> urls = received.get(key); if (urls != null) { urls.remove(url); } if (urls == null || urls.isEmpty()) { if (urls == null) { urls = new ConcurrentHashSet<URL>(); } URL empty = url.setProtocol(EMPTY_PROTOCOL); urls.add(empty); } List<URL> list = toList(urls); for (NotifyListener listener : entry.getValue()) { notify(key, listener, list); } } } } protected void subscribed(URL url, NotifyListener listener) { List<URL> urls = lookup(url); notify(url, listener, urls); } private List<URL> toList(Set<URL> urls) { List<URL> list = new ArrayList<URL>(); if (CollectionUtils.isNotEmpty(urls)) { list.addAll(urls); } return list; } @Override public void register(URL url) { super.register(url); registered(url); } @Override public void unregister(URL url) { super.unregister(url); unregistered(url); } @Override public void subscribe(URL url, NotifyListener listener) { super.subscribe(url, listener); subscribed(url, listener); } @Override public void unsubscribe(URL url, NotifyListener listener) { super.unsubscribe(url, listener); received.remove(url); } @Override public List<URL> lookup(URL url) { List<URL> urls = new ArrayList<>(); Map<String, List<URL>> notifiedUrls = getNotified().get(url); if (notifiedUrls != null && notifiedUrls.size() > 0) { for (List<URL> values : notifiedUrls.values()) { urls.addAll(values); } } if (urls.isEmpty()) { List<URL> cacheUrls = getCacheUrls(url); if (CollectionUtils.isNotEmpty(cacheUrls)) { urls.addAll(cacheUrls); } } if (urls.isEmpty()) { for (URL u : getRegistered()) { if (UrlUtils.isMatch(url, u)) { urls.add(u); } } } if (ANY_VALUE.equals(url.getServiceInterface())) { for (URL u : getSubscribed().keySet()) { if (UrlUtils.isMatch(url, u)) { urls.add(u); } } } return urls; } public MulticastSocket getMulticastSocket() { return multicastSocket; } public Map<URL, Set<URL>> getReceived() { return received; } }
5,383
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosRegistryFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Test for NacosRegistryFactory */ class NacosRegistryFactoryTest { private NacosRegistryFactory nacosRegistryFactory; @BeforeEach public void setup() { nacosRegistryFactory = new NacosRegistryFactory(); } @AfterEach public void teardown() {} @Test void testCreateRegistryCacheKey() { URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":8080?nacos.check=false"); String registryCacheKey1 = nacosRegistryFactory.createRegistryCacheKey(url); String registryCacheKey2 = nacosRegistryFactory.createRegistryCacheKey(url); Assertions.assertEquals(registryCacheKey1, registryCacheKey2); } @Test void testCreateRegistryCacheKeyWithNamespace() { URL url = URL.valueOf( "dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":8080?namespace=test&nacos.check=false"); String registryCacheKey1 = nacosRegistryFactory.createRegistryCacheKey(url); String registryCacheKey2 = nacosRegistryFactory.createRegistryCacheKey(url); Assertions.assertEquals(registryCacheKey1, registryCacheKey2); } }
5,384
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.rpc.model.ApplicationModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Test for NacosServiceDiscoveryFactory */ class NacosServiceDiscoveryFactoryTest { private NacosServiceDiscoveryFactory nacosServiceDiscoveryFactory; @BeforeEach public void setup() { nacosServiceDiscoveryFactory = new NacosServiceDiscoveryFactory(); ApplicationModel applicationModel = ApplicationModel.defaultModel(); applicationModel .getApplicationConfigManager() .setApplication(new ApplicationConfig("NacosServiceDiscoveryFactoryTest")); nacosServiceDiscoveryFactory.setApplicationModel(applicationModel); } @Test void testGetServiceDiscoveryWithCache() { URL url = URL.valueOf("dubbo://test:8080?nacos.check=false"); ServiceDiscovery discovery = nacosServiceDiscoveryFactory.createDiscovery(url); Assertions.assertTrue(discovery instanceof NacosServiceDiscovery); } }
5,385
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/MockNamingService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.nacos; import java.util.List; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; import com.alibaba.nacos.api.selector.AbstractSelector; public class MockNamingService implements NamingService { @Override public void registerInstance(String serviceName, String ip, int port) {} @Override public void registerInstance(String serviceName, String groupName, String ip, int port) {} @Override public void registerInstance(String serviceName, String ip, int port, String clusterName) {} @Override public void registerInstance(String serviceName, String groupName, String ip, int port, String clusterName) {} @Override public void registerInstance(String serviceName, Instance instance) {} @Override public void registerInstance(String serviceName, String groupName, Instance instance) throws NacosException {} @Override public void batchRegisterInstance(String serviceName, String groupName, List<Instance> instances) {} @Override public void deregisterInstance(String serviceName, String ip, int port) {} @Override public void deregisterInstance(String serviceName, String groupName, String ip, int port) {} @Override public void deregisterInstance(String serviceName, String ip, int port, String clusterName) {} @Override public void deregisterInstance(String serviceName, String groupName, String ip, int port, String clusterName) {} @Override public void deregisterInstance(String serviceName, Instance instance) {} @Override public void deregisterInstance(String serviceName, String groupName, Instance instance) {} @Override public void batchDeregisterInstance(String s, String s1, List<Instance> list) throws NacosException {} @Override public List<Instance> getAllInstances(String serviceName) { return null; } @Override public List<Instance> getAllInstances(String serviceName, String groupName) throws NacosException { return null; } @Override public List<Instance> getAllInstances(String serviceName, boolean subscribe) throws NacosException { return null; } @Override public List<Instance> getAllInstances(String serviceName, String groupName, boolean subscribe) { return null; } @Override public List<Instance> getAllInstances(String serviceName, List<String> clusters) { return null; } @Override public List<Instance> getAllInstances(String serviceName, String groupName, List<String> clusters) { return null; } @Override public List<Instance> getAllInstances(String serviceName, List<String> clusters, boolean subscribe) { return null; } @Override public List<Instance> getAllInstances( String serviceName, String groupName, List<String> clusters, boolean subscribe) { return null; } @Override public List<Instance> selectInstances(String serviceName, boolean healthy) { return null; } @Override public List<Instance> selectInstances(String serviceName, String groupName, boolean healthy) { return null; } @Override public List<Instance> selectInstances(String serviceName, boolean healthy, boolean subscribe) { return null; } @Override public List<Instance> selectInstances(String serviceName, String groupName, boolean healthy, boolean subscribe) { return null; } @Override public List<Instance> selectInstances(String serviceName, List<String> clusters, boolean healthy) { return null; } @Override public List<Instance> selectInstances( String serviceName, String groupName, List<String> clusters, boolean healthy) { return null; } @Override public List<Instance> selectInstances( String serviceName, List<String> clusters, boolean healthy, boolean subscribe) { return null; } @Override public List<Instance> selectInstances( String serviceName, String groupName, List<String> clusters, boolean healthy, boolean subscribe) { return null; } @Override public Instance selectOneHealthyInstance(String serviceName) { return null; } @Override public Instance selectOneHealthyInstance(String serviceName, String groupName) { return null; } @Override public Instance selectOneHealthyInstance(String serviceName, boolean subscribe) { return null; } @Override public Instance selectOneHealthyInstance(String serviceName, String groupName, boolean subscribe) { return null; } @Override public Instance selectOneHealthyInstance(String serviceName, List<String> clusters) { return null; } @Override public Instance selectOneHealthyInstance(String serviceName, String groupName, List<String> clusters) { return null; } @Override public Instance selectOneHealthyInstance(String serviceName, List<String> clusters, boolean subscribe) { return null; } @Override public Instance selectOneHealthyInstance( String serviceName, String groupName, List<String> clusters, boolean subscribe) { return null; } @Override public void subscribe(String serviceName, EventListener listener) throws NacosException {} @Override public void subscribe(String serviceName, String groupName, EventListener listener) throws NacosException {} @Override public void subscribe(String serviceName, List<String> clusters, EventListener listener) throws NacosException {} @Override public void subscribe(String serviceName, String groupName, List<String> clusters, EventListener listener) throws NacosException {} @Override public void unsubscribe(String serviceName, EventListener listener) {} @Override public void unsubscribe(String serviceName, String groupName, EventListener listener) {} @Override public void unsubscribe(String serviceName, List<String> clusters, EventListener listener) {} @Override public void unsubscribe(String serviceName, String groupName, List<String> clusters, EventListener listener) {} @Override public ListView<String> getServicesOfServer(int pageNo, int pageSize) { return null; } @Override public ListView<String> getServicesOfServer(int pageNo, int pageSize, String groupName) { return null; } @Override public ListView<String> getServicesOfServer(int pageNo, int pageSize, AbstractSelector selector) { return null; } @Override public ListView<String> getServicesOfServer(int pageNo, int pageSize, String groupName, AbstractSelector selector) { return null; } @Override public List<ServiceInfo> getSubscribeServices() { return null; } @Override public String getServerStatus() { return null; } @Override public void shutDown() {} }
5,386
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosRegistryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.registry.NotifyListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import com.alibaba.nacos.client.naming.NacosNamingService; 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 static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Test for NacosRegistry */ class NacosRegistryTest { private static final String serviceInterface = "org.apache.dubbo.registry.nacos.NacosService"; private final URL serviceUrl = URL.valueOf("nacos://127.0.0.1:3333/" + serviceInterface + "?interface=" + serviceInterface + "&notify=false&methods=test1,test2&category=providers&version=1.0.0&group=default&side=provider"); private NacosRegistryFactory nacosRegistryFactory; private NacosRegistry nacosRegistry; private URL registryUrl; @BeforeEach public void setUp() throws Exception { int nacosServerPort = NetUtils.getAvailablePort(); this.registryUrl = URL.valueOf("nacos://localhost:" + nacosServerPort + "?nacos.check=false"); this.nacosRegistryFactory = new NacosRegistryFactory(); this.nacosRegistry = (NacosRegistry) nacosRegistryFactory.createRegistry(registryUrl); } @AfterEach public void tearDown() throws Exception {} @Test void testRegister() { NamingService namingService = mock(NacosNamingService.class); try { String serviceName = "providers:org.apache.dubbo.registry.nacos.NacosService:1.0.0:default"; String category = this.serviceUrl.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); URL newUrl = this.serviceUrl.addParameter(CATEGORY_KEY, category); newUrl = newUrl.addParameter(PROTOCOL_KEY, this.serviceUrl.getProtocol()); newUrl = newUrl.addParameter(PATH_KEY, this.serviceUrl.getPath()); String ip = newUrl.getHost(); int port = newUrl.getPort(); Instance instance = new Instance(); instance.setIp(ip); instance.setPort(port); instance.setMetadata(new HashMap<>(newUrl.getParameters())); doNothing().when(namingService).registerInstance(serviceName, Constants.DEFAULT_GROUP, instance); } catch (NacosException e) { // ignore } NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); nacosRegistry = new NacosRegistry(this.registryUrl, nacosNamingServiceWrapper); Set<URL> registered; for (int i = 0; i < 2; i++) { nacosRegistry.register(serviceUrl); registered = nacosRegistry.getRegistered(); assertThat(registered.contains(serviceUrl), is(true)); } registered = nacosRegistry.getRegistered(); Assertions.assertEquals(1, registered.size()); } @Test void testUnRegister() { NamingService namingService = mock(NacosNamingService.class); try { String serviceName = "providers:org.apache.dubbo.registry.nacos.NacosService:1.0.0:default"; String category = this.serviceUrl.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); URL newUrl = this.serviceUrl.addParameter(CATEGORY_KEY, category); newUrl = newUrl.addParameter(PROTOCOL_KEY, this.serviceUrl.getProtocol()); newUrl = newUrl.addParameter(PATH_KEY, this.serviceUrl.getPath()); String ip = newUrl.getHost(); int port = newUrl.getPort(); Instance instance = new Instance(); instance.setIp(ip); instance.setPort(port); instance.setMetadata(new HashMap<>(newUrl.getParameters())); doNothing().when(namingService).registerInstance(serviceName, Constants.DEFAULT_GROUP, instance); doNothing().when(namingService).deregisterInstance(serviceName, Constants.DEFAULT_GROUP, ip, port); } catch (NacosException e) { // ignore } NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); nacosRegistry = new NacosRegistry(this.registryUrl, nacosNamingServiceWrapper); nacosRegistry.register(serviceUrl); Set<URL> registered = nacosRegistry.getRegistered(); assertThat(registered.contains(serviceUrl), is(true)); Assertions.assertEquals(1, registered.size()); nacosRegistry.unregister(serviceUrl); Assertions.assertFalse(registered.contains(serviceUrl)); Assertions.assertEquals(0, registered.size()); } @Test void testSubscribe() { NamingService namingService = mock(NacosNamingService.class); try { String serviceName = "providers:org.apache.dubbo.registry.nacos.NacosService:1.0.0:default"; String category = this.serviceUrl.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); URL newUrl = this.serviceUrl.addParameter(CATEGORY_KEY, category); newUrl = newUrl.addParameter(PROTOCOL_KEY, this.serviceUrl.getProtocol()); newUrl = newUrl.addParameter(PATH_KEY, this.serviceUrl.getPath()); String ip = newUrl.getHost(); int port = newUrl.getPort(); Instance instance = new Instance(); instance.setIp(ip); instance.setPort(port); instance.setMetadata(new HashMap<>(newUrl.getParameters())); List<Instance> instances = new ArrayList<>(); instances.add(instance); when(namingService.getAllInstances( serviceName, this.registryUrl.getParameter(GROUP_KEY, Constants.DEFAULT_GROUP))) .thenReturn(instances); } catch (NacosException e) { // ignore } NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); nacosRegistry = new NacosRegistry(this.registryUrl, nacosNamingServiceWrapper); NotifyListener listener = mock(NotifyListener.class); nacosRegistry.subscribe(serviceUrl, listener); Map<URL, Set<NotifyListener>> subscribed = nacosRegistry.getSubscribed(); Assertions.assertEquals(1, subscribed.size()); Assertions.assertEquals(1, subscribed.get(serviceUrl).size()); } @Test void testUnSubscribe() { NamingService namingService = mock(NacosNamingService.class); try { String serviceName = "providers:org.apache.dubbo.registry.nacos.NacosService:1.0.0:default"; String category = this.serviceUrl.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); URL newUrl = this.serviceUrl.addParameter(CATEGORY_KEY, category); newUrl = newUrl.addParameter(PROTOCOL_KEY, this.serviceUrl.getProtocol()); newUrl = newUrl.addParameter(PATH_KEY, this.serviceUrl.getPath()); String ip = newUrl.getHost(); int port = newUrl.getPort(); Instance instance = new Instance(); instance.setIp(ip); instance.setPort(port); instance.setMetadata(new HashMap<>(newUrl.getParameters())); List<Instance> instances = new ArrayList<>(); instances.add(instance); when(namingService.getAllInstances( serviceName, this.registryUrl.getParameter(GROUP_KEY, Constants.DEFAULT_GROUP))) .thenReturn(instances); } catch (NacosException e) { // ignore } NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); nacosRegistry = new NacosRegistry(this.registryUrl, nacosNamingServiceWrapper); NotifyListener listener = mock(NotifyListener.class); nacosRegistry.subscribe(serviceUrl, listener); Map<URL, Set<NotifyListener>> subscribed = nacosRegistry.getSubscribed(); Assertions.assertEquals(1, subscribed.size()); Assertions.assertEquals(1, subscribed.get(serviceUrl).size()); nacosRegistry.unsubscribe(serviceUrl, listener); subscribed = nacosRegistry.getSubscribed(); Assertions.assertEquals(1, subscribed.size()); Assertions.assertEquals(0, subscribed.get(serviceUrl).size()); } @Test void testIsConformRules() { NamingService namingService = mock(NacosNamingService.class); URL serviceUrlWithoutCategory = URL.valueOf("nacos://127.0.0.1:3333/" + serviceInterface + "?interface=" + serviceInterface + "&notify=false&methods=test1,test2&version=1.0.0&group=default"); try { String serviceName = "providers:org.apache.dubbo.registry.nacos.NacosService:1.0.0:default"; String category = this.serviceUrl.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); URL newUrl = this.serviceUrl.addParameter(CATEGORY_KEY, category); newUrl = newUrl.addParameter(PROTOCOL_KEY, this.serviceUrl.getProtocol()); newUrl = newUrl.addParameter(PATH_KEY, this.serviceUrl.getPath()); String ip = newUrl.getHost(); int port = newUrl.getPort(); Instance instance = new Instance(); instance.setIp(ip); instance.setPort(port); instance.setMetadata(new HashMap<>(newUrl.getParameters())); List<Instance> instances = new ArrayList<>(); instances.add(instance); when(namingService.getAllInstances( serviceName, this.registryUrl.getParameter(GROUP_KEY, Constants.DEFAULT_GROUP))) .thenReturn(instances); String serviceNameWithoutVersion = "providers:org.apache.dubbo.registry.nacos.NacosService:default"; String serviceName1 = "providers:org.apache.dubbo.registry.nacos.NacosService:1.0.0:default"; List<String> serviceNames = new ArrayList<>(); serviceNames.add(serviceNameWithoutVersion); serviceNames.add(serviceName1); ListView<String> result = new ListView<>(); result.setData(serviceNames); when(namingService.getServicesOfServer( 1, Integer.MAX_VALUE, registryUrl.getParameter(GROUP_KEY, Constants.DEFAULT_GROUP))) .thenReturn(result); } catch (NacosException e) { // ignore } NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); nacosRegistry = new NacosRegistry(this.registryUrl, nacosNamingServiceWrapper); Set<URL> registered; nacosRegistry.register(this.serviceUrl); nacosRegistry.register(serviceUrlWithoutCategory); registered = nacosRegistry.getRegistered(); Assertions.assertTrue(registered.contains(serviceUrl)); Assertions.assertTrue(registered.contains(serviceUrlWithoutCategory)); Assertions.assertEquals(2, registered.size()); URL serviceUrlWithWildcard = URL.valueOf("nacos://127.0.0.1:3333/" + serviceInterface + "?interface=org.apache.dubbo.registry.nacos.NacosService" + "&notify=false&methods=test1,test2&category=providers&version=*&group=default"); URL serviceUrlWithOutWildcard = URL.valueOf("nacos://127.0.0.1:3333/" + serviceInterface + "?interface=org.apache.dubbo.registry.nacos.NacosService" + "&notify=false&methods=test1,test2&category=providers&version=1.0.0&group=default"); NotifyListener listener = mock(NotifyListener.class); nacosRegistry.subscribe(serviceUrlWithWildcard, listener); nacosRegistry.subscribe(serviceUrlWithOutWildcard, listener); Map<URL, Set<NotifyListener>> subscribed = nacosRegistry.getSubscribed(); Assertions.assertEquals(2, registered.size()); Assertions.assertEquals(1, subscribed.get(serviceUrlWithOutWildcard).size()); Assertions.assertEquals(2, registered.size()); Assertions.assertEquals(1, subscribed.get(serviceUrlWithWildcard).size()); } }
5,387
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosNamingServiceWrapperTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.pojo.Instance; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class NacosNamingServiceWrapperTest { @Test void testSubscribe() throws NacosException { NacosConnectionManager connectionManager = Mockito.mock(NacosConnectionManager.class); NamingService namingService = Mockito.mock(NamingService.class); Mockito.when(connectionManager.getNamingService()).thenReturn(namingService); NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(connectionManager, 0, 0); EventListener eventListener = Mockito.mock(EventListener.class); nacosNamingServiceWrapper.subscribe("service_name", "test", eventListener); Mockito.verify(namingService, Mockito.times(1)).subscribe("service_name", "test", eventListener); nacosNamingServiceWrapper.subscribe("service_name", "test", eventListener); Mockito.verify(namingService, Mockito.times(2)).subscribe("service_name", "test", eventListener); nacosNamingServiceWrapper.unsubscribe("service_name", "test", eventListener); Mockito.verify(namingService, Mockito.times(1)).unsubscribe("service_name", "test", eventListener); nacosNamingServiceWrapper.unsubscribe("service_name", "test", eventListener); Mockito.verify(namingService, Mockito.times(1)).unsubscribe("service_name", "test", eventListener); nacosNamingServiceWrapper.unsubscribe("service_name", "mock", eventListener); Mockito.verify(namingService, Mockito.times(0)).unsubscribe("service_name", "mock", eventListener); } @Test void testSubscribeMultiManager() throws NacosException { NacosConnectionManager connectionManager = Mockito.mock(NacosConnectionManager.class); NamingService namingService1 = Mockito.mock(NamingService.class); NamingService namingService2 = Mockito.mock(NamingService.class); NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(connectionManager, 0, 0); EventListener eventListener = Mockito.mock(EventListener.class); Mockito.when(connectionManager.getNamingService()).thenReturn(namingService1); nacosNamingServiceWrapper.subscribe("service_name", "test", eventListener); Mockito.verify(namingService1, Mockito.times(1)).subscribe("service_name", "test", eventListener); Mockito.when(connectionManager.getNamingService()).thenReturn(namingService2); nacosNamingServiceWrapper.subscribe("service_name", "test", eventListener); Mockito.verify(namingService1, Mockito.times(2)).subscribe("service_name", "test", eventListener); nacosNamingServiceWrapper.unsubscribe("service_name", "test", eventListener); Mockito.verify(namingService1, Mockito.times(1)).unsubscribe("service_name", "test", eventListener); nacosNamingServiceWrapper.unsubscribe("service_name", "test", eventListener); Mockito.verify(namingService1, Mockito.times(1)).unsubscribe("service_name", "test", eventListener); nacosNamingServiceWrapper.unsubscribe("service_name", "mock", eventListener); Mockito.verify(namingService1, Mockito.times(0)).unsubscribe("service_name", "mock", eventListener); Mockito.verify(namingService2, Mockito.times(0)).unsubscribe("service_name", "mock", eventListener); } @Test void testRegisterNacos2_0_x() throws NacosException { List<NamingService> namingServiceList = new LinkedList<>(); NacosConnectionManager nacosConnectionManager = new NacosConnectionManager(URL.valueOf(""), false, 0, 0) { @Override protected NamingService createNamingService() { NamingService namingService = Mockito.mock(NamingService.class); namingServiceList.add(namingService); return namingService; } }; Assertions.assertEquals(1, namingServiceList.size()); NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(nacosConnectionManager, false, 0, 0); Instance instance1 = new Instance(); instance1.setIp("ip1"); instance1.setPort(1); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)).registerInstance("service_name", "test", instance1); Instance instance2 = new Instance(); instance2.setIp("ip2"); instance2.setPort(2); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(2, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)).registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(1), Mockito.times(1)).registerInstance("service_name", "test", instance2); Instance instance3 = new Instance(); instance3.setIp("ip3"); instance3.setPort(3); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance3); Assertions.assertEquals(3, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)).registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(1), Mockito.times(1)).registerInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(2), Mockito.times(1)).registerInstance("service_name", "test", instance3); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .deregisterInstance("service_name", "test", instance1); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(1), Mockito.times(1)) .deregisterInstance("service_name", "test", instance2); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); Mockito.verify(namingServiceList.get(2), Mockito.times(1)) .deregisterInstance("service_name", "test", instance3); } @Test void testRegisterNacos2_1_xClient2_0_xServer() throws NacosException { List<NamingService> namingServiceList = new LinkedList<>(); NacosConnectionManager nacosConnectionManager = new NacosConnectionManager(URL.valueOf(""), false, 0, 0) { @Override protected NamingService createNamingService() { NamingService namingService = Mockito.mock(NamingService.class); try { Mockito.doThrow(new NacosException()) .when(namingService) .batchRegisterInstance(Mockito.anyString(), Mockito.anyString(), Mockito.any(List.class)); } catch (NacosException e) { throw new RuntimeException(e); } namingServiceList.add(namingService); return namingService; } }; Assertions.assertEquals(1, namingServiceList.size()); NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(nacosConnectionManager, true, 0, 0); Instance instance1 = new Instance(); instance1.setIp("ip1"); instance1.setPort(1); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)).registerInstance("service_name", "test", instance1); Instance instance2 = new Instance(); instance2.setIp("ip2"); instance2.setPort(2); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(2, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)).registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(1), Mockito.times(1)).registerInstance("service_name", "test", instance2); Instance instance3 = new Instance(); instance3.setIp("ip3"); instance3.setPort(3); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance3); Assertions.assertEquals(3, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)).registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(1), Mockito.times(1)).registerInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(2), Mockito.times(1)).registerInstance("service_name", "test", instance3); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .deregisterInstance("service_name", "test", instance1); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(1), Mockito.times(1)) .deregisterInstance("service_name", "test", instance2); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .registerInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.any()); Mockito.verify(namingServiceList.get(1), Mockito.times(2)) .registerInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.any()); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .deregisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.any()); Mockito.verify(namingServiceList.get(1), Mockito.times(2)) .deregisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.any()); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); Mockito.verify(namingServiceList.get(2), Mockito.times(1)) .deregisterInstance("service_name", "test", instance3); } @Test void testRegisterNacos2_1_xClient2_1_xServer() throws NacosException { List<NamingService> namingServiceList = new LinkedList<>(); NacosConnectionManager nacosConnectionManager = new NacosConnectionManager(URL.valueOf(""), false, 0, 0) { @Override protected NamingService createNamingService() { NamingService namingService = Mockito.mock(NamingService.class); namingServiceList.add(namingService); return namingService; } }; Assertions.assertEquals(1, namingServiceList.size()); NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(nacosConnectionManager, true, 0, 0); Instance instance1 = new Instance(); instance1.setIp("ip1"); instance1.setPort(1); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)).registerInstance("service_name", "test", instance1); Instance instance2 = new Instance(); instance2.setIp("ip2"); instance2.setPort(2); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2)))); Instance instance3 = new Instance(); instance3.setIp("ip3"); instance3.setPort(3); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance3); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .deregisterInstance("service_name", "test", instance3); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .deregisterInstance("service_name", "test", instance3); // rerun nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(2)).registerInstance("service_name", "test", instance1); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance3); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(0), Mockito.times(3)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(0), Mockito.times(4)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .deregisterInstance("service_name", "test", instance3); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .deregisterInstance("service_name", "test", instance3); } @Test void testUnregister() throws NacosException { List<NamingService> namingServiceList = new LinkedList<>(); NacosConnectionManager nacosConnectionManager = new NacosConnectionManager(URL.valueOf(""), false, 0, 0) { @Override protected NamingService createNamingService() { NamingService namingService = Mockito.mock(NamingService.class); namingServiceList.add(namingService); return namingService; } }; Assertions.assertEquals(1, namingServiceList.size()); NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(nacosConnectionManager, true, 0, 0); Instance instance1 = new Instance(); instance1.setIp("ip1"); instance1.setPort(1); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)).registerInstance("service_name", "test", instance1); Instance instance2 = new Instance(); instance2.setIp("ip2"); instance2.setPort(2); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2)))); Instance instance3 = new Instance(); instance3.setIp("ip3"); instance3.setPort(3); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance3); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip2", 1); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip1", 2); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip1", 1); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip2", 2); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip2", 2); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip3", 3); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip3", 3); Mockito.verify(namingServiceList.get(0), Mockito.times(1)) .deregisterInstance("service_name", "test", instance3); // rerun nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Mockito.verify(namingServiceList.get(0), Mockito.times(2)).registerInstance("service_name", "test", instance1); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance3); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip1", 1); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip2", 2); Mockito.verify(namingServiceList.get(0), Mockito.times(3)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip1", 1); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip2", 2); Mockito.verify(namingServiceList.get(0), Mockito.times(4)) .batchRegisterInstance( Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip3", 3); Mockito.verify(namingServiceList.get(0), Mockito.times(2)) .deregisterInstance("service_name", "test", instance3); } @Test void testConcurrency() throws NacosException, InterruptedException { NacosConnectionManager connectionManager = Mockito.mock(NacosConnectionManager.class); CountDownLatch startLatch = new CountDownLatch(1); CountDownLatch stopLatch = new CountDownLatch(1); NamingService namingService = Mockito.mock(NamingService.class); Mockito.when(connectionManager.getNamingService()).thenReturn(namingService); NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(connectionManager, false, 0, 0); Instance instance = new Instance(); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance); NacosNamingServiceWrapper.InstancesInfo instancesInfo = nacosNamingServiceWrapper .getRegisterStatus() .get(new NacosNamingServiceWrapper.InstanceId("service_name", "test")); Assertions.assertEquals(1, instancesInfo.getInstances().size()); nacosNamingServiceWrapper .getRegisterStatus() .put( new NacosNamingServiceWrapper.InstanceId("service_name", "test"), new NacosNamingServiceWrapper.InstancesInfo() { private final NacosNamingServiceWrapper.InstancesInfo delegate = instancesInfo; @Override public void lock() { delegate.lock(); } @Override public void unlock() { delegate.unlock(); } @Override public List<NacosNamingServiceWrapper.InstanceInfo> getInstances() { try { if (startLatch.getCount() > 0) { Thread.sleep(1000); startLatch.countDown(); Thread.sleep(1000); } } catch (InterruptedException e) { throw new RuntimeException(e); } return delegate.getInstances(); } @Override public boolean isBatchRegistered() { return delegate.isBatchRegistered(); } @Override public void setBatchRegistered(boolean batchRegistered) { delegate.setBatchRegistered(batchRegistered); } @Override public boolean isValid() { return delegate.isValid(); } @Override public void setValid(boolean valid) { delegate.setValid(valid); } }); new Thread(() -> { try { startLatch.await(); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance); stopLatch.countDown(); } catch (Exception e) { throw new RuntimeException(e); } }) .start(); new Thread(() -> { try { nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance); } catch (NacosException e) { throw new RuntimeException(e); } }) .start(); stopLatch.await(); NacosNamingServiceWrapper.InstancesInfo instancesInfoNew = nacosNamingServiceWrapper .getRegisterStatus() .get(new NacosNamingServiceWrapper.InstanceId("service_name", "test")); Assertions.assertEquals(1, instancesInfoNew.getInstances().size()); Assertions.assertNotEquals(instancesInfo, instancesInfoNew); } @Test void testSuccess() { NamingService namingService = new MockNamingService() { @Override public void registerInstance(String serviceName, String groupName, Instance instance) {} @Override public List<Instance> getAllInstances(String serviceName, String groupName) { return null; } }; NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); try { nacosNamingServiceWrapper.registerInstance("Test", "Test", null); } catch (NacosException e) { Assertions.fail(e); } try { nacosNamingServiceWrapper.getAllInstances("Test", "Test"); } catch (NacosException e) { Assertions.fail(e); } } @Test void testFailNoRetry() { NamingService namingService = new MockNamingService() { @Override public void registerInstance(String serviceName, String groupName, Instance instance) throws NacosException { throw new NacosException(); } @Override public List<Instance> getAllInstances(String serviceName, String groupName) throws NacosException { throw new NacosException(); } }; NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); Assertions.assertThrows( NacosException.class, () -> nacosNamingServiceWrapper.registerInstance("Test", "Test", null)); Assertions.assertThrows(NacosException.class, () -> nacosNamingServiceWrapper.getAllInstances("Test", "Test")); } @Test void testFailRetry() { NamingService namingService = new MockNamingService() { private final AtomicInteger count1 = new AtomicInteger(0); private final AtomicInteger count2 = new AtomicInteger(0); @Override public void registerInstance(String serviceName, String groupName, Instance instance) throws NacosException { if (count1.incrementAndGet() < 10) { throw new NacosException(); } } @Override public List<Instance> getAllInstances(String serviceName, String groupName) throws NacosException { if (count2.incrementAndGet() < 10) { throw new NacosException(); } return null; } }; NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 5, 10); Assertions.assertThrows( NacosException.class, () -> nacosNamingServiceWrapper.registerInstance("Test", "Test", null)); try { nacosNamingServiceWrapper.registerInstance("Test", "Test", null); } catch (NacosException e) { Assertions.fail(e); } Assertions.assertThrows(NacosException.class, () -> nacosNamingServiceWrapper.getAllInstances("Test", "Test")); try { nacosNamingServiceWrapper.getAllInstances("Test", "Test"); } catch (NacosException e) { Assertions.fail(e); } } }
5,388
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Set; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.internal.util.collections.Sets; import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Test for NacosServiceDiscovery */ class NacosServiceDiscoveryTest { private static final String SERVICE_NAME = "NACOS_SERVICE"; private static final String LOCALHOST = "127.0.0.1"; protected URL registryUrl = URL.valueOf("nacos://127.0.0.1:" + NetUtils.getAvailablePort() + "?nacos.check=false"); private NacosServiceDiscovery nacosServiceDiscovery; private NacosNamingServiceWrapper namingServiceWrapper; protected String group = DEFAULT_GROUP; private DefaultServiceInstance createServiceInstance(String serviceName, String host, int port) { return new DefaultServiceInstance( serviceName, host, port, ScopeModelUtil.getApplicationModel(registryUrl.getScopeModel())); } public static class NacosServiceDiscoveryGroupTest1 extends NacosServiceDiscoveryTest { public NacosServiceDiscoveryGroupTest1() { super(); group = "test-group1"; registryUrl = URL.valueOf("nacos://127.0.0.1:" + NetUtils.getAvailablePort() + "?nacos.check=false") .addParameter("group", group); } } public static class NacosServiceDiscoveryGroupTest2 extends NacosServiceDiscoveryTest { public NacosServiceDiscoveryGroupTest2() { super(); group = "test-group2"; registryUrl = URL.valueOf("nacos://127.0.0.1:" + NetUtils.getAvailablePort() + "?nacos.check=false") .addParameter("group", group); } } public static class NacosServiceDiscoveryGroupTest3 extends NacosServiceDiscoveryTest { public NacosServiceDiscoveryGroupTest3() { super(); group = DEFAULT_GROUP; registryUrl = URL.valueOf("nacos://127.0.0.1:" + NetUtils.getAvailablePort() + "?nacos.check=false") .addParameter("group", "test-group3"); } @BeforeAll public static void beforeClass() { System.setProperty("dubbo.nacos-service-discovery.use-default-group", "true"); } @AfterAll public static void afterClass() { System.clearProperty("dubbo.nacos-service-discovery.use-default-group"); } } @BeforeEach public void init() throws Exception { ApplicationModel applicationModel = ApplicationModel.defaultModel(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig(SERVICE_NAME)); registryUrl.setScopeModel(applicationModel); // this.nacosServiceDiscovery = new NacosServiceDiscovery(SERVICE_NAME, registryUrl); this.nacosServiceDiscovery = new NacosServiceDiscovery(applicationModel, registryUrl); Field namingService = nacosServiceDiscovery.getClass().getDeclaredField("namingService"); namingService.setAccessible(true); namingServiceWrapper = mock(NacosNamingServiceWrapper.class); namingService.set(nacosServiceDiscovery, namingServiceWrapper); } @AfterEach public void destroy() throws Exception { nacosServiceDiscovery.destroy(); } @Test void testDoRegister() throws NacosException { DefaultServiceInstance serviceInstance = createServiceInstance(SERVICE_NAME, LOCALHOST, NetUtils.getAvailablePort()); // register nacosServiceDiscovery.doRegister(serviceInstance); ArgumentCaptor<Instance> instanceCaptor = ArgumentCaptor.forClass(Instance.class); verify(namingServiceWrapper, times(1)).registerInstance(any(), eq(group), instanceCaptor.capture()); Instance capture = instanceCaptor.getValue(); assertEquals(SERVICE_NAME, capture.getServiceName()); assertEquals(LOCALHOST, capture.getIp()); assertEquals(serviceInstance.getPort(), capture.getPort()); } @Test void testDoUnRegister() throws NacosException { // register DefaultServiceInstance serviceInstance = createServiceInstance(SERVICE_NAME, LOCALHOST, NetUtils.getAvailablePort()); // register nacosServiceDiscovery.doRegister(serviceInstance); // unRegister nacosServiceDiscovery.doUnregister(serviceInstance); ArgumentCaptor<Instance> instanceCaptor = ArgumentCaptor.forClass(Instance.class); verify(namingServiceWrapper, times(1)).deregisterInstance(any(), eq(group), instanceCaptor.capture()); Instance capture = instanceCaptor.getValue(); assertEquals(SERVICE_NAME, capture.getServiceName()); assertEquals(LOCALHOST, capture.getIp()); assertEquals(serviceInstance.getPort(), capture.getPort()); } @Test void testGetServices() throws NacosException { DefaultServiceInstance serviceInstance = createServiceInstance(SERVICE_NAME, LOCALHOST, NetUtils.getAvailablePort()); // register nacosServiceDiscovery.doRegister(serviceInstance); ArgumentCaptor<Instance> instance = ArgumentCaptor.forClass(Instance.class); verify(namingServiceWrapper, times(1)).registerInstance(any(), eq(group), instance.capture()); String serviceNameWithoutVersion = "providers:org.apache.dubbo.registry.nacos.NacosService:default"; String serviceName = "providers:org.apache.dubbo.registry.nacos.NacosService:1.0.0:default"; List<String> serviceNames = new ArrayList<>(); serviceNames.add(serviceNameWithoutVersion); serviceNames.add(serviceName); ListView<String> result = new ListView<>(); result.setData(serviceNames); when(namingServiceWrapper.getServicesOfServer(anyInt(), anyInt(), eq(group))) .thenReturn(result); Set<String> services = nacosServiceDiscovery.getServices(); assertEquals(2, services.size()); } @Test void testAddServiceInstancesChangedListener() { List<ServiceInstance> serviceInstances = new LinkedList<>(); // Add Listener nacosServiceDiscovery.addServiceInstancesChangedListener( new ServiceInstancesChangedListener(Sets.newSet(SERVICE_NAME), nacosServiceDiscovery) { @Override public void onEvent(ServiceInstancesChangedEvent event) { serviceInstances.addAll(event.getServiceInstances()); } }); nacosServiceDiscovery.register(); nacosServiceDiscovery.update(); nacosServiceDiscovery.unregister(); assertTrue(serviceInstances.isEmpty()); } }
5,389
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosConnectionsManagerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; 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; public class NacosConnectionsManagerTest { @Test public void testGet() { NamingService namingService = Mockito.mock(NamingService.class); NacosConnectionManager nacosConnectionManager = new NacosConnectionManager(namingService); Assertions.assertEquals(namingService, nacosConnectionManager.getNamingService()); Assertions.assertEquals(namingService, nacosConnectionManager.getNamingService()); Assertions.assertEquals(namingService, nacosConnectionManager.getNamingService()); } @Test public void testCreate() { List<NamingService> namingServiceList = new ArrayList<>(); NacosConnectionManager nacosConnectionManager = new NacosConnectionManager(URL.valueOf(""), false, 0, 0) { @Override protected NamingService createNamingService() { NamingService namingService = Mockito.mock(NamingService.class); namingServiceList.add(namingService); return namingService; } }; Assertions.assertEquals(1, namingServiceList.size()); Assertions.assertEquals(namingServiceList.get(0), nacosConnectionManager.getNamingService()); Assertions.assertEquals(namingServiceList.get(0), nacosConnectionManager.getNamingService()); Assertions.assertEquals(namingServiceList.get(0), nacosConnectionManager.getNamingService()); Assertions.assertEquals(namingServiceList.get(0), nacosConnectionManager.getNamingService()); LinkedList<NamingService> copy = new LinkedList<>(namingServiceList); Assertions.assertFalse(copy.contains(nacosConnectionManager.getNamingService(new HashSet<>(copy)))); copy = new LinkedList<>(namingServiceList); Assertions.assertFalse(copy.contains(nacosConnectionManager.getNamingService(new HashSet<>(copy)))); copy = new LinkedList<>(namingServiceList); Assertions.assertFalse(copy.contains(nacosConnectionManager.getNamingService(new HashSet<>(copy)))); copy = new LinkedList<>(namingServiceList); Assertions.assertFalse(copy.contains(nacosConnectionManager.getNamingService(new HashSet<>(copy)))); Assertions.assertEquals(5, namingServiceList.size()); copy = new LinkedList<>(namingServiceList); for (int i = 0; i < 1000; i++) { if (copy.size() == 0) { break; } copy.remove(nacosConnectionManager.getNamingService()); } Assertions.assertTrue(copy.isEmpty()); nacosConnectionManager.shutdownAll(); copy = new LinkedList<>(namingServiceList); Assertions.assertFalse(copy.contains(nacosConnectionManager.getNamingService())); } @Test void testRetryCreate() { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { AtomicInteger atomicInteger = new AtomicInteger(0); NamingService mock = new MockNamingService() { @Override public String getServerStatus() { return atomicInteger.incrementAndGet() > 10 ? UP : DOWN; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createNamingService((Properties) any())) .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848"); Assertions.assertThrows(IllegalStateException.class, () -> new NacosConnectionManager(url, true, 5, 10)); try { new NacosConnectionManager(url, true, 5, 10); } catch (Throwable t) { Assertions.fail(t); } } } @Test void testNoCheck() { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { NamingService mock = new MockNamingService() { @Override public String getServerStatus() { return DOWN; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createNamingService((Properties) any())) .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848"); try { new NacosConnectionManager(url, false, 5, 10); } catch (Throwable t) { Assertions.fail(t); } } } @Test void testDisable() { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { NamingService mock = new MockNamingService() { @Override public String getServerStatus() { return DOWN; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createNamingService((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 NacosConnectionManager(url, false, 5, 10); } catch (Throwable t) { Assertions.fail(t); } } } @Test void testRequest() { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { AtomicInteger atomicInteger = new AtomicInteger(0); NamingService mock = new MockNamingService() { @Override public List<Instance> getAllInstances(String serviceName, boolean subscribe) throws NacosException { if (atomicInteger.incrementAndGet() > 10) { return null; } else { throw new NacosException(); } } @Override public String getServerStatus() { return UP; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createNamingService((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 NacosConnectionManager(url, true, 5, 10)); try { new NacosConnectionManager(url, true, 5, 10); } catch (Throwable t) { Assertions.fail(t); } } } }
5,390
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.nacos.util; import org.apache.dubbo.common.URL; import org.apache.dubbo.metadata.report.MetadataReport; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.nacos.MockNamingService; import org.apache.dubbo.registry.nacos.NacosNamingServiceWrapper; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; 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; import static org.mockito.Mockito.mock; /** * Test for NacosNamingServiceUtils */ class NacosNamingServiceUtilsTest { private static MetadataReport metadataReport = Mockito.mock(MetadataReport.class); @Test void testToInstance() { ServiceInstance serviceInstance = mock(ServiceInstance.class); Instance instance = NacosNamingServiceUtils.toInstance(serviceInstance); Assertions.assertNotNull(instance); } @Test void testToServiceInstance() { URL registryUrl = URL.valueOf("test://test:8080/test"); Instance instance = new Instance(); instance.setServiceName("serviceName"); instance.setIp("1.1.1.1"); instance.setPort(800); instance.setWeight(2); instance.setHealthy(Boolean.TRUE); instance.setEnabled(Boolean.TRUE); Map<String, String> map = new HashMap<String, String>(); map.put("netType", "external"); map.put("version", "2.0"); instance.setMetadata(map); ServiceInstance serviceInstance = NacosNamingServiceUtils.toServiceInstance(registryUrl, instance); Assertions.assertNotNull(serviceInstance); Assertions.assertEquals(serviceInstance.isEnabled(), Boolean.TRUE); Assertions.assertEquals(serviceInstance.getServiceName(), "serviceName"); } @Test void testCreateNamingService() { URL url = URL.valueOf("test://test:8080/test?backup=backup&nacos.check=false"); NacosNamingServiceWrapper namingService = NacosNamingServiceUtils.createNamingService(url); Assertions.assertNotNull(namingService); } @Test void testRetryCreate() throws NacosException { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { AtomicInteger atomicInteger = new AtomicInteger(0); NamingService mock = new MockNamingService() { @Override public String getServerStatus() { return atomicInteger.incrementAndGet() > 10 ? UP : DOWN; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createNamingService((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, () -> NacosNamingServiceUtils.createNamingService(url)); try { NacosNamingServiceUtils.createNamingService(url); } catch (Throwable t) { Assertions.fail(t); } } } @Test void testDisable() { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { NamingService mock = new MockNamingService() { @Override public String getServerStatus() { return DOWN; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createNamingService((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 { NacosNamingServiceUtils.createNamingService(url); } catch (Throwable t) { Assertions.fail(t); } } } @Test void testRequest() { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { AtomicInteger atomicInteger = new AtomicInteger(0); NamingService mock = new MockNamingService() { @Override public List<Instance> getAllInstances(String serviceName, boolean subscribe) throws NacosException { if (atomicInteger.incrementAndGet() > 10) { return null; } else { throw new NacosException(); } } @Override public String getServerStatus() { return UP; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createNamingService((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, () -> NacosNamingServiceUtils.createNamingService(url)); try { NacosNamingServiceUtils.createNamingService(url); } catch (Throwable t) { Assertions.fail(t); } } } }
5,391
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.function.ThrowableFunction; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.registry.client.AbstractServiceDiscovery; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.listener.Event; import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.listener.NamingEvent; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION; import static org.apache.dubbo.common.function.ThrowableConsumer.execute; import static org.apache.dubbo.metadata.RevisionResolver.EMPTY_REVISION; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getExportedServicesRevision; import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.createNamingService; import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.getGroup; import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.toInstance; import static org.apache.dubbo.rpc.RpcException.REGISTRY_EXCEPTION; /** * Nacos {@link ServiceDiscovery} implementation * * @see ServiceDiscovery * @since 2.7.5 */ public class NacosServiceDiscovery extends AbstractServiceDiscovery { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final String group; private final NacosNamingServiceWrapper namingService; private static final String NACOS_SD_USE_DEFAULT_GROUP_KEY = "dubbo.nacos-service-discovery.use-default-group"; private final ConcurrentHashMap<String, NacosEventListener> eventListeners = new ConcurrentHashMap<>(); public NacosServiceDiscovery(ApplicationModel applicationModel, URL registryURL) { super(applicationModel, registryURL); this.namingService = createNamingService(registryURL); // backward compatibility for 3.0.x this.group = Boolean.parseBoolean( ConfigurationUtils.getProperty(applicationModel, NACOS_SD_USE_DEFAULT_GROUP_KEY, "false")) ? DEFAULT_GROUP : getGroup(registryURL); } @Override public void doDestroy() throws Exception { this.namingService.shutdown(); this.eventListeners.clear(); } @Override public void doRegister(ServiceInstance serviceInstance) { execute(namingService, service -> { Instance instance = toInstance(serviceInstance); service.registerInstance(instance.getServiceName(), group, instance); }); } @Override public void doUnregister(ServiceInstance serviceInstance) throws RuntimeException { execute(namingService, service -> { Instance instance = toInstance(serviceInstance); service.deregisterInstance(instance.getServiceName(), group, instance); }); } @Override protected void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) throws RuntimeException { if (EMPTY_REVISION.equals(getExportedServicesRevision(newServiceInstance)) || EMPTY_REVISION.equals( oldServiceInstance.getMetadata().get(EXPORTED_SERVICES_REVISION_PROPERTY_NAME))) { super.doUpdate(oldServiceInstance, newServiceInstance); return; } if (!Objects.equals(newServiceInstance.getHost(), oldServiceInstance.getHost()) || !Objects.equals(newServiceInstance.getPort(), oldServiceInstance.getPort())) { // Ignore if id changed. Should unregister first. super.doUpdate(oldServiceInstance, newServiceInstance); return; } Instance oldInstance = toInstance(oldServiceInstance); Instance newInstance = toInstance(newServiceInstance); try { this.serviceInstance = newServiceInstance; reportMetadata(newServiceInstance.getServiceMetadata()); execute(namingService, service -> { Instance instance = toInstance(serviceInstance); service.updateInstance(instance.getServiceName(), group, oldInstance, newInstance); }); } catch (Exception e) { throw new RpcException(REGISTRY_EXCEPTION, "Failed register instance " + newServiceInstance.toString(), e); } } @Override public Set<String> getServices() { return ThrowableFunction.execute(namingService, service -> { ListView<String> view = service.getServicesOfServer(0, Integer.MAX_VALUE, group); return new LinkedHashSet<>(view.getData()); }); } @Override public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException { return ThrowableFunction.execute( namingService, service -> service.selectInstances(serviceName, group, true).stream() .map((i) -> NacosNamingServiceUtils.toServiceInstance(registryURL, i)) .collect(Collectors.toList())); } @Override public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener) throws NullPointerException, IllegalArgumentException { // check if listener has already been added through another interface/service if (!instanceListeners.add(listener)) { return; } for (String serviceName : listener.getServiceNames()) { NacosEventListener nacosEventListener = eventListeners.get(serviceName); if (nacosEventListener != null) { nacosEventListener.addListener(listener); } else { try { nacosEventListener = new NacosEventListener(); nacosEventListener.addListener(listener); namingService.subscribe(serviceName, group, nacosEventListener); eventListeners.put(serviceName, nacosEventListener); } catch (NacosException e) { logger.error( REGISTRY_NACOS_EXCEPTION, "", "", "add nacos service instances changed listener fail ", e); } } } } @Override public void removeServiceInstancesChangedListener(ServiceInstancesChangedListener listener) throws IllegalArgumentException { if (!instanceListeners.remove(listener)) { return; } for (String serviceName : listener.getServiceNames()) { NacosEventListener nacosEventListener = eventListeners.get(serviceName); if (nacosEventListener != null) { nacosEventListener.removeListener(listener); if (nacosEventListener.isEmpty()) { eventListeners.remove(serviceName); try { namingService.unsubscribe(serviceName, group, nacosEventListener); } catch (NacosException e) { logger.error( REGISTRY_NACOS_EXCEPTION, "", "", "remove nacos service instances changed listener fail ", e); } } } } } public class NacosEventListener implements EventListener { private final Set<ServiceInstancesChangedListener> listeners = new ConcurrentHashSet<>(); @Override public void onEvent(Event e) { if (e instanceof NamingEvent) { for (ServiceInstancesChangedListener listener : listeners) { NamingEvent event = (NamingEvent) e; handleEvent(event, listener); } } } public void addListener(ServiceInstancesChangedListener listener) { listeners.add(listener); } public void removeListener(ServiceInstancesChangedListener listener) { listeners.remove(listener); } public boolean isEmpty() { return listeners.isEmpty(); } } @Override public URL getUrl() { return registryURL; } private void handleEvent(NamingEvent event, ServiceInstancesChangedListener listener) { String serviceName = event.getServiceName(); List<ServiceInstance> serviceInstances = event.getInstances().stream() .map((i) -> NacosNamingServiceUtils.toServiceInstance(registryURL, i)) .collect(Collectors.toList()); listener.onEvent(new ServiceInstancesChangedEvent(serviceName, serviceInstances)); } }
5,392
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosConnectionManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.LoggerCodeConstants; 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.registry.nacos.util.NacosNamingServiceUtils; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import static com.alibaba.nacos.api.PropertyKeyConst.PASSWORD; import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; import static com.alibaba.nacos.api.PropertyKeyConst.USERNAME; import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP; import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; 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; public class NacosConnectionManager { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NacosNamingServiceUtils.class); private final URL connectionURL; private final List<NamingService> namingServiceList = new LinkedList<>(); private final int retryTimes; private final int sleepMsBetweenRetries; private final boolean check; public NacosConnectionManager(URL connectionURL, boolean check, int retryTimes, int sleepMsBetweenRetries) { this.connectionURL = connectionURL; this.check = check; this.retryTimes = retryTimes; this.sleepMsBetweenRetries = sleepMsBetweenRetries; // create default one this.namingServiceList.add(createNamingService()); } /** * @deprecated for ut only */ @Deprecated protected NacosConnectionManager(NamingService namingService) { this.connectionURL = null; this.retryTimes = 0; this.sleepMsBetweenRetries = 0; this.check = false; // create default one this.namingServiceList.add(namingService); } public synchronized NamingService getNamingService() { if (namingServiceList.isEmpty()) { this.namingServiceList.add(createNamingService()); } return namingServiceList.get(ThreadLocalRandom.current().nextInt(namingServiceList.size())); } public synchronized NamingService getNamingService(Set<NamingService> selected) { List<NamingService> copyOfNamingService = new LinkedList<>(namingServiceList); copyOfNamingService.removeAll(selected); if (copyOfNamingService.isEmpty()) { this.namingServiceList.add(createNamingService()); return getNamingService(selected); } return copyOfNamingService.get(ThreadLocalRandom.current().nextInt(copyOfNamingService.size())); } public synchronized void shutdownAll() { for (NamingService namingService : namingServiceList) { try { namingService.shutDown(); } catch (Exception e) { logger.warn(REGISTRY_NACOS_EXCEPTION, "", "", "Unable to shutdown nacos naming service", e); } } this.namingServiceList.clear(); } /** * Create an instance of {@link NamingService} from specified {@link URL connection url} * * @return {@link NamingService} */ protected NamingService createNamingService() { Properties nacosProperties = buildNacosProperties(this.connectionURL); NamingService namingService = null; try { for (int i = 0; i < retryTimes + 1; i++) { namingService = NacosFactory.createNamingService(nacosProperties); String serverStatus = namingService.getServerStatus(); boolean namingServiceAvailable = testNamingService(namingService); if (!check || (UP.equals(serverStatus) && namingServiceAvailable)) { break; } else { logger.warn( LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION, "", "", "Failed to connect to nacos naming server. " + "Server status: " + serverStatus + ". " + "Naming Service Available: " + namingServiceAvailable + ". " + (i < retryTimes ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " : "Exceed retry max times.") + "Try times: " + (i + 1)); } namingService.shutDown(); namingService = null; Thread.sleep(sleepMsBetweenRetries); } } catch (NacosException e) { if (logger.isErrorEnabled()) { logger.error(REGISTRY_NACOS_EXCEPTION, "", "", e.getErrMsg(), e); } } catch (InterruptedException e) { logger.error(INTERNAL_INTERRUPTED, "", "", "Interrupted when creating nacos naming service client.", e); Thread.currentThread().interrupt(); throw new IllegalStateException(e); } if (namingService == null) { logger.error( REGISTRY_NACOS_EXCEPTION, "", "", "Failed to create nacos naming service client. Reason: server status check failed."); throw new IllegalStateException( "Failed to create nacos naming service client. Reason: server status check failed."); } return namingService; } private boolean testNamingService(NamingService namingService) { try { namingService.getAllInstances("Dubbo-Nacos-Test", false); 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 (StringUtils.isNotEmpty(backup)) { serverAddrBuilder.append(',').append(backup); } String serverAddr = serverAddrBuilder.toString(); properties.put(SERVER_ADDR, serverAddr); } private void setProperties(URL url, Properties properties) { putPropertyIfAbsent(url, properties, NACOS_NAMING_LOG_NAME, null); // @since 2.7.8 : Refactoring // Get the parameters from constants Map<String, String> parameters = url.getParameters(of(PropertyKeyConst.class)); // Put all parameters properties.putAll(parameters); if (StringUtils.isNotEmpty(url.getUsername())) { properties.put(USERNAME, url.getUsername()); } if (StringUtils.isNotEmpty(url.getPassword())) { properties.put(PASSWORD, url.getPassword()); } } private void putPropertyIfAbsent(URL url, Properties properties, String propertyName, String defaultValue) { String propertyValue = url.getParameter(propertyName); if (StringUtils.isNotEmpty(propertyValue)) { properties.setProperty(propertyName, propertyValue); } else { // when defaultValue is empty, we should not set empty value if (StringUtils.isNotEmpty(defaultValue)) { properties.setProperty(propertyName, defaultValue); } } } }
5,393
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.registry.client.AbstractServiceDiscoveryFactory; import org.apache.dubbo.registry.client.ServiceDiscovery; import static org.apache.dubbo.common.constants.CommonConstants.CONFIG_NAMESPACE_KEY; public class NacosServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory { @Override protected String createRegistryCacheKey(URL url) { String namespace = url.getParameter(CONFIG_NAMESPACE_KEY); url = URL.valueOf(url.toServiceStringWithoutResolving()); if (StringUtils.isNotEmpty(namespace)) { url = url.addParameter(CONFIG_NAMESPACE_KEY, namespace); } return url.toFullString(); } @Override protected ServiceDiscovery createDiscovery(URL registryURL) { return new NacosServiceDiscovery(applicationModel, registryURL); } }
5,394
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistryFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; import org.apache.dubbo.registry.support.AbstractRegistryFactory; import static org.apache.dubbo.common.constants.CommonConstants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.createNamingService; /** * Nacos {@link RegistryFactory} * * @since 2.6.5 */ public class NacosRegistryFactory extends AbstractRegistryFactory { @Override protected String createRegistryCacheKey(URL url) { String namespace = url.getParameter(CONFIG_NAMESPACE_KEY); url = URL.valueOf(url.toServiceStringWithoutResolving()); if (StringUtils.isNotEmpty(namespace)) { url = url.addParameter(CONFIG_NAMESPACE_KEY, namespace); } return url.toFullString(); } @Override protected Registry createRegistry(URL url) { return new NacosRegistry(url, createNamingService(url)); } }
5,395
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosAggregateListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.registry.NotifyListener; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; import java.util.stream.Collectors; import com.alibaba.nacos.api.naming.pojo.Instance; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NACOS_SUB_LEGACY; public class NacosAggregateListener { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NacosAggregateListener.class); private final NotifyListener notifyListener; private final Set<String> serviceNames = new ConcurrentHashSet<>(); private final Map<String, List<Instance>> serviceInstances = new ConcurrentHashMap<>(); private final AtomicBoolean warned = new AtomicBoolean(false); private static final Pattern SPLITTED_PATTERN = Pattern.compile(".*:.*:.*:.*"); public NacosAggregateListener(NotifyListener notifyListener) { this.notifyListener = notifyListener; } public List<Instance> saveAndAggregateAllInstances(String serviceName, List<Instance> instances) { serviceNames.add(serviceName); if (instances == null) { serviceInstances.remove(serviceName); } else { serviceInstances.put(serviceName, instances); } if (isLegacyName(serviceName) && instances != null && !instances.isEmpty() && warned.compareAndSet(false, true)) { logger.error( REGISTRY_NACOS_SUB_LEGACY, "", "", "Received not empty notification for legacy service name: " + serviceName + ", " + "instances: [" + instances.stream().map(Instance::getIp).collect(Collectors.joining(" ,")) + "]. " + "Please upgrade these Dubbo client(lower than 2.7.3) to the latest version. " + "Dubbo will remove the support for legacy service name in the future."); } return serviceInstances.values().stream().flatMap(List::stream).collect(Collectors.toList()); } private static boolean isLegacyName(String serviceName) { return !SPLITTED_PATTERN.matcher(serviceName).matches(); } public NotifyListener getNotifyListener() { return notifyListener; } public Set<String> getServiceNames() { return serviceNames; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NacosAggregateListener that = (NacosAggregateListener) o; return Objects.equals(notifyListener, that.notifyListener) && Objects.equals(serviceNames, that.serviceNames) && Objects.equals(serviceInstances, that.serviceInstances); } @Override public int hashCode() { return Objects.hash(notifyListener, serviceNames, serviceInstances); } }
5,396
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosNamingServiceWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.MethodUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.registry.nacos.function.NacosConsumer; import org.apache.dubbo.registry.nacos.function.NacosFunction; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; public class NacosNamingServiceWrapper { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NacosNamingServiceWrapper.class); private static final String INNERCLASS_SYMBOL = "$"; private static final String INNERCLASS_COMPATIBLE_SYMBOL = "___"; private final NacosConnectionManager nacosConnectionManager; private final int retryTimes; private final int sleepMsBetweenRetries; private final boolean isSupportBatchRegister; private final ConcurrentMap<InstanceId, InstancesInfo> registerStatus = new ConcurrentHashMap<>(); private final ConcurrentMap<SubscribeInfo, NamingService> subscribeStatus = new ConcurrentHashMap<>(); public NacosNamingServiceWrapper( NacosConnectionManager nacosConnectionManager, int retryTimes, int sleepMsBetweenRetries) { this.nacosConnectionManager = nacosConnectionManager; this.isSupportBatchRegister = MethodUtils.findMethod( NamingService.class, "batchRegisterInstance", String.class, String.class, List.class) != null; logger.info("Nacos batch register enable: " + isSupportBatchRegister); this.retryTimes = Math.max(retryTimes, 0); this.sleepMsBetweenRetries = sleepMsBetweenRetries; } /** * @deprecated for uts only */ @Deprecated protected NacosNamingServiceWrapper( NacosConnectionManager nacosConnectionManager, boolean isSupportBatchRegister, int retryTimes, int sleepMsBetweenRetries) { this.nacosConnectionManager = nacosConnectionManager; this.isSupportBatchRegister = isSupportBatchRegister; this.retryTimes = Math.max(retryTimes, 0); this.sleepMsBetweenRetries = sleepMsBetweenRetries; } public String getServerStatus() { return nacosConnectionManager.getNamingService().getServerStatus(); } public void subscribe(String serviceName, String group, EventListener eventListener) throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); SubscribeInfo subscribeInfo = new SubscribeInfo(nacosServiceName, group, eventListener); NamingService namingService = ConcurrentHashMapUtils.computeIfAbsent( subscribeStatus, subscribeInfo, info -> nacosConnectionManager.getNamingService()); accept(() -> namingService.subscribe(nacosServiceName, group, eventListener)); } public void unsubscribe(String serviceName, String group, EventListener eventListener) throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); SubscribeInfo subscribeInfo = new SubscribeInfo(nacosServiceName, group, eventListener); NamingService namingService = subscribeStatus.get(subscribeInfo); if (namingService != null) { accept(() -> namingService.unsubscribe(nacosServiceName, group, eventListener)); subscribeStatus.remove(subscribeInfo); } } public List<Instance> getAllInstances(String serviceName, String group) throws NacosException { return apply( () -> nacosConnectionManager.getNamingService().getAllInstances(handleInnerSymbol(serviceName), group)); } public void registerInstance(String serviceName, String group, Instance instance) throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); InstancesInfo instancesInfo = ConcurrentHashMapUtils.computeIfAbsent( registerStatus, new InstanceId(nacosServiceName, group), id -> new InstancesInfo()); try { instancesInfo.lock(); if (!instancesInfo.isValid()) { registerInstance(serviceName, group, instance); return; } if (instancesInfo.getInstances().isEmpty()) { // directly register NamingService namingService = nacosConnectionManager.getNamingService(); accept(() -> namingService.registerInstance(nacosServiceName, group, instance)); instancesInfo.getInstances().add(new InstanceInfo(instance, namingService)); return; } if (instancesInfo.getInstances().size() == 1 && isSupportBatchRegister) { InstanceInfo previous = instancesInfo.getInstances().get(0); List<Instance> instanceListToRegister = new ArrayList<>(); NamingService namingService = previous.getNamingService(); instanceListToRegister.add(previous.getInstance()); instanceListToRegister.add(instance); try { accept(() -> namingService.batchRegisterInstance(nacosServiceName, group, instanceListToRegister)); instancesInfo.getInstances().add(new InstanceInfo(instance, namingService)); instancesInfo.setBatchRegistered(true); return; } catch (NacosException e) { logger.info("Failed to batch register to nacos. Service Name: " + serviceName + ". Maybe nacos server not support. Will fallback to multi connection register."); // ignore } } if (instancesInfo.isBatchRegistered()) { NamingService namingService = instancesInfo.getInstances().get(0).getNamingService(); List<Instance> instanceListToRegister = new ArrayList<>(); for (InstanceInfo instanceInfo : instancesInfo.getInstances()) { instanceListToRegister.add(instanceInfo.getInstance()); } instanceListToRegister.add(instance); accept(() -> namingService.batchRegisterInstance(nacosServiceName, group, instanceListToRegister)); instancesInfo.getInstances().add(new InstanceInfo(instance, namingService)); return; } // fallback to register one by one Set<NamingService> selectedNamingServices = instancesInfo.getInstances().stream() .map(InstanceInfo::getNamingService) .collect(Collectors.toSet()); NamingService namingService = nacosConnectionManager.getNamingService(selectedNamingServices); accept(() -> namingService.registerInstance(nacosServiceName, group, instance)); instancesInfo.getInstances().add(new InstanceInfo(instance, namingService)); } finally { instancesInfo.unlock(); } } public void updateInstance(String serviceName, String group, Instance oldInstance, Instance newInstance) throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); InstancesInfo instancesInfo = ConcurrentHashMapUtils.computeIfAbsent( registerStatus, new InstanceId(nacosServiceName, group), id -> new InstancesInfo()); try { instancesInfo.lock(); if (!instancesInfo.isValid() || instancesInfo.getInstances().isEmpty()) { throw new IllegalArgumentException(serviceName + " has not been registered to nacos."); } Optional<InstanceInfo> optional = instancesInfo.getInstances().stream() .filter(instanceInfo -> instanceInfo.getInstance().equals(oldInstance)) .findAny(); if (!optional.isPresent()) { throw new IllegalArgumentException(oldInstance + " has not been registered to nacos."); } InstanceInfo oldInstanceInfo = optional.get(); instancesInfo.getInstances().remove(oldInstanceInfo); instancesInfo.getInstances().add(new InstanceInfo(newInstance, oldInstanceInfo.getNamingService())); if (isSupportBatchRegister && instancesInfo.isBatchRegistered()) { NamingService namingService = oldInstanceInfo.getNamingService(); List<Instance> instanceListToRegister = instancesInfo.getInstances().stream() .map(InstanceInfo::getInstance) .collect(Collectors.toList()); accept(() -> namingService.batchRegisterInstance(nacosServiceName, group, instanceListToRegister)); return; } // fallback to register one by one accept(() -> oldInstanceInfo.getNamingService().registerInstance(nacosServiceName, group, newInstance)); } finally { instancesInfo.unlock(); } } public void deregisterInstance(String serviceName, String group, String ip, int port) throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); InstancesInfo instancesInfo = ConcurrentHashMapUtils.computeIfAbsent( registerStatus, new InstanceId(nacosServiceName, group), id -> new InstancesInfo()); try { instancesInfo.lock(); List<Instance> instances = instancesInfo.getInstances().stream() .map(InstanceInfo::getInstance) .filter(instance -> Objects.equals(instance.getIp(), ip) && instance.getPort() == port) .collect(Collectors.toList()); for (Instance instance : instances) { deregisterInstance(serviceName, group, instance); } } finally { instancesInfo.unlock(); } } public void deregisterInstance(String serviceName, String group, Instance instance) throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); InstancesInfo instancesInfo = ConcurrentHashMapUtils.computeIfAbsent( registerStatus, new InstanceId(nacosServiceName, group), id -> new InstancesInfo()); try { instancesInfo.lock(); Optional<InstanceInfo> optional = instancesInfo.getInstances().stream() .filter(instanceInfo -> instanceInfo.getInstance().equals(instance)) .findAny(); if (!optional.isPresent()) { return; } InstanceInfo instanceInfo = optional.get(); instancesInfo.getInstances().remove(instanceInfo); if (instancesInfo.getInstances().isEmpty()) { registerStatus.remove(new InstanceId(nacosServiceName, group)); instancesInfo.setValid(false); } // only one registered if (instancesInfo.getInstances().isEmpty()) { // directly unregister accept(() -> instanceInfo.getNamingService().deregisterInstance(nacosServiceName, group, instance)); instancesInfo.setBatchRegistered(false); return; } if (instancesInfo.isBatchRegistered()) { // register the rest instances List<Instance> instanceListToRegister = new ArrayList<>(); for (InstanceInfo info : instancesInfo.getInstances()) { instanceListToRegister.add(info.getInstance()); } accept(() -> instanceInfo .getNamingService() .batchRegisterInstance(nacosServiceName, group, instanceListToRegister)); } else { // unregister one accept(() -> instanceInfo.getNamingService().deregisterInstance(nacosServiceName, group, instance)); } } finally { instancesInfo.unlock(); } } public ListView<String> getServicesOfServer(int pageNo, int pageSize, String group) throws NacosException { return apply(() -> nacosConnectionManager.getNamingService().getServicesOfServer(pageNo, pageSize, group)); } public List<Instance> selectInstances(String serviceName, String group, boolean healthy) throws NacosException { return apply(() -> nacosConnectionManager .getNamingService() .selectInstances(handleInnerSymbol(serviceName), group, healthy)); } public void shutdown() throws NacosException { this.nacosConnectionManager.shutdownAll(); } /** * see https://github.com/apache/dubbo/issues/7129 * nacos service name just support `0-9a-zA-Z-._:`, grpc interface is inner interface, need compatible. */ private String handleInnerSymbol(String serviceName) { if (StringUtils.isEmpty(serviceName)) { return null; } return serviceName.replace(INNERCLASS_SYMBOL, INNERCLASS_COMPATIBLE_SYMBOL); } protected static class InstanceId { private final String serviceName; private final String group; public InstanceId(String serviceName, String group) { this.serviceName = serviceName; this.group = group; } public String getServiceName() { return serviceName; } public String getGroup() { return group; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InstanceId that = (InstanceId) o; return Objects.equals(serviceName, that.serviceName) && Objects.equals(group, that.group); } @Override public int hashCode() { return Objects.hash(serviceName, group); } } protected static class InstancesInfo { private final Lock lock = new ReentrantLock(); private final List<InstanceInfo> instances = new ArrayList<>(); private volatile boolean batchRegistered = false; private volatile boolean valid = true; public void lock() { lock.lock(); } public void unlock() { lock.unlock(); } public List<InstanceInfo> getInstances() { return instances; } public boolean isBatchRegistered() { return batchRegistered; } public void setBatchRegistered(boolean batchRegistered) { this.batchRegistered = batchRegistered; } public boolean isValid() { return valid; } public void setValid(boolean valid) { this.valid = valid; } } protected static class InstanceInfo { private final Instance instance; private final NamingService namingService; public InstanceInfo(Instance instance, NamingService namingService) { this.instance = instance; this.namingService = namingService; } public Instance getInstance() { return instance; } public NamingService getNamingService() { return namingService; } } private static class SubscribeInfo { private final String serviceName; private final String group; private final EventListener eventListener; public SubscribeInfo(String serviceName, String group, EventListener eventListener) { this.serviceName = serviceName; this.group = group; this.eventListener = eventListener; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubscribeInfo that = (SubscribeInfo) o; return Objects.equals(serviceName, that.serviceName) && Objects.equals(group, that.group) && Objects.equals(eventListener, that.eventListener); } @Override public int hashCode() { return Objects.hash(serviceName, group, eventListener); } } /** * @deprecated for uts only */ @Deprecated protected Map<InstanceId, InstancesInfo> getRegisterStatus() { return registerStatus; } private <R> R apply(NacosFunction<R> command) throws NacosException { NacosException le = null; R result = null; int times = 0; for (; times < retryTimes + 1; times++) { try { result = command.apply(); le = null; break; } catch (NacosException e) { le = e; logger.warn( LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION, "", "", "Failed to request nacos naming server. " + (times < retryTimes ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " : "Exceed retry max times.") + "Try times: " + (times + 1), e); if (times < retryTimes) { try { Thread.sleep(sleepMsBetweenRetries); } catch (InterruptedException ex) { logger.warn( LoggerCodeConstants.INTERNAL_INTERRUPTED, "", "", "Interrupted when waiting to retry.", ex); Thread.currentThread().interrupt(); } } } } if (le != null) { throw le; } if (times > 1) { logger.info("Failed to request nacos naming server for " + (times - 1) + " times and finally success. " + "This may caused by high stress of nacos server."); } return result; } private void accept(NacosConsumer command) throws NacosException { NacosException le = null; int times = 0; for (; times < retryTimes + 1; times++) { try { command.accept(); le = null; break; } catch (NacosException e) { le = e; logger.warn( LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION, "", "", "Failed to request nacos naming server. " + (times < retryTimes ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " : "Exceed retry max times.") + "Try times: " + (times + 1), e); if (times < retryTimes) { try { Thread.sleep(sleepMsBetweenRetries); } catch (InterruptedException ex) { logger.warn( LoggerCodeConstants.INTERNAL_INTERRUPTED, "", "", "Interrupted when waiting to retry.", ex); Thread.currentThread().interrupt(); } } } } if (le != null) { throw le; } if (times > 1) { logger.info("Failed to request nacos naming server for " + (times - 1) + " times and finally success. " + "This may caused by high stress of nacos server."); } } }
5,397
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.url.component.DubboServiceAddressURL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryNotifier; import org.apache.dubbo.registry.support.FailbackRegistry; import org.apache.dubbo.registry.support.SkipFailbackWrapperException; import org.apache.dubbo.rpc.RpcException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; 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 java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.listener.Event; import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.listener.NamingEvent; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_ENABLE_EMPTY_PROTECTION; import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.ENABLE_EMPTY_PROTECTION_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_CONSUMER_URL_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; import static org.apache.dubbo.registry.Constants.ADMIN_PROTOCOL; import static org.apache.dubbo.registry.nacos.NacosServiceName.NAME_SEPARATOR; import static org.apache.dubbo.registry.nacos.NacosServiceName.valueOf; /** * Nacos {@link Registry} * * @see #SERVICE_NAME_SEPARATOR * @see #PAGINATION_SIZE * @see #LOOKUP_INTERVAL * @since 2.6.5 */ public class NacosRegistry extends FailbackRegistry { /** * All supported categories */ private static final List<String> ALL_SUPPORTED_CATEGORIES = Arrays.asList(PROVIDERS_CATEGORY, CONSUMERS_CATEGORY, ROUTERS_CATEGORY, CONFIGURATORS_CATEGORY); private static final int CATEGORY_INDEX = 0; private static final int SERVICE_INTERFACE_INDEX = 1; private static final int SERVICE_VERSION_INDEX = 2; private static final int SERVICE_GROUP_INDEX = 3; private static final String WILDCARD = "*"; private static final String UP = "UP"; /** * The separator for service name * Change a constant to be configurable, it's designed for Windows file name that is compatible with old * Nacos binary release(< 0.6.1) */ private static final String SERVICE_NAME_SEPARATOR = System.getProperty("nacos.service.name.separator", ":"); /** * The pagination size of query for Nacos service names(only for Dubbo-OPS) */ private static final int PAGINATION_SIZE = Integer.getInteger("nacos.service.names.pagination.size", 100); /** * The interval in second of lookup Nacos service names(only for Dubbo-OPS) */ private static final long LOOKUP_INTERVAL = Long.getLong("nacos.service.names.lookup.interval", 30); private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NacosRegistry.class); private final NacosNamingServiceWrapper namingService; /** * {@link ScheduledExecutorService} lookup Nacos service names(only for Dubbo-OPS) */ private volatile ScheduledExecutorService scheduledExecutorService; private final Map<URL, Map<NotifyListener, NacosAggregateListener>> originToAggregateListener = new ConcurrentHashMap<>(); private final Map<URL, Map<NacosAggregateListener, Map<String, EventListener>>> nacosListeners = new ConcurrentHashMap<>(); private final boolean supportLegacyServiceName; public NacosRegistry(URL url, NacosNamingServiceWrapper namingService) { super(url); this.namingService = namingService; this.supportLegacyServiceName = url.getParameter("nacos.subscribe.legacy-name", true); } @Override public boolean isAvailable() { return UP.equals(namingService.getServerStatus()); } @Override public List<URL> lookup(final URL url) { if (url == null) { throw new IllegalArgumentException("lookup url == null"); } try { List<URL> urls = new LinkedList<>(); Set<String> serviceNames = getServiceNames(url, null); for (String serviceName : serviceNames) { List<Instance> instances = namingService.getAllInstances(serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP)); urls.addAll(buildURLs(url, instances)); } return urls; } catch (SkipFailbackWrapperException exception) { throw exception; } catch (Exception cause) { throw new RpcException( "Failed to lookup " + url + " from nacos " + getUrl() + ", cause: " + cause.getMessage(), cause); } } @Override public void doRegister(URL url) { try { if (PROVIDER_SIDE.equals(url.getSide()) || getUrl().getParameter(REGISTER_CONSUMER_URL_KEY, false)) { String serviceName = getServiceName(url); Instance instance = createInstance(url); /** * namingService.registerInstance with {@link org.apache.dubbo.registry.support.AbstractRegistry#registryUrl} * default {@link DEFAULT_GROUP} * * in https://github.com/apache/dubbo/issues/5978 */ namingService.registerInstance(serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP), instance); } else { logger.info( "Please set 'dubbo.registry.parameters.register-consumer-url=true' to turn on consumer url registration."); } } catch (SkipFailbackWrapperException exception) { throw exception; } catch (Exception cause) { throw new RpcException( "Failed to register " + url + " to nacos " + getUrl() + ", cause: " + cause.getMessage(), cause); } } @Override public void doUnregister(final URL url) { try { String serviceName = getServiceName(url); Instance instance = createInstance(url); namingService.deregisterInstance( serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP), instance.getIp(), instance.getPort()); } catch (SkipFailbackWrapperException exception) { throw exception; } catch (Exception cause) { throw new RpcException( "Failed to unregister " + url + " to nacos " + getUrl() + ", cause: " + cause.getMessage(), cause); } } @Override public void doSubscribe(final URL url, final NotifyListener listener) { NacosAggregateListener nacosAggregateListener = new NacosAggregateListener(listener); originToAggregateListener .computeIfAbsent(url, k -> new ConcurrentHashMap<>()) .put(listener, nacosAggregateListener); Set<String> serviceNames = getServiceNames(url, nacosAggregateListener); doSubscribe(url, nacosAggregateListener, serviceNames); } private void doSubscribe(final URL url, final NacosAggregateListener listener, final Set<String> serviceNames) { try { if (isServiceNamesWithCompatibleMode(url)) { /** * Get all instances with serviceNames to avoid instance overwrite and but with empty instance mentioned * in https://github.com/apache/dubbo/issues/5885 and https://github.com/apache/dubbo/issues/5899 * * namingService.getAllInstances with {@link org.apache.dubbo.registry.support.AbstractRegistry#registryUrl} * default {@link DEFAULT_GROUP} * * in https://github.com/apache/dubbo/issues/5978 */ for (String serviceName : serviceNames) { List<Instance> instances = namingService.getAllInstances(serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP)); notifySubscriber(url, serviceName, listener, instances); } for (String serviceName : serviceNames) { subscribeEventListener(serviceName, url, listener); } } else { for (String serviceName : serviceNames) { List<Instance> instances = new LinkedList<>(); instances.addAll( namingService.getAllInstances(serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP))); String serviceInterface = serviceName; String[] segments = serviceName.split(SERVICE_NAME_SEPARATOR, -1); if (segments.length == 4) { serviceInterface = segments[SERVICE_INTERFACE_INDEX]; } URL subscriberURL = url.setPath(serviceInterface) .addParameters(INTERFACE_KEY, serviceInterface, CHECK_KEY, String.valueOf(false)); notifySubscriber(subscriberURL, serviceName, listener, instances); subscribeEventListener(serviceName, subscriberURL, listener); } } } catch (SkipFailbackWrapperException exception) { throw exception; } catch (Throwable cause) { throw new RpcException( "Failed to subscribe " + url + " to nacos " + getUrl() + ", cause: " + cause.getMessage(), cause); } } /** * Since 2.7.6 the legacy service name will be added to serviceNames * to fix bug with https://github.com/apache/dubbo/issues/5442 * * @param url * @return */ private boolean isServiceNamesWithCompatibleMode(final URL url) { return !isAdminProtocol(url) && createServiceName(url).isConcrete(); } @Override public void doUnsubscribe(URL url, NotifyListener listener) { if (isAdminProtocol(url)) { shutdownServiceNamesLookup(); } else { Map<NotifyListener, NacosAggregateListener> listenerMap = originToAggregateListener.get(url); if (listenerMap == null) { logger.warn( REGISTRY_NACOS_EXCEPTION, "", "", String.format( "No aggregate listener found for url %s, this service might have already been unsubscribed.", url)); return; } NacosAggregateListener nacosAggregateListener = listenerMap.remove(listener); if (nacosAggregateListener != null) { Set<String> serviceNames = nacosAggregateListener.getServiceNames(); try { doUnsubscribe(url, nacosAggregateListener, serviceNames); } catch (NacosException e) { logger.error( REGISTRY_NACOS_EXCEPTION, "", "", "Failed to unsubscribe " + url + " to nacos " + getUrl() + ", cause: " + e.getMessage(), e); } } if (listenerMap.isEmpty()) { originToAggregateListener.remove(url); } } } private void doUnsubscribe( final URL url, final NacosAggregateListener nacosAggregateListener, final Set<String> serviceNames) throws NacosException { for (String serviceName : serviceNames) { unsubscribeEventListener(serviceName, url, nacosAggregateListener); } } private void shutdownServiceNamesLookup() { if (scheduledExecutorService != null) { scheduledExecutorService.shutdown(); } } /** * Get the service names from the specified {@link URL url} * * @param url {@link URL} * @param listener {@link NotifyListener} * @return non-null */ private Set<String> getServiceNames(URL url, NacosAggregateListener listener) { if (isAdminProtocol(url)) { scheduleServiceNamesLookup(url, listener); return getServiceNamesForOps(url); } else { return getServiceNames0(url); } } private Set<String> getServiceNames0(URL url) { NacosServiceName serviceName = createServiceName(url); final Set<String> serviceNames; if (serviceName.isConcrete()) { // is the concrete service name serviceNames = new LinkedHashSet<>(); serviceNames.add(serviceName.toString()); if (supportLegacyServiceName) { // Add the legacy service name since 2.7.6 String legacySubscribedServiceName = getLegacySubscribedServiceName(url); if (!serviceName.toString().equals(legacySubscribedServiceName)) { // avoid duplicated service names serviceNames.add(legacySubscribedServiceName); } } } else { serviceNames = filterServiceNames(serviceName); } return serviceNames; } private Set<String> filterServiceNames(NacosServiceName serviceName) { try { Set<String> serviceNames = new LinkedHashSet<>(); serviceNames.addAll( namingService .getServicesOfServer(1, Integer.MAX_VALUE, getUrl().getGroup(Constants.DEFAULT_GROUP)) .getData() .stream() .filter(this::isConformRules) .map(NacosServiceName::new) .filter(serviceName::isCompatible) .map(NacosServiceName::toString) .collect(Collectors.toList())); return serviceNames; } catch (SkipFailbackWrapperException exception) { throw exception; } catch (Throwable cause) { throw new RpcException( "Failed to filter serviceName from nacos, url: " + getUrl() + ", serviceName: " + serviceName + ", cause: " + cause.getMessage(), cause); } } /** * Verify whether it is a dubbo service * * @param serviceName * @return * @since 2.7.12 */ private boolean isConformRules(String serviceName) { return serviceName.split(NAME_SEPARATOR, -1).length == 4; } /** * Get the legacy subscribed service name for compatible with Dubbo 2.7.3 and below * * @param url {@link URL} * @return non-null * @since 2.7.6 */ private String getLegacySubscribedServiceName(URL url) { StringBuilder serviceNameBuilder = new StringBuilder(DEFAULT_CATEGORY); appendIfPresent(serviceNameBuilder, url, INTERFACE_KEY); appendIfPresent(serviceNameBuilder, url, VERSION_KEY); appendIfPresent(serviceNameBuilder, url, GROUP_KEY); return serviceNameBuilder.toString(); } private void appendIfPresent(StringBuilder target, URL url, String parameterName) { String parameterValue = url.getParameter(parameterName); if (!StringUtils.isBlank(parameterValue)) { target.append(SERVICE_NAME_SEPARATOR).append(parameterValue); } } private boolean isAdminProtocol(URL url) { return ADMIN_PROTOCOL.equals(url.getProtocol()); } private void scheduleServiceNamesLookup(final URL url, final NacosAggregateListener listener) { if (scheduledExecutorService == null) { scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); scheduledExecutorService.scheduleAtFixedRate( () -> { Set<String> serviceNames = getAllServiceNames(); filterData(serviceNames, serviceName -> { boolean accepted = false; for (String category : ALL_SUPPORTED_CATEGORIES) { String prefix = category + SERVICE_NAME_SEPARATOR; if (serviceName != null && serviceName.startsWith(prefix)) { accepted = true; break; } } return accepted; }); doSubscribe(url, listener, serviceNames); }, LOOKUP_INTERVAL, LOOKUP_INTERVAL, TimeUnit.SECONDS); } } /** * Get the service names for Dubbo OPS * * @param url {@link URL} * @return non-null */ private Set<String> getServiceNamesForOps(URL url) { Set<String> serviceNames = getAllServiceNames(); filterServiceNames(serviceNames, url); return serviceNames; } private Set<String> getAllServiceNames() { try { final Set<String> serviceNames = new LinkedHashSet<>(); int pageIndex = 1; ListView<String> listView = namingService.getServicesOfServer( pageIndex, PAGINATION_SIZE, getUrl().getGroup(Constants.DEFAULT_GROUP)); // First page data List<String> firstPageData = listView.getData(); // Append first page into list serviceNames.addAll(firstPageData); // the total count int count = listView.getCount(); // the number of pages int pageNumbers = count / PAGINATION_SIZE; int remainder = count % PAGINATION_SIZE; // remain if (remainder > 0) { pageNumbers += 1; } // If more than 1 page while (pageIndex < pageNumbers) { listView = namingService.getServicesOfServer( ++pageIndex, PAGINATION_SIZE, getUrl().getGroup(Constants.DEFAULT_GROUP)); serviceNames.addAll(listView.getData()); } return serviceNames; } catch (SkipFailbackWrapperException exception) { throw exception; } catch (Throwable cause) { throw new RpcException( "Failed to get all serviceName from nacos, url: " + getUrl() + ", cause: " + cause.getMessage(), cause); } } private void filterServiceNames(Set<String> serviceNames, URL url) { final List<String> categories = getCategories(url); final String targetServiceInterface = url.getServiceInterface(); final String targetVersion = url.getVersion(""); final String targetGroup = url.getGroup(""); filterData(serviceNames, serviceName -> { // split service name to segments // (required) segments[0] = category // (required) segments[1] = serviceInterface // (optional) segments[2] = version // (optional) segments[3] = group String[] segments = serviceName.split(SERVICE_NAME_SEPARATOR, -1); int length = segments.length; if (length != 4) { // must present 4 segments return false; } String category = segments[CATEGORY_INDEX]; if (!categories.contains(category)) { // no match category return false; } String serviceInterface = segments[SERVICE_INTERFACE_INDEX]; // no match service interface if (!WILDCARD.equals(targetServiceInterface) && !StringUtils.isEquals(targetServiceInterface, serviceInterface)) { return false; } // no match service version String version = segments[SERVICE_VERSION_INDEX]; if (!WILDCARD.equals(targetVersion) && !StringUtils.isEquals(targetVersion, version)) { return false; } String group = segments[SERVICE_GROUP_INDEX]; return group == null || WILDCARD.equals(targetGroup) || StringUtils.isEquals(targetGroup, group); }); } private <T> void filterData(Collection<T> collection, NacosDataFilter<T> filter) { // remove if not accept collection.removeIf(data -> !filter.accept(data)); } @Deprecated private List<String> doGetServiceNames(URL url) { List<String> categories = getCategories(url); List<String> serviceNames = new ArrayList<>(categories.size()); for (String category : categories) { final String serviceName = getServiceName(url, category); serviceNames.add(serviceName); } return serviceNames; } @Override public void destroy() { super.destroy(); try { this.namingService.shutdown(); } catch (NacosException e) { logger.warn(REGISTRY_NACOS_EXCEPTION, "", "", "Unable to shutdown nacos naming service", e); } this.nacosListeners.clear(); } private List<URL> toUrlWithEmpty(URL consumerURL, Collection<Instance> instances) { List<URL> urls = buildURLs(consumerURL, instances); // Nacos does not support configurators and routers from registry, so all notifications are of providers type. if (urls.size() == 0 && !getUrl().getParameter(ENABLE_EMPTY_PROTECTION_KEY, DEFAULT_ENABLE_EMPTY_PROTECTION)) { logger.warn( REGISTRY_NACOS_EXCEPTION, "", "", "Received empty url address list and empty protection is disabled, will clear current available addresses"); URL empty = URLBuilder.from(consumerURL) .setProtocol(EMPTY_PROTOCOL) .addParameter(CATEGORY_KEY, DEFAULT_CATEGORY) .build(); urls.add(empty); } return urls; } private List<URL> buildURLs(URL consumerURL, Collection<Instance> instances) { List<URL> urls = new LinkedList<>(); if (instances != null && !instances.isEmpty()) { for (Instance instance : instances) { URL url = buildURL(consumerURL, instance); if (UrlUtils.isMatch(consumerURL, url)) { urls.add(url); } } } return urls; } private void subscribeEventListener(String serviceName, final URL url, final NacosAggregateListener listener) throws NacosException { Map<NacosAggregateListener, Map<String, EventListener>> listeners = nacosListeners.computeIfAbsent(url, k -> new ConcurrentHashMap<>()); Map<String, EventListener> eventListeners = listeners.computeIfAbsent(listener, k -> new ConcurrentHashMap<>()); EventListener eventListener = eventListeners.computeIfAbsent( serviceName, k -> new RegistryChildListenerImpl(serviceName, url, listener)); namingService.subscribe(serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP), eventListener); } private void unsubscribeEventListener(String serviceName, final URL url, final NacosAggregateListener listener) throws NacosException { Map<NacosAggregateListener, Map<String, EventListener>> listenerToServiceEvent = nacosListeners.get(url); if (listenerToServiceEvent == null) { return; } Map<String, EventListener> serviceToEventMap = listenerToServiceEvent.get(listener); if (serviceToEventMap == null) { return; } EventListener eventListener = serviceToEventMap.remove(serviceName); if (eventListener == null) { return; } namingService.unsubscribe( serviceName, getUrl().getParameter(GROUP_KEY, Constants.DEFAULT_GROUP), eventListener); if (serviceToEventMap.isEmpty()) { listenerToServiceEvent.remove(listener); } if (listenerToServiceEvent.isEmpty()) { nacosListeners.remove(url); } } /** * Notify the Enabled {@link Instance instances} to subscriber. * * @param url {@link URL} * @param listener {@link NotifyListener} * @param instances all {@link Instance instances} */ private void notifySubscriber( URL url, String serviceName, NacosAggregateListener listener, Collection<Instance> instances) { List<Instance> enabledInstances = new LinkedList<>(instances); if (enabledInstances.size() > 0) { // Instances filterEnabledInstances(enabledInstances); } List<URL> aggregatedUrls = toUrlWithEmpty(url, listener.saveAndAggregateAllInstances(serviceName, enabledInstances)); NacosRegistry.this.notify(url, listener.getNotifyListener(), aggregatedUrls); } /** * Get the categories from {@link URL} * * @param url {@link URL} * @return non-null array */ private List<String> getCategories(URL url) { return ANY_VALUE.equals(url.getServiceInterface()) ? ALL_SUPPORTED_CATEGORIES : Arrays.asList(DEFAULT_CATEGORY); } private URL buildURL(URL consumerURL, Instance instance) { Map<String, String> metadata = instance.getMetadata(); String protocol = metadata.get(PROTOCOL_KEY); String path = metadata.get(PATH_KEY); URL url = new ServiceConfigURL(protocol, instance.getIp(), instance.getPort(), path, instance.getMetadata()); return new DubboServiceAddressURL(url.getUrlAddress(), url.getUrlParam(), consumerURL, null); } private Instance createInstance(URL url) { // Append default category if absent String category = url.getCategory(DEFAULT_CATEGORY); URL newURL = url.addParameter(CATEGORY_KEY, category); newURL = newURL.addParameter(PROTOCOL_KEY, url.getProtocol()); newURL = newURL.addParameter(PATH_KEY, url.getPath()); String ip = url.getHost(); int port = url.getPort(); Instance instance = new Instance(); instance.setIp(ip); instance.setPort(port); instance.setMetadata(new HashMap<>(newURL.getParameters())); return instance; } private NacosServiceName createServiceName(URL url) { return valueOf(url); } private String getServiceName(URL url) { return getServiceName(url, url.getCategory(DEFAULT_CATEGORY)); } private String getServiceName(URL url, String category) { return category + SERVICE_NAME_SEPARATOR + url.getColonSeparatedKey(); } private void filterEnabledInstances(Collection<Instance> instances) { filterData(instances, Instance::isEnabled); } /** * A filter for Nacos data * * @since 2.6.5 */ private interface NacosDataFilter<T> { /** * Tests whether or not the specified data should be accepted. * * @param data The data to be tested * @return <code>true</code> if and only if <code>data</code> * should be accepted */ boolean accept(T data); } private class RegistryChildListenerImpl implements EventListener { private final RegistryNotifier notifier; private final String serviceName; private final URL consumerUrl; private final NacosAggregateListener listener; public RegistryChildListenerImpl(String serviceName, URL consumerUrl, NacosAggregateListener listener) { this.serviceName = serviceName; this.consumerUrl = consumerUrl; this.listener = listener; this.notifier = new RegistryNotifier(getUrl(), NacosRegistry.this.getDelay()) { @Override protected void doNotify(Object rawAddresses) { List<Instance> instances = (List<Instance>) rawAddresses; NacosRegistry.this.notifySubscriber(consumerUrl, serviceName, listener, instances); } }; } @Override public void onEvent(Event event) { if (event instanceof NamingEvent) { NamingEvent e = (NamingEvent) event; notifier.notify(e.getInstances()); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RegistryChildListenerImpl that = (RegistryChildListenerImpl) o; return Objects.equals(serviceName, that.serviceName) && Objects.equals(consumerUrl, that.consumerUrl) && Objects.equals(listener, that.listener); } @Override public int hashCode() { return Objects.hash(serviceName, consumerUrl, listener); } } }
5,398
0
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry
Create_ds/dubbo/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceName.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import java.util.Arrays; import java.util.Objects; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; import static org.apache.dubbo.common.utils.StringUtils.isBlank; /** * The service name of Nacos * * @since 2.7.3 */ public class NacosServiceName { public static final String NAME_SEPARATOR = ":"; public static final String VALUE_SEPARATOR = ","; public static final String WILDCARD = "*"; public static final String DEFAULT_PARAM_VALUE = ""; private static final int CATEGORY_INDEX = 0; private static final int SERVICE_INTERFACE_INDEX = 1; private static final int SERVICE_VERSION_INDEX = 2; private static final int SERVICE_GROUP_INDEX = 3; private String category; private String serviceInterface; private String version; private String group; private String value; public NacosServiceName() {} public NacosServiceName(URL url) { serviceInterface = url.getParameter(INTERFACE_KEY); category = isConcrete(serviceInterface) ? DEFAULT_CATEGORY : url.getCategory(); version = url.getVersion(DEFAULT_PARAM_VALUE); group = url.getGroup(DEFAULT_PARAM_VALUE); value = toValue(); } public NacosServiceName(String value) { this.value = value; String[] segments = value.split(NAME_SEPARATOR, -1); this.category = segments[CATEGORY_INDEX]; this.serviceInterface = segments[SERVICE_INTERFACE_INDEX]; this.version = segments[SERVICE_VERSION_INDEX]; this.group = segments[SERVICE_GROUP_INDEX]; } /** * Build an instance of {@link NacosServiceName} * * @param url * @return */ public static NacosServiceName valueOf(URL url) { return new NacosServiceName(url); } /** * Is the concrete service name or not * * @return if concrete , return <code>true</code>, or <code>false</code> */ public boolean isConcrete() { return isConcrete(serviceInterface) && isConcrete(version) && isConcrete(group); } public boolean isCompatible(NacosServiceName concreteServiceName) { if (!concreteServiceName.isConcrete()) { // The argument must be the concrete NacosServiceName return false; } // Not match comparison if (!StringUtils.isEquals(this.category, concreteServiceName.category) && !matchRange(this.category, concreteServiceName.category)) { return false; } if (!StringUtils.isEquals(this.serviceInterface, concreteServiceName.serviceInterface)) { return false; } // wildcard condition if (isWildcard(this.version)) { return true; } if (isWildcard(this.group)) { return true; } // range condition if (!StringUtils.isEquals(this.version, concreteServiceName.version) && !matchRange(this.version, concreteServiceName.version)) { return false; } if (!StringUtils.isEquals(this.group, concreteServiceName.group) && !matchRange(this.group, concreteServiceName.group)) { return false; } return true; } private boolean matchRange(String range, String value) { if (isBlank(range)) { return true; } if (!isRange(range)) { return false; } String[] values = range.split(VALUE_SEPARATOR); return Arrays.asList(values).contains(value); } private boolean isConcrete(String value) { return !isWildcard(value) && !isRange(value); } private boolean isWildcard(String value) { return WILDCARD.equals(value); } private boolean isRange(String value) { return value != null && value.indexOf(VALUE_SEPARATOR) > -1 && value.split(VALUE_SEPARATOR).length > 1; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } 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 getValue() { if (value == null) { value = toValue(); } return value; } private String toValue() { return new StringBuilder(category) .append(NAME_SEPARATOR) .append(serviceInterface) .append(NAME_SEPARATOR) .append(version) .append(NAME_SEPARATOR) .append(group) .toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof NacosServiceName)) { return false; } NacosServiceName that = (NacosServiceName) o; return Objects.equals(getValue(), that.getValue()); } @Override public int hashCode() { return Objects.hash(getValue()); } @Override public String toString() { return getValue(); } }
5,399