repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetricsConstants.java | dubbo-common/src/main/java/org/apache/dubbo/common/constants/MetricsConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.constants;
public interface MetricsConstants {
String PROTOCOL_PROMETHEUS = "prometheus";
String PROTOCOL_DEFAULT = "default";
String TAG_IP = "ip";
String TAG_PID = "pid";
String TAG_HOSTNAME = "hostname";
String TAG_APPLICATION_NAME = "application.name";
String TAG_APPLICATION_MODULE = "application.module.id";
String TAG_INTERFACE_KEY = "interface";
String TAG_METHOD_KEY = "method";
String TAG_GROUP_KEY = "group";
String TAG_VERSION_KEY = "version";
String TAG_APPLICATION_VERSION_KEY = "application.version";
String TAG_KEY_KEY = "key";
String TAG_CONFIG_CENTER = "config.center";
String TAG_CHANGE_TYPE = "change.type";
String TAG_ERROR_CODE = "error";
String ENABLE_JVM_METRICS_KEY = "enable.jvm";
String ENABLE_COLLECTOR_SYNC_KEY = "enable.collector.sync";
String COLLECTOR_SYNC_PERIOD_KEY = "collector.sync.period";
String AGGREGATION_COLLECTOR_KEY = "aggregation";
String AGGREGATION_ENABLED_KEY = "aggregation.enabled";
String AGGREGATION_BUCKET_NUM_KEY = "aggregation.bucket.num";
String AGGREGATION_TIME_WINDOW_SECONDS_KEY = "aggregation.time.window.seconds";
String HISTOGRAM_ENABLED_KEY = "histogram.enabled";
String PROMETHEUS_EXPORTER_ENABLED_KEY = "prometheus.exporter.enabled";
String PROMETHEUS_EXPORTER_ENABLE_HTTP_SERVICE_DISCOVERY_KEY = "prometheus.exporter.enable.http.service.discovery";
String PROMETHEUS_EXPORTER_HTTP_SERVICE_DISCOVERY_URL_KEY = "prometheus.exporter.http.service.discovery.url";
String PROMETHEUS_EXPORTER_METRICS_PORT_KEY = "prometheus.exporter.metrics.port";
String PROMETHEUS_EXPORTER_METRICS_PATH_KEY = "prometheus.exporter.metrics.path";
String PROMETHEUS_PUSHGATEWAY_ENABLED_KEY = "prometheus.pushgateway.enabled";
String PROMETHEUS_PUSHGATEWAY_BASE_URL_KEY = "prometheus.pushgateway.base.url";
String PROMETHEUS_PUSHGATEWAY_USERNAME_KEY = "prometheus.pushgateway.username";
String PROMETHEUS_PUSHGATEWAY_PASSWORD_KEY = "prometheus.pushgateway.password";
String PROMETHEUS_PUSHGATEWAY_PUSH_INTERVAL_KEY = "prometheus.pushgateway.push.interval";
String PROMETHEUS_PUSHGATEWAY_JOB_KEY = "prometheus.pushgateway.job";
int PROMETHEUS_DEFAULT_METRICS_PORT = 20888;
String PROMETHEUS_DEFAULT_METRICS_PATH = "/metrics";
int PROMETHEUS_DEFAULT_PUSH_INTERVAL = 30;
String PROMETHEUS_DEFAULT_JOB_NAME = "default_dubbo_job";
String METRIC_FILTER_START_TIME = "metric_filter_start_time";
String TAG_THREAD_NAME = "thread.pool.name";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/constants/FilterConstants.java | dubbo-common/src/main/java/org/apache/dubbo/common/constants/FilterConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.constants;
public interface FilterConstants {
String CACHE_KEY = "cache";
String VALIDATION_KEY = "validation";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java | dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.constants;
import org.apache.dubbo.common.URL;
import java.net.NetworkInterface;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.regex.Pattern;
public interface CommonConstants {
String DUBBO = "dubbo";
String TRIPLE = "tri";
String PROVIDER = "provider";
String CONSUMER = "consumer";
String CALLBACK = "callback";
String APPLICATION_KEY = "application";
String APPLICATION_VERSION_KEY = "application.version";
String APPLICATION_PROTOCOL_KEY = "application-protocol";
String METADATA_SERVICE_PORT_KEY = "metadata-service-port";
String METADATA_SERVICE_PROTOCOL_KEY = "metadata-service-protocol";
String METRICS_SERVICE_PORT_KEY = "metrics-service-port";
String METRICS_SERVICE_PROTOCOL_KEY = "metrics-service-protocol";
String LIVENESS_PROBE_KEY = "liveness-probe";
String READINESS_PROBE_KEY = "readiness-probe";
String STARTUP_PROBE = "startup-probe";
String REMOTE_APPLICATION_KEY = "remote.application";
String ENABLED_KEY = "enabled";
String DISABLED_KEY = "disabled";
String DEFAULT_DUBBO_PROPERTIES = "dubbo.properties";
String DEFAULT_DUBBO_MIGRATION_FILE = "dubbo-migration.yaml";
String ANY_VALUE = "*";
/**
* @since 2.7.8
*/
char COMMA_SEPARATOR_CHAR = ',';
String COMMA_SEPARATOR = ",";
String DOT_SEPARATOR = ".";
Pattern COMMA_SPLIT_PATTERN = Pattern.compile("\\s*[,]+\\s*");
String PATH_SEPARATOR = "/";
String PROTOCOL_SEPARATOR = "://";
String PROTOCOL_SEPARATOR_ENCODED = URL.encode(PROTOCOL_SEPARATOR);
String REGISTRY_SEPARATOR = "|";
Pattern REGISTRY_SPLIT_PATTERN = Pattern.compile("\\s*[|;]+\\s*");
Pattern D_REGISTRY_SPLIT_PATTERN = Pattern.compile("\\s*[|]+\\s*");
String SEMICOLON_SEPARATOR = ";";
Pattern SEMICOLON_SPLIT_PATTERN = Pattern.compile("\\s*[;]+\\s*");
Pattern EQUAL_SPLIT_PATTERN = Pattern.compile("\\s*[=]+\\s*");
String DEFAULT_PROXY = "javassist";
String DEFAULT_DIRECTORY = "dubbo";
String PROTOCOL_KEY = "protocol";
String DEFAULT_PROTOCOL = "dubbo";
String DEFAULT_THREAD_NAME = "Dubbo";
int DEFAULT_CORE_THREADS = 0;
int DEFAULT_THREADS = 200;
String EXECUTOR_SERVICE_COMPONENT_KEY = ExecutorService.class.getName();
String CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY = "CONSUMER_SHARED_SERVICE_EXECUTOR";
String THREADPOOL_KEY = "threadpool";
String THREAD_NAME_KEY = "threadname";
String CORE_THREADS_KEY = "corethreads";
String THREAD_POOL_EXHAUSTED_LISTENERS_KEY = "thread-pool-exhausted-listeners";
String JSON_CHECK_LEVEL_KEY = "jsonCheckLevel";
String THREADS_KEY = "threads";
String QUEUES_KEY = "queues";
String ALIVE_KEY = "alive";
String DEFAULT_THREADPOOL = "limited";
String DEFAULT_CLIENT_THREADPOOL = "cached";
String IO_THREADS_KEY = "iothreads";
String KEEP_ALIVE_KEY = "keep.alive";
int DEFAULT_QUEUES = 0;
int DEFAULT_ALIVE = 60 * 1000;
String TIMEOUT_KEY = "timeout";
int DEFAULT_TIMEOUT = 1000;
String SESSION_KEY = "session";
// used by invocation attachments to transfer timeout from Consumer to Provider.
// works as a replacement of TIMEOUT_KEY on wire, which seems to be totally useless in previous releases).
String TIMEOUT_ATTACHMENT_KEY = "_TO";
String TIMEOUT_ATTACHMENT_KEY_LOWER = "_to";
String TIME_COUNTDOWN_KEY = "timeout-countdown";
String ENABLE_TIMEOUT_COUNTDOWN_KEY = "enable-timeout-countdown";
String REMOVE_VALUE_PREFIX = "-";
String PROPERTIES_CHAR_SEPARATOR = "-";
String UNDERLINE_SEPARATOR = "_";
String SEPARATOR_REGEX = "_|-";
String GROUP_CHAR_SEPARATOR = ":";
String HIDE_KEY_PREFIX = ".";
String DOT_REGEX = "\\.";
String DEFAULT_KEY_PREFIX = "default.";
String DEFAULT_KEY = "default";
String PREFERRED_KEY = "preferred";
/**
* Default timeout value in milliseconds for server shutdown
*/
int DEFAULT_SERVER_SHUTDOWN_TIMEOUT = 10000;
String SIDE_KEY = "side";
String PROVIDER_SIDE = "provider";
String CONSUMER_SIDE = "consumer";
String ANYHOST_KEY = "anyhost";
String ANYHOST_VALUE = "0.0.0.0";
String LOCALHOST_KEY = "localhost";
String LOCALHOST_VALUE = "127.0.0.1";
String METHODS_KEY = "methods";
String METHOD_KEY = "method";
String PID_KEY = "pid";
String TIMESTAMP_KEY = "timestamp";
String GROUP_KEY = "group";
String PATH_KEY = "path";
String ADDRESS_KEY = "address";
String INTERFACE_KEY = "interface";
String FILE_KEY = "file";
String FILTER_KEY = "filter";
String DUMP_DIRECTORY = "dump.directory";
String DUMP_ENABLE = "dump.enable";
String CLASSIFIER_KEY = "classifier";
String VERSION_KEY = "version";
String REVISION_KEY = "revision";
String METADATA_KEY = "metadata-type";
String REPORT_METADATA_KEY = "report-metadata";
String REPORT_DEFINITION_KEY = "report-definition";
String DEFAULT_METADATA_STORAGE_TYPE = "local";
String REMOTE_METADATA_STORAGE_TYPE = "remote";
String INTERFACE_REGISTER_MODE = "interface";
String INSTANCE_REGISTER_MODE = "instance";
String DEFAULT_REGISTER_MODE = "all";
String GENERIC_KEY = "generic";
/**
* The composite metadata storage type includes {@link #DEFAULT_METADATA_STORAGE_TYPE "local"} and
* {@link #REMOTE_METADATA_STORAGE_TYPE "remote"}.
*
* @since 2.7.8
*/
String COMPOSITE_METADATA_STORAGE_TYPE = "composite";
/**
* Consumer side 's proxy class
*/
String PROXY_CLASS_REF = "refClass";
/**
* generic call
*/
String $INVOKE = "$invoke";
String $INVOKE_ASYNC = "$invokeAsync";
String GENERIC_PARAMETER_DESC = "Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/Object;";
/**
* echo call
*/
String $ECHO = "$echo";
/**
* package version in the manifest
*/
String RELEASE_KEY = "release";
String PROTOBUF_MESSAGE_CLASS_NAME = "com.google.protobuf.Message";
int MAX_PROXY_COUNT = 65535;
String MONITOR_KEY = "monitor";
String BACKGROUND_KEY = "background";
String CLUSTER_KEY = "cluster";
String MERGEABLE_CLUSTER_NAME = "mergeable";
String USERNAME_KEY = "username";
String PASSWORD_KEY = "password";
String HOST_KEY = "host";
String PORT_KEY = "port";
String DUBBO_IP_TO_BIND = "DUBBO_IP_TO_BIND";
/**
* broadcast cluster.
*/
String BROADCAST_CLUSTER = "broadcast";
@Deprecated
String SHUTDOWN_WAIT_SECONDS_KEY = "dubbo.service.shutdown.wait.seconds";
String SHUTDOWN_WAIT_KEY = "dubbo.service.shutdown.wait";
String DUBBO_PROTOCOL = "dubbo";
String DUBBO_LABELS = "dubbo.labels";
String DUBBO_ENV_KEYS = "dubbo.env.keys";
String CONFIG_CONFIGFILE_KEY = "config-file";
String CONFIG_ENABLE_KEY = "highest-priority";
String CONFIG_NAMESPACE_KEY = "namespace";
String CHECK_KEY = "check";
String BACKLOG_KEY = "backlog";
String HEARTBEAT_EVENT = null;
String MOCK_HEARTBEAT_EVENT = "H";
String READONLY_EVENT = "R";
String WRITEABLE_EVENT = "W";
String REFERENCE_FILTER_KEY = "reference.filter";
String HEADER_FILTER_KEY = "header.filter";
String INVOCATION_INTERCEPTOR_KEY = "invocation.interceptor";
String INVOKER_LISTENER_KEY = "invoker.listener";
String REGISTRY_PROTOCOL_LISTENER_KEY = "registry.protocol.listener";
String DUBBO_VERSION_KEY = "dubbo";
String TAG_KEY = "dubbo.tag";
/**
* To decide whether to make connection when the client is created
*/
String LAZY_CONNECT_KEY = "lazy";
String STUB_EVENT_KEY = "dubbo.stub.event";
String REFERENCE_INTERCEPTOR_KEY = "reference.interceptor";
String SERVICE_FILTER_KEY = "service.filter";
String EXPORTER_LISTENER_KEY = "exporter.listener";
/**
* After simplify the registry, should add some parameter individually for provider.
*
* @since 2.7.0
*/
String EXTRA_KEYS_KEY = "extra-keys";
String GENERIC_SERIALIZATION_NATIVE_JAVA = "nativejava";
String GENERIC_SERIALIZATION_GSON = "gson";
String GENERIC_SERIALIZATION_DEFAULT = "true";
String GENERIC_SERIALIZATION_BEAN = "bean";
String GENERIC_RAW_RETURN = "raw.return";
String GENERIC_SERIALIZATION_PROTOBUF = "protobuf-json";
String GENERIC_WITH_CLZ_KEY = "generic.include.class";
/**
* Whether to cache locally, default is true
*/
String REGISTRY_LOCAL_FILE_CACHE_ENABLED = "file-cache";
String METADATA_INFO_CACHE_EXPIRE_KEY = "metadata-info-cache.expire";
int DEFAULT_METADATA_INFO_CACHE_EXPIRE = 10 * 60 * 1000;
String METADATA_INFO_CACHE_SIZE_KEY = "metadata-info-cache.size";
int DEFAULT_METADATA_INFO_CACHE_SIZE = 16;
/**
* The limit of callback service instances for one interface on every client
*/
String CALLBACK_INSTANCES_LIMIT_KEY = "callbacks";
/**
* The default limit number for callback service instances
*
* @see #CALLBACK_INSTANCES_LIMIT_KEY
*/
int DEFAULT_CALLBACK_INSTANCES = 1;
String LOADBALANCE_KEY = "loadbalance";
String DEFAULT_LOADBALANCE = "random";
String RETRIES_KEY = "retries";
String FORKS_KEY = "forks";
int DEFAULT_RETRIES = 2;
int DEFAULT_FAILBACK_TIMES = 3;
String INTERFACES = "interfaces";
String SSL_ENABLED_KEY = "ssl-enabled";
String SERVICE_PATH_PREFIX = "service.path.prefix";
String PROTOCOL_SERVER_SERVLET = "servlet";
String PROTOCOL_SERVER = "server";
String IPV6_KEY = "ipv6";
/**
* The parameter key for the class path of the ServiceNameMapping {@link Properties} file
*
* @since 2.7.8
*/
String SERVICE_NAME_MAPPING_PROPERTIES_FILE_KEY = "service-name-mapping.properties-path";
/**
* The default class path of the ServiceNameMapping {@link Properties} file
*
* @since 2.7.8
*/
String DEFAULT_SERVICE_NAME_MAPPING_PROPERTIES_PATH = "META-INF/dubbo/service-name-mapping.properties";
String ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE = "dubbo.security.serialize.generic.native-java-enable";
String SERIALIZE_BLOCKED_LIST_FILE_PATH = "security/serialize.blockedlist";
String SERIALIZE_ALLOW_LIST_FILE_PATH = "security/serialize.allowlist";
String SERIALIZE_CHECK_STATUS_KEY = "dubbo.application.serialize-check-status";
String QOS_LIVE_PROBE_EXTENSION = "dubbo.application.liveness-probe";
String QOS_READY_PROBE_EXTENSION = "dubbo.application.readiness-probe";
String QOS_STARTUP_PROBE_EXTENSION = "dubbo.application.startup-probe";
String REGISTRY_DELAY_NOTIFICATION_KEY = "delay-notification";
String CACHE_CLEAR_TASK_INTERVAL = "dubbo.application.url.cache.task.interval";
String CACHE_CLEAR_WAITING_THRESHOLD = "dubbo.application.url.cache.clear.waiting";
String CLUSTER_INTERCEPTOR_COMPATIBLE_KEY = "dubbo.application.cluster.interceptor.compatible";
String UTF8ENCODE = "UTF-8";
/**
* Pseudo URL prefix for loading from the class path: "classpath:".
*/
String CLASSPATH_URL_PREFIX = "classpath:";
String DEFAULT_VERSION = "0.0.0";
String ROUTER_KEY = "router";
String EXPORT_ASYNC_KEY = "export-async";
String REFER_ASYNC_KEY = "refer-async";
String EXPORT_BACKGROUND_KEY = "export-background";
String REFER_BACKGROUND_KEY = "refer-background";
String EXPORT_THREAD_NUM_KEY = "export-thread-num";
String REFER_THREAD_NUM_KEY = "refer-thread-num";
int DEFAULT_EXPORT_THREAD_NUM = 10;
int DEFAULT_REFER_THREAD_NUM = 10;
int DEFAULT_DELAY_NOTIFICATION_TIME = 5000;
int DEFAULT_DELAY_EXECUTE_TIMES = 10;
/**
* Url merge processor key
*/
String URL_MERGE_PROCESSOR_KEY = "url-merge-processor";
String DUBBO_MONITOR_ADDRESS = "dubbo.monitor.address";
String SERVICE_NAME_MAPPING_KEY = "service-name-mapping";
String SCOPE_MODEL = "scopeModel";
String SERVICE_MODEL = "serviceModel";
String OS_LINUX_PREFIX = "linux";
String OS_WIN_PREFIX = "win";
String RECONNECT_TASK_TRY_COUNT = "dubbo.reconnect.reconnectTaskTryCount";
int DEFAULT_RECONNECT_TASK_TRY_COUNT = 10;
String RECONNECT_TASK_PERIOD = "dubbo.reconnect.reconnectTaskPeriod";
int DEFAULT_RECONNECT_TASK_PERIOD = 1000;
String RESELECT_COUNT = "dubbo.reselect.count";
int DEFAULT_RESELECT_COUNT = 10;
String ENABLE_CONNECTIVITY_VALIDATION = "dubbo.connectivity.validation";
String DUBBO_INTERNAL_APPLICATION = "DUBBO_INTERNAL_APPLICATION";
String RETRY_TIMES_KEY = "retry-times";
String RETRY_PERIOD_KEY = "retry-period";
String SYNC_REPORT_KEY = "sync-report";
String CYCLE_REPORT_KEY = "cycle-report";
String WORKING_CLASSLOADER_KEY = "WORKING_CLASSLOADER";
String STAGED_CLASSLOADER_KEY = "STAGED_CLASSLOADER";
String PROVIDER_ASYNC_KEY = "PROVIDER_ASYNC";
String REGISTER_IP_KEY = "register.ip";
String CURRENT_CLUSTER_INVOKER_KEY = "currentClusterInvoker";
String ENABLE_ROUTER_SNAPSHOT_PRINT_KEY = "ENABLE_ROUTER_SNAPSHOT_PRINT";
String INJVM_COPY_UTIL_KEY = "injvm-copy-util";
String INJVM_IGNORE_SAME_MODULE_KEY = "injvm.ignore.same-module";
String NATIVE_STUB = "nativestub";
String METADATA = "metadata";
String IGNORE_LISTEN_SHUTDOWN_HOOK = "dubbo.shutdownHook.listenIgnore";
String OPTIMIZER_KEY = "optimizer";
/**
* @since 3.1.0
*/
String MESH_ENABLE = "mesh-enable";
/**
* @since 3.1.0
*/
Integer DEFAULT_MESH_PORT = 80;
/**
* @since 3.1.0
*/
String SVC = ".svc.";
/**
* Domain name suffix used inside k8s.
*
* @since 3.1.0
*/
String DEFAULT_CLUSTER_DOMAIN = "cluster.local";
/**
* @since 3.1.0
*/
String UNLOAD_CLUSTER_RELATED = "unloadClusterRelated";
/**
* used for thread isolation between services
*/
String SERVICE_EXECUTOR = "service-executor";
String EXECUTOR_MANAGEMENT_MODE = "executor-management-mode";
String EXECUTOR_MANAGEMENT_MODE_DEFAULT = "default";
String EXECUTOR_MANAGEMENT_MODE_ISOLATION = "isolation";
/**
* used in JVMUtil.java ,Control stack print lines, default is 32 lines
*/
String DUBBO_JSTACK_MAXLINE = "dubbo.jstack-dump.max-line";
String ENCODE_IN_IO_THREAD_KEY = "encode.in.io";
boolean DEFAULT_ENCODE_IN_IO_THREAD = false;
String PAYLOAD = "payload";
String DUBBO_METRICS_CONFIGCENTER_ENABLE = "dubbo.metrics.configcenter.enable";
Integer TRI_EXCEPTION_CODE_NOT_EXISTS = 0;
String PACKABLE_METHOD_FACTORY_KEY = "serialize.packable.factory";
String DUBBO_PACKABLE_METHOD_FACTORY = "dubbo.application.parameters." + PACKABLE_METHOD_FACTORY_KEY;
String DUBBO_TAG_HEADER = "dubbo-tag";
String REST_SERVICE_DEPLOYER_URL_ATTRIBUTE_KEY = "restServiceDeployerAttributeKey";
String POD_NAMESPACE = "POD_NAMESPACE";
String CLUSTER_DOMAIN = "CLUSTER_DOMAIN";
String EXT_PROTOCOL = "ext.protocol";
String PREFERRED_PROTOCOL = "preferred.protocol";
String IS_EXTRA = "isExtra";
String ZOOKEEPER_ENSEMBLE_TRACKER_KEY = "zookeeper.ensemble.tracker";
String DUBBO_VERSIONS_KEY = "META-INF/dubbo-versions";
String TRIPLE_PREFIX = "triple.";
/**
* System-related VM properties
*/
interface SystemProperty {
String USER_HOME = "user.home";
String SYSTEM_JAVA_VERSION = "java.version";
String SYSTEM_JAVA_IO_TMPDIR = "java.io.tmpdir";
String SYSTEM_LINE_SEPARATOR = "line.separator";
String SERIALIZATION_SECURITY_CHECK_KEY = "serialization.security.check";
String SYSTEM_BYTE_ACCESSOR_KEY = "byte.accessor";
String SYSTEM_OS_NAME = "os.name";
String SYSTEM_OS_VERSION = "os.version";
String JAVA_RUNTIME_NAME = "java.runtime.name";
String JAVA_RUNTIME_VERSION = "java.runtime.version";
String JAVA_VM_NAME = "java.vm.name";
String JAVA_VM_VERSION = "java.vm.version";
String JAVA_VM_INFO = "java.vm.info";
String JAVA_HOME = "java.home";
String OS_ARCH = "os.arch";
String SYSTEM_FILE_ENCODING = "file.encoding";
String SYSTEM_TCP_RESPONSE_TIMEOUT = "sun.rmi.transport.tcp.responseTimeout";
}
/**
* Third-party-related VM properties
*/
interface ThirdPartyProperty {
String NETTY_EPOLL_ENABLE_KEY = "netty.epoll.enable";
String SET_FUTURE_IN_SYNC_MODE = "future.sync.set";
String CLEAR_FUTURE_AFTER_GET = "future.clear.once";
String APOLLO_ADDR_KEY = "apollo.meta";
String APOLLO_CLUSTER_KEY = "apollo.cluster";
String APOLLO_ENV_KEY = "env";
String APOLLO_APPID_KEY = "app.id";
String NACOS_SERVICE_NAME_SEPARATOR = "nacos.service.name.separator";
String GRAALVM_NATIVEIMAGE_IMAGECODE = "org.graalvm.nativeimage.imagecode";
/**
* The JVM arguments to set if it can use embedded zookeeper, the default value is {@code true}.
*/
String ZOOKEEPER_CONFIG_ENABLE_EMBEDDED = "enableEmbeddedZookeeper";
}
/**
* Dubbo custom VM properties
*/
interface DubboProperty {
String DUBBO_MIGRATION_FILE_ENABLE = "dubbo.migration-file.enable";
String DUBBO_MIGRATION_KEY = "dubbo.migration.file";
String DUBBO_APPLICATION_LOGGER = "dubbo.application.logger";
String DUBBO_PROPERTIES_KEY = "dubbo.properties.file";
String DUBBO_PREFER_JSON_FRAMEWORK_NAME = "dubbo.json-framework.prefer";
/**
* used in JVMUtil.java ,Control stack print lines, default is 32 lines
*/
String DUBBO_JSTACK_MAXLINE = "dubbo.jstack-dump.max-line";
/**
* The property name for {@link NetworkInterface#getDisplayName() the name of network interface} that the Dubbo
* application will be ignored
*
* @since 2.7.6
*/
String DUBBO_NETWORK_IGNORED_INTERFACE = "dubbo.network.interface.ignored";
/**
* The property name for {@link NetworkInterface#getDisplayName() the name of network interface} that the Dubbo
* application prefers
*
* @since 2.7.6
*/
String DUBBO_PREFERRED_NETWORK_INTERFACE = "dubbo.network.interface.preferred";
/**
* The property name for {@link NetworkInterface#isPointToPoint() return whether a network interface is a point
* to point interface} that the Dubbo application will determine whether to ignore the point-to-point network
* interface
*
* @since 3.3
*/
String DUBBO_NETWORK_INTERFACE_POINT_TO_POINT_IGNORED = "dubbo.network.interface.point-to-point.ignored";
String DUBBO_CLASS_DESERIALIZE_ALLOWED_LIST = "dubbo.security.serialize.allowedClassList";
String DUBBO_CLASS_DESERIALIZE_BLOCKED_LIST = "dubbo.security.serialize.blockedClassList";
String DUBBO_CLASS_DESERIALIZE_OPEN_CHECK = "dubbo.security.serialize.openCheckClass";
String DUBBO_CLASS_DESERIALIZE_BLOCK_ALL = "dubbo.security.serialize.blockAllClassExceptAllow";
String DUBBO_RESOLVE_FILE = "dubbo.resolve.file";
String DUBBO_IP_TO_REGISTRY = "DUBBO_IP_TO_REGISTRY";
String DUBBO_MONITOR_ADDRESS = "dubbo.monitor.address";
String DUBBO_CONTAINER_KEY = "dubbo.container";
String DUBBO_SHUTDOWN_HOOK_KEY = "dubbo.shutdown.hook";
String DUBBO_SPRING_CONFIG = "dubbo.spring.config";
String DUBBO_MAPPING_CACHE_FILEPATH = "dubbo.mapping.cache.filePath";
String DUBBO_MAPPING_CACHE_FILENAME = "dubbo.mapping.cache.fileName";
String DUBBO_MAPPING_CACHE_ENTRYSIZE = "dubbo.mapping.cache.entrySize";
String DUBBO_MAPPING_CACHE_MAXFILESIZE = "dubbo.mapping.cache.maxFileSize";
String DUBBO_META_CACHE_FILEPATH = "dubbo.meta.cache.filePath";
String DUBBO_META_CACHE_FILENAME = "dubbo.meta.cache.fileName";
String DUBBO_META_CACHE_ENTRYSIZE = "dubbo.meta.cache.entrySize";
String DUBBO_META_CACHE_MAXFILESIZE = "dubbo.meta.cache.maxFileSize";
String DUBBO_USE_SECURE_RANDOM_ID = "dubbo.application.use-secure-random-request-id";
String DUBBO_CLOSE_TIMEOUT_CONFIG_KEY = "dubbo.protocol.default-close-timeout";
String DUBBO_HEARTBEAT_CONFIG_KEY = "dubbo.protocol.default-heartbeat";
String DUBBO_DEFAULT_REMOTING_SERIALIZATION_PROPERTY = "DUBBO_DEFAULT_SERIALIZATION";
String DUBBO_HESSIAN_ALLOW_NON_SERIALIZABLE = "dubbo.hessian.allowNonSerializable";
String DUBBO_HESSIAN_WHITELIST = "dubbo.application.hessian2.whitelist";
String DUBBO_HESSIAN_ALLOW = "dubbo.application.hessian2.allow";
String DUBBO_HESSIAN_DENY = "dubbo.application.hessian2.deny";
String DUBBO_MANUAL_REGISTER_KEY = "dubbo.application.manual-register";
String DUBBO2_COMPACT_ENABLE = "dubbo.compact.enable";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoggerCodeConstants.java | dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoggerCodeConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.constants;
/**
* <p>Constants of Error Codes used in logger.
*
* <p>Format: <i>[Category]-[Code]</i>, where:
* <li>[Category] is the category code which identifies the module.
* <li>[Code] is the detailed code.
* <li>Every blanks should be filled with positive number.
*
* <br /><br />
* <p>Hint:
* <li>Synchronize this file across different branches. (Use merge and cherry-pick.)
* <li>Double-check the usage in different branches before deleting any of the error code.
* <li>If applicable, use error code that already appears in this file.
* <li>If it's required to add an error code, find an error code that's marked by 'Absent', and rename it. (so that no code is wasted)
* <li>Update the corresponding file in dubbo-website repository.
*/
public interface LoggerCodeConstants {
// Common module
String COMMON_THREAD_POOL_EXHAUSTED = "0-1";
String COMMON_PROPERTY_TYPE_MISMATCH = "0-2";
String COMMON_CACHE_PATH_INACCESSIBLE = "0-3";
String COMMON_CACHE_MAX_FILE_SIZE_LIMIT_EXCEED = "0-4";
String COMMON_CACHE_MAX_ENTRY_COUNT_LIMIT_EXCEED = "0-5";
String COMMON_THREAD_INTERRUPTED_EXCEPTION = "0-6";
String COMMON_CLASS_NOT_FOUND = "0-7";
String COMMON_REFLECTIVE_OPERATION_FAILED = "0-8";
String COMMON_FAILED_NOTIFY_EVENT = "0-9";
String COMMON_UNSUPPORTED_INVOKER = "0-10";
String COMMON_FAILED_STOP_HTTP_SERVER = "0-11";
String COMMON_UNEXPECTED_EXCEPTION = "0-12";
String COMMON_METRICS_COLLECTOR_EXCEPTION = "0-13";
String COMMON_MONITOR_EXCEPTION = "0-14";
String COMMON_ERROR_LOAD_EXTENSION = "0-15";
String COMMON_EXECUTORS_NO_FOUND = "0-16";
String COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN = "0-17";
String COMMON_ERROR_USE_THREAD_POOL = "0-18";
String COMMON_ERROR_RUN_THREAD_TASK = "0-19";
String COMMON_UNEXPECTED_CREATE_DUMP = "0-20";
String COMMON_ERROR_TOO_MANY_INSTANCES = "0-21";
String COMMON_IO_EXCEPTION = "0-22";
String COMMON_JSON_CONVERT_EXCEPTION = "0-23";
String COMMON_FAILED_OVERRIDE_FIELD = "0-24";
String COMMON_FAILED_LOAD_MAPPING_CACHE = "0-25";
String COMMON_METADATA_PROCESSOR = "0-26";
String COMMON_ISOLATED_EXECUTOR_CONFIGURATION_ERROR = "0-27";
String VULNERABILITY_WARNING = "0-28";
String COMMON_NOT_FOUND_TRACER_DEPENDENCY = "0-29";
// Registry module
String REGISTRY_ADDRESS_INVALID = "1-1";
/**
* Absent. Merged with 0-2.
*/
String REGISTRY_ABSENCE = "1-2";
String REGISTRY_FAILED_URL_EVICTING = "1-3";
String REGISTRY_EMPTY_ADDRESS = "1-4";
String REGISTRY_NO_PARAMETERS_URL = "1-5";
String REGISTRY_FAILED_CLEAR_CACHED_URLS = "1-6";
String REGISTRY_FAILED_NOTIFY_EVENT = "1-7";
String REGISTRY_FAILED_DESTROY_UNREGISTER_URL = "1-8";
String REGISTRY_FAILED_READ_WRITE_CACHE_FILE = "1-9";
String REGISTRY_FAILED_DELETE_LOCKFILE = "1-10";
String REGISTRY_FAILED_CREATE_INSTANCE = "1-11";
String REGISTRY_FAILED_FETCH_INSTANCE = "1-12";
String REGISTRY_EXECUTE_RETRYING_TASK = "1-13";
String REGISTRY_FAILED_PARSE_DYNAMIC_CONFIG = "1-14";
String REGISTRY_FAILED_DESTROY_SERVICE = "1-15";
String REGISTRY_UNSUPPORTED_CATEGORY = "1-16";
String REGISTRY_FAILED_REFRESH_ADDRESS = "1-17";
String REGISTRY_MISSING_METADATA_CONFIG_PORT = "1-18";
String REGISTRY_ERROR_LISTEN_KUBERNETES = "1-19";
String REGISTRY_UNABLE_MATCH_KUBERNETES = "1-20";
String REGISTRY_UNABLE_FIND_SERVICE_KUBERNETES = "1-21";
String REGISTRY_UNABLE_ACCESS_KUBERNETES = "1-22";
/**
* Absent. Original '1-23' is changed to '81-3'.
*/
String REGISTRY_FAILED_DOWNLOAD_FILE = "1-23";
/**
* Absent. Original '1-24' is changed to '81-1'.
*/
String REGISTRY_FAILED_START_ZOOKEEPER = "1-24";
/**
* Absent. Original '1-25' is changed to '81-2'.
*/
String REGISTRY_FAILED_STOP_ZOOKEEPER = "1-25";
String REGISTRY_FAILED_GENERATE_CERT_ISTIO = "1-26";
String REGISTRY_FAILED_GENERATE_KEY_ISTIO = "1-27";
String REGISTRY_RECEIVE_ERROR_MSG_ISTIO = "1-28";
String REGISTRY_ERROR_READ_FILE_ISTIO = "1-29";
String REGISTRY_ERROR_REQUEST_XDS = "1-30";
String REGISTRY_ERROR_RESPONSE_XDS = "1-31";
String REGISTRY_ERROR_CREATE_CHANNEL_XDS = "1-32";
String REGISTRY_ERROR_INITIALIZE_XDS = "1-33";
String REGISTRY_ERROR_PARSING_XDS = "1-34";
String REGISTRY_ZOOKEEPER_EXCEPTION = "1-35";
/**
* Absent. Merged with 99-0.
*/
String REGISTRY_UNEXPECTED_EXCEPTION = "1-36";
String REGISTRY_NACOS_EXCEPTION = "1-37";
String REGISTRY_SOCKET_EXCEPTION = "1-38";
String REGISTRY_FAILED_LOAD_METADATA = "1-39";
String REGISTRY_ROUTER_WAIT_LONG = "1-40";
String REGISTRY_ISTIO_EXCEPTION = "1-41";
String REGISTRY_NACOS_SUB_LEGACY = "1-42";
// Cluster module 2-x
String CLUSTER_FAILED_SITE_SELECTION = "2-1";
String CLUSTER_NO_VALID_PROVIDER = "2-2";
String CLUSTER_FAILED_STOP = "2-3";
String CLUSTER_FAILED_LOAD_MERGER = "2-4";
String CLUSTER_FAILED_RESELECT_INVOKERS = "2-5";
String CLUSTER_CONDITIONAL_ROUTE_LIST_EMPTY = "2-6";
String CLUSTER_FAILED_EXEC_CONDITION_ROUTER = "2-7";
String CLUSTER_ERROR_RESPONSE = "2-8";
String CLUSTER_TIMER_RETRY_FAILED = "2-9";
String CLUSTER_FAILED_INVOKE_SERVICE = "2-10";
String CLUSTER_TAG_ROUTE_INVALID = "2-11";
String CLUSTER_TAG_ROUTE_EMPTY = "2-12";
String CLUSTER_FAILED_RECEIVE_RULE = "2-13";
String CLUSTER_SCRIPT_EXCEPTION = "2-14";
String CLUSTER_FAILED_RULE_PARSING = "2-15";
String CLUSTER_FAILED_MULTIPLE_RETRIES = "2-16";
String CLUSTER_FAILED_MOCK_REQUEST = "2-17";
String CLUSTER_NO_RULE_LISTENER = "2-18";
String CLUSTER_EXECUTE_FILTER_EXCEPTION = "2-19";
String CLUSTER_FAILED_GROUP_MERGE = "2-20";
// Proxy module. 3-1
String PROXY_FAILED_CONVERT_URL = "3-1";
String PROXY_FAILED_EXPORT_SERVICE = "3-2";
/**
* Absent. Merged with 3-8.
*/
String PROXY_33 = "3-3";
String PROXY_TIMEOUT_REQUEST = "3-4";
String PROXY_ERROR_ASYNC_RESPONSE = "3-5";
String PROXY_UNSUPPORTED_INVOKER = "3-6";
String PROXY_TIMEOUT_RESPONSE = "3-7";
String PROXY_FAILED = "3-8";
// Protocol module.
String PROTOCOL_UNSUPPORTED = "4-1";
String PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER = "4-2";
String PROTOCOL_FAILED_REFER_INVOKER = "4-3";
String PROTOCOL_UNSAFE_SERIALIZATION = "4-4";
String PROTOCOL_FAILED_CLOSE_STREAM = "4-5";
String PROTOCOL_ERROR_DESERIALIZE = "4-6";
String PROTOCOL_ERROR_CLOSE_CLIENT = "4-7";
String PROTOCOL_ERROR_CLOSE_SERVER = "4-8";
String PROTOCOL_FAILED_PARSE = "4-9";
String PROTOCOL_FAILED_SERIALIZE_TRIPLE = "4-10";
String PROTOCOL_FAILED_REQUEST = "4-11";
String PROTOCOL_FAILED_CREATE_STREAM_TRIPLE = "4-12";
String PROTOCOL_TIMEOUT_SERVER = "4-13";
String PROTOCOL_FAILED_RESPONSE = "4-14";
String PROTOCOL_STREAM_LISTENER = "4-15";
String PROTOCOL_CLOSED_SERVER = "4-16";
String PROTOCOL_FAILED_DESTROY_INVOKER = "4-17";
String PROTOCOL_FAILED_LOAD_MODEL = "4-18";
String PROTOCOL_INCORRECT_PARAMETER_VALUES = "4-19";
String PROTOCOL_FAILED_DECODE = "4-20";
String PROTOCOL_UNTRUSTED_SERIALIZE_CLASS = "4-21";
// Config module
String CONFIG_FAILED_CONNECT_REGISTRY = "5-1";
String CONFIG_FAILED_SHUTDOWN_HOOK = "5-2";
String CONFIG_FAILED_DESTROY_INVOKER = "5-3";
String CONFIG_NO_METHOD_FOUND = "5-4";
String CONFIG_FAILED_LOAD_ENV_VARIABLE = "5-5";
String CONFIG_PROPERTY_CONFLICT = "5-6";
String CONFIG_UNEXPORT_ERROR = "5-7";
String CONFIG_USE_RANDOM_PORT = "5-8";
String CONFIG_FAILED_EXPORT_SERVICE = "5-9";
String CONFIG_SERVER_DISCONNECTED = "5-10";
String CONFIG_REGISTER_INSTANCE_ERROR = "5-11";
String CONFIG_REFRESH_INSTANCE_ERROR = "5-12";
String CONFIG_UNABLE_DESTROY_MODEL = "5-13";
String CONFIG_FAILED_START_MODEL = "5-14";
String CONFIG_FAILED_REFERENCE_MODEL = "5-15";
String CONFIG_FAILED_FIND_PROTOCOL = "5-16";
String CONFIG_PARAMETER_FORMAT_ERROR = "5-17";
String CONFIG_FAILED_NOTIFY_EVENT = "5-18";
/**
* Absent. Changed to 81-4.
*/
String CONFIG_ZOOKEEPER_SERVER_ERROR = "5-19";
String CONFIG_STOP_DUBBO_ERROR = "5-20";
String CONFIG_FAILED_EXECUTE_DESTROY = "5-21";
String CONFIG_FAILED_INIT_CONFIG_CENTER = "5-22";
String CONFIG_FAILED_WAIT_EXPORT_REFER = "5-23";
String CONFIG_FAILED_REFER_SERVICE = "5-24";
String CONFIG_UNDEFINED_PROTOCOL = "5-25";
String CONFIG_METADATA_SERVICE_EXPORTED = "5-26";
String CONFIG_API_WRONG_USE = "5-27";
String CONFIG_NO_ANNOTATIONS_FOUND = "5-28";
String CONFIG_NO_BEANS_SCANNED = "5-29";
String CONFIG_DUPLICATED_BEAN_DEFINITION = "5-30";
String CONFIG_WARN_STATUS_CHECKER = "5-31";
String CONFIG_FAILED_CLOSE_CONNECT_APOLLO = "5-32";
String CONFIG_NOT_EFFECT_EMPTY_RULE_APOLLO = "5-33";
String CONFIG_ERROR_NACOS = "5-34";
String CONFIG_START_DUBBO_ERROR = "5-35";
String CONFIG_FILTER_VALIDATION_EXCEPTION = "5-36";
String CONFIG_ERROR_PROCESS_LISTENER = "5-37";
String CONFIG_UNDEFINED_ARGUMENT = "5-38";
String CONFIG_DUBBO_BEAN_INITIALIZER = "5-39";
String CONFIG_DUBBO_BEAN_NOT_FOUND = "5-40";
String CONFIG_SSL_PATH_LOAD_FAILED = "5-41";
String CONFIG_SSL_CERT_GENERATE_FAILED = "5-42";
String CONFIG_SSL_CONNECT_INSECURE = "5-43";
// Transport module
String TRANSPORT_FAILED_CONNECT_PROVIDER = "6-1";
String TRANSPORT_CLIENT_CONNECT_TIMEOUT = "6-2";
String TRANSPORT_FAILED_CLOSE = "6-3";
/**
* Absent. Merged to 99-0.
*/
String TRANSPORT_UNEXPECTED_EXCEPTION = "6-4";
String TRANSPORT_FAILED_DISCONNECT_PROVIDER = "6-5";
String TRANSPORT_UNSUPPORTED_MESSAGE = "6-6";
String TRANSPORT_CONNECTION_LIMIT_EXCEED = "6-7";
String TRANSPORT_FAILED_DECODE = "6-8";
String TRANSPORT_FAILED_SERIALIZATION = "6-9";
String TRANSPORT_EXCEED_PAYLOAD_LIMIT = "6-10";
String TRANSPORT_UNSUPPORTED_CHARSET = "6-11";
String TRANSPORT_FAILED_DESTROY_ZOOKEEPER = "6-12";
String TRANSPORT_FAILED_CLOSE_STREAM = "6-13";
String TRANSPORT_FAILED_RESPONSE = "6-14";
String TRANSPORT_SKIP_UNUSED_STREAM = "6-15";
String TRANSPORT_FAILED_RECONNECT = "6-16";
// qos plugin
String QOS_PROFILER_DISABLED = "7-1";
String QOS_PROFILER_ENABLED = "7-2";
String QOS_PROFILER_WARN_PERCENT = "7-3";
String QOS_FAILED_START_SERVER = "7-4";
String QOS_COMMAND_NOT_FOUND = "7-5";
String QOS_UNEXPECTED_EXCEPTION = "7-6";
String QOS_PERMISSION_DENY_EXCEPTION = "7-7";
// MCP plugin
String MCP_FAILED_START_SERVER = "8-1";
// Testing module (8[X], where [X] is number of the module to be tested.)
String TESTING_REGISTRY_FAILED_TO_START_ZOOKEEPER = "81-1";
String TESTING_REGISTRY_FAILED_TO_STOP_ZOOKEEPER = "81-2";
String TESTING_REGISTRY_FAILED_TO_DOWNLOAD_ZK_FILE = "81-3";
String TESTING_INIT_ZOOKEEPER_SERVER_ERROR = "81-4";
// Internal unknown error.
/**
* Unknown internal error. (99-0)
*/
String INTERNAL_ERROR = "99-0";
String INTERNAL_INTERRUPTED = "99-1";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java | dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.constants;
public interface RegistryConstants {
String REGISTRY_KEY = "registry";
String REGISTRY_CLUSTER_KEY = "REGISTRY_CLUSTER";
String REGISTRY_CLUSTER_TYPE_KEY = "registry-cluster-type";
String REGISTRY_PROTOCOL = "registry";
String DYNAMIC_KEY = "dynamic";
String CATEGORY_KEY = "category";
String PROVIDERS_CATEGORY = "providers";
String CONSUMERS_CATEGORY = "consumers";
String ROUTERS_CATEGORY = "routers";
String DYNAMIC_ROUTERS_CATEGORY = "dynamicrouters";
String DEFAULT_CATEGORY = PROVIDERS_CATEGORY;
String CONFIGURATORS_CATEGORY = "configurators";
String ALL_CATEGORIES = "providers,configurators,routers";
String DYNAMIC_CONFIGURATORS_CATEGORY = "dynamicconfigurators";
String APP_DYNAMIC_CONFIGURATORS_CATEGORY = "appdynamicconfigurators";
String ROUTERS_SUFFIX = ".routers";
String EMPTY_PROTOCOL = "empty";
String ROUTE_PROTOCOL = "route";
String ROUTE_SCRIPT_PROTOCOL = "script";
String OVERRIDE_PROTOCOL = "override";
String COMPATIBLE_CONFIG_KEY = "compatible_config";
String REGISTER_MODE_KEY = "register-mode";
String DUBBO_REGISTER_MODE_DEFAULT_KEY = "dubbo.application.register-mode";
String DUBBO_PUBLISH_INTERFACE_DEFAULT_KEY = "dubbo.application.publish-interface";
String DUBBO_PUBLISH_INSTANCE_DEFAULT_KEY = "dubbo.application.publish-instance";
String DEFAULT_REGISTER_MODE_INTERFACE = "interface";
String DEFAULT_REGISTER_MODE_INSTANCE = "instance";
String DEFAULT_REGISTER_MODE_ALL = "all";
/**
* The parameter key of Dubbo Registry type
*
* @since 2.7.5
*/
String REGISTRY_TYPE_KEY = "registry-type";
/**
* The parameter value of Service-Oriented Registry type
*
* @since 2.7.5
*/
String SERVICE_REGISTRY_TYPE = "service";
/**
* The protocol for Service Discovery
*
* @since 2.7.5
*/
String SERVICE_REGISTRY_PROTOCOL = "service-discovery-registry";
/**
* Specify registry level services consumer needs to subscribe to, multiple values should be separated using ",".
*/
String SUBSCRIBED_SERVICE_NAMES_KEY = "subscribed-services";
String PROVIDED_BY = "provided-by";
/**
* The provider tri port
*
* @since 3.1.0
*/
String PROVIDER_PORT = "provider-port";
/**
* provider namespace
*
* @since 3.1.1
*/
String PROVIDER_NAMESPACE = "provider-namespace";
/**
* The request size of service instances
*
* @since 2.7.5
*/
String INSTANCES_REQUEST_SIZE_KEY = "instances-request-size";
/**
* The default request size of service instances
*/
int DEFAULT_INSTANCES_REQUEST_SIZE = 100;
String ACCEPTS_KEY = "accepts";
String REGISTRY_ZONE = "registry_zone";
String REGISTRY_ZONE_FORCE = "registry_zone_force";
String ZONE_KEY = "zone";
String REGISTRY_SERVICE_REFERENCE_PATH = "org.apache.dubbo.registry.RegistryService";
String INIT = "INIT";
float DEFAULT_HASHMAP_LOAD_FACTOR = 0.75f;
String ENABLE_EMPTY_PROTECTION_KEY = "enable-empty-protection";
boolean DEFAULT_ENABLE_EMPTY_PROTECTION = false;
String REGISTER_CONSUMER_URL_KEY = "register-consumer-url";
String REGISTRY_PROTOCOL_TYPE = "registry-protocol-type";
/**
* export noting suffix servicename
* by default, dubbo export servicename is "${interface}:${version}:", this servicename with ':' suffix
* for compatible, we should export noting suffix servicename, eg: ${interface}:${version}
*/
String NACOS_REGISTER_COMPATIBLE = "nacos.register-compatible";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegisterTypeEnum.java | dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegisterTypeEnum.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.constants;
/**
* Indicate that a service need to be registered to registry or not
*/
public enum RegisterTypeEnum {
/**
* Never register. Cannot be registered by any command(like QoS-online).
*/
NEVER_REGISTER,
/**
* Manual register. Can be registered by command(like QoS-online), but not register by default.
*/
MANUAL_REGISTER,
/**
* (INTERNAL) Auto register by deployer. Will be registered after deployer started.
* (Delay publish when starting. Prevent service from being invoked before all services are started)
*/
AUTO_REGISTER_BY_DEPLOYER,
/**
* Auto register. Will be registered when one service is exported.
*/
AUTO_REGISTER;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/constants/QosConstants.java | dubbo-common/src/main/java/org/apache/dubbo/common/constants/QosConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.constants;
public interface QosConstants {
String QOS_ENABLE = "qos.enable";
String QOS_CHECK = "qos.check";
String QOS_HOST = "qos.host";
String QOS_PORT = "qos.port";
String ACCEPT_FOREIGN_IP = "qos.accept.foreign.ip";
String ACCEPT_FOREIGN_IP_WHITELIST = "qos.accept.foreign.ip.whitelist";
String ANONYMOUS_ACCESS_PERMISSION_LEVEL = "qos.anonymous.access.permission.level";
String ANONYMOUS_ACCESS_ALLOW_COMMANDS = "qos.anonymous.access.allow.commands";
String QOS_ENABLE_COMPATIBLE = "qos-enable";
String QOS_HOST_COMPATIBLE = "qos-host";
String QOS_PORT_COMPATIBLE = "qos-port";
String ACCEPT_FOREIGN_IP_COMPATIBLE = "qos-accept-foreign-ip";
String ACCEPT_FOREIGN_IP_WHITELIST_COMPATIBLE = "qos-accept-foreign-ip-whitelist";
String ANONYMOUS_ACCESS_PERMISSION_LEVEL_COMPATIBLE = "qos-anonymous-access-permission-level";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ClusterRules.java | dubbo-common/src/main/java/org/apache/dubbo/common/constants/ClusterRules.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.constants;
/**
* constant for Cluster fault-tolerant mode
*/
public interface ClusterRules {
/**
* When invoke fails, log the initial error and retry other invokers
* (retry n times, which means at most n different invokers will be invoked)
**/
String FAIL_OVER = "failover";
/**
* Execute exactly once, which means this policy will throw an exception immediately in case of an invocation error.
**/
String FAIL_FAST = "failfast";
/**
* When invoke fails, log the error message and ignore this error by returning an empty Result.
**/
String FAIL_SAFE = "failsafe";
/**
* When fails, record failure requests and schedule for retry on a regular interval.
**/
String FAIL_BACK = "failback";
/**
* Invoke a specific number of invokers concurrently, usually used for demanding real-time operations, but need to waste more service resources.
**/
String FORKING = "forking";
/**
* Call all providers by broadcast, call them one by one, and report an error if any one reports an error
**/
String BROADCAST = "broadcast";
String AVAILABLE = "available";
String MERGEABLE = "mergeable";
String EMPTY = "";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/context/Lifecycle.java | dubbo-common/src/main/java/org/apache/dubbo/common/context/Lifecycle.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.context;
import org.apache.dubbo.common.resource.Disposable;
/**
* The Lifecycle of Dubbo component
*
* @since 2.7.5
*/
public interface Lifecycle extends Disposable {
/**
* Initialize the component before {@link #start() start}
*
* @return current {@link Lifecycle}
* @throws IllegalStateException
*/
void initialize() throws IllegalStateException;
/**
* Start the component
*
* @return current {@link Lifecycle}
* @throws IllegalStateException
*/
void start() throws IllegalStateException;
/**
* Destroy the component
*
* @throws IllegalStateException
*/
void destroy() throws IllegalStateException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/context/LifecycleAdapter.java | dubbo-common/src/main/java/org/apache/dubbo/common/context/LifecycleAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.context;
public abstract class LifecycleAdapter implements Lifecycle {
@Override
public void initialize() throws IllegalStateException {}
@Override
public void start() throws IllegalStateException {}
@Override
public void destroy() throws IllegalStateException {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/context/ApplicationExt.java | dubbo-common/src/main/java/org/apache/dubbo/common/context/ApplicationExt.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.context;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
@SPI(scope = ExtensionScope.APPLICATION)
public interface ApplicationExt extends Lifecycle {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/context/ModuleExt.java | dubbo-common/src/main/java/org/apache/dubbo/common/context/ModuleExt.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.context;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
@SPI(scope = ExtensionScope.MODULE)
public interface ModuleExt extends Lifecycle {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToByteConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToByteConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert;
import org.apache.dubbo.common.utils.StringUtils;
/**
* The class to convert {@link String} to {@link Byte}
*
* @since 3.0.4
*/
public class StringToByteConverter implements StringConverter<Byte> {
@Override
public Byte convert(String source) {
return StringUtils.isNotEmpty(source) ? Byte.valueOf(source) : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 9;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToCharArrayConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToCharArrayConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
/**
* The class to convert {@link String} to <code>char[]</code>
*
* @since 2.7.6
*/
public class StringToCharArrayConverter implements StringConverter<char[]> {
@Override
public char[] convert(String source) {
return isNotEmpty(source) ? source.toCharArray() : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 7;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToFloatConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToFloatConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert;
import static java.lang.Float.valueOf;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
/**
* The class to convert {@link String} to {@link Float}
*
* @since 2.7.6
*/
public class StringToFloatConverter implements StringConverter<Float> {
@Override
public Float convert(String source) {
return isNotEmpty(source) ? valueOf(source) : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 4;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/ConverterUtil.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/ConverterUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
public class ConverterUtil {
private final FrameworkModel frameworkModel;
private final ConcurrentMap<Class<?>, ConcurrentMap<Class<?>, List<Converter>>> converterCache =
new ConcurrentHashMap<>();
public ConverterUtil(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
/**
* Get the Converter instance from {@link ExtensionLoader} with the specified source and target type
*
* @param sourceType the source type
* @param targetType the target type
* @return
* @see ExtensionLoader#getSupportedExtensionInstances()
*/
public Converter<?, ?> getConverter(Class<?> sourceType, Class<?> targetType) {
ConcurrentMap<Class<?>, List<Converter>> toTargetMap =
ConcurrentHashMapUtils.computeIfAbsent(converterCache, sourceType, (k) -> new ConcurrentHashMap<>());
List<Converter> converters = ConcurrentHashMapUtils.computeIfAbsent(
toTargetMap,
targetType,
(k) -> frameworkModel.getExtensionLoader(Converter.class).getSupportedExtensionInstances().stream()
.filter(converter -> converter.accept(sourceType, targetType))
.collect(Collectors.toList()));
return converters.size() > 0 ? converters.get(0) : null;
}
/**
* Convert the value of source to target-type value if possible
*
* @param source the value of source
* @param targetType the target type
* @param <T> the target type
* @return <code>null</code> if can't be converted
* @since 2.7.8
*/
public <T> T convertIfPossible(Object source, Class<T> targetType) {
Converter converter = getConverter(source.getClass(), targetType);
if (converter != null) {
return (T) converter.convert(source);
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToOptionalConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToOptionalConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert;
import java.util.Optional;
import static java.util.Optional.ofNullable;
/**
* The class to convert {@link String} to {@link Optional}
*
* @since 2.7.6
*/
public class StringToOptionalConverter implements StringConverter<Optional> {
@Override
public Optional convert(String source) {
return ofNullable(source);
}
@Override
public int getPriority() {
return MIN_PRIORITY;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToIntegerConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToIntegerConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert;
import static java.lang.Integer.valueOf;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
/**
* The class to convert {@link String} to {@link Integer}
*
* @since 2.7.6
*/
public class StringToIntegerConverter implements StringConverter<Integer> {
@Override
public Integer convert(String source) {
return isNotEmpty(source) ? valueOf(source) : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToDoubleConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToDoubleConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert;
import static java.lang.Double.valueOf;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
/**
* The class to convert {@link String} to {@link Double}
*
* @since 2.7.6
*/
public class StringToDoubleConverter implements StringConverter<Double> {
@Override
public Double convert(String source) {
return isNotEmpty(source) ? valueOf(source) : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 3;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToDurationConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToDurationConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.common.utils.StringUtils;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
public class StringToDurationConverter implements StringConverter<Duration> {
@Override
public Duration convert(String source) {
return isNotEmpty(source) ? DurationStyle.detectAndParse(source) : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 10;
}
enum DurationStyle {
/**
* Simple formatting, for example '1s'.
*/
SIMPLE("^([+-]?\\d+)([a-zA-Z]{0,2})$") {
@Override
public Duration parse(String value, ChronoUnit unit) {
try {
Matcher matcher = matcher(value);
Assert.assertTrue(matcher.matches(), "Does not match simple duration pattern");
String suffix = matcher.group(2);
return (StringUtils.isNotBlank(suffix)
? TimeUnit.fromSuffix(suffix)
: TimeUnit.fromChronoUnit(unit))
.parse(matcher.group(1));
} catch (Exception ex) {
throw new IllegalArgumentException("'" + value + "' is not a valid simple duration", ex);
}
}
},
/**
* ISO-8601 formatting.
*/
ISO8601("^[+-]?[pP].*$") {
@Override
public Duration parse(String value, ChronoUnit unit) {
try {
return Duration.parse(value);
} catch (Exception ex) {
throw new IllegalArgumentException("'" + value + "' is not a valid ISO-8601 duration", ex);
}
}
};
private final Pattern pattern;
DurationStyle(String pattern) {
this.pattern = Pattern.compile(pattern);
}
protected final boolean matches(String value) {
return this.pattern.matcher(value).matches();
}
protected final Matcher matcher(String value) {
return this.pattern.matcher(value);
}
/**
* Parse the given value to a duration.
*
* @param value the value to parse
* @return a duration
*/
public Duration parse(String value) {
return parse(value, null);
}
/**
* Parse the given value to a duration.
*
* @param value the value to parse
* @param unit the duration unit to use if the value doesn't specify one ({@code null}
* will default to ms)
* @return a duration
*/
public abstract Duration parse(String value, ChronoUnit unit);
/**
* Detect the style then parse the value to return a duration.
*
* @param value the value to parse
* @return the parsed duration
* @throws IllegalArgumentException if the value is not a known style or cannot be
* parsed
*/
public static Duration detectAndParse(String value) {
return detectAndParse(value, null);
}
/**
* Detect the style then parse the value to return a duration.
*
* @param value the value to parse
* @param unit the duration unit to use if the value doesn't specify one ({@code null}
* will default to ms)
* @return the parsed duration
* @throws IllegalArgumentException if the value is not a known style or cannot be
* parsed
*/
public static Duration detectAndParse(String value, ChronoUnit unit) {
return detect(value).parse(value, unit);
}
/**
* Detect the style from the given source value.
*
* @param value the source value
* @return the duration style
* @throws IllegalArgumentException if the value is not a known style
*/
public static DurationStyle detect(String value) {
Assert.notNull(value, "Value must not be null");
for (DurationStyle candidate : values()) {
if (candidate.matches(value)) {
return candidate;
}
}
throw new IllegalArgumentException("'" + value + "' is not a valid duration");
}
/**
* Time Unit that support.
*/
enum TimeUnit {
/**
* Nanoseconds.
*/
NANOS(ChronoUnit.NANOS, "ns", Duration::toNanos),
/**
* Microseconds.
*/
MICROS(ChronoUnit.MICROS, "us", (duration) -> duration.toNanos() / 1000L),
/**
* Milliseconds.
*/
MILLIS(ChronoUnit.MILLIS, "ms", Duration::toMillis),
/**
* Seconds.
*/
SECONDS(ChronoUnit.SECONDS, "s", Duration::getSeconds),
/**
* Minutes.
*/
MINUTES(ChronoUnit.MINUTES, "m", Duration::toMinutes),
/**
* Hours.
*/
HOURS(ChronoUnit.HOURS, "h", Duration::toHours),
/**
* Days.
*/
DAYS(ChronoUnit.DAYS, "d", Duration::toDays);
private final ChronoUnit chronoUnit;
private final String suffix;
private final Function<Duration, Long> longValue;
TimeUnit(ChronoUnit chronoUnit, String suffix, Function<Duration, Long> toUnit) {
this.chronoUnit = chronoUnit;
this.suffix = suffix;
this.longValue = toUnit;
}
public Duration parse(String value) {
return Duration.of(Long.parseLong(value), this.chronoUnit);
}
public long longValue(Duration value) {
return this.longValue.apply(value);
}
public static TimeUnit fromChronoUnit(ChronoUnit chronoUnit) {
if (chronoUnit == null) {
return TimeUnit.MILLIS;
}
for (TimeUnit candidate : values()) {
if (candidate.chronoUnit == chronoUnit) {
return candidate;
}
}
throw new IllegalArgumentException("Unknown unit " + chronoUnit);
}
public static TimeUnit fromSuffix(String suffix) {
for (TimeUnit candidate : values()) {
if (candidate.suffix.equalsIgnoreCase(suffix)) {
return candidate;
}
}
throw new IllegalArgumentException("Unknown unit '" + suffix + "'");
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/Converter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/Converter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.lang.Prioritized;
import static org.apache.dubbo.common.utils.ClassUtils.isAssignableFrom;
import static org.apache.dubbo.common.utils.TypeUtils.findActualTypeArgument;
/**
* A class to convert the source-typed value to the target-typed value
*
* @param <S> The source type
* @param <T> The target type
* @since 2.7.6
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
@FunctionalInterface
public interface Converter<S, T> extends Prioritized {
/**
* Accept the source type and target type or not
*
* @param sourceType the source type
* @param targetType the target type
* @return if accepted, return <code>true</code>, or <code>false</code>
*/
default boolean accept(Class<?> sourceType, Class<?> targetType) {
return isAssignableFrom(sourceType, getSourceType()) && isAssignableFrom(targetType, getTargetType());
}
/**
* Convert the source-typed value to the target-typed value
*
* @param source the source-typed value
* @return the target-typed value
*/
T convert(S source);
/**
* Get the source type
*
* @return non-null
*/
default Class<S> getSourceType() {
return findActualTypeArgument(getClass(), Converter.class, 0);
}
/**
* Get the target type
*
* @return non-null
*/
default Class<T> getTargetType() {
return findActualTypeArgument(getClass(), Converter.class, 1);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToShortConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToShortConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert;
import static java.lang.Short.valueOf;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
/**
* The class to convert {@link String} to {@link Short}
*
* @since 2.7.6
*/
public class StringToShortConverter implements StringConverter<Short> {
@Override
public Short convert(String source) {
return isNotEmpty(source) ? valueOf(source) : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 2;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToCharacterConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToCharacterConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert;
import static org.apache.dubbo.common.utils.StringUtils.length;
/**
* The class to convert {@link String} to {@link Character}
*
* @since 2.7.6
*/
public class StringToCharacterConverter implements StringConverter<Character> {
@Override
public Character convert(String source) {
int length = length(source);
if (length == 0) {
return null;
}
if (length > 1) {
throw new IllegalArgumentException("The source String is more than one character!");
}
return source.charAt(0);
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 8;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToStringConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToStringConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert;
/**
* A class to covert {@link String} to {@link String} value, just no-op
*
* @since 2.7.6
*/
public class StringToStringConverter implements StringConverter<String> {
@Override
public String convert(String source) {
return source;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert;
/**
* A class to covert {@link String} to the target-typed value
*
* @see Converter
* @since 2.7.6
*/
@FunctionalInterface
public interface StringConverter<T> extends Converter<String, T> {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToBooleanConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToBooleanConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert;
import static java.lang.Boolean.valueOf;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
/**
* The class to convert {@link String} to {@link Boolean}
*
* @since 2.7.6
*/
public class StringToBooleanConverter implements StringConverter<Boolean> {
@Override
public Boolean convert(String source) {
return isNotEmpty(source) ? valueOf(source) : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 5;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToLongConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToLongConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert;
import static java.lang.Long.valueOf;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
/**
* The class to convert {@link String} to {@link Long}
*
* @since 2.7.6
*/
public class StringToLongConverter implements StringConverter<Long> {
@Override
public Long convert(String source) {
return isNotEmpty(source) ? valueOf(source) : null;
}
@Override
public int getPriority() {
return NORMAL_PRIORITY + 1;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToBlockingDequeConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToBlockingDequeConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
/**
* The class to convert {@link String} to {@link BlockingDeque}-based value
*
* @since 2.7.6
*/
public class StringToBlockingDequeConverter extends StringToIterableConverter<BlockingDeque> {
public StringToBlockingDequeConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected BlockingDeque createMultiValue(int size, Class<?> multiValueType) {
return new LinkedBlockingDeque(size);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToCollectionConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToCollectionConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.Collection;
/**
* The class to convert {@link String} to {@link Collection}-based value
*
* @since 2.7.6
*/
public class StringToCollectionConverter extends StringToIterableConverter<Collection> {
public StringToCollectionConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected Collection createMultiValue(int size, Class<?> multiValueType) {
return new ArrayList(size);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/MultiValueConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/MultiValueConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.lang.Prioritized;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Collection;
import static org.apache.dubbo.common.utils.TypeUtils.findActualTypeArgument;
/**
* An interface to convert the source-typed value to multiple value, e.g , Java array, {@link Collection} or
* sub-interfaces
*
* @param <S> The source type
* @since 2.7.6
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface MultiValueConverter<S> extends Prioritized {
/**
* Accept the source type and target type or not
*
* @param sourceType the source type
* @param multiValueType the multi-value type
* @return if accepted, return <code>true</code>, or <code>false</code>
*/
boolean accept(Class<S> sourceType, Class<?> multiValueType);
/**
* Convert the source to be the multiple value
*
* @param source the source-typed value
* @param multiValueType the multi-value type
* @param elementType the element type
* @return
*/
Object convert(S source, Class<?> multiValueType, Class<?> elementType);
/**
* Get the source type
*
* @return non-null
*/
default Class<S> getSourceType() {
return findActualTypeArgument(getClass(), MultiValueConverter.class, 0);
}
/**
* Find the {@link MultiValueConverter} instance from {@link ExtensionLoader} with the specified source and target type
*
* @param sourceType the source type
* @param targetType the target type
* @return <code>null</code> if not found
* @see ExtensionLoader#getSupportedExtensionInstances()
* @since 2.7.8
* @deprecated will be removed in 3.3.0
*/
@Deprecated
static MultiValueConverter<?> find(Class<?> sourceType, Class<?> targetType) {
return FrameworkModel.defaultModel()
.getExtensionLoader(MultiValueConverter.class)
.getSupportedExtensionInstances()
.stream()
.filter(converter -> converter.accept(sourceType, targetType))
.findFirst()
.orElse(null);
}
/**
* @deprecated will be removed in 3.3.0
*/
@Deprecated
static <T> T convertIfPossible(Object source, Class<?> multiValueType, Class<?> elementType) {
Class<?> sourceType = source.getClass();
MultiValueConverter converter = find(sourceType, multiValueType);
if (converter != null) {
return (T) converter.convert(source, multiValueType, elementType);
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToSortedSetConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToSortedSetConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* The class to convert {@link String} to {@link SortedSet}-based value
*
* @since 2.7.6
*/
public class StringToSortedSetConverter extends StringToIterableConverter<SortedSet> {
public StringToSortedSetConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected SortedSet createMultiValue(int size, Class<?> multiValueType) {
return new TreeSet();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToMultiValueConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToMultiValueConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.common.utils.ArrayUtils;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
import static org.apache.dubbo.common.utils.StringUtils.split;
/**
* The class to convert {@link String} to multiple value object
*
* @see MultiValueConverter
* @since 2.7.6
*/
public interface StringToMultiValueConverter extends MultiValueConverter<String> {
@Override
default Object convert(String source, Class<?> multiValueType, Class<?> elementType) {
if (isEmpty(source)) {
return null;
}
// split by the comma
String[] segments = split(source, ',');
if (ArrayUtils.isEmpty(segments)) { // If empty array, create an array with only one element
segments = new String[] {source};
}
int size = segments.length;
return convert(segments, size, multiValueType, elementType);
}
/**
* Convert the segments to multiple value object
*
* @param segments the String array of content
* @param size the size of multiple value object
* @param targetType the target type
* @param elementType the element type
* @return multiple value object
*/
Object convert(String[] segments, int size, Class<?> targetType, Class<?> elementType);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToArrayConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToArrayConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.common.convert.Converter;
import org.apache.dubbo.common.convert.ConverterUtil;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.lang.reflect.Array;
import static java.lang.reflect.Array.newInstance;
/**
* The class to convert {@link String} to array-type object
*
* @since 2.7.6
*/
public class StringToArrayConverter implements StringToMultiValueConverter {
private ConverterUtil converterUtil;
public StringToArrayConverter(FrameworkModel frameworkModel) {
converterUtil = frameworkModel.getBeanFactory().getBean(ConverterUtil.class);
}
public boolean accept(Class<String> type, Class<?> multiValueType) {
if (multiValueType != null && multiValueType.isArray()) {
return true;
}
return false;
}
@Override
public Object convert(String[] segments, int size, Class<?> targetType, Class<?> elementType) {
Class<?> componentType = targetType.getComponentType();
Converter converter = converterUtil.getConverter(String.class, componentType);
Object array = newInstance(componentType, size);
for (int i = 0; i < size; i++) {
Array.set(array, i, converter.convert(segments[i]));
}
return array;
}
@Override
public int getPriority() {
return MIN_PRIORITY;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToSetConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToSetConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.HashSet;
import java.util.Set;
/**
* The class to convert {@link String} to {@link Set}-based value
*
* @since 2.7.6
*/
public class StringToSetConverter extends StringToIterableConverter<Set> {
public StringToSetConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected Set createMultiValue(int size, Class<?> multiValueType) {
return new HashSet(size);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToDequeConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToDequeConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* The class to convert {@link String} to {@link Deque}-based value
*
* @since 2.7.6
*/
public class StringToDequeConverter extends StringToIterableConverter<Deque> {
public StringToDequeConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected Deque createMultiValue(int size, Class<?> multiValueType) {
return new ArrayDeque(size);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToBlockingQueueConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToBlockingQueueConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
/**
* The class to convert {@link String} to {@link BlockingDeque}-based value
*
* @since 2.7.6
*/
public class StringToBlockingQueueConverter extends StringToIterableConverter<BlockingQueue> {
public StringToBlockingQueueConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected BlockingQueue createMultiValue(int size, Class<?> multiValueType) {
return new ArrayBlockingQueue(size);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToIterableConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToIterableConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.common.convert.ConverterUtil;
import org.apache.dubbo.common.convert.StringConverter;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Collection;
import java.util.Optional;
import static org.apache.dubbo.common.utils.ClassUtils.getAllInterfaces;
import static org.apache.dubbo.common.utils.ClassUtils.isAssignableFrom;
import static org.apache.dubbo.common.utils.TypeUtils.findActualTypeArgument;
/**
* The class to convert {@link String} to {@link Iterable}-based value
*
* @since 2.7.6
*/
public abstract class StringToIterableConverter<T extends Iterable> implements StringToMultiValueConverter {
private ConverterUtil converterUtil;
public StringToIterableConverter(FrameworkModel frameworkModel) {
converterUtil = frameworkModel.getBeanFactory().getBean(ConverterUtil.class);
}
public boolean accept(Class<String> type, Class<?> multiValueType) {
return isAssignableFrom(getSupportedType(), multiValueType);
}
@Override
public final Object convert(String[] segments, int size, Class<?> multiValueType, Class<?> elementType) {
Optional<StringConverter> stringConverter = getStringConverter(elementType);
return stringConverter
.map(converter -> {
T convertedObject = createMultiValue(size, multiValueType);
if (convertedObject instanceof Collection) {
Collection collection = (Collection) convertedObject;
for (int i = 0; i < size; i++) {
String segment = segments[i];
Object element = converter.convert(segment);
collection.add(element);
}
return collection;
}
return convertedObject;
})
.orElse(null);
}
protected abstract T createMultiValue(int size, Class<?> multiValueType);
protected Optional<StringConverter> getStringConverter(Class<?> elementType) {
StringConverter converter = (StringConverter) converterUtil.getConverter(String.class, elementType);
return Optional.ofNullable(converter);
}
protected final Class<T> getSupportedType() {
return findActualTypeArgument(getClass(), StringToIterableConverter.class, 0);
}
@Override
public final int getPriority() {
int level = getAllInterfaces(getSupportedType(), type -> isAssignableFrom(Iterable.class, type))
.size();
return MIN_PRIORITY - level;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToListConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToListConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.List;
/**
* The class to convert {@link String} to {@link List}-based value
*
* @since 2.7.6
*/
public class StringToListConverter extends StringToIterableConverter<List> {
public StringToListConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected List createMultiValue(int size, Class<?> multiValueType) {
return new ArrayList(size);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToQueueConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToQueueConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Queue;
/**
* The class to convert {@link String} to {@link Deque}-based value
*
* @since 2.7.6
*/
public class StringToQueueConverter extends StringToIterableConverter<Queue> {
public StringToQueueConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected Queue createMultiValue(int size, Class<?> multiValueType) {
return new ArrayDeque(size);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToNavigableSetConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToNavigableSetConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.NavigableSet;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* The class to convert {@link String} to {@link SortedSet}-based value
*
* @since 2.7.6
*/
public class StringToNavigableSetConverter extends StringToIterableConverter<NavigableSet> {
public StringToNavigableSetConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected NavigableSet createMultiValue(int size, Class<?> multiValueType) {
return new TreeSet();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToTransferQueueConverter.java | dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToTransferQueueConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.convert.multiple;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;
/**
* The class to convert {@link String} to {@link TransferQueue}-based value
*
* @since 2.7.6
*/
public class StringToTransferQueueConverter extends StringToIterableConverter<TransferQueue> {
public StringToTransferQueueConverter(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected TransferQueue createMultiValue(int size, Class<?> multiValueType) {
return new LinkedTransferQueue();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/serialization/ClassHolder.java | dubbo-common/src/main/java/org/apache/dubbo/common/serialization/ClassHolder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialization;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class ClassHolder {
private final ConcurrentHashMap<String, Set<Class<?>>> classCache = new ConcurrentHashMap<>();
public void storeClass(Class<?> clazz) {
ConcurrentHashMapUtils.computeIfAbsent(classCache, clazz.getName(), k -> new ConcurrentHashSet<>())
.add(clazz);
}
public Class<?> loadClass(String className, ClassLoader classLoader) {
Set<Class<?>> classList = classCache.get(className);
if (classList == null) {
return null;
}
for (Class<?> clazz : classList) {
if (classLoader.equals(clazz.getClassLoader())) {
return clazz;
}
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/serialization/PreferSerializationProvider.java | dubbo-common/src/main/java/org/apache/dubbo/common/serialization/PreferSerializationProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialization;
public interface PreferSerializationProvider {
String getPreferSerialization();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/Compiler.java | dubbo-common/src/main/java/org/apache/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 org.apache.dubbo.common.compiler;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* Compiler. (SPI, Singleton, ThreadSafe)
*/
@SPI(value = "javassist", scope = ExtensionScope.FRAMEWORK)
public interface Compiler {
/**
* Compile java source code.
*
* @param code Java source code
* @param classLoader classloader
* @return Compiled class
* @deprecated use {@link Compiler#compile(Class, String, ClassLoader)} to support JDK 16
*/
@Deprecated
default Class<?> compile(String code, ClassLoader classLoader) {
return compile(null, code, classLoader);
}
/**
* Compile java source code.
*
* @param neighbor A class belonging to the same package that this
* class belongs to. It is used to load the class. (For JDK 16 and above)
* @param code Java source code
* @param classLoader classloader
* @return Compiled class
*/
default Class<?> compile(Class<?> neighbor, String code, ClassLoader classLoader) {
return compile(code, classLoader);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JdkCompiler.java | dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JdkCompiler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.compiler.support;
import javax.tools.DiagnosticCollector;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* JdkCompiler. (SPI, Singleton, ThreadSafe)
*/
public class JdkCompiler extends AbstractCompiler {
private final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
private final DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
private final ClassLoaderImpl classLoader;
private final JavaFileManagerImpl javaFileManager;
private final List<String> options;
private static final String DEFAULT_JAVA_VERSION = "1.8";
private static List<String> buildDefaultOptions(String javaVersion) {
return Arrays.asList("-source", javaVersion, "-target", javaVersion);
}
private static List<String> buildDefaultOptions() {
return buildDefaultOptions(DEFAULT_JAVA_VERSION);
}
public JdkCompiler(List<String> options) {
this.options = new ArrayList<>(options);
StandardJavaFileManager manager = compiler.getStandardFileManager(diagnosticCollector, null, null);
final ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (loader instanceof URLClassLoader
&& (!"sun.misc.Launcher$AppClassLoader".equals(loader.getClass().getName()))) {
try {
URLClassLoader urlClassLoader = (URLClassLoader) loader;
List<File> files = new ArrayList<>();
for (URL url : urlClassLoader.getURLs()) {
files.add(new File(url.getFile()));
}
manager.setLocation(StandardLocation.CLASS_PATH, files);
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoaderImpl>() {
@Override
public ClassLoaderImpl run() {
return new ClassLoaderImpl(loader);
}
});
javaFileManager = new JavaFileManagerImpl(manager, classLoader);
}
public JdkCompiler() {
this(buildDefaultOptions());
}
public JdkCompiler(String javaVersion) {
this(buildDefaultOptions(javaVersion));
}
@Override
public Class<?> doCompile(ClassLoader ignored, String name, String sourceCode) throws Throwable {
int i = name.lastIndexOf('.');
String packageName = i < 0 ? "" : name.substring(0, i);
String className = i < 0 ? name : name.substring(i + 1);
JavaFileObjectImpl javaFileObject = new JavaFileObjectImpl(className, sourceCode);
javaFileManager.putFileForInput(
StandardLocation.SOURCE_PATH, packageName, className + ClassUtils.JAVA_EXTENSION, javaFileObject);
Boolean result = compiler.getTask(
null,
javaFileManager,
diagnosticCollector,
options,
null,
Collections.singletonList(javaFileObject))
.call();
if (result == null || !result) {
throw new IllegalStateException(
"Compilation failed. class: " + name + ", diagnostics: " + diagnosticCollector.getDiagnostics());
}
return classLoader.loadClass(name);
}
private static final class JavaFileObjectImpl extends SimpleJavaFileObject {
private final CharSequence source;
private ByteArrayOutputStream bytecode;
public JavaFileObjectImpl(final String baseName, final CharSequence source) {
super(ClassUtils.toURI(baseName + ClassUtils.JAVA_EXTENSION), Kind.SOURCE);
this.source = source;
}
JavaFileObjectImpl(final String name, final Kind kind) {
super(ClassUtils.toURI(name), kind);
source = null;
}
public JavaFileObjectImpl(URI uri, Kind kind) {
super(uri, kind);
source = null;
}
@Override
public CharSequence getCharContent(final boolean ignoreEncodingErrors) throws UnsupportedOperationException {
if (source == null) {
throw new UnsupportedOperationException("source == null");
}
return source;
}
@Override
public InputStream openInputStream() {
return new ByteArrayInputStream(getByteCode());
}
@Override
public OutputStream openOutputStream() {
return bytecode = new ByteArrayOutputStream();
}
public byte[] getByteCode() {
return bytecode.toByteArray();
}
}
private static final class JavaFileManagerImpl extends ForwardingJavaFileManager<JavaFileManager> {
private final ClassLoaderImpl classLoader;
private final Map<URI, JavaFileObject> fileObjects = new HashMap<>();
public JavaFileManagerImpl(JavaFileManager fileManager, ClassLoaderImpl classLoader) {
super(fileManager);
this.classLoader = classLoader;
}
@Override
public FileObject getFileForInput(Location location, String packageName, String relativeName)
throws IOException {
FileObject o = fileObjects.get(uri(location, packageName, relativeName));
if (o != null) {
return o;
}
return super.getFileForInput(location, packageName, relativeName);
}
public void putFileForInput(
StandardLocation location, String packageName, String relativeName, JavaFileObject file) {
fileObjects.put(uri(location, packageName, relativeName), file);
}
private URI uri(Location location, String packageName, String relativeName) {
return ClassUtils.toURI(location.getName() + '/' + packageName + '/' + relativeName);
}
@Override
public JavaFileObject getJavaFileForOutput(
Location location, String qualifiedName, Kind kind, FileObject outputFile) throws IOException {
JavaFileObject file = new JavaFileObjectImpl(qualifiedName, kind);
classLoader.add(qualifiedName, file);
return file;
}
@Override
public ClassLoader getClassLoader(JavaFileManager.Location location) {
return classLoader;
}
@Override
public String inferBinaryName(Location loc, JavaFileObject file) {
if (file instanceof JavaFileObjectImpl) {
return file.getName();
}
return super.inferBinaryName(loc, file);
}
@Override
public Iterable<JavaFileObject> list(Location location, String packageName, Set<Kind> kinds, boolean recurse)
throws IOException {
Iterable<JavaFileObject> result = super.list(location, packageName, kinds, recurse);
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
ArrayList<JavaFileObject> files = new ArrayList<>();
if (location == StandardLocation.CLASS_PATH && kinds.contains(JavaFileObject.Kind.CLASS)) {
for (JavaFileObject file : fileObjects.values()) {
if (file.getKind() == Kind.CLASS && file.getName().startsWith(packageName)) {
files.add(file);
}
}
files.addAll(classLoader.files());
} else if (location == StandardLocation.SOURCE_PATH && kinds.contains(JavaFileObject.Kind.SOURCE)) {
for (JavaFileObject file : fileObjects.values()) {
if (file.getKind() == Kind.SOURCE && file.getName().startsWith(packageName)) {
files.add(file);
}
}
}
for (JavaFileObject file : result) {
files.add(file);
}
return files;
}
}
private static final class ClassLoaderImpl extends ClassLoader {
private final Map<String, JavaFileObject> classes = new HashMap<>();
ClassLoaderImpl(final ClassLoader parentClassLoader) {
super(parentClassLoader);
}
Collection<JavaFileObject> files() {
return Collections.unmodifiableCollection(classes.values());
}
@Override
protected Class<?> findClass(final String qualifiedClassName) throws ClassNotFoundException {
JavaFileObject file = classes.get(qualifiedClassName);
if (file != null) {
byte[] bytes = ((JavaFileObjectImpl) file).getByteCode();
return defineClass(qualifiedClassName, bytes, 0, bytes.length);
}
try {
return org.apache.dubbo.common.utils.ClassUtils.forNameWithCallerClassLoader(
qualifiedClassName, getClass());
} catch (ClassNotFoundException nf) {
return super.findClass(qualifiedClassName);
}
}
void add(final String qualifiedClassName, final JavaFileObject javaFile) {
classes.put(qualifiedClassName, javaFile);
}
@Override
protected synchronized Class<?> loadClass(final String name, final boolean resolve)
throws ClassNotFoundException {
return super.loadClass(name, resolve);
}
@Override
public InputStream getResourceAsStream(final String name) {
if (name.endsWith(ClassUtils.CLASS_EXTENSION)) {
String qualifiedClassName = name.substring(0, name.length() - ClassUtils.CLASS_EXTENSION.length())
.replace('/', '.');
JavaFileObjectImpl file = (JavaFileObjectImpl) classes.get(qualifiedClassName);
if (file != null) {
return new ByteArrayInputStream(file.getByteCode());
}
}
return super.getResourceAsStream(name);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AbstractCompiler.java | dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AbstractCompiler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.compiler.support;
import org.apache.dubbo.common.compiler.Compiler;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Abstract compiler. (SPI, Prototype, ThreadSafe)
*/
public abstract class AbstractCompiler implements Compiler {
private static final Pattern PACKAGE_PATTERN = Pattern.compile("package\\s+([$_a-zA-Z][$_a-zA-Z0-9\\.]*);");
private static final Pattern CLASS_PATTERN = Pattern.compile("class\\s+([$_a-zA-Z][$_a-zA-Z0-9]*)\\s+");
private static final Map<String, Lock> CLASS_IN_CREATION_MAP = new ConcurrentHashMap<>();
@Override
public Class<?> compile(Class<?> neighbor, String code, ClassLoader classLoader) {
code = code.trim();
Matcher matcher = PACKAGE_PATTERN.matcher(code);
String pkg;
if (matcher.find()) {
pkg = matcher.group(1);
} else {
pkg = "";
}
matcher = CLASS_PATTERN.matcher(code);
String cls;
if (matcher.find()) {
cls = matcher.group(1);
} else {
throw new IllegalArgumentException("No such class name in " + code);
}
String className = pkg != null && pkg.length() > 0 ? pkg + "." + cls : cls;
Lock lock = CLASS_IN_CREATION_MAP.get(className);
if (lock == null) {
CLASS_IN_CREATION_MAP.putIfAbsent(className, new ReentrantLock());
lock = CLASS_IN_CREATION_MAP.get(className);
}
try {
lock.lock();
return Class.forName(className, true, classLoader);
} catch (ClassNotFoundException e) {
if (!code.endsWith("}")) {
throw new IllegalStateException("The java code not endsWith \"}\", code: \n" + code + "\n");
}
try {
return doCompile(neighbor, classLoader, className, code);
} catch (RuntimeException t) {
throw t;
} catch (Throwable t) {
throw new IllegalStateException("Failed to compile class, cause: " + t.getMessage() + ", class: "
+ className + ", code: \n" + code + "\n, stack: " + ClassUtils.toString(t));
}
} finally {
lock.unlock();
}
}
protected Class<?> doCompile(ClassLoader classLoader, String name, String source) throws Throwable {
return null;
}
protected Class<?> doCompile(Class<?> neighbor, ClassLoader classLoader, String name, String source)
throws Throwable {
return doCompile(classLoader, name, source);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/CtClassBuilder.java | dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/CtClassBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.compiler.support;
import org.apache.dubbo.common.bytecode.DubboLoaderClassPath;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.CtNewConstructor;
import javassist.CtNewMethod;
import javassist.LoaderClassPath;
import javassist.NotFoundException;
/**
* CtClassBuilder is builder for CtClass
* <p>
* contains all the information, including:
* <p>
* class name, imported packages, super class name, implemented interfaces, constructors, fields, methods.
*/
public class CtClassBuilder {
private String className;
private String superClassName = "java.lang.Object";
private final List<String> imports = new ArrayList<>();
private final Map<String, String> fullNames = new HashMap<>();
private final List<String> ifaces = new ArrayList<>();
private final List<String> constructors = new ArrayList<>();
private final List<String> fields = new ArrayList<>();
private final List<String> methods = new ArrayList<>();
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getSuperClassName() {
return superClassName;
}
public void setSuperClassName(String superClassName) {
this.superClassName = getQualifiedClassName(superClassName);
}
public List<String> getImports() {
return imports;
}
public void addImports(String pkg) {
int pi = pkg.lastIndexOf('.');
if (pi > 0) {
String pkgName = pkg.substring(0, pi);
this.imports.add(pkgName);
if (!pkg.endsWith(".*")) {
fullNames.put(pkg.substring(pi + 1), pkg);
}
}
}
public List<String> getInterfaces() {
return ifaces;
}
public void addInterface(String iface) {
this.ifaces.add(getQualifiedClassName(iface));
}
public List<String> getConstructors() {
return constructors;
}
public void addConstructor(String constructor) {
this.constructors.add(constructor);
}
public List<String> getFields() {
return fields;
}
public void addField(String field) {
this.fields.add(field);
}
public List<String> getMethods() {
return methods;
}
public void addMethod(String method) {
this.methods.add(method);
}
/**
* get full qualified class name
*
* @param className super class name, maybe qualified or not
*/
protected String getQualifiedClassName(String className) {
if (className.contains(".")) {
return className;
}
if (fullNames.containsKey(className)) {
return fullNames.get(className);
}
return ClassUtils.forName(imports.toArray(new String[0]), className).getName();
}
/**
* build CtClass object
*/
public CtClass build(ClassLoader classLoader) throws NotFoundException, CannotCompileException {
ClassPool pool = new ClassPool(true);
pool.insertClassPath(new LoaderClassPath(classLoader));
pool.insertClassPath(new DubboLoaderClassPath());
// create class
CtClass ctClass = pool.makeClass(className, pool.get(superClassName));
// add imported packages
imports.forEach(pool::importPackage);
// add implemented interfaces
for (String iface : ifaces) {
ctClass.addInterface(pool.get(iface));
}
// add constructors
for (String constructor : constructors) {
ctClass.addConstructor(CtNewConstructor.make(constructor, ctClass));
}
// add fields
for (String field : fields) {
ctClass.addField(CtField.make(field, ctClass));
}
// add methods
for (String method : methods) {
ctClass.addMethod(CtNewMethod.make(method, ctClass));
}
return ctClass;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JavassistCompiler.java | dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JavassistCompiler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.compiler.support;
import org.apache.dubbo.common.bytecode.DubboLoaderClassPath;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.LoaderClassPath;
/**
* JavassistCompiler. (SPI, Singleton, ThreadSafe)
*/
public class JavassistCompiler extends AbstractCompiler {
private static final Pattern IMPORT_PATTERN = Pattern.compile("import\\s+([\\w\\.\\*]+);\n");
private static final Pattern EXTENDS_PATTERN = Pattern.compile("\\s+extends\\s+([\\w\\.]+)[^\\{]*\\{\n");
private static final Pattern IMPLEMENTS_PATTERN = Pattern.compile("\\s+implements\\s+([\\w\\.]+)\\s*\\{\n");
private static final Pattern METHODS_PATTERN = Pattern.compile("\n(private|public|protected)\\s+");
private static final Pattern FIELD_PATTERN = Pattern.compile("[^\n]+=[^\n]+;");
@Override
public Class<?> doCompile(Class<?> neighbor, ClassLoader classLoader, String name, String source) throws Throwable {
CtClassBuilder builder = new CtClassBuilder();
builder.setClassName(name);
// process imported classes
Matcher matcher = IMPORT_PATTERN.matcher(source);
while (matcher.find()) {
builder.addImports(matcher.group(1).trim());
}
// process extended super class
matcher = EXTENDS_PATTERN.matcher(source);
if (matcher.find()) {
builder.setSuperClassName(matcher.group(1).trim());
}
// process implemented interfaces
matcher = IMPLEMENTS_PATTERN.matcher(source);
if (matcher.find()) {
String[] ifaces = matcher.group(1).trim().split("\\,");
Arrays.stream(ifaces).forEach(i -> builder.addInterface(i.trim()));
}
// process constructors, fields, methods
String body = source.substring(source.indexOf('{') + 1, source.length() - 1);
String[] methods = METHODS_PATTERN.split(body);
String className = ClassUtils.getSimpleClassName(name);
Arrays.stream(methods).map(String::trim).filter(m -> !m.isEmpty()).forEach(method -> {
if (method.startsWith(className)) {
builder.addConstructor("public " + method);
} else if (FIELD_PATTERN.matcher(method).matches()) {
builder.addField("private " + method);
} else {
builder.addMethod("public " + method);
}
});
// compile
CtClass cls = builder.build(classLoader);
ClassPool cp = cls.getClassPool();
if (classLoader == null) {
classLoader = cp.getClassLoader();
}
cp.insertClassPath(new LoaderClassPath(classLoader));
cp.insertClassPath(new DubboLoaderClassPath());
try {
return cp.toClass(cls, neighbor, classLoader, JavassistCompiler.class.getProtectionDomain());
} catch (Throwable t) {
if (!(t instanceof CannotCompileException)) {
return cp.toClass(cls, classLoader, JavassistCompiler.class.getProtectionDomain());
}
throw t;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/ClassUtils.java | dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/ClassUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.compiler.support;
import org.apache.dubbo.common.utils.StringUtils;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* ClassUtils. (Tool, Static, ThreadSafe)
*/
public class ClassUtils {
public static final String CLASS_EXTENSION = ".class";
public static final String JAVA_EXTENSION = ".java";
private static final int JIT_LIMIT = 5 * 1024;
private ClassUtils() {}
public static Object newInstance(String name) {
try {
return forName(name).getDeclaredConstructor().newInstance();
} catch (InstantiationException
| IllegalAccessException
| InvocationTargetException
| NoSuchMethodException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
public static Class<?> forName(String[] packages, String className) {
try {
return classForName(className);
} catch (ClassNotFoundException e) {
if (packages != null && packages.length > 0) {
for (String pkg : packages) {
try {
return classForName(pkg + "." + className);
} catch (ClassNotFoundException ignore) {
}
}
}
throw new IllegalStateException(e.getMessage(), e);
}
}
public static Class<?> forName(String className) {
try {
return classForName(className);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
public static Class<?> classForName(String className) throws ClassNotFoundException {
switch (className) {
case "boolean":
return boolean.class;
case "byte":
return byte.class;
case "char":
return char.class;
case "short":
return short.class;
case "int":
return int.class;
case "long":
return long.class;
case "float":
return float.class;
case "double":
return double.class;
case "boolean[]":
return boolean[].class;
case "byte[]":
return byte[].class;
case "char[]":
return char[].class;
case "short[]":
return short[].class;
case "int[]":
return int[].class;
case "long[]":
return long[].class;
case "float[]":
return float[].class;
case "double[]":
return double[].class;
default:
}
try {
return arrayForName(className);
} catch (ClassNotFoundException e) {
// try to load from java.lang package
if (className.indexOf('.') == -1) {
try {
return arrayForName("java.lang." + className);
} catch (ClassNotFoundException ignore) {
// ignore, let the original exception be thrown
}
}
throw e;
}
}
private static Class<?> arrayForName(String className) throws ClassNotFoundException {
return Class.forName(
className.endsWith("[]") ? "[L" + className.substring(0, className.length() - 2) + ";" : className,
true,
Thread.currentThread().getContextClassLoader());
}
public static Class<?> getBoxedClass(Class<?> type) {
if (type == boolean.class) {
return Boolean.class;
} else if (type == char.class) {
return Character.class;
} else if (type == byte.class) {
return Byte.class;
} else if (type == short.class) {
return Short.class;
} else if (type == int.class) {
return Integer.class;
} else if (type == long.class) {
return Long.class;
} else if (type == float.class) {
return Float.class;
} else if (type == double.class) {
return Double.class;
} else {
return type;
}
}
public static Boolean boxed(boolean v) {
return Boolean.valueOf(v);
}
public static Character boxed(char v) {
return Character.valueOf(v);
}
public static Byte boxed(byte v) {
return Byte.valueOf(v);
}
public static Short boxed(short v) {
return Short.valueOf(v);
}
public static Integer boxed(int v) {
return Integer.valueOf(v);
}
public static Long boxed(long v) {
return Long.valueOf(v);
}
public static Float boxed(float v) {
return Float.valueOf(v);
}
public static Double boxed(double v) {
return Double.valueOf(v);
}
public static Object boxed(Object v) {
return v;
}
public static boolean unboxed(Boolean v) {
return v == null ? false : v.booleanValue();
}
public static char unboxed(Character v) {
return v == null ? '\0' : v.charValue();
}
public static byte unboxed(Byte v) {
return v == null ? 0 : v.byteValue();
}
public static short unboxed(Short v) {
return v == null ? 0 : v.shortValue();
}
public static int unboxed(Integer v) {
return v == null ? 0 : v.intValue();
}
public static long unboxed(Long v) {
return v == null ? 0 : v.longValue();
}
public static float unboxed(Float v) {
return v == null ? 0 : v.floatValue();
}
public static double unboxed(Double v) {
return v == null ? 0 : v.doubleValue();
}
public static Object unboxed(Object v) {
return v;
}
public static boolean isNotEmpty(Object object) {
return getSize(object) > 0;
}
public static int getSize(Object object) {
if (object == null) {
return 0;
}
if (object instanceof Collection<?>) {
return ((Collection<?>) object).size();
} else if (object instanceof Map<?, ?>) {
return ((Map<?, ?>) object).size();
} else if (object.getClass().isArray()) {
return Array.getLength(object);
} else {
return -1;
}
}
public static URI toURI(String name) {
try {
return new URI(name);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public static boolean isBeforeJava5(String javaVersion) {
return (StringUtils.isEmpty(javaVersion)
|| "1.0".equals(javaVersion)
|| "1.1".equals(javaVersion)
|| "1.2".equals(javaVersion)
|| "1.3".equals(javaVersion)
|| "1.4".equals(javaVersion));
}
public static boolean isBeforeJava6(String javaVersion) {
return isBeforeJava5(javaVersion) || "1.5".equals(javaVersion);
}
public static String toString(Throwable e) {
StringWriter w = new StringWriter();
PrintWriter p = new PrintWriter(w);
p.print(e.getClass().getName() + ": ");
if (e.getMessage() != null) {
p.print(e.getMessage() + "\n");
}
p.println();
try {
e.printStackTrace(p);
return w.toString();
} finally {
p.close();
}
}
public static void checkBytecode(String name, byte[] bytecode) {
if (bytecode.length > JIT_LIMIT) {
System.err.println(
"The template bytecode too long, may be affect the JIT compiler. template class: " + name);
}
}
public static String getSizeMethod(Class<?> cls) {
try {
return cls.getMethod("size", new Class<?>[0]).getName() + "()";
} catch (NoSuchMethodException e) {
try {
return cls.getMethod("length", new Class<?>[0]).getName() + "()";
} catch (NoSuchMethodException e2) {
try {
return cls.getMethod("getSize", new Class<?>[0]).getName() + "()";
} catch (NoSuchMethodException e3) {
try {
return cls.getMethod("getLength", new Class<?>[0]).getName() + "()";
} catch (NoSuchMethodException e4) {
return null;
}
}
}
}
}
public static String getMethodName(Method method, Class<?>[] parameterClasses, String rightCode) {
StringBuilder buf = new StringBuilder(rightCode);
if (method.getParameterTypes().length > parameterClasses.length) {
Class<?>[] types = method.getParameterTypes();
for (int i = parameterClasses.length; i < types.length; i++) {
if (buf.length() > 0) {
buf.append(',');
}
Class<?> type = types[i];
String def;
if (type == boolean.class) {
def = "false";
} else if (type == char.class) {
def = "\'\\0\'";
} else if (type == byte.class
|| type == short.class
|| type == int.class
|| type == long.class
|| type == float.class
|| type == double.class) {
def = "0";
} else {
def = "null";
}
buf.append(def);
}
}
return method.getName() + "(" + buf + ")";
}
public static Method searchMethod(Class<?> currentClass, String name, Class<?>[] parameterTypes)
throws NoSuchMethodException {
if (currentClass == null) {
throw new NoSuchMethodException("class == null");
}
try {
return currentClass.getMethod(name, parameterTypes);
} catch (NoSuchMethodException e) {
for (Method method : currentClass.getMethods()) {
if (method.getName().equals(name)
&& parameterTypes.length == method.getParameterTypes().length
&& Modifier.isPublic(method.getModifiers())) {
if (parameterTypes.length > 0) {
Class<?>[] types = method.getParameterTypes();
boolean match = true;
for (int i = 0; i < parameterTypes.length; i++) {
if (!types[i].isAssignableFrom(parameterTypes[i])) {
match = false;
break;
}
}
if (!match) {
continue;
}
}
return method;
}
}
throw e;
}
}
public static String getInitCode(Class<?> type) {
if (byte.class.equals(type)
|| short.class.equals(type)
|| int.class.equals(type)
|| long.class.equals(type)
|| float.class.equals(type)
|| double.class.equals(type)) {
return "0";
} else if (char.class.equals(type)) {
return "'\\0'";
} else if (boolean.class.equals(type)) {
return "false";
} else {
return "null";
}
}
public static <K, V> Map<K, V> toMap(Map.Entry<K, V>[] entries) {
Map<K, V> map = new HashMap<>();
if (entries != null && entries.length > 0) {
for (Map.Entry<K, V> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
}
return map;
}
/**
* get simple class name from qualified class name
*/
public static String getSimpleClassName(String qualifiedName) {
if (null == qualifiedName) {
return null;
}
int i = qualifiedName.lastIndexOf('.');
return i < 0 ? qualifiedName : qualifiedName.substring(i + 1);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AdaptiveCompiler.java | dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AdaptiveCompiler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.compiler.support;
import org.apache.dubbo.common.compiler.Compiler;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
/**
* AdaptiveCompiler. (SPI, Singleton, ThreadSafe)
*/
@Adaptive
public class AdaptiveCompiler implements Compiler, ScopeModelAware {
private FrameworkModel frameworkModel;
@Override
public void setFrameworkModel(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
private static volatile String DEFAULT_COMPILER;
public static void setDefaultCompiler(String compiler) {
DEFAULT_COMPILER = compiler;
}
@Override
public Class<?> compile(Class<?> neighbor, String code, ClassLoader classLoader) {
Compiler compiler;
ExtensionLoader<Compiler> loader = frameworkModel.getExtensionLoader(Compiler.class);
String name = DEFAULT_COMPILER; // copy reference
if (name != null && name.length() > 0) {
compiler = loader.getExtension(name);
} else {
compiler = loader.getDefaultExtension();
}
return compiler.compile(neighbor, code, classLoader);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/MethodConfig.java | dubbo-common/src/main/java/org/apache/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 org.apache.dubbo.config;
import org.apache.dubbo.common.config.Environment;
import org.apache.dubbo.common.config.InmemoryConfiguration;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.MethodUtils;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.AsyncMethodInfo;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.apache.dubbo.config.Constants.ON_INVOKE_INSTANCE_PARAMETER_KEY;
import static org.apache.dubbo.config.Constants.ON_INVOKE_METHOD_PARAMETER_KEY;
import static org.apache.dubbo.config.Constants.ON_RETURN_INSTANCE_PARAMETER_KEY;
import static org.apache.dubbo.config.Constants.ON_RETURN_METHOD_PARAMETER_KEY;
import static org.apache.dubbo.config.Constants.ON_THROW_INSTANCE_PARAMETER_KEY;
import static org.apache.dubbo.config.Constants.ON_THROW_METHOD_PARAMETER_KEY;
/**
* The method configuration
*
* @export
*/
public class MethodConfig extends AbstractMethodConfig {
private static final long serialVersionUID = 884908855422675941L;
/**
* The method name
*/
private String name;
/**
* Stat
*/
private Integer stat;
/**
* Whether to retry
*/
private Boolean retry;
/**
* If it's reliable
*/
private Boolean reliable;
/**
* Thread limits for method invocations
*/
private Integer executes;
/**
* If it's deprecated
*/
private Boolean deprecated;
/**
* Whether to enable sticky
*/
private Boolean sticky;
/**
* Whether you need to return
*/
private Boolean isReturn;
/**
* Callback instance when async-call is invoked
*/
private Object oninvoke;
/**
* Callback method when async-call is invoked
*/
private String oninvokeMethod;
/**
* Callback instance when async-call is returned
*/
private Object onreturn;
/**
* Callback method when async-call is returned
*/
private String onreturnMethod;
/**
* Callback instance when async-call has exception thrown
*/
private Object onthrow;
/**
* Callback method when async-call has exception thrown
*/
private String onthrowMethod;
/**
* The method arguments
*/
private List<ArgumentConfig> arguments;
/**
* TODO remove service and serviceId
* These properties come from MethodConfig's parent Config module, they will neither be collected directly from xml or API nor be delivered to url
*/
private String service;
private String serviceId;
/**
* The preferred prefix of parent
*/
private String parentPrefix;
public MethodConfig() {}
public MethodConfig(ModuleModel moduleModel) {
super(moduleModel);
}
/**
* TODO remove this construct, the callback method processing logic needs to rely on Spring context
*/
@Deprecated
public MethodConfig(Method method) {
appendAnnotation(Method.class, method);
this.setReturn(method.isReturn());
String split = ".";
if (!"".equals(method.oninvoke()) && method.oninvoke().lastIndexOf(split) > 0) {
int index = method.oninvoke().lastIndexOf(split);
String ref = method.oninvoke().substring(0, index);
String methodName = method.oninvoke().substring(index + 1);
this.setOninvoke(ref);
this.setOninvokeMethod(methodName);
}
if (!"".equals(method.onreturn()) && method.onreturn().lastIndexOf(split) > 0) {
int index = method.onreturn().lastIndexOf(split);
String ref = method.onreturn().substring(0, index);
String methodName = method.onreturn().substring(index + 1);
this.setOnreturn(ref);
this.setOnreturnMethod(methodName);
}
if (!"".equals(method.onthrow()) && method.onthrow().lastIndexOf(split) > 0) {
int index = method.onthrow().lastIndexOf(split);
String ref = method.onthrow().substring(0, index);
String methodName = method.onthrow().substring(index + 1);
this.setOnthrow(ref);
this.setOnthrowMethod(methodName);
}
if (method.arguments() != null && method.arguments().length != 0) {
List<ArgumentConfig> argumentConfigs = new ArrayList<>(method.arguments().length);
this.setArguments(argumentConfigs);
for (int i = 0; i < method.arguments().length; i++) {
ArgumentConfig argumentConfig = new ArgumentConfig(method.arguments()[i]);
argumentConfigs.add(argumentConfig);
}
}
}
/**
* TODO remove constructMethodConfig
*
* @param methods
* @return
*/
@Deprecated
public static List<MethodConfig> constructMethodConfig(Method[] methods) {
if (methods != null && methods.length != 0) {
List<MethodConfig> methodConfigs = new ArrayList<>(methods.length);
for (int i = 0; i < methods.length; i++) {
MethodConfig methodConfig = new MethodConfig(methods[i]);
methodConfigs.add(methodConfig);
}
return methodConfigs;
}
return Collections.emptyList();
}
/**
* Get method prefixes
*
* @return
*/
@Override
@Parameter(excluded = true, attribute = false)
public List<String> getPrefixes() {
// parent prefix + method name
if (parentPrefix != null) {
List<String> prefixes = new ArrayList<>();
prefixes.add(parentPrefix + "." + this.getName());
return prefixes;
}
return null;
}
@Override
protected void processExtraRefresh(String preferredPrefix, InmemoryConfiguration subPropsConfiguration) {
// refresh ArgumentConfigs
if (this.getArguments() != null && this.getArguments().size() > 0) {
for (ArgumentConfig argument : this.getArguments()) {
refreshArgument(argument, subPropsConfiguration);
}
}
}
private void refreshArgument(ArgumentConfig argument, InmemoryConfiguration subPropsConfiguration) {
if (argument.getIndex() != null && argument.getIndex() >= 0) {
String prefix = argument.getIndex() + ".";
Environment environment = getScopeModel().modelEnvironment();
List<java.lang.reflect.Method> methods =
MethodUtils.getMethods(argument.getClass(), method -> method.getDeclaringClass() != Object.class);
for (java.lang.reflect.Method method : methods) {
if (MethodUtils.isSetter(method)) {
String propertyName = extractPropertyName(method.getName());
// ignore attributes: 'index' / 'type'
if (StringUtils.isEquals(propertyName, "index") || StringUtils.isEquals(propertyName, "type")) {
continue;
}
// convert camelCase/snake_case to kebab-case
String kebabPropertyName = prefix + StringUtils.convertToSplitName(propertyName, "-");
try {
String value = StringUtils.trim(subPropsConfiguration.getString(kebabPropertyName));
if (StringUtils.hasText(value)
&& ClassUtils.isTypeMatch(method.getParameterTypes()[0], value)) {
value = environment.resolvePlaceholders(value);
method.invoke(
argument,
ClassUtils.convertPrimitive(
ScopeModelUtil.getFrameworkModel(getScopeModel()),
method.getParameterTypes()[0],
value));
}
} catch (Exception e) {
logger.info("Failed to override the property " + method.getName() + " in "
+ this.getClass().getSimpleName()
+ ", please make sure every property has getter/setter method provided.");
}
}
}
}
}
public AsyncMethodInfo convertMethodConfig2AsyncInfo() {
if ((getOninvoke() == null && getOnreturn() == null && getOnthrow() == null)) {
return null;
}
// check config conflict
if (Boolean.FALSE.equals(isReturn()) && (getOnreturn() != null || getOnthrow() != null)) {
throw new IllegalStateException(
"method config error : return attribute must be set true when on-return or on-throw has been set.");
}
AsyncMethodInfo asyncMethodInfo = new AsyncMethodInfo();
asyncMethodInfo.setOninvokeInstance(getOninvoke());
asyncMethodInfo.setOnreturnInstance(getOnreturn());
asyncMethodInfo.setOnthrowInstance(getOnthrow());
try {
if (StringUtils.isNotEmpty(oninvokeMethod)) {
asyncMethodInfo.setOninvokeMethod(getMethodByName(getOninvoke().getClass(), oninvokeMethod));
}
if (StringUtils.isNotEmpty(onreturnMethod)) {
asyncMethodInfo.setOnreturnMethod(getMethodByName(getOnreturn().getClass(), onreturnMethod));
}
if (StringUtils.isNotEmpty(onthrowMethod)) {
asyncMethodInfo.setOnthrowMethod(getMethodByName(getOnthrow().getClass(), onthrowMethod));
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
return asyncMethodInfo;
}
private java.lang.reflect.Method getMethodByName(Class<?> clazz, String methodName) {
try {
return ReflectUtils.findMethodByMethodName(clazz, methodName);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
/**
* Set default field values of MethodConfig.
*
* @see org.apache.dubbo.config.annotation.Method
*/
@Override
protected void checkDefault() {
super.checkDefault();
// set default field values
// org.apache.dubbo.config.annotation.Method.isReturn() default true;
if (isReturn() == null) {
setReturn(true);
}
// org.apache.dubbo.config.annotation.Method.sent() default true;
if (getSent() == null) {
setSent(true);
}
}
@Parameter(excluded = true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
// FIXME, add id strategy in ConfigManager
// if (StringUtils.isEmpty(id)) {
// id = name;
// }
}
public Integer getStat() {
return stat;
}
@Deprecated
public void setStat(Integer stat) {
this.stat = stat;
}
@Deprecated
public Boolean isRetry() {
return retry;
}
@Deprecated
public void setRetry(Boolean retry) {
this.retry = retry;
}
@Deprecated
public Boolean isReliable() {
return reliable;
}
@Deprecated
public void setReliable(Boolean reliable) {
this.reliable = reliable;
}
public Integer getExecutes() {
return executes;
}
public void setExecutes(Integer executes) {
this.executes = executes;
}
public Boolean getDeprecated() {
return deprecated;
}
public void setDeprecated(Boolean deprecated) {
this.deprecated = deprecated;
}
public List<ArgumentConfig> getArguments() {
return arguments;
}
@SuppressWarnings("unchecked")
public void setArguments(List<? extends ArgumentConfig> arguments) {
this.arguments = (List<ArgumentConfig>) arguments;
}
public Boolean getSticky() {
return sticky;
}
public void setSticky(Boolean sticky) {
this.sticky = sticky;
}
@Parameter(key = ON_RETURN_INSTANCE_PARAMETER_KEY, excluded = true, attribute = true)
public Object getOnreturn() {
return onreturn;
}
public void setOnreturn(Object onreturn) {
this.onreturn = onreturn;
}
@Parameter(key = ON_RETURN_METHOD_PARAMETER_KEY, excluded = true, attribute = true)
public String getOnreturnMethod() {
return onreturnMethod;
}
public void setOnreturnMethod(String onreturnMethod) {
this.onreturnMethod = onreturnMethod;
}
@Parameter(key = ON_THROW_INSTANCE_PARAMETER_KEY, excluded = true, attribute = true)
public Object getOnthrow() {
return onthrow;
}
public void setOnthrow(Object onthrow) {
this.onthrow = onthrow;
}
@Parameter(key = ON_THROW_METHOD_PARAMETER_KEY, excluded = true, attribute = true)
public String getOnthrowMethod() {
return onthrowMethod;
}
public void setOnthrowMethod(String onthrowMethod) {
this.onthrowMethod = onthrowMethod;
}
@Parameter(key = ON_INVOKE_INSTANCE_PARAMETER_KEY, excluded = true, attribute = true)
public Object getOninvoke() {
return oninvoke;
}
public void setOninvoke(Object oninvoke) {
this.oninvoke = oninvoke;
}
@Parameter(key = ON_INVOKE_METHOD_PARAMETER_KEY, excluded = true, attribute = true)
public String getOninvokeMethod() {
return oninvokeMethod;
}
public void setOninvokeMethod(String oninvokeMethod) {
this.oninvokeMethod = oninvokeMethod;
}
public Boolean isReturn() {
return isReturn;
}
public void setReturn(Boolean isReturn) {
this.isReturn = isReturn;
}
@Parameter(excluded = true, attribute = false)
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
@Parameter(excluded = true, attribute = false)
public String getServiceId() {
return serviceId;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public void setParentPrefix(String parentPrefix) {
this.parentPrefix = parentPrefix;
}
@Parameter(excluded = true, attribute = false)
public String getParentPrefix() {
return parentPrefix;
}
public void addArgument(ArgumentConfig argumentConfig) {
if (arguments == null) {
arguments = new ArrayList<>();
}
arguments.add(argumentConfig);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/AbstractConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.config.Environment;
import org.apache.dubbo.common.config.InmemoryConfiguration;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.FieldUtils;
import org.apache.dubbo.common.utils.MethodUtils;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.ToStringUtils;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.context.ConfigMode;
import org.apache.dubbo.config.support.Nested;
import org.apache.dubbo.config.support.Parameter;
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.ScopeModelUtil;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import java.beans.Transient;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
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.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_OVERRIDE_FIELD;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_REFLECTIVE_OPERATION_FAILED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION;
import static org.apache.dubbo.common.utils.ClassUtils.isSimpleType;
import static org.apache.dubbo.config.Constants.PARAMETERS;
/**
* Utility methods and public methods for parsing configuration
*
* @export
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public abstract class AbstractConfig implements Serializable {
private static final long serialVersionUID = 4267533505537413570L;
protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractConfig.class);
/**
* tag name cache, speed up get tag name frequently
*/
private static final ConcurrentMap<Class, String> tagNameCache = new ConcurrentHashMap<>();
/**
* attributed getter method cache for equals(), hashCode() and toString()
*/
private static final ConcurrentMap<Class, List<Method>> attributedMethodCache = new ConcurrentHashMap<>();
/**
* The suffix container
*/
private static final String[] SUFFIXES = new String[] {"Config", "Bean", "ConfigBase"};
/**
* Identifier for this configuration.
*/
private String id;
/**
* Indicates whether the configuration has been refreshed (true if refreshed).
*/
protected final AtomicBoolean refreshed = new AtomicBoolean(false);
/**
* Specifies if this configuration should be refreshed (true for refreshing).
*/
protected transient volatile boolean needRefresh = true;
/**
* Indicates if this is the default configuration (true for default).
*/
protected Boolean isDefault;
/**
* The scope model of this config instance.
* <p>
* <b>NOTE:</b> the model maybe changed during config processing,
* the extension spi instance needs to be reinitialized after changing the model!
*/
private transient volatile ScopeModel scopeModel;
public AbstractConfig() {
this(null);
}
public AbstractConfig(ScopeModel scopeModel) {
this.setScopeModel(scopeModel);
}
public static String getTagName(Class<?> cls) {
return ConcurrentHashMapUtils.computeIfAbsent(tagNameCache, cls, (key) -> {
String tag = cls.getSimpleName();
for (String suffix : SUFFIXES) {
if (tag.endsWith(suffix)) {
tag = tag.substring(0, tag.length() - suffix.length());
break;
}
}
return StringUtils.camelToSplitName(tag, "-");
});
}
public static String getPluralTagName(Class<?> cls) {
String tagName = getTagName(cls);
if (tagName.endsWith("y")) {
// e.g. registry -> registries
return tagName.substring(0, tagName.length() - 1) + "ies";
} else if (tagName.endsWith("s")) {
// e.g. metrics -> metricses
return tagName + "es";
}
return tagName + "s";
}
public static void appendParameters(Map<String, String> parameters, Object config) {
appendParameters(parameters, config, null);
}
public static void appendParameters(Map<String, String> parameters, Object config, String prefix) {
appendParameters0(parameters, config, prefix, true);
}
/**
* Put attributes of specify 'config' into 'parameters' argument
*/
public static void appendAttributes(Map<String, String> parameters, Object config) {
appendParameters0(parameters, config, null, false);
}
public static void appendAttributes(Map<String, String> parameters, Object config, String prefix) {
appendParameters0(parameters, config, prefix, false);
}
private static void appendParameters0(
Map<String, String> parameters, Object config, String prefix, boolean asParameters) {
if (config == null) {
return;
}
// If asParameters=false, it means append attributes, ignore @Parameter annotation's attributes except 'append'
// and 'attribute'
// How to select the appropriate one from multiple getter methods of the property?
// e.g. Using String getGeneric() or Boolean isGeneric()? Judge by field type ?
// Currently, use @Parameter.attribute() to determine whether it is an attribute.
BeanInfo beanInfo = getBeanInfo(config.getClass());
for (MethodDescriptor methodDescriptor : beanInfo.getMethodDescriptors()) {
Method method = methodDescriptor.getMethod();
try {
String name = method.getName();
if (MethodUtils.isGetter(method)) {
if (method.getReturnType() == Object.class) {
continue;
}
String key;
Parameter parameter = method.getAnnotation(Parameter.class);
if (asParameters) {
if (parameter != null && parameter.excluded()) {
continue;
}
// get parameter key
if (parameter != null && parameter.key().length() > 0) {
key = parameter.key();
} else {
key = calculatePropertyFromGetter(name);
}
} else { // as attributes
// filter non attribute
if (parameter != null && !parameter.attribute()) {
continue;
}
// get attribute name
String propertyName = calculateAttributeFromGetter(name);
// convert camelCase/snake_case to kebab-case
key = StringUtils.convertToSplitName(propertyName, "-");
}
Object value = method.invoke(config);
String str = String.valueOf(value).trim();
if (value != null && str.length() > 0) {
if (asParameters && parameter != null && parameter.escaped()) {
str = URL.encode(str);
}
if (parameter != null && parameter.append()) {
String pre = parameters.get(key);
if (pre != null && pre.length() > 0) {
str = pre + "," + str;
// Remove duplicate values
Set<String> set = StringUtils.splitToSet(str, ',');
str = StringUtils.join(set, ",");
}
}
if (prefix != null && prefix.length() > 0) {
key = prefix + "." + key;
}
parameters.put(key, str);
} else if (asParameters && parameter != null && parameter.required()) {
throw new IllegalStateException(config.getClass().getSimpleName() + "." + key + " == null");
}
} else if (isParametersGetter(method)) {
Map<String, String> map = (Map<String, String>) method.invoke(config);
map = convert(map, prefix);
if (asParameters) {
// put all parameters to url
parameters.putAll(map);
} else {
// encode parameters to string for config overriding, see AbstractConfig#refresh()
String key = calculatePropertyFromGetter(name);
String encodeParameters = StringUtils.encodeParameters(map);
if (encodeParameters != null) {
parameters.put(key, encodeParameters);
}
}
} else if (isNestedGetter(config, method)) {
Object inner = method.invoke(config);
String fieldName = MethodUtils.extractFieldName(method);
String nestedPrefix = prefix == null ? fieldName : prefix + "." + fieldName;
appendParameters0(parameters, inner, nestedPrefix, asParameters);
}
} catch (Exception e) {
throw new IllegalStateException("Append parameters failed: " + e.getMessage(), e);
}
}
}
protected static String extractPropertyName(String setter) {
String propertyName = setter.substring("set".length());
propertyName = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1);
return propertyName;
}
private static String calculatePropertyToGetter(String name) {
return "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
}
private static String calculatePropertyToSetter(String name) {
return "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
}
private static String calculatePropertyFromGetter(String name) {
int i = name.startsWith("get") ? 3 : 2;
return StringUtils.camelToSplitName(name.substring(i, i + 1).toLowerCase() + name.substring(i + 1), ".");
}
private static String calculateAttributeFromGetter(String getter) {
int i = getter.startsWith("get") ? 3 : 2;
return getter.substring(i, i + 1).toLowerCase() + getter.substring(i + 1);
}
private static void invokeSetParameters(Class c, Object o, Map map) {
try {
Method method =
ReflectUtils.findMethodByMethodSignature(c, "setParameters", new String[] {Map.class.getName()});
if (method != null && isParametersSetter(method)) {
method.invoke(o, map);
}
} catch (Throwable t) {
// ignore
}
}
private static Map<String, String> invokeGetParameters(Class c, Object o) {
try {
Method method = ReflectUtils.findMethodByMethodSignature(c, "getParameters", null);
if (method != null && isParametersGetter(method)) {
return (Map<String, String>) method.invoke(o);
}
} catch (Throwable t) {
// ignore
}
return null;
}
private static boolean isParametersGetter(Method method) {
String name = method.getName();
return ("getParameters".equals(name)
&& Modifier.isPublic(method.getModifiers())
&& method.getParameterTypes().length == 0
&& method.getReturnType() == Map.class);
}
private static boolean isPropertySetter(Method method) {
String name = method.getName();
if (name.startsWith("set")
&& name.length() > 3
&& Modifier.isPublic(method.getModifiers())
&& method.getParameterCount() == 1) {
Class<?> paramType = method.getParameterTypes()[0];
if (paramType.isArray()) {
Class<?> componentType = paramType.getComponentType();
return componentType.isPrimitive() || isSimpleType(componentType);
} else {
return paramType.isPrimitive() || isSimpleType(paramType);
}
}
return false;
}
private static boolean isParametersSetter(Method method) {
return ("setParameters".equals(method.getName())
&& Modifier.isPublic(method.getModifiers())
&& method.getParameterCount() == 1
&& Map.class == method.getParameterTypes()[0]
&& method.getReturnType() == void.class);
}
private static boolean isNestedGetter(Object obj, Method method) {
String name = method.getName();
boolean isGetter = (name.startsWith("get") || name.startsWith("is"))
&& !"get".equals(name)
&& !"is".equals(name)
&& !"getClass".equals(name)
&& !"getObject".equals(name)
&& Modifier.isPublic(method.getModifiers())
&& method.getParameterTypes().length == 0
&& (!method.getReturnType().isPrimitive() && !isSimpleType(method.getReturnType()));
if (!isGetter) {
return false;
} else {
// Extract fieldName only when necessary.
String fieldName = MethodUtils.extractFieldName(method);
Field field = FieldUtils.getDeclaredField(obj.getClass(), fieldName);
return field != null && field.isAnnotationPresent(Nested.class);
}
}
private static boolean isNestedSetter(Object obj, Method method) {
boolean isSetter = method.getName().startsWith("set")
&& !"set".equals(method.getName())
&& Modifier.isPublic(method.getModifiers())
&& method.getParameterCount() == 1
&& method.getParameterTypes()[0] != null
&& (!method.getParameterTypes()[0].isPrimitive() && !isSimpleType(method.getParameterTypes()[0]));
if (!isSetter) {
return false;
} else {
// Extract fieldName only when necessary.
String fieldName = MethodUtils.extractFieldName(method);
Field field = FieldUtils.getDeclaredField(obj.getClass(), fieldName);
return field != null && field.isAnnotationPresent(Nested.class);
}
}
/**
* @param parameters the raw parameters
* @param prefix the prefix
* @return the parameters whose raw key will replace "-" to "."
* @revised 2.7.8 "private" to be "protected"
*/
protected static Map<String, String> convert(Map<String, String> parameters, String prefix) {
if (parameters == null || parameters.isEmpty()) {
return new HashMap<>();
}
Map<String, String> result = new HashMap<>();
String pre = (StringUtils.isNotEmpty(prefix) ? prefix + "." : "");
for (Map.Entry<String, String> entry : parameters.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
result.put(pre + key, value);
// For compatibility, key like "registry-type" will have a duplicate key "registry.type"
if (Arrays.binarySearch(Constants.DOT_COMPATIBLE_KEYS, key) >= 0) {
result.put(pre + key.replace('-', '.'), value);
}
}
return result;
}
@Transient
public ApplicationModel getApplicationModel() {
if (scopeModel == null) {
setScopeModel(getDefaultModel());
}
if (scopeModel instanceof ApplicationModel) {
return (ApplicationModel) scopeModel;
} else if (scopeModel instanceof ModuleModel) {
return ((ModuleModel) scopeModel).getApplicationModel();
} else {
throw new IllegalStateException("scope model is invalid: " + scopeModel);
}
}
@Transient
public ScopeModel getScopeModel() {
if (scopeModel == null) {
setScopeModel(getDefaultModel());
}
return scopeModel;
}
@Transient
protected ScopeModel getDefaultModel() {
return ApplicationModel.defaultModel();
}
public final void setScopeModel(ScopeModel scopeModel) {
if (scopeModel != null && this.scopeModel != scopeModel) {
checkScopeModel(scopeModel);
ScopeModel oldScopeModel = this.scopeModel;
this.scopeModel = scopeModel;
// reinitialize spi extension and change referenced config's scope model
this.postProcessAfterScopeModelChanged(oldScopeModel, this.scopeModel);
}
}
protected void checkScopeModel(ScopeModel scopeModel) {
if (!(scopeModel instanceof ApplicationModel)) {
throw new IllegalArgumentException(
"Invalid scope model, expect to be a ApplicationModel but got: " + scopeModel);
}
}
/**
* Subclass should override this method to initialize its SPI extensions and change referenced config's scope model.
* <p>
* For example:
* <pre>
* protected void postProcessAfterScopeModelChanged() {
* super.postProcessAfterScopeModelChanged();
* // re-initialize spi extension
* this.protocol = this.getExtensionLoader(Protocol.class).getAdaptiveExtension();
* // change referenced config's scope model
* if (this.providerConfig != null && this.providerConfig.getScopeModel() != scopeModel) {
* this.providerConfig.setScopeModel(scopeModel);
* }
* }
* </pre>
*
* @param oldScopeModel
* @param newScopeModel
*/
protected void postProcessAfterScopeModelChanged(ScopeModel oldScopeModel, ScopeModel newScopeModel) {
// remove this config from old ConfigManager
// if (oldScopeModel != null && oldScopeModel instanceof ApplicationModel) {
// ((ApplicationModel)oldScopeModel).getApplicationConfigManager().removeConfig(this);
// }
}
protected <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
if (scopeModel == null) {
setScopeModel(getScopeModel());
}
return scopeModel.getExtensionLoader(type);
}
@Parameter(excluded = true)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* Copy attributes from annotation
*
* @param annotationClass
* @param annotation
*/
protected void appendAnnotation(Class<?> annotationClass, Object annotation) {
Method[] methods = annotationClass.getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() != Object.class
&& method.getDeclaringClass() != Annotation.class
&& method.getReturnType() != void.class
&& method.getParameterTypes().length == 0
&& Modifier.isPublic(method.getModifiers())
&& !Modifier.isStatic(method.getModifiers())) {
try {
String property = method.getName();
if ("interfaceClass".equals(property) || "interfaceName".equals(property)) {
property = "interface";
}
String setter = calculatePropertyToSetter(property);
Object value = method.invoke(annotation);
if (value != null && !value.equals(method.getDefaultValue())) {
Class<?> parameterType = ReflectUtils.getBoxedClass(method.getReturnType());
if ("filter".equals(property) || "listener".equals(property)) {
parameterType = String.class;
value = StringUtils.join((String[]) value, ",");
} else if ("parameters".equals(property)) {
parameterType = Map.class;
value = CollectionUtils.toStringMap((String[]) value);
}
try {
Method setterMethod = getClass().getMethod(setter, parameterType);
setterMethod.invoke(this, value);
} catch (NoSuchMethodException e) {
// ignore
}
}
} catch (Throwable e) {
logger.error(COMMON_REFLECTIVE_OPERATION_FAILED, "", "", e.getMessage(), e);
}
}
}
}
/**
* <p>
* <b>The new instance of the AbstractConfig subclass should return empty metadata.</b>
* The purpose is to get the attributes set by the user instead of the default value when the {@link #refresh()} method handles attribute overrides.
* </p>
*
* <p><b>The default value of the field should be set in the {@link #checkDefault()} method</b>,
* which will be called at the end of {@link #refresh()}, so that it will not affect the behavior of attribute overrides.</p>
*
* <p></p>
* Should be called after Config was fully initialized.
* <p>
* Notice! This method should include all properties in the returning map, treat @Parameter differently compared to appendParameters?
* </p>
* // FIXME: this method should be completely replaced by appendParameters?
* // -- Url parameter may use key, but props override only use property name. So replace it with appendAttributes().
*
* @see AbstractConfig#checkDefault()
* @see AbstractConfig#appendParameters(Map, Object, String)
*/
@Transient
public Map<String, String> getMetaData() {
return getMetaData(null);
}
@Transient
public Map<String, String> getMetaData(String prefix) {
Map<String, String> metaData = new HashMap<>();
appendAttributes(metaData, this, prefix);
return metaData;
}
private static BeanInfo getBeanInfo(Class cls) {
BeanInfo beanInfo;
try {
beanInfo = Introspector.getBeanInfo(cls);
} catch (IntrospectionException e) {
throw new IllegalStateException(e.getMessage(), e);
}
return beanInfo;
}
private static boolean isWritableProperty(BeanInfo beanInfo, String key) {
for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
if (key.equals(propertyDescriptor.getName())) {
return propertyDescriptor.getWriteMethod() != null;
}
}
return false;
}
@Parameter(excluded = true, attribute = false)
@Transient
public List<String> getPrefixes() {
List<String> prefixes = new ArrayList<>();
if (StringUtils.hasText(this.getId())) {
// dubbo.{tag-name}s.{id}
prefixes.add(CommonConstants.DUBBO + "." + getPluralTagName(this.getClass()) + "." + this.getId());
}
// check name
String name = ReflectUtils.getProperty(this, "getName");
if (StringUtils.hasText(name)) {
// dubbo.{tag-name}s.{name}
String prefix = CommonConstants.DUBBO + "." + getPluralTagName(this.getClass()) + "." + name;
if (!prefixes.contains(prefix)) {
prefixes.add(prefix);
}
}
// dubbo.{tag-name}
prefixes.add(getTypePrefix(this.getClass()));
return prefixes;
}
public static String getTypePrefix(Class<? extends AbstractConfig> cls) {
return CommonConstants.DUBBO + "." + getTagName(cls);
}
@Transient
public ConfigMode getConfigMode() {
return getApplicationModel().getApplicationConfigManager().getConfigMode();
}
public void overrideWithConfig(AbstractConfig newOne, boolean overrideAll) {
if (!Objects.equals(this.getClass(), newOne.getClass())) {
// ignore if two config is not the same class
return;
}
List<Method> methods =
MethodUtils.getMethods(this.getClass(), method -> method.getDeclaringClass() != Object.class);
for (Method method : methods) {
try {
Method getterMethod;
try {
String propertyName = extractPropertyName(method.getName());
String getterName = calculatePropertyToGetter(propertyName);
getterMethod = this.getClass().getMethod(getterName);
} catch (Exception ignore) {
continue;
}
if (MethodUtils.isSetter(method)) {
Object oldOne = getterMethod.invoke(this);
// if old one is null or need to override
if (overrideAll || oldOne == null) {
Object newResult = getterMethod.invoke(newOne);
// if new one is non-null and new one is not equals old one
if (newResult != null && !Objects.equals(newResult, oldOne)) {
method.invoke(this, newResult);
}
}
} else if (isParametersSetter(method)) {
Object oldOne = getterMethod.invoke(this);
Object newResult = getterMethod.invoke(newOne);
Map<String, String> oldMap = null;
if (oldOne instanceof Map) {
oldMap = (Map) oldOne;
}
Map<String, String> newMap = null;
if (newResult instanceof Map) {
newMap = (Map) newResult;
}
// if new map is null, skip
if (newMap == null) {
continue;
}
// if old map is null, override with new map
if (oldMap == null) {
invokeSetParameters(newMap, this);
continue;
}
// if mode is OVERRIDE_IF_ABSENT, put all old map entries to new map, will override the same key
// if mode is OVERRIDE_ALL, put all keyed entries not in new map from old map to new map (ignore the
// same key appeared in old map)
if (overrideAll) {
oldMap.forEach(newMap::putIfAbsent);
} else {
newMap.putAll(oldMap);
}
invokeSetParameters(newMap, this);
} else if (isNestedSetter(this, method)) {
// not support
}
} catch (Throwable t) {
logger.error(
COMMON_FAILED_OVERRIDE_FIELD,
"",
"",
"Failed to override field value of config bean: " + this,
t);
throw new IllegalStateException("Failed to override field value of config bean: " + this, t);
}
}
}
/**
* Dubbo config property override
*/
public void refresh() {
if (needRefresh) {
try {
// check and init before do refresh
preProcessRefresh();
refreshWithPrefixes(getPrefixes(), getConfigMode());
} catch (Exception e) {
logger.error(
COMMON_FAILED_OVERRIDE_FIELD,
"",
"",
"Failed to override field value of config bean: " + this,
e);
throw new IllegalStateException("Failed to override field value of config bean: " + this, e);
}
postProcessRefresh();
}
refreshed.set(true);
}
protected void refreshWithPrefixes(List<String> prefixes, ConfigMode configMode) {
Environment environment = getScopeModel().modelEnvironment();
List<Map<String, String>> configurationMaps = environment.getConfigurationMaps();
// Search props starts with PREFIX in order
String preferredPrefix = null;
for (String prefix : prefixes) {
if (ConfigurationUtils.hasSubProperties(configurationMaps, prefix)) {
preferredPrefix = prefix;
break;
}
}
if (preferredPrefix == null) {
preferredPrefix = prefixes.get(0);
}
// Extract sub props (which key was starts with preferredPrefix)
Collection<Map<String, String>> instanceConfigMaps = environment.getConfigurationMaps(this, preferredPrefix);
Map<String, String> subProperties = ConfigurationUtils.getSubProperties(instanceConfigMaps, preferredPrefix);
InmemoryConfiguration subPropsConfiguration = new InmemoryConfiguration(subProperties);
if (logger.isDebugEnabled()) {
String idOrName = "";
if (StringUtils.hasText(this.getId())) {
idOrName = "[id=" + this.getId() + "]";
} else {
String name = ReflectUtils.getProperty(this, "getName");
if (StringUtils.hasText(name)) {
idOrName = "[name=" + name + "]";
}
}
logger.debug("Refreshing " + this.getClass().getSimpleName() + idOrName + " with prefix ["
+ preferredPrefix + "], extracted props: "
+ subProperties);
}
assignProperties(this, environment, subProperties, subPropsConfiguration, configMode);
// process extra refresh of subclass, e.g. refresh method configs
processExtraRefresh(preferredPrefix, subPropsConfiguration);
}
private void assignProperties(
Object obj,
Environment environment,
Map<String, String> properties,
InmemoryConfiguration configuration,
ConfigMode configMode) {
// if old one (this) contains non-null value, do not override
boolean overrideIfAbsent = configMode == ConfigMode.OVERRIDE_IF_ABSENT;
// even if old one (this) contains non-null value, do override
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/MetricsConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/MetricsConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.config.nested.AggregationConfig;
import org.apache.dubbo.config.nested.HistogramConfig;
import org.apache.dubbo.config.nested.PrometheusConfig;
import org.apache.dubbo.config.support.Nested;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashMap;
import java.util.Map;
/**
* Configuration for the metrics.
*/
public class MetricsConfig extends AbstractConfig {
private static final long serialVersionUID = -9089919311611546383L;
/**
* Protocol used for metrics.
*/
private String protocol;
/**
* Whether to enable JVM metrics collection.
*/
private Boolean enableJvm;
/**
* Whether to enable thread pool metrics collection.
*/
private Boolean enableThreadpool;
/**
* Whether to enable registry metrics collection.
*/
private Boolean enableRegistry;
/**
* Whether to enable metadata metrics collection.
*/
private Boolean enableMetadata;
/**
* Whether to export metrics service.
*/
private Boolean exportMetricsService;
/**
* Whether to enable Netty metrics collection.
*/
private Boolean enableNetty;
/**
* Whether to enable metrics initialization.
*/
private Boolean enableMetricsInit;
/**
* Whether to enable collector synchronization.
*/
private Boolean enableCollectorSync;
/**
* Collector synchronization period.
*/
private Integer collectorSyncPeriod;
/**
* Configuration for Prometheus metrics collection.
*/
@Nested
private PrometheusConfig prometheus;
/**
* Configuration for metrics aggregation.
*/
@Nested
private AggregationConfig aggregation;
/**
* Configuration for metrics histogram.
*/
@Nested
private HistogramConfig histogram;
/**
* Protocol used for metrics collection and export.
*/
private String exportServiceProtocol;
/**
* Port used for exporting metrics services.
*/
private Integer exportServicePort;
/**
* Decide whether to use the global registry of Micrometer.
*/
private Boolean useGlobalRegistry;
/**
* Whether to enable RPC (Remote Procedure Call) metrics collection.
*/
private Boolean enableRpc;
/**
* The level of metrics collection, which can be "SERVICE" or "METHOD". The default is "METHOD".
*/
private String rpcLevel;
public MetricsConfig() {}
public MetricsConfig(ApplicationModel applicationModel) {
super(applicationModel);
}
public URL toUrl() {
Map<String, String> map = new HashMap<>();
appendParameters(map, this);
// ignore address parameter, use specified url in each metrics server config
// the address "localhost" here is meaningless
URL url = UrlUtils.parseURL("localhost", map);
url = url.setScopeModel(getScopeModel());
return url;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public Boolean getEnableJvm() {
return enableJvm;
}
public String getRpcLevel() {
return rpcLevel;
}
public void setRpcLevel(String rpcLevel) {
this.rpcLevel = rpcLevel;
}
public void setEnableJvm(Boolean enableJvm) {
this.enableJvm = enableJvm;
}
public Boolean getEnableRegistry() {
return enableRegistry;
}
public void setEnableRegistry(Boolean enableRegistry) {
this.enableRegistry = enableRegistry;
}
public PrometheusConfig getPrometheus() {
return prometheus;
}
public void setPrometheus(PrometheusConfig prometheus) {
this.prometheus = prometheus;
}
public AggregationConfig getAggregation() {
return aggregation;
}
public void setAggregation(AggregationConfig aggregation) {
this.aggregation = aggregation;
}
public HistogramConfig getHistogram() {
return histogram;
}
public void setHistogram(HistogramConfig histogram) {
this.histogram = histogram;
}
public String getExportServiceProtocol() {
return exportServiceProtocol;
}
public void setExportServiceProtocol(String exportServiceProtocol) {
this.exportServiceProtocol = exportServiceProtocol;
}
public Integer getExportServicePort() {
return exportServicePort;
}
public void setExportServicePort(Integer exportServicePort) {
this.exportServicePort = exportServicePort;
}
public Boolean getEnableMetadata() {
return enableMetadata;
}
public void setEnableMetadata(Boolean enableMetadata) {
this.enableMetadata = enableMetadata;
}
public Boolean getExportMetricsService() {
return exportMetricsService;
}
public void setExportMetricsService(Boolean exportMetricsService) {
this.exportMetricsService = exportMetricsService;
}
public Boolean getEnableThreadpool() {
return enableThreadpool;
}
public void setEnableThreadpool(Boolean enableThreadpool) {
this.enableThreadpool = enableThreadpool;
}
public Boolean getEnableMetricsInit() {
return enableMetricsInit;
}
public void setEnableMetricsInit(Boolean enableMetricsInit) {
this.enableMetricsInit = enableMetricsInit;
}
public Boolean getEnableCollectorSync() {
return enableCollectorSync;
}
public void setEnableCollectorSync(Boolean enableCollectorSync) {
this.enableCollectorSync = enableCollectorSync;
}
public Integer getCollectorSyncPeriod() {
return collectorSyncPeriod;
}
public void setCollectorSyncPeriod(Integer collectorSyncPeriod) {
this.collectorSyncPeriod = collectorSyncPeriod;
}
public Boolean getUseGlobalRegistry() {
return useGlobalRegistry;
}
public void setUseGlobalRegistry(Boolean useGlobalRegistry) {
this.useGlobalRegistry = useGlobalRegistry;
}
public Boolean getEnableRpc() {
return enableRpc;
}
public void setEnableRpc(Boolean enableRpc) {
this.enableRpc = enableRpc;
}
public Boolean getEnableNetty() {
return enableNetty;
}
public void setEnableNetty(Boolean enableNetty) {
this.enableNetty = enableNetty;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/ArgumentConfig.java | dubbo-common/src/main/java/org/apache/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 org.apache.dubbo.config;
import org.apache.dubbo.config.annotation.Argument;
import org.apache.dubbo.config.support.Parameter;
import java.io.Serializable;
/**
* The method arguments configuration
*
* @export
*/
public class ArgumentConfig implements Serializable {
private static final long serialVersionUID = -2165482463925213595L;
/**
* The argument index: index -1 represents not set
*/
private Integer index = -1;
/**
* Argument type
*/
private String type;
/**
* Whether the argument is the callback interface
*/
private Boolean callback;
public ArgumentConfig() {}
public ArgumentConfig(Argument argument) {
this.index = argument.index();
this.type = argument.type();
this.callback = argument.callback();
}
@Parameter(excluded = true)
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
@Parameter(excluded = true)
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void setCallback(Boolean callback) {
this.callback = callback;
}
public Boolean isCallback() {
return callback;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java | dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.compact.Dubbo2CompactUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.RegexProperties;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.context.ConfigMode;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ServiceMetadata;
import org.apache.dubbo.rpc.service.GenericService;
import org.apache.dubbo.rpc.support.ProtocolUtils;
import java.beans.Transient;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.USER_HOME;
import static org.apache.dubbo.common.constants.CommonConstants.UNLOAD_CLUSTER_RELATED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION;
/**
* Base configuration for the service reference.
*
* @export
*/
public abstract class ReferenceConfigBase<T> extends AbstractReferenceConfig {
private static final long serialVersionUID = -5864351140409987595L;
private static final String ORIGIN_CONFIG = "ORIGIN_CONFIG";
/**
* The interface class of the reference service.
*/
protected Class<?> interfaceClass;
/**
* The URL for peer-to-peer invocation.
*/
protected String url;
/**
* The default consumer configuration.
*/
protected ConsumerConfig consumer;
/**
* In mesh mode, this flag uninstalls the directory, router, and load balancing configurations related to the cluster in the currently invoked invoker.
* It delegates retry, load balancing, timeout, and other traffic management capabilities to Sidecar.
*/
protected Boolean unloadClusterRelated;
public ReferenceConfigBase() {
serviceMetadata = new ServiceMetadata();
serviceMetadata.addAttribute(ORIGIN_CONFIG, this);
}
public ReferenceConfigBase(ModuleModel moduleModel) {
super(moduleModel);
serviceMetadata = new ServiceMetadata();
serviceMetadata.addAttribute(ORIGIN_CONFIG, this);
}
public ReferenceConfigBase(Reference reference) {
serviceMetadata = new ServiceMetadata();
serviceMetadata.addAttribute(ORIGIN_CONFIG, this);
appendAnnotation(Reference.class, reference);
setMethods(MethodConfig.constructMethodConfig(reference.methods()));
}
public ReferenceConfigBase(ModuleModel moduleModel, Reference reference) {
super(moduleModel);
serviceMetadata = new ServiceMetadata();
serviceMetadata.addAttribute(ORIGIN_CONFIG, this);
appendAnnotation(Reference.class, reference);
setMethods(MethodConfig.constructMethodConfig(reference.methods()));
}
public boolean shouldCheck() {
checkDefault();
Boolean shouldCheck = isCheck();
if (shouldCheck == null && getConsumer() != null) {
shouldCheck = getConsumer().isCheck();
}
if (shouldCheck == null) {
// default true
shouldCheck = true;
}
return shouldCheck;
}
public boolean shouldInit() {
checkDefault();
Boolean shouldInit = isInit();
if (shouldInit == null && getConsumer() != null) {
shouldInit = getConsumer().isInit();
}
if (shouldInit == null) {
// default is true
return true;
}
return shouldInit;
}
@Override
protected void preProcessRefresh() {
super.preProcessRefresh();
if (consumer == null) {
consumer = getModuleConfigManager()
.getDefaultConsumer()
.orElseThrow(() -> new IllegalStateException("Default consumer is not initialized"));
}
// try set properties from `dubbo.reference` if not set in current config
refreshWithPrefixes(super.getPrefixes(), ConfigMode.OVERRIDE_IF_ABSENT);
}
@Override
@Parameter(excluded = true, attribute = false)
public List<String> getPrefixes() {
List<String> prefixes = new ArrayList<>();
// dubbo.reference.{interface-name}
prefixes.add(DUBBO + ".reference." + interfaceName);
return prefixes;
}
@Override
@Transient
public Map<String, String> getMetaData() {
return getMetaData(null);
}
@Override
public Map<String, String> getMetaData(String prefix) {
Map<String, String> metaData = new HashMap<>();
ConsumerConfig consumer = this.getConsumer();
// consumer should be initialized at preProcessRefresh()
if (isRefreshed() && consumer == null) {
throw new IllegalStateException("Consumer is not initialized");
}
// use consumer attributes as default value
appendAttributes(metaData, consumer, prefix);
appendAttributes(metaData, this, prefix);
return metaData;
}
/**
* Get service interface class of this reference.
* The actual service type of remote provider.
*
* @return
*/
public Class<?> getServiceInterfaceClass() {
Class<?> actualInterface = interfaceClass;
if (interfaceClass == GenericService.class) {
try {
if (getInterfaceClassLoader() != null) {
actualInterface = Class.forName(interfaceName, false, getInterfaceClassLoader());
} else {
actualInterface = Class.forName(interfaceName);
}
} catch (ClassNotFoundException e) {
return null;
}
}
return actualInterface;
}
/**
* Get proxy interface class of this reference.
* The proxy interface class is used to create proxy instance.
*
* @return
*/
public Class<?> getInterfaceClass() {
if (interfaceClass != null) {
return interfaceClass;
}
String generic = getGeneric();
if (StringUtils.isBlank(generic) && getConsumer() != null) {
generic = getConsumer().getGeneric();
}
if (getInterfaceClassLoader() != null) {
interfaceClass = determineInterfaceClass(generic, interfaceName, getInterfaceClassLoader());
} else {
interfaceClass = determineInterfaceClass(generic, interfaceName);
}
return interfaceClass;
}
/**
* Determine the interface of the proxy class
*
* @param generic
* @param interfaceName
* @return
*/
public static Class<?> determineInterfaceClass(String generic, String interfaceName) {
return determineInterfaceClass(generic, interfaceName, ClassUtils.getClassLoader());
}
public static Class<?> determineInterfaceClass(String generic, String interfaceName, ClassLoader classLoader) {
if (ProtocolUtils.isGeneric(generic)) {
return Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isGenericServiceClassLoaded()
? Dubbo2CompactUtils.getGenericServiceClass()
: GenericService.class;
}
try {
if (StringUtils.isNotEmpty(interfaceName)) {
return Class.forName(interfaceName, true, classLoader);
}
} catch (ClassNotFoundException t) {
throw new IllegalStateException(t.getMessage(), t);
}
return null;
}
@Override
protected void postProcessAfterScopeModelChanged(ScopeModel oldScopeModel, ScopeModel newScopeModel) {
super.postProcessAfterScopeModelChanged(oldScopeModel, newScopeModel);
if (this.consumer != null && this.consumer.getScopeModel() != getScopeModel()) {
this.consumer.setScopeModel(getScopeModel());
}
}
public void setInterface(Class<?> interfaceClass) {
if (interfaceClass != null && !interfaceClass.isInterface()) {
throw new IllegalStateException("The interface class " + interfaceClass + " is not a interface!");
}
setInterface(interfaceClass == null ? null : interfaceClass.getName());
this.interfaceClass = interfaceClass;
if (getInterfaceClassLoader() == null) {
setInterfaceClassLoader(interfaceClass == null ? null : interfaceClass.getClassLoader());
} else {
if (interfaceClass != null) {
try {
if (!interfaceClass.equals(
Class.forName(interfaceClass.getName(), false, getInterfaceClassLoader()))) {
// interfaceClass is not visible from origin classloader, override the classloader from
// interfaceClass into referenceConfig
setInterfaceClassLoader(interfaceClass.getClassLoader());
}
} catch (ClassNotFoundException e) {
// class not found from origin classloader, override the classloader from interfaceClass into
// referenceConfig
setInterfaceClassLoader(interfaceClass.getClassLoader());
}
}
}
}
@Parameter(excluded = true)
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public ConsumerConfig getConsumer() {
return consumer;
}
public void setConsumer(ConsumerConfig consumer) {
this.consumer = consumer;
}
@Parameter(key = UNLOAD_CLUSTER_RELATED)
public Boolean getUnloadClusterRelated() {
return unloadClusterRelated;
}
public void setUnloadClusterRelated(Boolean unloadClusterRelated) {
this.unloadClusterRelated = unloadClusterRelated;
}
@Transient
public ServiceMetadata getServiceMetadata() {
return serviceMetadata;
}
protected void resolveFile() {
String resolve = System.getProperty(interfaceName);
String resolveFile = null;
if (StringUtils.isEmpty(resolve)) {
resolveFile = SystemPropertyConfigUtils.getSystemProperty(CommonConstants.DubboProperty.DUBBO_RESOLVE_FILE);
if (StringUtils.isEmpty(resolveFile)) {
File userResolveFile = new File(
new File(SystemPropertyConfigUtils.getSystemProperty(USER_HOME)), "dubbo-resolve.properties");
if (userResolveFile.exists()) {
resolveFile = userResolveFile.getAbsolutePath();
}
}
if (resolveFile != null && resolveFile.length() > 0) {
Properties properties = new RegexProperties();
try (FileInputStream fis = new FileInputStream(resolveFile)) {
properties.load(fis);
} catch (IOException e) {
throw new IllegalStateException("Failed to load " + resolveFile + ", cause: " + e.getMessage(), e);
}
resolve = properties.getProperty(interfaceName);
}
}
if (StringUtils.isNotEmpty(resolve)) {
url = resolve;
if (logger.isWarnEnabled()) {
if (resolveFile != null) {
logger.warn(
COMMON_UNEXPECTED_EXCEPTION,
"",
"",
"Using default dubbo resolve file " + resolveFile + " replace " + interfaceName + ""
+ resolve + " to p2p invoke remote service.");
} else {
logger.warn(
COMMON_UNEXPECTED_EXCEPTION,
"",
"",
"Using -D" + interfaceName + "=" + resolve + " to p2p invoke remote service.");
}
}
}
}
@Override
protected void computeValidRegistryIds() {
if (consumer != null && notHasSelfRegistryProperty()) {
setRegistries(consumer.getRegistries());
setRegistryIds(consumer.getRegistryIds());
}
super.computeValidRegistryIds();
}
@Parameter(excluded = true, attribute = false)
public String getUniqueServiceName() {
return interfaceName != null ? URL.buildKey(interfaceName, getGroup(), getVersion()) : null;
}
@Override
public String getVersion() {
return StringUtils.isEmpty(this.version)
? (consumer != null ? consumer.getVersion() : this.version)
: this.version;
}
@Override
public String getGroup() {
return StringUtils.isEmpty(this.group) ? (consumer != null ? consumer.getGroup() : this.group) : this.group;
}
public Boolean shouldReferAsync() {
Boolean shouldReferAsync = getReferAsync();
if (shouldReferAsync == null) {
shouldReferAsync = consumer != null && consumer.getReferAsync() != null && consumer.getReferAsync();
}
return shouldReferAsync;
}
@Transient
public abstract T get(boolean check);
@Transient
public abstract void checkOrDestroy(long timeout);
@Transient
public final T get() {
return get(true);
}
public void destroy() {
getModuleConfigManager().removeConfig(this);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/ProtocolConfig.java | dubbo-common/src/main/java/org/apache/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 org.apache.dubbo.config;
import org.apache.dubbo.common.serialization.PreferSerializationProvider;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.nested.TripleConfig;
import org.apache.dubbo.config.support.Nested;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Optional;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.JSON_CHECK_LEVEL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SSL_ENABLED_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_POOL_EXHAUSTED_LISTENERS_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION;
/**
* Configuration for the protocol.
*/
public class ProtocolConfig extends AbstractConfig {
private static final long serialVersionUID = 6913423882496634749L;
/**
* The name of the protocol.
*/
private String name;
/**
* The service's IP address (useful when there are multiple network cards available).
*/
private String host;
/**
* The service's port number.
*/
private Integer port;
/**
* The context path for the service.
*/
private String contextpath;
/**
* The name of the thread pool.
*/
private String threadpool;
/**
* The core thread size of the thread pool.
*/
private Integer corethreads;
/**
* The fixed size of the thread pool.
*/
private Integer threads;
/**
* The fixed size of the IO thread pool.
*/
private Integer iothreads;
/**
* The keep-alive time for threads in the thread pool (default unit is TimeUnit.MILLISECONDS).
*/
private Integer alive;
/**
* The length of the thread pool's queue.
*/
private Integer queues;
/**
* Listeners for exhausted thread pool.
*/
private String threadPoolExhaustedListeners;
/**
* The maximum acceptable connections.
*/
private Integer accepts;
/**
* The protocol codec.
*/
private String codec;
/**
* The serialization method.
*/
private String serialization;
/**
* Specifies the preferred serialization method for the consumer.
* If specified, the consumer will use this parameter first.
* If the Dubbo Sdk you are using contains the serialization type, the serialization method specified by the argument is used.
* <p>
* When this parameter is null or the serialization type specified by this parameter does not exist in the Dubbo SDK, the serialization type specified by serialization is used.
* If the Dubbo SDK if still does not exist, the default type of the Dubbo SDK is used.
* For Dubbo SDK >= 3.2, <code>preferSerialization</code> takes precedence over <code>serialization</code>
* <p>
* Supports multiple values separated by commas, e.g., "fastjson2,fastjson,hessian2".
*/
private String preferSerialization; // default:fastjson2,hessian2
/**
* The character set used for communication.
*/
private String charset;
/**
* The maximum payload length.
*/
private Integer payload;
/**
* The buffer size.
*/
private Integer buffer;
/**
* The interval for sending heartbeats.
*/
private Integer heartbeat;
/**
* The access log configuration.
*/
private String accesslog;
/**
* The transporter used for communication.
*/
private String transporter;
/**
* The method of information exchange.
*/
private String exchanger;
/**
* The thread dispatch mode.
*/
private String dispatcher;
/**
* The networker implementation.
*/
private String networker;
/**
* The server implementation.
*/
private String server;
/**
* The client implementation.
*/
private String client;
/**
* Supported Telnet commands, separated by commas.
*/
private String telnet;
/**
* The command line prompt.
*/
private String prompt;
/**
* The status check configuration.
*/
private String status;
/**
* Indicates whether the service should be registered.
*/
private Boolean register;
// TODO: Move this property to the provider configuration.
/**
* Indicates whether it is a persistent connection.
*/
private Boolean keepAlive;
// TODO: Move this property to the provider configuration.
/**
* The optimizer used for dubbo protocol.
*/
private String optimizer;
/**
* Additional extensions.
*/
private String extension;
/**
* Custom parameters.
*/
private Map<String, String> parameters;
/**
* Indicates whether SSL is enabled.
*/
private Boolean sslEnabled;
/**
* Extra protocol for this service, using Port Unification Server.
*/
private String extProtocol;
private String preferredProtocol;
/**
* JSON check level for serialization.
*/
private String jsonCheckLevel;
/**
* Indicates whether to support no interface.
*/
private Boolean noInterfaceSupport;
@Nested
private TripleConfig triple;
public ProtocolConfig() {}
public ProtocolConfig(ApplicationModel applicationModel) {
super(applicationModel);
}
public ProtocolConfig(String name) {
setName(name);
}
public ProtocolConfig(ApplicationModel applicationModel, String name) {
super(applicationModel);
setName(name);
}
public ProtocolConfig(String name, int port) {
setName(name);
setPort(port);
}
public ProtocolConfig(ApplicationModel applicationModel, String name, int port) {
super(applicationModel);
setName(name);
setPort(port);
}
@Override
protected void checkDefault() {
super.checkDefault();
if (name == null) {
name = DUBBO_PROTOCOL;
}
if (StringUtils.isBlank(preferSerialization)) {
preferSerialization = serialization != null
? serialization
: getScopeModel()
.getBeanFactory()
.getBean(PreferSerializationProvider.class)
.getPreferSerialization();
}
}
@Parameter(excluded = true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Parameter(excluded = true)
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
@Parameter(excluded = true)
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
@Deprecated
@Parameter(excluded = true, attribute = false)
public String getPath() {
return getContextpath();
}
@Deprecated
public void setPath(String path) {
setContextpath(path);
}
@Parameter(excluded = true)
public String getContextpath() {
return contextpath;
}
public void setContextpath(String contextpath) {
this.contextpath = contextpath;
}
public String getThreadpool() {
return threadpool;
}
public void setThreadpool(String threadpool) {
this.threadpool = threadpool;
}
@Parameter(key = JSON_CHECK_LEVEL_KEY)
public String getJsonCheckLevel() {
return jsonCheckLevel;
}
public void setJsonCheckLevel(String jsonCheckLevel) {
this.jsonCheckLevel = jsonCheckLevel;
}
@Parameter(key = THREAD_POOL_EXHAUSTED_LISTENERS_KEY)
public String getThreadPoolExhaustedListeners() {
return threadPoolExhaustedListeners;
}
public void setThreadPoolExhaustedListeners(String threadPoolExhaustedListeners) {
this.threadPoolExhaustedListeners = threadPoolExhaustedListeners;
}
public Integer getCorethreads() {
return corethreads;
}
public void setCorethreads(Integer corethreads) {
this.corethreads = corethreads;
}
public Integer getThreads() {
return threads;
}
public void setThreads(Integer threads) {
this.threads = threads;
}
public Integer getIothreads() {
return iothreads;
}
public void setIothreads(Integer iothreads) {
this.iothreads = iothreads;
}
public Integer getAlive() {
return alive;
}
public void setAlive(Integer alive) {
this.alive = alive;
}
public Integer getQueues() {
return queues;
}
public void setQueues(Integer queues) {
this.queues = queues;
}
public Integer getAccepts() {
return accepts;
}
public void setAccepts(Integer accepts) {
this.accepts = accepts;
}
public String getCodec() {
return codec;
}
public void setCodec(String codec) {
this.codec = codec;
}
public String getSerialization() {
return serialization;
}
public void setSerialization(String serialization) {
this.serialization = serialization;
}
public String getPreferSerialization() {
return preferSerialization;
}
public void setPreferSerialization(String preferSerialization) {
this.preferSerialization = preferSerialization;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
public Integer getPayload() {
return payload;
}
public void setPayload(Integer payload) {
this.payload = payload;
}
public Integer getBuffer() {
return buffer;
}
public void setBuffer(Integer buffer) {
this.buffer = buffer;
}
public Integer getHeartbeat() {
return heartbeat;
}
public void setHeartbeat(Integer heartbeat) {
this.heartbeat = heartbeat;
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public String getAccesslog() {
return accesslog;
}
public void setAccesslog(String accesslog) {
this.accesslog = accesslog;
}
public String getTelnet() {
return telnet;
}
public void setTelnet(String telnet) {
this.telnet = telnet;
}
@Parameter(escaped = true)
public String getPrompt() {
return prompt;
}
public void setPrompt(String prompt) {
this.prompt = prompt;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Boolean isRegister() {
return register;
}
public void setRegister(Boolean register) {
this.register = register;
}
public String getTransporter() {
return transporter;
}
public void setTransporter(String transporter) {
this.transporter = transporter;
}
public String getExchanger() {
return exchanger;
}
public void setExchanger(String exchanger) {
this.exchanger = exchanger;
}
/**
* typo, switch to use {@link #getDispatcher()}
*
* @deprecated {@link #getDispatcher()}
*/
@Deprecated
@Parameter(excluded = true, attribute = false)
public String getDispather() {
return getDispatcher();
}
/**
* typo, switch to use {@link #getDispatcher()}
*
* @deprecated {@link #setDispatcher(String)}
*/
@Deprecated
public void setDispather(String dispather) {
setDispatcher(dispather);
}
public String getDispatcher() {
return dispatcher;
}
public void setDispatcher(String dispatcher) {
this.dispatcher = dispatcher;
}
public String getNetworker() {
return networker;
}
public void setNetworker(String networker) {
this.networker = networker;
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
@Parameter(key = SSL_ENABLED_KEY)
public Boolean getSslEnabled() {
return sslEnabled;
}
public void setSslEnabled(Boolean sslEnabled) {
this.sslEnabled = sslEnabled;
}
public Boolean getKeepAlive() {
return keepAlive;
}
public void setKeepAlive(Boolean keepAlive) {
this.keepAlive = keepAlive;
}
public String getOptimizer() {
return optimizer;
}
public void setOptimizer(String optimizer) {
this.optimizer = optimizer;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
@Override
@Parameter(excluded = true, attribute = false)
public boolean isValid() {
return StringUtils.isNotEmpty(name);
}
public String getExtProtocol() {
return extProtocol;
}
public void setExtProtocol(String extProtocol) {
this.extProtocol = extProtocol;
}
public String getPreferredProtocol() {
return preferredProtocol;
}
public void setPreferredProtocol(String preferredProtocol) {
this.preferredProtocol = preferredProtocol;
}
public Boolean isNoInterfaceSupport() {
return noInterfaceSupport;
}
public void setNoInterfaceSupport(Boolean noInterfaceSupport) {
this.noInterfaceSupport = noInterfaceSupport;
}
public TripleConfig getTriple() {
return triple;
}
@Parameter(excluded = true)
public TripleConfig getTripleOrDefault() {
if (triple == null) {
triple = new TripleConfig();
}
return triple;
}
public void setTriple(TripleConfig triple) {
this.triple = triple;
}
public void mergeProtocol(ProtocolConfig sourceConfig) {
if (sourceConfig == null) {
return;
}
Field[] targetFields = getClass().getDeclaredFields();
try {
Map<String, Object> protocolConfigMap = CollectionUtils.objToMap(sourceConfig);
for (Field targetField : targetFields) {
Optional.ofNullable(protocolConfigMap.get(targetField.getName()))
.ifPresent(value -> {
try {
targetField.setAccessible(true);
if (targetField.get(this) == null) {
targetField.set(this, value);
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
}
} catch (Exception e) {
logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "merge protocol config fail, error: ", e);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.config.context.ModuleConfigManager;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import java.beans.Transient;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* Abstract configuration for the method.
*
* @export
*/
public abstract class AbstractMethodConfig extends AbstractConfig {
private static final long serialVersionUID = 5809761483000878437L;
/**
* Timeout for remote invocation in milliseconds.
*/
protected Integer timeout;
/**
* Retry times for failed invocations.
*/
protected Integer retries;
/**
* Maximum concurrent invocations allowed.
*/
protected Integer actives;
/**
* Load balancing strategy for service invocation.
*/
protected String loadbalance;
/**
* Enable asynchronous invocation. Note that it is unreliable asynchronous, ignoring return values and not blocking threads.
*/
protected Boolean async;
/**
* Acknowledge asynchronous-sent invocations.
*/
protected Boolean sent;
/**
* Mock class name to be called when a service fails to execute. The mock doesn't support on the provider side,
* and it is executed when a non-business exception occurs after a remote service call.
*/
protected String mock;
/**
* Merger for result data.
*/
protected String merger;
/**
* Cache provider for caching return results. available options: lru, threadlocal, jcache etc.
*/
protected String cache;
/**
* Enable JSR303 standard annotation validation for method parameters.
*/
protected String validation;
/**
* Customized parameters for configuration.
*/
protected Map<String, String> parameters;
/**
* Forks for forking cluster.
*/
protected Integer forks;
public AbstractMethodConfig() {}
public AbstractMethodConfig(ModuleModel moduleModel) {
super(moduleModel);
}
@Override
@Transient
public ModuleModel getScopeModel() {
return (ModuleModel) super.getScopeModel();
}
@Override
@Transient
protected ScopeModel getDefaultModel() {
return ApplicationModel.defaultModel().getDefaultModule();
}
@Override
protected void checkScopeModel(ScopeModel scopeModel) {
if (!(scopeModel instanceof ModuleModel)) {
throw new IllegalArgumentException(
"Invalid scope model, expect to be a ModuleModel but got: " + scopeModel);
}
}
@Transient
protected ModuleConfigManager getModuleConfigManager() {
return getScopeModel().getConfigManager();
}
public Integer getForks() {
return forks;
}
public void setForks(Integer forks) {
this.forks = forks;
}
public Integer getTimeout() {
return timeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
public Integer getRetries() {
return retries;
}
public void setRetries(Integer retries) {
this.retries = retries;
}
public String getLoadbalance() {
return loadbalance;
}
public void setLoadbalance(String loadbalance) {
this.loadbalance = loadbalance;
}
public Boolean isAsync() {
return async;
}
public void setAsync(Boolean async) {
this.async = async;
}
public Integer getActives() {
return actives;
}
public void setActives(Integer actives) {
this.actives = actives;
}
public Boolean getSent() {
return sent;
}
public void setSent(Boolean sent) {
this.sent = sent;
}
@Parameter(escaped = true)
public String getMock() {
return mock;
}
public void setMock(String mock) {
this.mock = mock;
}
/**
* Set the property "mock"
*
* @param mock the value of mock
* @since 2.7.6
* @deprecated use {@link #setMock(String)} instead
*/
@Deprecated
public void setMock(Object mock) {
if (mock == null) {
return;
}
this.setMock(String.valueOf(mock));
}
public String getMerger() {
return merger;
}
public void setMerger(String merger) {
this.merger = merger;
}
public String getCache() {
return cache;
}
public void setCache(String cache) {
this.cache = cache;
}
public String getValidation() {
return validation;
}
public void setValidation(String validation) {
this.validation = validation;
}
public Map<String, String> getParameters() {
this.parameters = Optional.ofNullable(this.parameters).orElseGet(HashMap::new);
return this.parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/ConfigKeys.java | dubbo-common/src/main/java/org/apache/dubbo/config/ConfigKeys.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.context.ConfigMode;
/**
* External config keys list
* @see org.apache.dubbo.spring.boot.autoconfigure.DubboConfigurationProperties
*/
public interface ConfigKeys {
/**
* The basePackages to scan , the multiple-value is delimited by comma
* @see org.apache.dubbo.config.spring.context.annotation.EnableDubbo#scanBasePackages()
*/
String DUBBO_SCAN_BASE_PACKAGES = "dubbo.scan.base-packages";
/**
* Change dubbo config mode, available values from {@link ConfigMode}. Default value is {@link ConfigMode#STRICT}.
* @see ConfigMode
* @see ConfigManager#configMode
*/
String DUBBO_CONFIG_MODE = "dubbo.config.mode";
/**
* Ignore invalid method config. Default value is false.
*/
String DUBBO_CONFIG_IGNORE_INVALID_METHOD_CONFIG = "dubbo.config.ignore-invalid-method-config";
/**
* Ignore duplicated interface (service/reference) config. Default value is false.
*/
String DUBBO_CONFIG_IGNORE_DUPLICATED_INTERFACE = "dubbo.config.ignore-duplicated-interface";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/TracingConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/TracingConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.config.nested.BaggageConfig;
import org.apache.dubbo.config.nested.ExporterConfig;
import org.apache.dubbo.config.nested.PropagationConfig;
import org.apache.dubbo.config.nested.SamplingConfig;
import org.apache.dubbo.config.support.Nested;
import org.apache.dubbo.rpc.model.ApplicationModel;
/**
* Configuration for tracing.
*/
public class TracingConfig extends AbstractConfig {
private static final long serialVersionUID = -9089919311611546383L;
/**
* Indicates whether the feature is enabled (default is false).
*/
private Boolean enabled = false;
/**
* Configuration for sampling.
*/
@Nested
private SamplingConfig sampling = new SamplingConfig();
/**
* Configuration for baggage.
*/
@Nested
private BaggageConfig baggage = new BaggageConfig();
/**
* Configuration for propagation.
*/
@Nested
private PropagationConfig propagation = new PropagationConfig();
/**
* Configuration for the tracing exporter.
*/
@Nested
private ExporterConfig tracingExporter = new ExporterConfig();
public TracingConfig() {}
public TracingConfig(ApplicationModel applicationModel) {
super(applicationModel);
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public SamplingConfig getSampling() {
return sampling;
}
public void setSampling(SamplingConfig sampling) {
this.sampling = sampling;
}
public BaggageConfig getBaggage() {
return baggage;
}
public void setBaggage(BaggageConfig baggage) {
this.baggage = baggage;
}
public PropagationConfig getPropagation() {
return propagation;
}
public void setPropagation(PropagationConfig propagation) {
this.propagation = propagation;
}
public ExporterConfig getTracingExporter() {
return tracingExporter;
}
public void setTracingExporter(ExporterConfig tracingExporter) {
this.tracingExporter = tracingExporter;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.CONFIG_CONFIGFILE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CONFIG_ENABLE_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.RemotingConstants.BACKUP_KEY;
import static org.apache.dubbo.common.utils.PojoUtils.updatePropertyIfAbsent;
import static org.apache.dubbo.config.Constants.CONFIG_APP_CONFIGFILE_KEY;
import static org.apache.dubbo.config.Constants.ZOOKEEPER_PROTOCOL;
/**
* Configuration for the config center.
*/
public class ConfigCenterConfig extends AbstractConfig {
private final AtomicBoolean initialized = new AtomicBoolean(false);
/**
* The protocol used for accessing the config center.
*/
private String protocol;
/**
* The address (URL or hostname) of the config center server.
*/
private String address;
/**
* The port number for the config center server.
*/
private Integer port;
/**
* The config center cluster, its actual meaning may vary depending on the specific config center product.
*/
private String cluster;
/**
* The namespace of the config center, generally used for multi-tenancy.
* Its actual meaning depends on the specific config center you use. Default value is CommonConstants.DUBBO.
*/
private String namespace;
/**
* The group of the config center, often used to identify an isolated space for a batch of config items.
* Its actual meaning depends on the specific config center you use. Default value is CommonConstants.DUBBO.
*/
private String group;
/**
* Username for authentication with the config center.
*/
private String username;
/**
* Password for authentication with the config center.
*/
private String password;
/**
* The timeout for accessing the config center. Default value is 30000L.
*/
private Long timeout;
/**
* If the config center should have the highest priority and override all other configurations.
* Deprecated and no longer used. Default value is true.
*/
private Boolean highestPriority;
/**
* Behavior when the initial connection attempt to the config center fails.
* 'true' means interrupt the whole process once a failure occurs. Default value is true.
*/
private Boolean check;
/**
* Key mapping for properties files. Most of the time, you do not need to change this parameter.
* Default value is CommonConstants.DEFAULT_DUBBO_PROPERTIES.
*/
private String configFile;
/**
* The properties file under 'configFile' is global shared, while '.properties' under this one is limited only to this application.
*/
private String appConfigFile;
/**
* Additional parameters specific to your config center product can be added here.
* For example, with XML:
* <dubbo:config-center>
* <dubbo:parameter key="{your key}" value="{your value}" />
* </dubbo:config-center>
*/
private Map<String, String> parameters;
/**
* External configuration for the config center.
*/
private Map<String, String> externalConfiguration;
/**
* Application-specific external configuration for the config center.
*/
private Map<String, String> appExternalConfiguration;
public ConfigCenterConfig() {}
public ConfigCenterConfig(ApplicationModel applicationModel) {
super(applicationModel);
}
@Override
protected void checkDefault() {
super.checkDefault();
if (namespace == null) {
namespace = CommonConstants.DUBBO;
}
if (group == null) {
group = CommonConstants.DUBBO;
}
if (timeout == null) {
timeout = 30000L;
}
if (check == null) {
check = true;
}
if (configFile == null) {
configFile = CommonConstants.DEFAULT_DUBBO_PROPERTIES;
}
}
public URL toUrl() {
Map<String, String> map = new HashMap<>();
appendParameters(map, this);
if (StringUtils.isEmpty(address)) {
address = ANYHOST_VALUE;
}
map.put(PATH_KEY, ConfigCenterConfig.class.getName());
// use 'zookeeper' as the default config center.
if (StringUtils.isEmpty(map.get(PROTOCOL_KEY))) {
map.put(PROTOCOL_KEY, ZOOKEEPER_PROTOCOL);
}
return UrlUtils.parseURL(address, map).setScopeModel(getScopeModel());
}
public boolean checkOrUpdateInitialized(boolean update) {
return initialized.compareAndSet(false, update);
}
public void setInitialized(boolean val) {
initialized.set(val);
}
public Map<String, String> getExternalConfiguration() {
return externalConfiguration;
}
public Map<String, String> getAppExternalConfiguration() {
return appExternalConfiguration;
}
public void setExternalConfig(Map<String, String> externalConfiguration) {
this.externalConfiguration = externalConfiguration;
}
public void setAppExternalConfig(Map<String, String> appExternalConfiguration) {
this.appExternalConfiguration = appExternalConfiguration;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
@Parameter(excluded = true)
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
if (address != null) {
try {
URL url = URL.valueOf(address);
updatePropertyIfAbsent(this::getUsername, this::setUsername, url.getUsername());
updatePropertyIfAbsent(this::getPassword, this::setPassword, url.getPassword());
updatePropertyIfAbsent(this::getProtocol, this::setProtocol, url.getProtocol());
updatePropertyIfAbsent(this::getPort, this::setPort, url.getPort());
Map<String, String> params = url.getParameters();
if (CollectionUtils.isNotEmptyMap(params)) {
params.remove(BACKUP_KEY);
}
updateParameters(params);
} catch (Exception ignored) {
}
}
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getCluster() {
return cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public Boolean isCheck() {
return check;
}
public void setCheck(Boolean check) {
this.check = check;
}
@Deprecated
@Parameter(key = CONFIG_ENABLE_KEY)
public Boolean isHighestPriority() {
return highestPriority;
}
@Deprecated
public void setHighestPriority(Boolean highestPriority) {
this.highestPriority = highestPriority;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Long getTimeout() {
return timeout;
}
public void setTimeout(Long timeout) {
this.timeout = timeout;
}
@Parameter(key = CONFIG_CONFIGFILE_KEY)
public String getConfigFile() {
return configFile;
}
public void setConfigFile(String configFile) {
this.configFile = configFile;
}
@Parameter(excluded = true, key = CONFIG_APP_CONFIGFILE_KEY)
public String getAppConfigFile() {
return appConfigFile;
}
public void setAppConfigFile(String appConfigFile) {
this.appConfigFile = appConfigFile;
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
@Override
@Parameter(excluded = true, attribute = false)
public boolean isValid() {
if (StringUtils.isEmpty(address)) {
return false;
}
return address.contains("://") || StringUtils.isNotEmpty(protocol);
}
public void updateParameters(Map<String, String> parameters) {
if (CollectionUtils.isEmptyMap(parameters)) {
return;
}
if (this.parameters == null) {
this.parameters = parameters;
} else {
this.parameters.putAll(parameters);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashMap;
import java.util.Map;
import static org.apache.dubbo.common.constants.CommonConstants.CYCLE_REPORT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REPORT_DEFINITION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REPORT_METADATA_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.RETRY_PERIOD_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.RETRY_TIMES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SYNC_REPORT_KEY;
import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY;
import static org.apache.dubbo.common.utils.PojoUtils.updatePropertyIfAbsent;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
/**
* Configuration for the metadata report.
*
* @export
*/
public class MetadataReportConfig extends AbstractConfig {
private static final long serialVersionUID = 55233L;
/**
* The protocol for the metadata center.
*/
private String protocol;
/**
* The address of the metadata center.
*/
private String address;
/**
* The default port for the metadata center.
*/
private Integer port;
/**
* The username used to log in to the metadata center.
*/
private String username;
/**
* The password used to log in to the metadata center.
*/
private String password;
/**
* The request timeout in milliseconds for the metadata center.
*/
private Integer timeout;
/**
* The group for the metadata center, which is similar to the registry group.
*/
private String group;
/**
* Customized parameters for the metadata center.
*/
private Map<String, String> parameters;
/**
* The number of retry times when connecting to the metadata center.
*/
private Integer retryTimes;
/**
* The retry period in milliseconds when connecting to the metadata center.
*/
private Integer retryPeriod;
/**
* By default, the metadata store will store full metadata repeatedly every day.
*/
private Boolean cycleReport;
/**
* Synchronization report, with the default value as asynchronous.
*/
private Boolean syncReport;
/**
* Whether to use a cluster configuration for the metadata center.
*/
private Boolean cluster;
/**
* The registry ID for the metadata center.
*/
private String registry;
/**
* The file path for saving the metadata center's dynamic list.
*/
private String file;
/**
* Decide the behavior when the initial connection attempt fails, where 'true' means interrupt the whole process once it fails.
* The default value is true.
*/
private Boolean check;
/**
* Whether to report metadata.
*/
private Boolean reportMetadata;
/**
* Whether to report definition.
*/
private Boolean reportDefinition;
public MetadataReportConfig() {}
public MetadataReportConfig(ApplicationModel applicationModel) {
super(applicationModel);
}
public MetadataReportConfig(String address) {
setAddress(address);
}
public MetadataReportConfig(ApplicationModel applicationModel, String address) {
super(applicationModel);
setAddress(address);
}
public URL toUrl() throws IllegalArgumentException {
String address = this.getAddress();
if (isEmpty(address)) {
throw new IllegalArgumentException("The address of metadata report is invalid.");
}
Map<String, String> map = new HashMap<>();
URL url = URL.valueOf(address, getScopeModel());
// Issue : https://github.com/apache/dubbo/issues/6491
// Append the parameters from address
map.putAll(url.getParameters());
// Append or overrides the properties as parameters
appendParameters(map, this);
// Normalize the parameters
map.putAll(convert(map, null));
// put the protocol of URL as the "metadata"
map.put(METADATA, isEmpty(url.getProtocol()) ? map.get(PROTOCOL_KEY) : url.getProtocol());
return new ServiceConfigURL(
METADATA,
StringUtils.isBlank(url.getUsername()) ? this.getUsername() : url.getUsername(),
StringUtils.isBlank(url.getPassword()) ? this.getPassword() : url.getPassword(),
url.getHost(),
url.getPort(),
url.getPath(),
map)
.setScopeModel(getScopeModel());
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
@Parameter(excluded = true)
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
if (address != null) {
try {
URL url = URL.valueOf(address);
// Refactor since 2.7.8
updatePropertyIfAbsent(this::getUsername, this::setUsername, url.getUsername());
updatePropertyIfAbsent(this::getPassword, this::setPassword, url.getPassword());
updatePropertyIfAbsent(this::getProtocol, this::setProtocol, url.getProtocol());
updatePropertyIfAbsent(this::getPort, this::setPort, url.getPort());
Map<String, String> params = url.getParameters();
if (CollectionUtils.isNotEmptyMap(params)) {
params.remove(BACKUP_KEY);
}
updateParameters(params);
} catch (Exception ignored) {
}
}
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getTimeout() {
return timeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
@Parameter(key = RETRY_TIMES_KEY)
public Integer getRetryTimes() {
return retryTimes;
}
public void setRetryTimes(Integer retryTimes) {
this.retryTimes = retryTimes;
}
@Parameter(key = RETRY_PERIOD_KEY)
public Integer getRetryPeriod() {
return retryPeriod;
}
public void setRetryPeriod(Integer retryPeriod) {
this.retryPeriod = retryPeriod;
}
@Parameter(key = CYCLE_REPORT_KEY)
public Boolean getCycleReport() {
return cycleReport;
}
public void setCycleReport(Boolean cycleReport) {
this.cycleReport = cycleReport;
}
@Parameter(key = SYNC_REPORT_KEY)
public Boolean getSyncReport() {
return syncReport;
}
public void setSyncReport(Boolean syncReport) {
this.syncReport = syncReport;
}
@Override
@Parameter(excluded = true, attribute = false)
public boolean isValid() {
return StringUtils.isNotEmpty(address);
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public Boolean getCluster() {
return cluster;
}
public void setCluster(Boolean cluster) {
this.cluster = cluster;
}
public String getRegistry() {
return registry;
}
public void setRegistry(String registry) {
this.registry = registry;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public void updateParameters(Map<String, String> parameters) {
if (CollectionUtils.isEmptyMap(parameters)) {
return;
}
if (this.parameters == null) {
this.parameters = parameters;
} else {
this.parameters.putAll(parameters);
}
}
public Boolean isCheck() {
return check;
}
public void setCheck(Boolean check) {
this.check = check;
}
@Parameter(key = REPORT_METADATA_KEY)
public Boolean getReportMetadata() {
return reportMetadata;
}
public void setReportMetadata(Boolean reportMetadata) {
this.reportMetadata = reportMetadata;
}
@Parameter(key = REPORT_DEFINITION_KEY)
public Boolean getReportDefinition() {
return reportDefinition;
}
public void setReportDefinition(Boolean reportDefinition) {
this.reportDefinition = reportDefinition;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/ModuleConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/ModuleConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import java.beans.Transient;
import java.util.ArrayList;
import java.util.List;
/**
* Configuration for the module.
*
* @export
*/
public class ModuleConfig extends AbstractConfig {
private static final long serialVersionUID = 5508512956753757169L;
/**
* The module name
*/
private String name;
/**
* The module version
*/
private String version;
/**
* The module owner
*/
private String owner;
/**
* The module's organization
*/
private String organization;
/**
* Registry centers
*/
private List<RegistryConfig> registries;
/**
* Monitor center
*/
private MonitorConfig monitor;
/**
* Whether to start the module in the background.
* If started in the background, it does not await finish on Spring ContextRefreshedEvent.
*
* @see org.apache.dubbo.config.spring.context.DubboDeployApplicationListener
*/
private Boolean background;
/**
* Whether the reference is referred asynchronously.
*/
private Boolean referAsync;
/**
* The thread number for asynchronous reference pool size.
*/
private Integer referThreadNum;
/**
* Whether the service is exported asynchronously.
*/
private Boolean exportAsync;
/**
* The thread number for asynchronous export pool size.
*/
private Integer exportThreadNum;
/**
* The timeout to check references.
*/
private Long checkReferenceTimeout;
public ModuleConfig() {
super();
}
public ModuleConfig(ModuleModel moduleModel) {
super(moduleModel);
}
public ModuleConfig(String name) {
this();
setName(name);
}
public ModuleConfig(ModuleModel moduleModel, String name) {
this(moduleModel);
setName(name);
}
@Override
protected void checkDefault() {
super.checkDefault();
// default is false
if (background == null) {
background = false;
}
}
@Override
protected void checkScopeModel(ScopeModel scopeModel) {
if (!(scopeModel instanceof ModuleModel)) {
throw new IllegalArgumentException(
"Invalid scope model, expect to be a ModuleModel but got: " + scopeModel);
}
}
@Override
@Transient
public ModuleModel getScopeModel() {
return (ModuleModel) super.getScopeModel();
}
@Override
@Transient
protected ScopeModel getDefaultModel() {
return ApplicationModel.defaultModel().getDefaultModule();
}
@Parameter(key = "module")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Parameter(key = "module.version")
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
@Parameter(key = "module.owner")
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
@Parameter(key = "module.organization")
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
public RegistryConfig getRegistry() {
return CollectionUtils.isEmpty(registries) ? null : registries.get(0);
}
public void setRegistry(RegistryConfig registry) {
List<RegistryConfig> registries = new ArrayList<>(1);
registries.add(registry);
this.registries = registries;
}
public List<RegistryConfig> getRegistries() {
return registries;
}
@SuppressWarnings({"unchecked"})
public void setRegistries(List<? extends RegistryConfig> registries) {
this.registries = (List<RegistryConfig>) registries;
}
public MonitorConfig getMonitor() {
return monitor;
}
public void setMonitor(MonitorConfig monitor) {
this.monitor = monitor;
}
public void setMonitor(String monitor) {
this.monitor = new MonitorConfig(monitor);
}
public Boolean getBackground() {
return background;
}
/**
* Whether start module in background.
* If start in background, do not await finish on Spring ContextRefreshedEvent.
*
* @see org.apache.dubbo.config.spring.context.DubboDeployApplicationListener
*/
public void setBackground(Boolean background) {
this.background = background;
}
public Integer getReferThreadNum() {
return referThreadNum;
}
public void setReferThreadNum(Integer referThreadNum) {
this.referThreadNum = referThreadNum;
}
public Integer getExportThreadNum() {
return exportThreadNum;
}
public void setExportThreadNum(Integer exportThreadNum) {
this.exportThreadNum = exportThreadNum;
}
public Boolean getReferAsync() {
return referAsync;
}
public void setReferAsync(Boolean referAsync) {
this.referAsync = referAsync;
}
public Boolean getExportAsync() {
return exportAsync;
}
public void setExportAsync(Boolean exportAsync) {
this.exportAsync = exportAsync;
}
public Long getCheckReferenceTimeout() {
return checkReferenceTimeout;
}
public void setCheckReferenceTimeout(Long checkReferenceTimeout) {
this.checkReferenceTimeout = checkReferenceTimeout;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/ProviderConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/ProviderConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.ArrayList;
import java.util.Arrays;
import static org.apache.dubbo.common.constants.CommonConstants.EXPORT_BACKGROUND_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.EXPORT_THREAD_NUM_KEY;
/**
* Configuration for the service provider.
*
* @export
* @see org.apache.dubbo.config.ProtocolConfig
* @see ServiceConfigBase
*/
public class ProviderConfig extends AbstractServiceConfig {
private static final long serialVersionUID = 6913423882496634749L;
/* ======== Default values for protocols, which take effect when protocol attributes are not set ======== */
/**
* The IP addresses of the service (used when there are multiple network cards available).
*/
private String host;
/**
* The port of the service.
*/
private Integer port;
/**
* The context path of the service.
*/
private String contextpath;
/**
* The thread pool configuration.
*/
private String threadpool;
/**
* The name of the thread pool.
*/
private String threadname;
/**
* The size of the thread pool (fixed size).
*/
private Integer threads;
/**
* The size of the I/O thread pool (fixed size).
*/
private Integer iothreads;
/**
* The keep-alive time of the thread pool, default unit: TimeUnit.MILLISECONDS.
*/
private Integer alive;
/**
* The length of the thread pool queue.
*/
private Integer queues;
/**
* The maximum number of acceptable connections.
*/
private Integer accepts;
/**
* The codec used by the protocol.
*/
private String codec;
/**
* The charset used for serialization.
*/
private String charset;
/**
* The maximum payload length.
*/
private Integer payload;
/**
* The size of the network I/O buffer.
*/
private Integer buffer;
/**
* The transporter used by the protocol.
*/
private String transporter;
/**
* The method of information exchange.
*/
private String exchanger;
/**
* The mode of thread dispatching.
*/
private String dispatcher;
/**
* The networker used by the protocol.
*/
private String networker;
/**
* The server-side implementation model of the protocol.
*/
private String server;
/**
* The client-side implementation model of the protocol.
*/
private String client;
/**
* Supported telnet commands, separated by commas.
*/
private String telnet;
/**
* The command line prompt.
*/
private String prompt;
/**
* The status check configuration.
*/
private String status;
/**
* The wait time when stopping the service.
*/
private Integer wait;
/**
* The number of threads for the asynchronous export pool.
*/
private Integer exportThreadNum;
/**
* Whether the export should run in the background or not.
*
* @deprecated Replace with {@link ModuleConfig#setBackground(Boolean)}
* @see ModuleConfig#setBackground(Boolean)
*/
private Boolean exportBackground;
public ProviderConfig() {}
public ProviderConfig(ModuleModel moduleModel) {
super(moduleModel);
}
@Deprecated
public void setProtocol(String protocol) {
this.protocols = new ArrayList<>(Arrays.asList(new ProtocolConfig(protocol)));
}
@Parameter(excluded = true)
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
@Parameter(excluded = true)
public Integer getPort() {
return port;
}
@Deprecated
public void setPort(Integer port) {
this.port = port;
}
@Deprecated
@Parameter(excluded = true, attribute = false)
public String getPath() {
return getContextpath();
}
@Deprecated
public void setPath(String path) {
setContextpath(path);
}
@Parameter(excluded = true)
public String getContextpath() {
return contextpath;
}
public void setContextpath(String contextpath) {
this.contextpath = contextpath;
}
public String getThreadpool() {
return threadpool;
}
public void setThreadpool(String threadpool) {
this.threadpool = threadpool;
}
public String getThreadname() {
return threadname;
}
public void setThreadname(String threadname) {
this.threadname = threadname;
}
public Integer getThreads() {
return threads;
}
public void setThreads(Integer threads) {
this.threads = threads;
}
public Integer getIothreads() {
return iothreads;
}
public void setIothreads(Integer iothreads) {
this.iothreads = iothreads;
}
public Integer getAlive() {
return alive;
}
public void setAlive(Integer alive) {
this.alive = alive;
}
public Integer getQueues() {
return queues;
}
public void setQueues(Integer queues) {
this.queues = queues;
}
public Integer getAccepts() {
return accepts;
}
public void setAccepts(Integer accepts) {
this.accepts = accepts;
}
public String getCodec() {
return codec;
}
public void setCodec(String codec) {
this.codec = codec;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
public Integer getPayload() {
return payload;
}
public void setPayload(Integer payload) {
this.payload = payload;
}
public Integer getBuffer() {
return buffer;
}
public void setBuffer(Integer buffer) {
this.buffer = buffer;
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public String getTelnet() {
return telnet;
}
public void setTelnet(String telnet) {
this.telnet = telnet;
}
@Parameter(escaped = true)
public String getPrompt() {
return prompt;
}
public void setPrompt(String prompt) {
this.prompt = prompt;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTransporter() {
return transporter;
}
public void setTransporter(String transporter) {
this.transporter = transporter;
}
public String getExchanger() {
return exchanger;
}
public void setExchanger(String exchanger) {
this.exchanger = exchanger;
}
/**
* typo, switch to use {@link #getDispatcher()}
*
* @deprecated {@link #getDispatcher()}
*/
@Deprecated
@Parameter(excluded = true, attribute = false)
public String getDispather() {
return getDispatcher();
}
/**
* typo, switch to use {@link #getDispatcher()}
*
* @deprecated {@link #setDispatcher(String)}
*/
@Deprecated
public void setDispather(String dispather) {
setDispatcher(dispather);
}
public String getDispatcher() {
return dispatcher;
}
public void setDispatcher(String dispatcher) {
this.dispatcher = dispatcher;
}
public String getNetworker() {
return networker;
}
public void setNetworker(String networker) {
this.networker = networker;
}
public Integer getWait() {
return wait;
}
public void setWait(Integer wait) {
this.wait = wait;
}
@Deprecated
@Parameter(key = EXPORT_THREAD_NUM_KEY, excluded = true)
public Integer getExportThreadNum() {
return exportThreadNum;
}
@Deprecated
public void setExportThreadNum(Integer exportThreadNum) {
this.exportThreadNum = exportThreadNum;
}
/**
* @deprecated replace with {@link ModuleConfig#getBackground()}
* @see ModuleConfig#getBackground()
*/
@Deprecated
@Parameter(key = EXPORT_BACKGROUND_KEY, excluded = true)
public Boolean getExportBackground() {
return exportBackground;
}
/**
* Whether export should run in background or not.
*
* @deprecated replace with {@link ModuleConfig#setBackground(Boolean)}
* @see ModuleConfig#setBackground(Boolean)
*/
@Deprecated
public void setExportBackground(Boolean exportBackground) {
this.exportBackground = exportBackground;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.aot.NativeDetector;
import org.apache.dubbo.common.compiler.support.AdaptiveCompiler;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.config.Environment;
import org.apache.dubbo.common.config.InmemoryConfiguration;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import org.apache.dubbo.rpc.model.ServiceMetadata;
import java.beans.Transient;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INVOKER_LISTENER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_NO_METHOD_FOUND;
import static org.apache.dubbo.config.Constants.DEFAULT_NATIVE_PROXY;
/**
* Abstract configuration for the interface.
*
* @export
*/
public abstract class AbstractInterfaceConfig extends AbstractMethodConfig {
private static final long serialVersionUID = -1559314110797223229L;
/**
* Interface name of the exported service.
*/
protected String interfaceName;
/**
* ClassLoader associated with the interface.
*/
protected transient ClassLoader interfaceClassLoader;
/**
* Version of the remote service referenced by the consumer/provider.
*/
protected String version;
/**
* Group of the remote service referenced by the consumer/provider.
*/
protected String group;
/**
* Service metadata configuration.
*/
protected ServiceMetadata serviceMetadata;
/**
* Local implementation class name for the service interface.
*/
protected String local;
/**
* Local stub class name for the service interface.
*/
protected String stub;
/**
* Service monitoring configuration.
*/
protected MonitorConfig monitor;
/**
* Strategy for generating dynamic agents (options: "jdk" or "javassist").
*/
protected String proxy;
/**
* Cluster type for service.
*/
protected String cluster;
/**
* Filters for service exposure or reference (multiple filters can be separated by commas).
*/
protected String filter;
/**
* Listeners for service exposure or reference (multiple listeners can be separated by commas).
*/
protected String listener;
/**
* Owner of the service providers.
*/
protected String owner;
/**
* Connection limits: 0 for shared connection, otherwise specifying connections for the service.
*/
protected Integer connections;
/**
* Layer of service providers.
*/
protected String layer;
/**
* Application configuration for the service.
*/
protected ApplicationConfig application;
/**
* Module configuration for the service.
*/
protected ModuleConfig module;
/**
* Registries where the service will be registered (use this or registryIds, not both).
*/
protected List<RegistryConfig> registries;
/**
* Method-specific configuration.
*/
private List<MethodConfig> methods;
/**
* Registry IDs for service registration (use this or registries, not both).
*/
protected String registryIds;
/**
* Event handler for connection establishment.
*/
protected String onconnect;
/**
* Event handler for disconnection.
*/
protected String ondisconnect;
/**
* Metadata report configuration.
*/
protected MetadataReportConfig metadataReportConfig;
/**
* Configuration center settings.
*/
protected ConfigCenterConfig configCenter;
/**
* Callback limits for the service.
*/
private Integer callbacks;
/**
* Service scope ("local" implies searching in the current JVM only).
*/
private String scope;
/**
* Custom tag for the service configuration.
*/
protected String tag;
/**
* Enable service authentication.
*/
private Boolean auth;
/**
* Authenticator for authentication
*/
private String authenticator;
/**
* Username for basic authenticator
*/
private String username;
/**
* Password for basic authenticator
*/
private String password;
/**
* Use separate instances for services with the same serviceKey (applies when using ReferenceConfig and SimpleReferenceCache together).
* Directly calling ReferenceConfig.get() will not check this attribute.
*/
private Boolean singleton;
public AbstractInterfaceConfig() {}
public AbstractInterfaceConfig(ModuleModel moduleModel) {
super(moduleModel);
}
/**
* The url of the reference service
*/
protected final transient List<URL> urls = new ArrayList<>();
@Transient
public List<URL> getExportedUrls() {
return urls;
}
public URL toUrl() {
return urls.isEmpty() ? null : urls.iterator().next();
}
public List<URL> toUrls() {
return urls;
}
@Override
protected void postProcessAfterScopeModelChanged(ScopeModel oldScopeModel, ScopeModel newScopeModel) {
super.postProcessAfterScopeModelChanged(oldScopeModel, newScopeModel);
// change referenced config's scope model
ApplicationModel applicationModel = ScopeModelUtil.getApplicationModel(getScopeModel());
if (this.configCenter != null && this.configCenter.getScopeModel() != applicationModel) {
this.configCenter.setScopeModel(applicationModel);
}
if (this.metadataReportConfig != null && this.metadataReportConfig.getScopeModel() != applicationModel) {
this.metadataReportConfig.setScopeModel(applicationModel);
}
if (this.monitor != null && this.monitor.getScopeModel() != applicationModel) {
this.monitor.setScopeModel(applicationModel);
}
if (CollectionUtils.isNotEmpty(this.registries)) {
this.registries.forEach(registryConfig -> {
if (registryConfig.getScopeModel() != applicationModel) {
registryConfig.setScopeModel(applicationModel);
}
});
}
}
/**
* Check whether the registry config is exists, and then conversion it to {@link RegistryConfig}
*/
protected void checkRegistry() {
convertRegistryIdsToRegistries();
for (RegistryConfig registryConfig : registries) {
if (!registryConfig.isValid()) {
throw new IllegalStateException("No registry config found or it's not a valid config! "
+ "The registry config is: " + registryConfig);
}
}
}
public static void appendRuntimeParameters(Map<String, String> map) {
map.put(DUBBO_VERSION_KEY, Version.getProtocolVersion());
map.put(RELEASE_KEY, Version.getVersion());
map.put(TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis()));
if (ConfigUtils.getPid() > 0) {
map.put(PID_KEY, String.valueOf(ConfigUtils.getPid()));
}
}
/**
* To obtain the method list in the port, use reflection when in native mode and javassist otherwise.
*
* @param interfaceClass
* @return
*/
protected String[] methods(Class<?> interfaceClass) {
if (NativeDetector.inNativeImage()) {
return Arrays.stream(interfaceClass.getMethods())
.map(Method::getName)
.toArray(String[]::new);
} else {
return ClassUtils.getMethodNames(interfaceClass);
}
}
protected Environment getEnvironment() {
return getScopeModel().modelEnvironment();
}
@Override
protected void processExtraRefresh(String preferredPrefix, InmemoryConfiguration subPropsConfiguration) {
if (StringUtils.hasText(interfaceName)) {
Class<?> interfaceClass;
try {
interfaceClass = ClassUtils.forName(interfaceName);
} catch (ClassNotFoundException e) {
// There may be no interface class when generic call
return;
}
checkInterface();
// Auto create MethodConfig/ArgumentConfig according to config props
Map<String, String> configProperties = subPropsConfiguration.getProperties();
Method[] methods;
try {
methods = interfaceClass.getMethods();
} catch (Throwable e) {
// NoClassDefFoundError may be thrown if interface class's dependency jar is missing
return;
}
for (Method method : methods) {
if (ConfigurationUtils.hasSubProperties(configProperties, method.getName())) {
MethodConfig methodConfig = getMethodByName(method.getName());
// Add method config if not found
if (methodConfig == null) {
methodConfig = new MethodConfig();
methodConfig.setName(method.getName());
this.addMethod(methodConfig);
}
// Add argument config
// dubbo.service.{interfaceName}.{methodName}.{arg-index}.xxx=xxx
java.lang.reflect.Parameter[] arguments = method.getParameters();
for (int i = 0; i < arguments.length; i++) {
if (getArgumentByIndex(methodConfig, i) == null
&& hasArgumentConfigProps(configProperties, methodConfig.getName(), i)) {
ArgumentConfig argumentConfig = new ArgumentConfig();
argumentConfig.setIndex(i);
methodConfig.addArgument(argumentConfig);
}
}
}
}
// refresh MethodConfigs
List<MethodConfig> methodConfigs = this.getMethods();
if (methodConfigs != null && methodConfigs.size() > 0) {
// whether ignore invalid method config
Object ignoreInvalidMethodConfigVal = getEnvironment()
.getConfiguration()
.getProperty(ConfigKeys.DUBBO_CONFIG_IGNORE_INVALID_METHOD_CONFIG, "false");
boolean ignoreInvalidMethodConfig = Boolean.parseBoolean(ignoreInvalidMethodConfigVal.toString());
Class<?> finalInterfaceClass = interfaceClass;
List<MethodConfig> validMethodConfigs = methodConfigs.stream()
.filter(methodConfig -> {
methodConfig.setParentPrefix(preferredPrefix);
methodConfig.setScopeModel(getScopeModel());
methodConfig.refresh();
// verify method config
return verifyMethodConfig(methodConfig, finalInterfaceClass, ignoreInvalidMethodConfig);
})
.collect(Collectors.toList());
this.setMethods(validMethodConfigs);
}
}
}
/**
* it is used for skipping the check of interface since dubbo 3.2
* rest and triple protocol allow the service is implement class
*/
protected void checkInterface() {}
protected boolean verifyMethodConfig(
MethodConfig methodConfig, Class<?> interfaceClass, boolean ignoreInvalidMethodConfig) {
String methodName = methodConfig.getName();
if (StringUtils.isEmpty(methodName)) {
String msg = "<dubbo:method> name attribute is required! Please check: " + "<dubbo:service interface=\""
+ interfaceName + "\" ... >" + "<dubbo:method name=\"\" ... /></<dubbo:reference>";
if (ignoreInvalidMethodConfig) {
logger.warn(CONFIG_NO_METHOD_FOUND, "", "", msg);
return false;
} else {
throw new IllegalStateException(msg);
}
}
boolean hasMethod = Arrays.stream(interfaceClass.getMethods())
.anyMatch(method -> method.getName().equals(methodName));
if (!hasMethod) {
String msg = "Found invalid method config, the interface " + interfaceClass.getName()
+ " not found method \"" + methodName + "\" : [" + methodConfig + "]";
if (ignoreInvalidMethodConfig) {
logger.warn(CONFIG_NO_METHOD_FOUND, "", "", msg);
return false;
} else {
if (!isNeedCheckMethod()) {
msg = "Generic call: " + msg;
logger.warn(CONFIG_NO_METHOD_FOUND, "", "", msg);
} else {
throw new IllegalStateException(msg);
}
}
}
return true;
}
private ArgumentConfig getArgumentByIndex(MethodConfig methodConfig, int argIndex) {
if (methodConfig.getArguments() != null && methodConfig.getArguments().size() > 0) {
for (ArgumentConfig argument : methodConfig.getArguments()) {
if (argument.getIndex() != null && argument.getIndex() == argIndex) {
return argument;
}
}
}
return null;
}
@Transient
protected boolean isNeedCheckMethod() {
return true;
}
private boolean hasArgumentConfigProps(Map<String, String> configProperties, String methodName, int argIndex) {
String argPrefix = methodName + "." + argIndex + ".";
return ConfigurationUtils.hasSubProperties(configProperties, argPrefix);
}
protected MethodConfig getMethodByName(String name) {
if (methods != null && methods.size() > 0) {
for (MethodConfig methodConfig : methods) {
if (StringUtils.isEquals(methodConfig.getName(), name)) {
return methodConfig;
}
}
}
return null;
}
/**
* Legitimacy check of stub, note that: the local will deprecated, and replace with <code>stub</code>
*
* @param interfaceClass for provider side, it is the {@link Class} of the service that will be exported; for consumer
* side, it is the {@link Class} of the remote service interface
*/
protected void checkStubAndLocal(Class<?> interfaceClass) {
verifyStubAndLocal(local, "Local", interfaceClass);
verifyStubAndLocal(stub, "Stub", interfaceClass);
}
private void verifyStubAndLocal(String className, String label, Class<?> interfaceClass) {
if (ConfigUtils.isNotEmpty(className)) {
Class<?> localClass = ConfigUtils.isDefault(className)
? ReflectUtils.forName(interfaceClass.getName() + label)
: ReflectUtils.forName(className);
verify(interfaceClass, localClass);
}
}
private void verify(Class<?> interfaceClass, Class<?> localClass) {
if (!interfaceClass.isAssignableFrom(localClass)) {
throw new IllegalStateException("The local implementation class " + localClass.getName()
+ " not implement interface " + interfaceClass.getName());
}
try {
// Check if the localClass a constructor with parameter whose type is interfaceClass
ReflectUtils.findConstructor(localClass, interfaceClass);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("No such constructor \"public " + localClass.getSimpleName() + "("
+ interfaceClass.getName() + ")\" in local implementation class " + localClass.getName());
}
}
private void convertRegistryIdsToRegistries() {
computeValidRegistryIds();
if (StringUtils.isEmpty(registryIds)) {
if (CollectionUtils.isEmpty(registries)) {
List<RegistryConfig> registryConfigs = getConfigManager().getDefaultRegistries();
registryConfigs = new ArrayList<>(registryConfigs);
setRegistries(registryConfigs);
}
} else {
String[] ids = COMMA_SPLIT_PATTERN.split(registryIds);
List<RegistryConfig> tmpRegistries = new ArrayList<>();
Arrays.stream(ids).forEach(id -> {
if (tmpRegistries.stream().noneMatch(reg -> reg.getId().equals(id))) {
Optional<RegistryConfig> globalRegistry = getConfigManager().getRegistry(id);
if (globalRegistry.isPresent()) {
tmpRegistries.add(globalRegistry.get());
} else {
throw new IllegalStateException("Registry not found: " + id);
}
}
});
setRegistries(tmpRegistries);
}
}
protected boolean notHasSelfRegistryProperty() {
return CollectionUtils.isEmpty(registries) && StringUtils.isEmpty(registryIds);
}
protected void completeCompoundConfigs(AbstractInterfaceConfig interfaceConfig) {
if (interfaceConfig != null) {
if (application == null) {
setApplication(interfaceConfig.getApplication());
}
if (module == null) {
setModule(interfaceConfig.getModule());
}
if (notHasSelfRegistryProperty()) {
setRegistries(interfaceConfig.getRegistries());
setRegistryIds(interfaceConfig.getRegistryIds());
}
if (monitor == null) {
setMonitor(interfaceConfig.getMonitor());
}
}
if (module != null) {
if (notHasSelfRegistryProperty()) {
setRegistries(module.getRegistries());
}
if (monitor == null) {
setMonitor(module.getMonitor());
}
}
if (application != null) {
if (notHasSelfRegistryProperty()) {
setRegistries(application.getRegistries());
setRegistryIds(application.getRegistryIds());
}
if (monitor == null) {
setMonitor(application.getMonitor());
}
}
}
protected void computeValidRegistryIds() {
if (application != null && notHasSelfRegistryProperty()) {
setRegistries(application.getRegistries());
setRegistryIds(application.getRegistryIds());
}
}
/**
* @return local
* @deprecated Replace to <code>getStub()</code>
*/
@Deprecated
public String getLocal() {
return local;
}
/**
* @param local
* @deprecated Replace to <code>setStub(Boolean)</code>
*/
@Deprecated
public void setLocal(Boolean local) {
if (local == null) {
setLocal((String) null);
} else {
setLocal(local.toString());
}
}
/**
* @param local
* @deprecated Replace to <code>setStub(String)</code>
*/
@Deprecated
public void setLocal(String local) {
this.local = local;
}
public String getStub() {
return stub;
}
public void setStub(Boolean stub) {
if (stub == null) {
setStub((String) null);
} else {
setStub(stub.toString());
}
}
public void setStub(String stub) {
this.stub = stub;
}
public String getCluster() {
return cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getProxy() {
if (NativeDetector.inNativeImage()) {
return DEFAULT_NATIVE_PROXY;
} else {
return this.proxy;
}
}
public void setProxy(String proxy) {
if (NativeDetector.inNativeImage()) {
this.proxy = DEFAULT_NATIVE_PROXY;
AdaptiveCompiler.setDefaultCompiler(DEFAULT_NATIVE_PROXY);
} else {
this.proxy = proxy;
}
}
public Integer getConnections() {
return connections;
}
public void setConnections(Integer connections) {
this.connections = connections;
}
@Parameter(key = REFERENCE_FILTER_KEY, append = true)
public String getFilter() {
return filter;
}
public void setFilter(String filter) {
this.filter = filter;
}
@Parameter(key = INVOKER_LISTENER_KEY, append = true)
public String getListener() {
return listener;
}
public void setListener(String listener) {
this.listener = listener;
}
public String getLayer() {
return layer;
}
public void setLayer(String layer) {
this.layer = layer;
}
/**
* Always use the global ApplicationConfig
*/
public ApplicationConfig getApplication() {
if (application != null) {
return application;
}
return getConfigManager().getApplicationOrElseThrow();
}
/**
* @param application
* @deprecated Use {@link org.apache.dubbo.config.AbstractConfig#setScopeModel(ScopeModel)}
*/
@Deprecated
public void setApplication(ApplicationConfig application) {
this.application = application;
if (application != null) {
getConfigManager().setApplication(application);
}
}
public ModuleConfig getModule() {
if (module != null) {
return module;
}
return getModuleConfigManager().getModule().orElse(null);
}
/**
* @param module
* @deprecated Use {@link org.apache.dubbo.config.AbstractConfig#setScopeModel(ScopeModel)}
*/
@Deprecated
public void setModule(ModuleConfig module) {
this.module = module;
if (module != null) {
getModuleConfigManager().setModule(module);
}
}
public RegistryConfig getRegistry() {
return CollectionUtils.isEmpty(registries) ? null : registries.get(0);
}
public void setRegistry(RegistryConfig registry) {
if (registry != null) {
List<RegistryConfig> registries = new ArrayList<>(1);
registries.add(registry);
setRegistries(registries);
} else {
this.registries = null;
}
}
public List<RegistryConfig> getRegistries() {
return registries;
}
@SuppressWarnings({"unchecked"})
public void setRegistries(List<? extends RegistryConfig> registries) {
this.registries = (List<RegistryConfig>) registries;
}
@Parameter(excluded = true)
public String getRegistryIds() {
return registryIds;
}
public void setRegistryIds(String registryIds) {
this.registryIds = registryIds;
}
public List<MethodConfig> getMethods() {
return methods;
}
public void setMethods(List<? extends MethodConfig> methods) {
this.methods = (methods != null) ? new ArrayList<>(methods) : null;
}
/**
* It is only used in native scenarios to get methodConfigs.
* @param methodsJson
*/
public void setMethodsJson(List<String> methodsJson) {
if (methodsJson != null) {
this.methods = new ArrayList<>();
methodsJson.forEach(
(methodConfigJson) -> methods.add(JsonUtils.toJavaObject(methodConfigJson, MethodConfig.class)));
} else {
this.methods = null;
}
}
public void addMethod(MethodConfig methodConfig) {
if (this.methods == null) {
this.methods = new ArrayList<>();
}
this.methods.add(methodConfig);
}
public MonitorConfig getMonitor() {
if (monitor != null) {
return monitor;
}
// FIXME: instead of return null, we should set default monitor when getMonitor() return null in ConfigManager
return getConfigManager().getMonitor().orElse(null);
}
/**
* @deprecated Use {@link org.apache.dubbo.config.context.ConfigManager#setMonitor(MonitorConfig)}
*/
@Deprecated
public void setMonitor(String monitor) {
setMonitor(new MonitorConfig(monitor));
}
/**
* @deprecated Use {@link org.apache.dubbo.config.context.ConfigManager#setMonitor(MonitorConfig)}
*/
@Deprecated
public void setMonitor(MonitorConfig monitor) {
this.monitor = monitor;
if (monitor != null) {
getConfigManager().setMonitor(monitor);
}
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
/**
* @deprecated Use {@link org.apache.dubbo.config.context.ConfigManager#getConfigCenter(String)}
*/
@Deprecated
public ConfigCenterConfig getConfigCenter() {
if (configCenter != null) {
return configCenter;
}
Collection<ConfigCenterConfig> configCenterConfigs = getConfigManager().getConfigCenters();
if (CollectionUtils.isNotEmpty(configCenterConfigs)) {
return configCenterConfigs.iterator().next();
}
return null;
}
/**
* @deprecated Use {@link org.apache.dubbo.config.context.ConfigManager#addConfigCenter(ConfigCenterConfig)}
*/
@Deprecated
public void setConfigCenter(ConfigCenterConfig configCenter) {
this.configCenter = configCenter;
if (configCenter != null) {
getConfigManager().addConfigCenter(configCenter);
}
}
public Integer getCallbacks() {
return callbacks;
}
public void setCallbacks(Integer callbacks) {
this.callbacks = callbacks;
}
public String getOnconnect() {
return onconnect;
}
public void setOnconnect(String onconnect) {
this.onconnect = onconnect;
}
public String getOndisconnect() {
return ondisconnect;
}
public void setOndisconnect(String ondisconnect) {
this.ondisconnect = ondisconnect;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
/**
* @deprecated Use {@link org.apache.dubbo.config.context.ConfigManager#getMetadataConfigs()}
*/
@Deprecated
public MetadataReportConfig getMetadataReportConfig() {
if (metadataReportConfig != null) {
return metadataReportConfig;
}
Collection<MetadataReportConfig> metadataReportConfigs =
getConfigManager().getMetadataConfigs();
if (CollectionUtils.isNotEmpty(metadataReportConfigs)) {
return metadataReportConfigs.iterator().next();
}
return null;
}
/**
* @deprecated Use {@link org.apache.dubbo.config.context.ConfigManager#addMetadataReport(MetadataReportConfig)}
*/
@Deprecated
public void setMetadataReportConfig(MetadataReportConfig metadataReportConfig) {
this.metadataReportConfig = metadataReportConfig;
if (metadataReportConfig != null) {
getConfigManager().addMetadataReport(metadataReportConfig);
}
}
@Parameter(key = TAG_KEY)
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public Boolean getAuth() {
return auth;
}
public void setAuth(Boolean auth) {
this.auth = auth;
}
public String getAuthenticator() {
return authenticator;
}
public AbstractInterfaceConfig setAuthenticator(String authenticator) {
this.authenticator = authenticator;
return this;
}
public String getUsername() {
return username;
}
public AbstractInterfaceConfig setUsername(String username) {
this.username = username;
return this;
}
public String getPassword() {
return password;
}
public AbstractInterfaceConfig setPassword(String password) {
this.password = password;
return this;
}
public SslConfig getSslConfig() {
return getConfigManager().getSsl().orElse(null);
}
public Boolean getSingleton() {
return singleton;
}
public void setSingleton(Boolean singleton) {
this.singleton = singleton;
}
protected void initServiceMetadata(AbstractInterfaceConfig interfaceConfig) {
serviceMetadata.setVersion(getVersion(interfaceConfig));
serviceMetadata.setGroup(getGroup(interfaceConfig));
serviceMetadata.setDefaultGroup(getGroup(interfaceConfig));
serviceMetadata.setServiceInterfaceName(getInterface());
}
public String getGroup(AbstractInterfaceConfig interfaceConfig) {
return StringUtils.isEmpty(getGroup())
? (interfaceConfig != null ? interfaceConfig.getGroup() : getGroup())
: getGroup();
}
public String getVersion(AbstractInterfaceConfig interfaceConfig) {
return StringUtils.isEmpty(getVersion())
? (interfaceConfig != null ? interfaceConfig.getVersion() : getVersion())
: getVersion();
}
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 getInterface() {
return interfaceName;
}
public void setInterface(String interfaceName) {
this.interfaceName = interfaceName;
}
@Transient
public ClassLoader getInterfaceClassLoader() {
return interfaceClassLoader;
}
public void setInterfaceClassLoader(ClassLoader interfaceClassLoader) {
this.interfaceClassLoader = interfaceClassLoader;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.support.ProtocolUtils;
import java.beans.Transient;
import static org.apache.dubbo.common.constants.CommonConstants.INVOKER_LISTENER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REFER_ASYNC_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.ROUTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.STUB_EVENT_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDED_BY;
import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDER_NAMESPACE;
import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDER_PORT;
/**
* AbstractConsumerConfig
*
* @export
* @see ReferenceConfigBase
*/
public abstract class AbstractReferenceConfig extends AbstractInterfaceConfig {
private static final long serialVersionUID = -2786526984373031126L;
// ======== Reference config default values, will take effect if reference's attribute is not set ========
/**
* Check if service provider exists, if not exists, it will be fast fail
*/
protected Boolean check;
/**
* Whether to eagle-init
*/
protected Boolean init;
/**
* Whether to use generic interface
*/
protected String generic;
/**
* Whether to find reference's instance from the current JVM
*/
protected Boolean injvm;
/**
* Lazy create connection
*/
protected Boolean lazy;
protected String reconnect;
protected Boolean sticky;
/**
* Whether to support event in stub.
*/
// TODO solve merge problem
protected Boolean stubevent; // = Constants.DEFAULT_STUB_EVENT;
/**
* declares which app or service this interface belongs to
*/
protected String providedBy;
/**
* By VirtualService and DestinationRule, envoy will generate a new route rule,such as 'demo.default.svc.cluster.local:80',the default port is 80.
* When you want to specify the provider port,you can use this config.
*
* @since 3.1.0
*/
protected Integer providerPort;
/**
* assign the namespace that provider belong to
* @since 3.1.1
*/
protected String providerNamespace;
protected String router;
/**
* Weather the reference is referred asynchronously
*
* @see ModuleConfig#referAsync
* @deprecated
*/
@Deprecated
private Boolean referAsync;
/**
* client type
*/
protected String client;
/**
* Only the service provider of the specified protocol is invoked, and other protocols are ignored.
*/
protected String protocol;
public AbstractReferenceConfig() {}
public AbstractReferenceConfig(ModuleModel moduleModel) {
super(moduleModel);
}
@Override
protected void checkDefault() {
super.checkDefault();
if (sticky == null) {
sticky = false;
}
}
public Boolean isCheck() {
return check;
}
public void setCheck(Boolean check) {
this.check = check;
}
public Boolean isInit() {
return init;
}
public void setInit(Boolean init) {
this.init = init;
}
/**
* @deprecated Replace to {@link AbstractReferenceConfig#getGeneric()}
*/
@Deprecated
@Parameter(excluded = true, attribute = false)
public Boolean isGeneric() {
return this.generic != null ? ProtocolUtils.isGeneric(generic) : null;
}
/**
* @deprecated Replace to {@link AbstractReferenceConfig#setGeneric(String)}
*/
@Deprecated
public void setGeneric(Boolean generic) {
if (generic != null) {
this.generic = generic.toString();
}
}
public String getGeneric() {
return generic;
}
public void setGeneric(String generic) {
if (StringUtils.isEmpty(generic)) {
return;
}
if (ProtocolUtils.isValidGenericValue(generic)) {
this.generic = generic;
} else {
throw new IllegalArgumentException("Unsupported generic type " + generic);
}
}
@Override
@Transient
protected boolean isNeedCheckMethod() {
return StringUtils.isEmpty(getGeneric());
}
/**
* @return
* @deprecated instead, use the parameter <b>scope</> to judge if it's in jvm, scope=local
*/
@Deprecated
public Boolean isInjvm() {
return injvm;
}
/**
* @param injvm
* @deprecated instead, use the parameter <b>scope</b> to judge if it's in jvm, scope=local
*/
@Deprecated
public void setInjvm(Boolean injvm) {
this.injvm = injvm;
}
@Override
@Parameter(key = REFERENCE_FILTER_KEY, append = true)
public String getFilter() {
return super.getFilter();
}
@Override
@Parameter(key = INVOKER_LISTENER_KEY, append = true)
public String getListener() {
return super.getListener();
}
@Override
public void setListener(String listener) {
super.setListener(listener);
}
public Boolean getLazy() {
return lazy;
}
public void setLazy(Boolean lazy) {
this.lazy = lazy;
}
@Override
public void setOnconnect(String onconnect) {
if (onconnect != null && onconnect.length() > 0) {
this.stubevent = true;
}
super.setOnconnect(onconnect);
}
@Override
public void setOndisconnect(String ondisconnect) {
if (ondisconnect != null && ondisconnect.length() > 0) {
this.stubevent = true;
}
super.setOndisconnect(ondisconnect);
}
@Parameter(key = STUB_EVENT_KEY)
public Boolean getStubevent() {
return stubevent;
}
public String getReconnect() {
return reconnect;
}
public void setReconnect(String reconnect) {
this.reconnect = reconnect;
}
public Boolean getSticky() {
return sticky;
}
public void setSticky(Boolean sticky) {
this.sticky = sticky;
}
@Parameter(key = PROVIDED_BY)
public String getProvidedBy() {
return providedBy;
}
public void setProvidedBy(String providedBy) {
this.providedBy = providedBy;
}
@Parameter(key = PROVIDER_PORT)
public Integer getProviderPort() {
return providerPort;
}
public void setProviderPort(Integer providerPort) {
this.providerPort = providerPort;
}
@Parameter(key = PROVIDER_NAMESPACE)
public String getProviderNamespace() {
return providerNamespace;
}
public void setProviderNamespace(String providerNamespace) {
this.providerNamespace = providerNamespace;
}
@Parameter(key = ROUTER_KEY, append = true)
public String getRouter() {
return router;
}
public void setRouter(String router) {
this.router = router;
}
@Deprecated
@Parameter(key = REFER_ASYNC_KEY)
public Boolean getReferAsync() {
return referAsync;
}
@Deprecated
public void setReferAsync(Boolean referAsync) {
this.referAsync = referAsync;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/ConsumerConfig.java | dubbo-common/src/main/java/org/apache/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 org.apache.dubbo.config;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ModuleModel;
import static org.apache.dubbo.common.constants.CommonConstants.MESH_ENABLE;
import static org.apache.dubbo.common.constants.CommonConstants.REFER_BACKGROUND_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REFER_THREAD_NUM_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.SYSTEM_TCP_RESPONSE_TIMEOUT;
import static org.apache.dubbo.common.constants.CommonConstants.URL_MERGE_PROCESSOR_KEY;
/**
* The service consumer default configuration
*
* @export
*/
public class ConsumerConfig extends AbstractReferenceConfig {
private static final long serialVersionUID = 2827274711143680600L;
/**
* Consumer thread pool type: cached, fixed, limit, eager
*/
private String threadpool;
/**
* Consumer threadpool core thread size
*/
private Integer corethreads;
/**
* Consumer threadpool thread size
*/
private Integer threads;
/**
* Consumer threadpool queue size
*/
private Integer queues;
/**
* By default, a TCP long-connection communication is shared between the consumer process and the provider process.
* This property can be set to share multiple TCP long-connection communications. Note that only the dubbo protocol takes effect.
*/
private Integer shareconnections;
/**
* Url Merge Processor
* Used to customize the URL merge of consumer and provider
*/
private String urlMergeProcessor;
/**
* Thread num for asynchronous refer pool size
*/
private Integer referThreadNum;
/**
* Whether refer should run in background or not.
*
* @see ModuleConfig#setBackground(Boolean)
* @deprecated replace with {@link ModuleConfig#setBackground(Boolean)}
*/
private Boolean referBackground;
/**
* enable mesh mode
*
* @since 3.1.0
*/
private Boolean meshEnable;
public ConsumerConfig() {}
public ConsumerConfig(ModuleModel moduleModel) {
super(moduleModel);
}
@Override
public void setTimeout(Integer timeout) {
super.setTimeout(timeout);
String rmiTimeout = SystemPropertyConfigUtils.getSystemProperty(SYSTEM_TCP_RESPONSE_TIMEOUT);
if (timeout != null && timeout > 0 && (StringUtils.isEmpty(rmiTimeout))) {
SystemPropertyConfigUtils.setSystemProperty(SYSTEM_TCP_RESPONSE_TIMEOUT, String.valueOf(timeout));
}
}
public String getThreadpool() {
return threadpool;
}
public void setThreadpool(String threadpool) {
this.threadpool = threadpool;
}
public Integer getCorethreads() {
return corethreads;
}
public void setCorethreads(Integer corethreads) {
this.corethreads = corethreads;
}
public Integer getThreads() {
return threads;
}
public void setThreads(Integer threads) {
this.threads = threads;
}
public Integer getQueues() {
return queues;
}
public void setQueues(Integer queues) {
this.queues = queues;
}
public Integer getShareconnections() {
return shareconnections;
}
public void setShareconnections(Integer shareconnections) {
this.shareconnections = shareconnections;
}
@Parameter(key = URL_MERGE_PROCESSOR_KEY)
public String getUrlMergeProcessor() {
return urlMergeProcessor;
}
public void setUrlMergeProcessor(String urlMergeProcessor) {
this.urlMergeProcessor = urlMergeProcessor;
}
@Parameter(key = REFER_THREAD_NUM_KEY, excluded = true)
public Integer getReferThreadNum() {
return referThreadNum;
}
public void setReferThreadNum(Integer referThreadNum) {
this.referThreadNum = referThreadNum;
}
@Deprecated
@Parameter(key = REFER_BACKGROUND_KEY, excluded = true)
public Boolean getReferBackground() {
return referBackground;
}
/**
* Whether refer should run in background or not.
*
* @see ModuleConfig#setBackground(Boolean)
* @deprecated replace with {@link ModuleConfig#setBackground(Boolean)}
*/
@Deprecated
public void setReferBackground(Boolean referBackground) {
this.referBackground = referBackground;
}
@Parameter(key = MESH_ENABLE)
public Boolean getMeshEnable() {
return meshEnable;
}
public void setMeshEnable(Boolean meshEnable) {
this.meshEnable = meshEnable;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/ServiceConfigBase.java | dubbo-common/src/main/java/org/apache/dubbo/config/ServiceConfigBase.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.constants.RegisterTypeEnum;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.config.context.ConfigMode;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ServiceMetadata;
import org.apache.dubbo.rpc.service.GenericService;
import org.apache.dubbo.rpc.support.ProtocolUtils;
import java.beans.Transient;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
/**
* Base configuration for service.
*
* @export
*/
@SuppressWarnings({"rawtypes", "deprecation"})
public abstract class ServiceConfigBase<T> extends AbstractServiceConfig {
private static final long serialVersionUID = 3033787999037024738L;
/**
* The interface class of the exported service.
*/
protected Class<?> interfaceClass;
/**
* The reference to the interface implementation.
*/
protected transient T ref;
/**
* The service name, which is used to uniquely identify the service.
*/
protected String path;
/**
* The provider configuration for this service.
*/
protected ProviderConfig provider;
/**
* A comma-separated list of provider IDs.
*/
protected String providerIds;
/**
* Indicates whether the service is a GenericService.
* If set, this means that the service is a generic service that can handle multiple types.
*/
protected volatile String generic;
public ServiceConfigBase() {
serviceMetadata = new ServiceMetadata();
serviceMetadata.addAttribute("ORIGIN_CONFIG", this);
}
public ServiceConfigBase(ModuleModel moduleModel) {
super(moduleModel);
serviceMetadata = new ServiceMetadata();
serviceMetadata.addAttribute("ORIGIN_CONFIG", this);
}
public ServiceConfigBase(Service service) {
serviceMetadata = new ServiceMetadata();
serviceMetadata.addAttribute("ORIGIN_CONFIG", this);
appendAnnotation(Service.class, service);
setMethods(MethodConfig.constructMethodConfig(service.methods()));
}
public ServiceConfigBase(ModuleModel moduleModel, Service service) {
super(moduleModel);
serviceMetadata = new ServiceMetadata();
serviceMetadata.addAttribute("ORIGIN_CONFIG", this);
appendAnnotation(Service.class, service);
setMethods(MethodConfig.constructMethodConfig(service.methods()));
}
@Override
public void setProtocols(List<? extends ProtocolConfig> protocols) {
super.setProtocols(protocols);
checkInterface();
}
@Override
protected void postProcessAfterScopeModelChanged(ScopeModel oldScopeModel, ScopeModel newScopeModel) {
super.postProcessAfterScopeModelChanged(oldScopeModel, newScopeModel);
if (this.provider != null && this.provider.getScopeModel() != getScopeModel()) {
this.provider.setScopeModel(getScopeModel());
}
}
public boolean shouldExport() {
Boolean export = getExport();
// default value is true
return export == null || export;
}
@Override
public Boolean getExport() {
return (export == null && provider != null) ? provider.getExport() : export;
}
public boolean shouldDelay() {
Integer delay = getDelay();
return delay != null && delay > 0;
}
@Override
public Integer getDelay() {
return (delay == null && provider != null) ? provider.getDelay() : delay;
}
protected void checkRef() {
// reference should not be null, and is the implementation of the given interface
if (ref == null) {
throw new IllegalStateException("ref not allow null!");
}
if (!interfaceClass.isInstance(ref)) {
throw new IllegalStateException("The class "
+ getClassDesc(ref.getClass()) + " unimplemented interface "
+ getClassDesc(interfaceClass) + "!");
}
}
private String getClassDesc(Class clazz) {
ClassLoader classLoader = clazz.getClassLoader();
return clazz.getName() + "[classloader=" + classLoader.getClass().getName() + "@" + classLoader.hashCode()
+ "]";
}
public Optional<String> getContextPath(ProtocolConfig protocolConfig) {
String contextPath = protocolConfig.getContextpath();
if (StringUtils.isEmpty(contextPath) && provider != null) {
contextPath = provider.getContextpath();
}
return Optional.ofNullable(contextPath);
}
protected Class getServiceClass(T ref) {
return ref.getClass();
}
@Override
protected void preProcessRefresh() {
super.preProcessRefresh();
convertProviderIdToProvider();
if (provider == null) {
provider = getModuleConfigManager()
.getDefaultProvider()
.orElseThrow(() -> new IllegalStateException("Default provider is not initialized"));
}
// try set properties from `dubbo.service` if not set in current config
refreshWithPrefixes(super.getPrefixes(), ConfigMode.OVERRIDE_IF_ABSENT);
}
@Override
@Transient
public Map<String, String> getMetaData() {
return getMetaData(null);
}
@Override
public Map<String, String> getMetaData(String prefix) {
Map<String, String> metaData = new HashMap<>();
ProviderConfig provider = this.getProvider();
// provider should be initialized at preProcessRefresh()
if (isRefreshed() && provider == null) {
throw new IllegalStateException("Provider is not initialized");
}
// use provider attributes as default value
appendAttributes(metaData, provider, prefix);
// Finally, put the service's attributes, overriding previous attributes
appendAttributes(metaData, this, prefix);
return metaData;
}
protected void checkProtocol() {
if (provider != null && notHasSelfProtocolProperty()) {
setProtocols(provider.getProtocols());
setProtocolIds(provider.getProtocolIds());
}
convertProtocolIdsToProtocols();
}
private boolean notHasSelfProtocolProperty() {
return CollectionUtils.isEmpty(protocols) && StringUtils.isEmpty(protocolIds);
}
protected void completeCompoundConfigs() {
completeCompoundConfigs(provider);
if (provider != null) {
if (notHasSelfProtocolProperty()) {
setProtocols(provider.getProtocols());
setProtocolIds(provider.getProtocolIds());
}
if (configCenter == null) {
setConfigCenter(provider.getConfigCenter());
}
}
}
protected void convertProviderIdToProvider() {
if (provider == null && StringUtils.hasText(providerIds)) {
provider = getModuleConfigManager()
.getProvider(providerIds)
.orElseThrow(() -> new IllegalStateException("Provider config not found: " + providerIds));
}
}
protected void convertProtocolIdsToProtocols() {
if (StringUtils.isEmpty(protocolIds)) {
if (CollectionUtils.isEmpty(protocols)) {
List<ProtocolConfig> protocolConfigs = getConfigManager().getDefaultProtocols();
if (CollectionUtils.isEmpty(protocolConfigs)) {
throw new IllegalStateException("The default protocol has not been initialized.");
}
setProtocols(protocolConfigs);
}
} else {
String[] idsArray = COMMA_SPLIT_PATTERN.split(protocolIds);
Set<String> idsSet = new LinkedHashSet<>(Arrays.asList(idsArray));
List<ProtocolConfig> tmpProtocols = new ArrayList<>();
for (String id : idsSet) {
Optional<ProtocolConfig> globalProtocol = getConfigManager().getProtocol(id);
if (globalProtocol.isPresent()) {
tmpProtocols.add(globalProtocol.get());
} else {
throw new IllegalStateException("Protocol not found: " + id);
}
}
setProtocols(tmpProtocols);
}
}
public Class<?> getInterfaceClass() {
if (interfaceClass != null) {
return interfaceClass;
}
if (ref instanceof GenericService) {
return GenericService.class;
}
try {
if (StringUtils.isNotEmpty(interfaceName)) {
interfaceClass = Class.forName(
interfaceName, true, Thread.currentThread().getContextClassLoader());
}
} catch (ClassNotFoundException t) {
throw new IllegalStateException(t.getMessage(), t);
}
return interfaceClass;
}
/**
* @see #setInterface(Class)
* @deprecated
*/
public void setInterfaceClass(Class<?> interfaceClass) {
setInterface(interfaceClass);
}
public void setInterface(Class<?> interfaceClass) {
this.interfaceClass = interfaceClass;
checkInterface();
setInterface(interfaceClass == null ? null : interfaceClass.getName());
if (getInterfaceClassLoader() == null) {
setInterfaceClassLoader(interfaceClass == null ? null : interfaceClass.getClassLoader());
}
}
@Override
public void checkInterface() {
if (interfaceClass == null || interfaceClass.isInterface()) {
return;
}
List<ProtocolConfig> protocols = getProtocols();
if (CollectionUtils.isEmpty(protocols)) {
return;
}
for (ProtocolConfig protocol : protocols) {
String name = protocol.getName();
if (CommonConstants.TRIPLE.equals(name) && Boolean.TRUE.equals(protocol.isNoInterfaceSupport())) {
return;
}
if (Constants.REST_PROTOCOL.equals(name)) {
return;
}
}
throw new IllegalStateException("The interface class " + interfaceClass + " is not a interface!");
}
@Transient
public T getRef() {
return ref;
}
public void setRef(T ref) {
this.ref = ref;
}
@Parameter(excluded = true)
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public ProviderConfig getProvider() {
return provider;
}
public void setProvider(ProviderConfig provider) {
getModuleConfigManager().addProvider(provider);
this.provider = provider;
}
@Parameter(excluded = true)
public String getProviderIds() {
return providerIds;
}
public void setProviderIds(String providerIds) {
this.providerIds = providerIds;
}
public String getGeneric() {
return generic;
}
public void setGeneric(String generic) {
if (StringUtils.isEmpty(generic)) {
return;
}
if (ProtocolUtils.isValidGenericValue(generic)) {
this.generic = generic;
} else {
throw new IllegalArgumentException("Unsupported generic type " + generic);
}
}
@Transient
public ServiceMetadata getServiceMetadata() {
return serviceMetadata;
}
@Override
@Transient
@Parameter(excluded = true, attribute = false)
public List<String> getPrefixes() {
List<String> prefixes = new ArrayList<>();
// dubbo.service.{interface-name}
prefixes.add(DUBBO + ".service." + interfaceName);
return prefixes;
}
@Parameter(excluded = true, attribute = false)
public String getUniqueServiceName() {
return interfaceName != null ? URL.buildKey(interfaceName, getGroup(), getVersion()) : null;
}
@Override
public String getGroup() {
return StringUtils.isEmpty(this.group) ? (provider != null ? provider.getGroup() : this.group) : this.group;
}
@Override
public String getVersion() {
return StringUtils.isEmpty(this.version)
? (provider != null ? provider.getVersion() : this.version)
: this.version;
}
@Override
protected void computeValidRegistryIds() {
if (provider != null && notHasSelfRegistryProperty()) {
setRegistries(provider.getRegistries());
setRegistryIds(provider.getRegistryIds());
}
super.computeValidRegistryIds();
}
public Boolean shouldExportAsync() {
Boolean shouldExportAsync = getExportAsync();
if (shouldExportAsync == null) {
shouldExportAsync = provider != null && provider.getExportAsync() != null && provider.getExportAsync();
}
return shouldExportAsync;
}
/**
* export service and auto start application instance
*/
public final void export() {
export(RegisterTypeEnum.AUTO_REGISTER);
}
public abstract void unexport();
public abstract boolean isExported();
public abstract boolean isUnexported();
/**
* Export service to network
*
* @param registerType register type of current export action.
*/
public abstract void export(RegisterTypeEnum registerType);
/**
* Register delay published service to registry.
*/
public final void register() {
register(false);
}
/**
* Register delay published service to registry.
*
* @param byDeployer register by deployer or not.
*/
public abstract void register(boolean byDeployer);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.beans.Transient;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executor;
import static org.apache.dubbo.common.constants.CommonConstants.EXPORTER_LISTENER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.EXPORT_ASYNC_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_EXECUTOR;
import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_FILTER_KEY;
/**
* Abstract configuration for the service.
*
* @export
*/
public abstract class AbstractServiceConfig extends AbstractInterfaceConfig {
private static final long serialVersionUID = -9026290350363878309L;
/**
* The service version.
*/
protected String version;
/**
* The service group.
*/
protected String group;
/**
* Whether the service is deprecated.
*/
protected Boolean deprecated;
/**
* The time delay to register the service (in milliseconds).
*/
protected Integer delay;
/**
* Whether to export the service.
*/
protected Boolean export;
/**
* The service weight.
*/
protected Integer weight;
/**
* Document center for the service.
*/
protected String document;
/**
* Whether to register the service as a dynamic service on the registry. If true, the service
* will be enabled automatically after registration, and manual disabling is required to stop it.
*/
protected Boolean dynamic;
/**
* Whether to use a token for authentication.
*/
protected String token;
/**
* Whether to export access logs to logs.
*/
protected String accesslog;
/**
* List of protocols the service will export with (use this or protocolIds, not both).
*/
protected List<ProtocolConfig> protocols;
/**
* Id list of protocols the service will export with (use this or protocols, not both).
*/
protected String protocolIds;
/**
* Max allowed executing times.
*/
private Integer executes;
/**
* Whether to register the service.
*/
private Boolean register;
/**
* Warm-up period for the service.
*/
private Integer warmup;
/**
* Serialization type for service communication.
*/
private String serialization;
/**
* Specifies the preferred serialization method for the consumer.
* If specified, the consumer will use this parameter first.
* If the Dubbo Sdk you are using contains the serialization type, the serialization method specified by the argument is used.
* <p>
* When this parameter is null or the serialization type specified by this parameter does not exist in the Dubbo SDK, the serialization type specified by serialization is used.
* If the Dubbo SDK if still does not exist, the default type of the Dubbo SDK is used.
* For Dubbo SDK >= 3.2, <code>preferSerialization</code> takes precedence over <code>serialization</code>
* <p>
* Supports multiple values separated by commas, e.g., "fastjson2,fastjson,hessian2".
*/
private String preferSerialization; // Default: fastjson2, hessian2
/**
* Weather the service is export asynchronously
* @deprecated
* @see ModuleConfig#exportAsync
*/
@Deprecated
private Boolean exportAsync;
/**
* used for thread pool isolation between services
*/
private Executor executor;
/**
* Payload max length.
*/
private Integer payload;
/**
* Whether to use java_package in IDL as path. Default use package.
* This param only available when service using native stub.
*/
private Boolean useJavaPackageAsPath;
public AbstractServiceConfig() {}
public AbstractServiceConfig(ModuleModel moduleModel) {
super(moduleModel);
}
@Override
protected void checkDefault() {
super.checkDefault();
if (deprecated == null) {
deprecated = false;
}
if (dynamic == null) {
dynamic = true;
}
if (useJavaPackageAsPath == null) {
useJavaPackageAsPath = false;
}
if (StringUtils.isBlank(preferSerialization)) {
preferSerialization = serialization;
}
}
@Override
public String getVersion() {
return version;
}
@Override
public void setVersion(String version) {
this.version = version;
}
@Override
public String getGroup() {
return group;
}
@Override
public void setGroup(String group) {
this.group = group;
}
public Integer getDelay() {
return delay;
}
public void setDelay(Integer delay) {
this.delay = delay;
}
public Boolean getExport() {
return export;
}
public void setExport(Boolean export) {
this.export = export;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
@Parameter(escaped = true)
public String getDocument() {
return document;
}
public void setDocument(String document) {
this.document = document;
}
public String getToken() {
return token;
}
public void setToken(Boolean token) {
if (token == null) {
setToken((String) null);
} else {
setToken(String.valueOf(token));
}
}
public void setToken(String token) {
this.token = token;
}
public Boolean isDeprecated() {
return deprecated;
}
public void setDeprecated(Boolean deprecated) {
this.deprecated = deprecated;
}
public Boolean isDynamic() {
return dynamic;
}
public void setDynamic(Boolean dynamic) {
this.dynamic = dynamic;
}
public List<ProtocolConfig> getProtocols() {
return protocols;
}
@SuppressWarnings({"unchecked"})
public void setProtocols(List<? extends ProtocolConfig> protocols) {
this.protocols = (List<ProtocolConfig>) protocols;
}
public ProtocolConfig getProtocol() {
return CollectionUtils.isEmpty(protocols) ? null : protocols.get(0);
}
public void setProtocol(ProtocolConfig protocol) {
setProtocols(new ArrayList<>(Collections.singletonList(protocol)));
}
@Parameter(excluded = true)
public String getProtocolIds() {
return protocolIds;
}
public void setProtocolIds(String protocolIds) {
this.protocolIds = protocolIds;
}
public String getAccesslog() {
return accesslog;
}
public void setAccesslog(Boolean accesslog) {
if (accesslog == null) {
setAccesslog((String) null);
} else {
setAccesslog(String.valueOf(accesslog));
}
}
public void setAccesslog(String accesslog) {
this.accesslog = accesslog;
}
public Integer getExecutes() {
return executes;
}
public void setExecutes(Integer executes) {
this.executes = executes;
}
@Override
@Parameter(key = SERVICE_FILTER_KEY, append = true)
public String getFilter() {
return super.getFilter();
}
@Override
@Parameter(key = EXPORTER_LISTENER_KEY, append = true)
public String getListener() {
return listener;
}
@Override
public void setListener(String listener) {
this.listener = listener;
}
public Boolean isRegister() {
return register;
}
public void setRegister(Boolean register) {
this.register = register;
}
public Integer getWarmup() {
return warmup;
}
public void setWarmup(Integer warmup) {
this.warmup = warmup;
}
public String getSerialization() {
return serialization;
}
public void setSerialization(String serialization) {
this.serialization = serialization;
}
public String getPreferSerialization() {
return preferSerialization;
}
public void setPreferSerialization(String preferSerialization) {
this.preferSerialization = preferSerialization;
}
@Deprecated
@Parameter(key = EXPORT_ASYNC_KEY)
public Boolean getExportAsync() {
return exportAsync;
}
@Deprecated
public void setExportAsync(Boolean exportAsync) {
this.exportAsync = exportAsync;
}
public void setExecutor(Executor executor) {
this.executor = executor;
}
@Parameter(key = SERVICE_EXECUTOR)
@Transient
public Executor getExecutor() {
return executor;
}
public Integer getPayload() {
return payload;
}
public void setPayload(Integer payload) {
this.payload = payload;
}
@Parameter(excluded = true, attribute = false)
public Boolean getUseJavaPackageAsPath() {
return useJavaPackageAsPath;
}
public void setUseJavaPackageAsPath(Boolean useJavaPackageAsPath) {
this.useJavaPackageAsPath = useJavaPackageAsPath;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/Constants.java | dubbo-common/src/main/java/org/apache/dubbo/config/Constants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP_COMPATIBLE;
import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP_WHITELIST_COMPATIBLE;
import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE_COMPATIBLE;
import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST_COMPATIBLE;
import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT_COMPATIBLE;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY;
public interface Constants {
String STATUS_KEY = "status";
String CONTEXTPATH_KEY = "contextpath";
String LISTENER_KEY = "listener";
String LAYER_KEY = "layer";
// General
/**
* Config id
*/
String ID = "id";
/**
* Application name;
*/
String NAME = "name";
/**
* Application owner name;
*/
String OWNER = "owner";
/**
* Running application organization name.
*/
String ORGANIZATION = "organization";
/**
* Application architecture name.
*/
String ARCHITECTURE = "architecture";
/**
* Environment name
*/
String ENVIRONMENT = "environment";
/**
* Test environment key.
*/
String TEST_ENVIRONMENT = "test";
/**
* Development environment key.
*/
String DEVELOPMENT_ENVIRONMENT = "develop";
/**
* Production environment key.
*/
String PRODUCTION_ENVIRONMENT = "product";
String CONFIG_CONFIGFILE_KEY = "config-file";
String CONFIG_ENABLE_KEY = "highest-priority";
String CONFIG_APP_CONFIGFILE_KEY = "app-config-file";
String MULTICAST = "multicast";
String DUBBO_PORT_TO_REGISTRY = "DUBBO_PORT_TO_REGISTRY";
String DUBBO_PORT_TO_BIND = "DUBBO_PORT_TO_BIND";
String SCOPE_NONE = "none";
String ON_INVOKE_METHOD_PARAMETER_KEY = "oninvoke.method";
String ON_RETURN_METHOD_PARAMETER_KEY = "onreturn.method";
String ON_THROW_METHOD_PARAMETER_KEY = "onthrow.method";
String ON_INVOKE_INSTANCE_PARAMETER_KEY = "oninvoke.instance";
String ON_RETURN_INSTANCE_PARAMETER_KEY = "onreturn.instance";
String ON_THROW_INSTANCE_PARAMETER_KEY = "onthrow.instance";
String ON_INVOKE_METHOD_ATTRIBUTE_KEY = "oninvoke-method";
String ON_RETURN_METHOD_ATTRIBUTE_KEY = "onreturn-method";
String ON_THROW_METHOD_ATTRIBUTE_KEY = "onthrow-method";
String ON_INVOKE_INSTANCE_ATTRIBUTE_KEY = "oninvoke-instance";
String ON_RETURN_INSTANCE_ATTRIBUTE_KEY = "onreturn-instance";
String ON_THROW_INSTANCE_ATTRIBUTE_KEY = "onthrow-instance";
// FIXME: is this still useful?
String SHUTDOWN_TIMEOUT_KEY = "shutdown.timeout";
String PROTOCOLS_SUFFIX = "dubbo.protocols.";
String REGISTRIES_SUFFIX = "dubbo.registries.";
String ZOOKEEPER_PROTOCOL = "zookeeper";
String REGISTER_KEY = "register";
String MULTI_SERIALIZATION_KEY = "serialize.multiple";
String[] DOT_COMPATIBLE_KEYS = new String[] {
QOS_ENABLE_COMPATIBLE,
QOS_HOST_COMPATIBLE,
QOS_PORT_COMPATIBLE,
ACCEPT_FOREIGN_IP_COMPATIBLE,
ACCEPT_FOREIGN_IP_WHITELIST_COMPATIBLE,
REGISTRY_TYPE_KEY
};
String IGNORE_CHECK_KEYS = "ignoreCheckKeys";
String PARAMETERS = "parameters";
String SERVER_THREAD_POOL_NAME = "DubboServerHandler";
String SERVER_THREAD_POOL_PREFIX = SERVER_THREAD_POOL_NAME + "-";
String CLIENT_THREAD_POOL_NAME = "DubboClientHandler";
String CLIENT_THREAD_POOL_PREFIX = CLIENT_THREAD_POOL_NAME + "-";
String REST_PROTOCOL = "rest";
String DEFAULT_NATIVE_COMPILER = "jdk";
String DEFAULT_NATIVE_PROXY = "jdk";
String DEFAULT_APP_NAME = "DEFAULT_DUBBO_APP";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/MonitorConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/MonitorConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Map;
/**
* Configuration for the monitor.
*
* @export
*/
public class MonitorConfig extends AbstractConfig {
private static final long serialVersionUID = -1184681514659198203L;
/**
* The protocol of the monitor. If the value is "registry" it will search the monitor address from the registry center.
* Otherwise, it will directly connect to the monitor center.
*/
private String protocol;
/**
* The monitor address
*/
private String address;
/**
* The monitor username
*/
private String username;
/**
* The monitor password
*/
private String password;
/**
* The monitor group
*/
private String group;
/**
* The monitor version
*/
private String version;
/**
* The monitor reporting interval
*/
private String interval;
/**
* Customized parameters
*/
private Map<String, String> parameters;
public MonitorConfig() {}
public MonitorConfig(ApplicationModel applicationModel) {
super(applicationModel);
}
public MonitorConfig(String address) {
this.address = address;
}
public MonitorConfig(ApplicationModel applicationModel, String address) {
super(applicationModel);
this.address = address;
}
@Parameter(excluded = true)
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Parameter(excluded = true)
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
@Parameter(excluded = true)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Parameter(excluded = true)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
public String getInterval() {
return interval;
}
public void setInterval(String interval) {
this.interval = interval;
}
@Override
@Parameter(excluded = true, attribute = false)
public boolean isValid() {
return StringUtils.isNotEmpty(address) || RegistryConstants.REGISTRY_PROTOCOL.equals(protocol);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.aot.NativeDetector;
import org.apache.dubbo.common.compiler.support.AdaptiveCompiler;
import org.apache.dubbo.common.infra.InfraAdapter;
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.StringUtils;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_VERSION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY;
import static org.apache.dubbo.common.constants.CommonConstants.DUMP_ENABLE;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION;
import static org.apache.dubbo.common.constants.CommonConstants.HOST_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.LIVENESS_PROBE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_SERVICE_PORT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_SERVICE_PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.READINESS_PROBE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_LOCAL_FILE_CACHE_ENABLED;
import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.STARTUP_PROBE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION;
import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP;
import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP_COMPATIBLE;
import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP_WHITELIST;
import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP_WHITELIST_COMPATIBLE;
import static org.apache.dubbo.common.constants.QosConstants.ANONYMOUS_ACCESS_ALLOW_COMMANDS;
import static org.apache.dubbo.common.constants.QosConstants.ANONYMOUS_ACCESS_PERMISSION_LEVEL;
import static org.apache.dubbo.common.constants.QosConstants.ANONYMOUS_ACCESS_PERMISSION_LEVEL_COMPATIBLE;
import static org.apache.dubbo.common.constants.QosConstants.QOS_CHECK;
import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE;
import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE_COMPATIBLE;
import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST;
import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST_COMPATIBLE;
import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT;
import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT_COMPATIBLE;
import static org.apache.dubbo.common.constants.RegistryConstants.ENABLE_EMPTY_PROTECTION_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_MODE_KEY;
import static org.apache.dubbo.config.Constants.DEFAULT_APP_NAME;
import static org.apache.dubbo.config.Constants.DEFAULT_NATIVE_COMPILER;
import static org.apache.dubbo.config.Constants.DEVELOPMENT_ENVIRONMENT;
import static org.apache.dubbo.config.Constants.PRODUCTION_ENVIRONMENT;
import static org.apache.dubbo.config.Constants.TEST_ENVIRONMENT;
/**
* Configuration for the dubbo application.
*
* @export
*/
public class ApplicationConfig extends AbstractConfig {
private static final long serialVersionUID = 5508512956753757169L;
private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(ApplicationConfig.class);
/**
* The Application name.
*/
private String name;
/**
* The application version.
*/
private String version;
/**
* The application owner.
*/
private String owner;
/**
* The application's organization (BU).
*/
private String organization;
/**
* Architecture layer.
*/
private String architecture;
/**
* Environment, e.g., dev, test, or production.
*/
private String environment;
/**
* Java compiler.
*/
private String compiler;
/**
* The type of log access.
*/
private String logger;
/**
* Registry centers.
*/
private List<RegistryConfig> registries;
/**
* The comma-separated list of registry IDs to which the service will be registered.
*/
private String registryIds;
/**
* Monitor center.
*/
private MonitorConfig monitor;
/**
* Directory for saving thread dump.
*/
private String dumpDirectory;
/**
* Whether to enable saving thread dump or not.
*/
private Boolean dumpEnable;
/**
* Whether to enable Quality of Service (QoS) or not.
*/
private Boolean qosEnable;
/**
* Whether QoS should start successfully or not, will check qosEnable first.
*/
private Boolean qosCheck;
/**
* The QoS host to listen.
*/
private String qosHost;
/**
* The QoS port to listen.
*/
private Integer qosPort;
/**
* Should we accept foreign IP or not?
*/
private Boolean qosAcceptForeignIp;
/**
* When we disable accepting foreign IP, support specifying foreign IPs in the whitelist.
*/
private String qosAcceptForeignIpWhitelist;
/**
* The anonymous (any foreign IP) access permission level, default is NONE, which means no access to any command.
*/
private String qosAnonymousAccessPermissionLevel;
/**
* The anonymous (any foreign IP) allowed commands, default is empty, which means no access to any command.
*/
private String qosAnonymousAllowCommands;
/**
* Customized parameters.
*/
private Map<String, String> parameters;
/**
* Config the shutdown wait.
*/
private String shutwait;
/**
* Hostname.
*/
private String hostname;
/**
* Metadata type, local or remote. If 'remote' is chosen, you need to specify a metadata center further.
*/
private String metadataType;
/**
* Used to control whether to register the instance with the registry or not. Set to 'false' only when the instance is a pure consumer.
*/
private Boolean registerConsumer;
/**
* Repository.
*/
private String repository;
/**
* Whether to enable file caching.
*/
private Boolean enableFileCache;
/**
* The preferred protocol (name) of this application, convenient for places where it's hard to determine the preferred protocol.
*/
private String protocol;
/**
* The protocol used for peer-to-peer metadata transmission.
*/
private String metadataServiceProtocol;
/**
* Metadata Service, used in Service Discovery.
*/
private Integer metadataServicePort;
/**
* The retry interval of service name mapping.
*/
private Integer mappingRetryInterval;
/**
* Used to set extensions of the probe in QoS.
*/
private String livenessProbe;
/**
* The probe for checking the readiness of the application.
*/
private String readinessProbe;
/**
* The probe for checking the startup of the application.
*/
private String startupProbe;
/**
* Register mode.
*/
private String registerMode;
/**
* Whether to enable protection against empty objects.
*/
private Boolean enableEmptyProtection;
/**
* The status of class serialization checking.
*/
private String serializeCheckStatus;
/**
* Whether to automatically trust serialized classes.
*/
private Boolean autoTrustSerializeClass;
/**
* The trust level for serialized classes.
*/
private Integer trustSerializeClassLevel;
/**
* Whether to check serializable.
*/
private Boolean checkSerializable;
/**
* Thread pool management mode: 'default' or 'isolation'.
*/
private String executorManagementMode;
/**
* Only use the new version of metadataService (MetadataServiceV2).
* <br> MetadataServiceV2 have better compatibility with other language's dubbo implement (dubbo-go).
* <br> If set to false (default):
* <br> 1. If your services are using triple protocol and {@link #metadataServiceProtocol} is not set
* <br> - Dubbo will export both MetadataService and MetadataServiceV2 with triple
* <br> 2. Set {@link #metadataServiceProtocol} = tri
* <br> - Dubbo will export both MetadataService and MetadataServiceV2 with triple
* <br> 3. Set {@link #metadataServiceProtocol} != tri
* <br> - Dubbo will only export MetadataService
* <br> 4. Your services are not using triple protocol, and {@link #metadataServiceProtocol} is not set
* <br> - Dubbo will only export MetadataService
* <br>
* <br> If set to true, dubbo will try to only use MetadataServiceV2.
* <br> It only activates when meet at least one of the following cases:
* <br> 1. Manually set {@link #metadataServiceProtocol} = tri
* <br> 2. Your services are using triple protocol
* <br>
*/
private Boolean onlyUseMetadataV2;
public ApplicationConfig() {}
public ApplicationConfig(ApplicationModel applicationModel) {
super(applicationModel);
}
public ApplicationConfig(String name) {
setName(name);
}
public ApplicationConfig(ApplicationModel applicationModel, String name) {
super(applicationModel);
setName(name);
}
@Override
protected void checkDefault() {
super.checkDefault();
if (protocol == null) {
protocol = DUBBO;
}
if (hostname == null) {
try {
hostname = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
LOGGER.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to get the hostname of current instance.", e);
hostname = "UNKNOWN";
}
}
if (executorManagementMode == null) {
executorManagementMode = EXECUTOR_MANAGEMENT_MODE_ISOLATION;
}
if (enableFileCache == null) {
enableFileCache = Boolean.TRUE;
}
}
@Parameter(key = APPLICATION_KEY, required = true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Parameter(key = APPLICATION_VERSION_KEY)
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
public String getArchitecture() {
return architecture;
}
public void setArchitecture(String architecture) {
this.architecture = architecture;
}
public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
if (environment != null
&& !(DEVELOPMENT_ENVIRONMENT.equals(environment)
|| TEST_ENVIRONMENT.equals(environment)
|| PRODUCTION_ENVIRONMENT.equals(environment))) {
throw new IllegalStateException(String.format(
"Unsupported environment: %s, only support %s/%s/%s, default is %s.",
environment,
DEVELOPMENT_ENVIRONMENT,
TEST_ENVIRONMENT,
PRODUCTION_ENVIRONMENT,
PRODUCTION_ENVIRONMENT));
}
this.environment = environment;
}
public RegistryConfig getRegistry() {
return CollectionUtils.isEmpty(registries) ? null : registries.get(0);
}
public void setRegistry(RegistryConfig registry) {
List<RegistryConfig> registries = new ArrayList<>(1);
registries.add(registry);
this.registries = registries;
}
public List<RegistryConfig> getRegistries() {
return registries;
}
@SuppressWarnings({"unchecked"})
public void setRegistries(List<? extends RegistryConfig> registries) {
this.registries = (List<RegistryConfig>) registries;
}
@Parameter(excluded = true)
public String getRegistryIds() {
return registryIds;
}
public void setRegistryIds(String registryIds) {
this.registryIds = registryIds;
}
public MonitorConfig getMonitor() {
return monitor;
}
public void setMonitor(String monitor) {
this.monitor = new MonitorConfig(monitor);
}
public void setMonitor(MonitorConfig monitor) {
this.monitor = monitor;
}
public String getCompiler() {
if (NativeDetector.inNativeImage()) {
return DEFAULT_NATIVE_COMPILER;
} else {
return compiler;
}
}
public void setCompiler(String compiler) {
if (NativeDetector.inNativeImage()) {
this.compiler = DEFAULT_NATIVE_COMPILER;
AdaptiveCompiler.setDefaultCompiler(DEFAULT_NATIVE_COMPILER);
} else {
this.compiler = compiler;
AdaptiveCompiler.setDefaultCompiler(compiler);
}
}
public String getLogger() {
return logger;
}
public void setLogger(String logger) {
this.logger = logger;
LoggerFactory.setLoggerAdapter(getApplicationModel().getFrameworkModel(), logger);
}
@Parameter(key = DUMP_DIRECTORY)
public String getDumpDirectory() {
return dumpDirectory;
}
public void setDumpDirectory(String dumpDirectory) {
this.dumpDirectory = dumpDirectory;
}
@Parameter(key = DUMP_ENABLE)
public Boolean getDumpEnable() {
return dumpEnable;
}
public void setDumpEnable(Boolean dumpEnable) {
this.dumpEnable = dumpEnable;
}
@Parameter(key = QOS_ENABLE)
public Boolean getQosEnable() {
return qosEnable;
}
public void setQosEnable(Boolean qosEnable) {
this.qosEnable = qosEnable;
}
@Parameter(key = QOS_CHECK)
public Boolean getQosCheck() {
return qosCheck;
}
public void setQosCheck(Boolean qosCheck) {
this.qosCheck = qosCheck;
}
@Parameter(key = QOS_HOST)
public String getQosHost() {
return qosHost;
}
public void setQosHost(String qosHost) {
this.qosHost = qosHost;
}
@Parameter(key = QOS_PORT)
public Integer getQosPort() {
return qosPort;
}
public void setQosPort(Integer qosPort) {
this.qosPort = qosPort;
}
@Parameter(key = ACCEPT_FOREIGN_IP)
public Boolean getQosAcceptForeignIp() {
return qosAcceptForeignIp;
}
public void setQosAcceptForeignIp(Boolean qosAcceptForeignIp) {
this.qosAcceptForeignIp = qosAcceptForeignIp;
}
@Parameter(key = ACCEPT_FOREIGN_IP_WHITELIST)
public String getQosAcceptForeignIpWhitelist() {
return qosAcceptForeignIpWhitelist;
}
public void setQosAcceptForeignIpWhitelist(String qosAcceptForeignIpWhitelist) {
this.qosAcceptForeignIpWhitelist = qosAcceptForeignIpWhitelist;
}
@Parameter(key = ANONYMOUS_ACCESS_PERMISSION_LEVEL)
public String getQosAnonymousAccessPermissionLevel() {
return qosAnonymousAccessPermissionLevel;
}
public void setQosAnonymousAccessPermissionLevel(String qosAnonymousAccessPermissionLevel) {
this.qosAnonymousAccessPermissionLevel = qosAnonymousAccessPermissionLevel;
}
@Parameter(key = ANONYMOUS_ACCESS_ALLOW_COMMANDS)
public String getQosAnonymousAllowCommands() {
return qosAnonymousAllowCommands;
}
public void setQosAnonymousAllowCommands(String qosAnonymousAllowCommands) {
this.qosAnonymousAllowCommands = qosAnonymousAllowCommands;
}
/**
* The format is the same as the springboot, including: getQosEnableCompatible(), getQosPortCompatible(), getQosAcceptForeignIpCompatible().
*
*/
@Parameter(key = QOS_ENABLE_COMPATIBLE, excluded = true, attribute = false)
public Boolean getQosEnableCompatible() {
return getQosEnable();
}
public void setQosEnableCompatible(Boolean qosEnable) {
setQosEnable(qosEnable);
}
@Parameter(key = QOS_HOST_COMPATIBLE, excluded = true, attribute = false)
public String getQosHostCompatible() {
return getQosHost();
}
public void setQosHostCompatible(String qosHost) {
this.setQosHost(qosHost);
}
@Parameter(key = QOS_PORT_COMPATIBLE, excluded = true, attribute = false)
public Integer getQosPortCompatible() {
return getQosPort();
}
public void setQosPortCompatible(Integer qosPort) {
this.setQosPort(qosPort);
}
@Parameter(key = ACCEPT_FOREIGN_IP_COMPATIBLE, excluded = true, attribute = false)
public Boolean getQosAcceptForeignIpCompatible() {
return this.getQosAcceptForeignIp();
}
public void setQosAcceptForeignIpCompatible(Boolean qosAcceptForeignIp) {
this.setQosAcceptForeignIp(qosAcceptForeignIp);
}
@Parameter(key = ACCEPT_FOREIGN_IP_WHITELIST_COMPATIBLE, excluded = true, attribute = false)
public String getQosAcceptForeignIpWhitelistCompatible() {
return this.getQosAcceptForeignIpWhitelist();
}
public void setQosAcceptForeignIpWhitelistCompatible(String qosAcceptForeignIpWhitelist) {
this.setQosAcceptForeignIpWhitelist(qosAcceptForeignIpWhitelist);
}
@Parameter(key = ANONYMOUS_ACCESS_PERMISSION_LEVEL_COMPATIBLE, excluded = true, attribute = false)
public String getQosAnonymousAccessPermissionLevelCompatible() {
return this.getQosAnonymousAccessPermissionLevel();
}
public void setQosAnonymousAccessPermissionLevelCompatible(String qosAnonymousAccessPermissionLevel) {
this.setQosAnonymousAccessPermissionLevel(qosAnonymousAccessPermissionLevel);
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
public String getShutwait() {
return shutwait;
}
public void setShutwait(String shutwait) {
System.setProperty(SHUTDOWN_WAIT_KEY, shutwait);
this.shutwait = shutwait;
}
@Parameter(excluded = true)
public String getHostname() {
return hostname;
}
@Override
@Parameter(excluded = true, attribute = false)
public boolean isValid() {
return !StringUtils.isEmpty(name);
}
@Parameter(key = METADATA_KEY)
public String getMetadataType() {
return metadataType;
}
public void setMetadataType(String metadataType) {
this.metadataType = metadataType;
}
public Boolean getRegisterConsumer() {
return registerConsumer;
}
public void setRegisterConsumer(Boolean registerConsumer) {
this.registerConsumer = registerConsumer;
}
public String getRepository() {
return repository;
}
public void setRepository(String repository) {
this.repository = repository;
}
@Parameter(key = REGISTRY_LOCAL_FILE_CACHE_ENABLED)
public Boolean getEnableFileCache() {
return enableFileCache;
}
public void setEnableFileCache(Boolean enableFileCache) {
this.enableFileCache = enableFileCache;
}
@Parameter(key = REGISTER_MODE_KEY)
public String getRegisterMode() {
return registerMode;
}
public void setRegisterMode(String registerMode) {
this.registerMode = registerMode;
}
@Parameter(key = ENABLE_EMPTY_PROTECTION_KEY)
public Boolean getEnableEmptyProtection() {
return enableEmptyProtection;
}
public void setEnableEmptyProtection(Boolean enableEmptyProtection) {
this.enableEmptyProtection = enableEmptyProtection;
}
@Parameter(excluded = true, key = APPLICATION_PROTOCOL_KEY)
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
@Parameter(key = METADATA_SERVICE_PORT_KEY)
public Integer getMetadataServicePort() {
return metadataServicePort;
}
public void setMetadataServicePort(Integer metadataServicePort) {
this.metadataServicePort = metadataServicePort;
}
public Integer getMappingRetryInterval() {
return mappingRetryInterval;
}
public void setMappingRetryInterval(Integer mappingRetryInterval) {
this.mappingRetryInterval = mappingRetryInterval;
}
@Parameter(key = METADATA_SERVICE_PROTOCOL_KEY)
public String getMetadataServiceProtocol() {
return metadataServiceProtocol;
}
public void setMetadataServiceProtocol(String metadataServiceProtocol) {
this.metadataServiceProtocol = metadataServiceProtocol;
}
@Parameter(key = LIVENESS_PROBE_KEY)
public String getLivenessProbe() {
return livenessProbe;
}
public void setLivenessProbe(String livenessProbe) {
this.livenessProbe = livenessProbe;
}
@Parameter(key = READINESS_PROBE_KEY)
public String getReadinessProbe() {
return readinessProbe;
}
public void setReadinessProbe(String readinessProbe) {
this.readinessProbe = readinessProbe;
}
@Parameter(key = STARTUP_PROBE)
public String getStartupProbe() {
return startupProbe;
}
public void setStartupProbe(String startupProbe) {
this.startupProbe = startupProbe;
}
public String getSerializeCheckStatus() {
return serializeCheckStatus;
}
public void setSerializeCheckStatus(String serializeCheckStatus) {
this.serializeCheckStatus = serializeCheckStatus;
}
public Boolean getAutoTrustSerializeClass() {
return autoTrustSerializeClass;
}
public void setAutoTrustSerializeClass(Boolean autoTrustSerializeClass) {
this.autoTrustSerializeClass = autoTrustSerializeClass;
}
public Integer getTrustSerializeClassLevel() {
return trustSerializeClassLevel;
}
public void setTrustSerializeClassLevel(Integer trustSerializeClassLevel) {
this.trustSerializeClassLevel = trustSerializeClassLevel;
}
public Boolean getCheckSerializable() {
return checkSerializable;
}
public void setCheckSerializable(Boolean checkSerializable) {
this.checkSerializable = checkSerializable;
}
public void setExecutorManagementMode(String executorManagementMode) {
this.executorManagementMode = executorManagementMode;
}
@Parameter(key = EXECUTOR_MANAGEMENT_MODE)
public String getExecutorManagementMode() {
return executorManagementMode;
}
@Parameter(excluded = true)
public Boolean getOnlyUseMetadataV2() {
return onlyUseMetadataV2;
}
public void setOnlyUseMetadataV2(Boolean onlyUseMetadataV2) {
this.onlyUseMetadataV2 = onlyUseMetadataV2;
}
@Override
public void refresh() {
super.refresh();
appendEnvironmentProperties();
if (StringUtils.isEmpty(getName())) {
this.setName(DEFAULT_APP_NAME);
LOGGER.warn(
COMMON_UNEXPECTED_EXCEPTION,
"",
"",
"No application name was set, '" + DEFAULT_APP_NAME
+ "' will be used as the default application name,"
+ " it's highly recommended to set a unique and customized name for it can be critical for some service governance features.");
}
}
private void appendEnvironmentProperties() {
if (parameters == null) {
parameters = new HashMap<>();
}
Set<InfraAdapter> adapters = this.getExtensionLoader(InfraAdapter.class).getSupportedExtensionInstances();
if (CollectionUtils.isNotEmpty(adapters)) {
Map<String, String> inputParameters = new HashMap<>();
inputParameters.put(APPLICATION_KEY, getName());
inputParameters.put(HOST_KEY, getHostname());
for (InfraAdapter adapter : adapters) {
Map<String, String> extraParameters = adapter.getExtraAttributes(inputParameters);
if (CollectionUtils.isNotEmptyMap(extraParameters)) {
extraParameters.forEach((key, value) -> {
for (String prefix : this.getPrefixes()) {
prefix += ".";
if (key.startsWith(prefix)) {
key = key.substring(prefix.length());
}
parameters.put(key, value);
break;
}
});
}
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/SslConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/SslConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.utils.IOUtils;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.beans.Transient;
import java.io.IOException;
import java.io.InputStream;
/**
* Configuration for ssl.
*
* @export
*/
public class SslConfig extends AbstractConfig {
private static final long serialVersionUID = 4072725016922915851L;
public static final String SERVER_KEY_CERT_CHAIN_PATH = "server-key-cert-chain-path";
public static final String SERVER_PRIVATE_KEY_PATH = "server-private-key-path";
public static final String SERVER_KEY_PASSWORD = "server-key-password";
public static final String SERVER_TRUST_CERT_COLLECTION_PATH = "server-trust-cert-collection-path";
public static final String CLIENT_KEY_CERT_CHAIN_PATH = "client-key-cert-chain-path";
public static final String CLIENT_PRIVATE_KEY_PATH = "client-private-key-path";
public static final String CLIENT_KEY_PASSWORD = "client-key-password";
public static final String CLIENT_TRUST_CERT_COLLECTION_PATH = "client-trust-cert-collection-path";
/**
* Path to the server's key certificate chain file.
*/
private String serverKeyCertChainPath;
/**
* Path to the server's private key file.
*/
private String serverPrivateKeyPath;
/**
* Password for the server's private key (if applicable).
*/
private String serverKeyPassword;
/**
* Path to the server's trust certificate collection file.
*/
private String serverTrustCertCollectionPath;
/**
* Path to the client's key certificate chain file.
*/
private String clientKeyCertChainPath;
/**
* Path to the client's private key file.
*/
private String clientPrivateKeyPath;
/**
* Password for the client's private key (if applicable).
*/
private String clientKeyPassword;
/**
* Path to the client's trust certificate collection file.
*/
private String clientTrustCertCollectionPath;
/**
* Input stream for the server's key certificate chain (if provided).
*/
private InputStream serverKeyCertChainPathStream;
/**
* Input stream for the server's private key (if provided).
*/
private InputStream serverPrivateKeyPathStream;
/**
* Input stream for the server's trust certificate collection (if provided).
*/
private InputStream serverTrustCertCollectionPathStream;
/**
* Input stream for the client's key certificate chain (if provided).
*/
private InputStream clientKeyCertChainPathStream;
/**
* Input stream for the client's private key (if provided).
*/
private InputStream clientPrivateKeyPathStream;
/**
* Input stream for the client's trust certificate collection (if provided).
*/
private InputStream clientTrustCertCollectionPathStream;
/**
* Address for Certificate Authority (CA).
*/
private String caAddress;
/**
* Environment type for SSL configuration.
*/
private String envType;
/**
* Path to the CA certificate file.
*/
private String caCertPath;
/**
* Path to the OIDC (OpenID Connect) token file.
*/
private String oidcTokenPath;
public SslConfig() {}
public SslConfig(ApplicationModel applicationModel) {
super(applicationModel);
}
@Parameter(key = SERVER_KEY_CERT_CHAIN_PATH)
public String getServerKeyCertChainPath() {
return serverKeyCertChainPath;
}
public void setServerKeyCertChainPath(String serverKeyCertChainPath) {
this.serverKeyCertChainPath = serverKeyCertChainPath;
}
@Parameter(key = SERVER_PRIVATE_KEY_PATH)
public String getServerPrivateKeyPath() {
return serverPrivateKeyPath;
}
public void setServerPrivateKeyPath(String serverPrivateKeyPath) {
this.serverPrivateKeyPath = serverPrivateKeyPath;
}
@Parameter(key = SERVER_KEY_PASSWORD)
public String getServerKeyPassword() {
return serverKeyPassword;
}
public void setServerKeyPassword(String serverKeyPassword) {
this.serverKeyPassword = serverKeyPassword;
}
@Parameter(key = SERVER_TRUST_CERT_COLLECTION_PATH)
public String getServerTrustCertCollectionPath() {
return serverTrustCertCollectionPath;
}
public void setServerTrustCertCollectionPath(String serverTrustCertCollectionPath) {
this.serverTrustCertCollectionPath = serverTrustCertCollectionPath;
}
@Parameter(key = CLIENT_KEY_CERT_CHAIN_PATH)
public String getClientKeyCertChainPath() {
return clientKeyCertChainPath;
}
public void setClientKeyCertChainPath(String clientKeyCertChainPath) {
this.clientKeyCertChainPath = clientKeyCertChainPath;
}
@Parameter(key = CLIENT_PRIVATE_KEY_PATH)
public String getClientPrivateKeyPath() {
return clientPrivateKeyPath;
}
public void setClientPrivateKeyPath(String clientPrivateKeyPath) {
this.clientPrivateKeyPath = clientPrivateKeyPath;
}
@Parameter(key = CLIENT_KEY_PASSWORD)
public String getClientKeyPassword() {
return clientKeyPassword;
}
public void setClientKeyPassword(String clientKeyPassword) {
this.clientKeyPassword = clientKeyPassword;
}
@Parameter(key = CLIENT_TRUST_CERT_COLLECTION_PATH)
public String getClientTrustCertCollectionPath() {
return clientTrustCertCollectionPath;
}
public void setClientTrustCertCollectionPath(String clientTrustCertCollectionPath) {
this.clientTrustCertCollectionPath = clientTrustCertCollectionPath;
}
public String getCaAddress() {
return caAddress;
}
public void setCaAddress(String caAddress) {
this.caAddress = caAddress;
}
public String getEnvType() {
return envType;
}
public void setEnvType(String envType) {
this.envType = envType;
}
public String getCaCertPath() {
return caCertPath;
}
public void setCaCertPath(String caCertPath) {
this.caCertPath = caCertPath;
}
public String getOidcTokenPath() {
return oidcTokenPath;
}
public void setOidcTokenPath(String oidcTokenPath) {
this.oidcTokenPath = oidcTokenPath;
}
@Transient
public InputStream getServerKeyCertChainPathStream() throws IOException {
if (serverKeyCertChainPath != null) {
serverKeyCertChainPathStream =
IOUtils.getURL(serverKeyCertChainPath).openStream();
}
return serverKeyCertChainPathStream;
}
public void setServerKeyCertChainPathStream(InputStream serverKeyCertChainPathStream) {
this.serverKeyCertChainPathStream = serverKeyCertChainPathStream;
}
@Transient
public InputStream getServerPrivateKeyPathStream() throws IOException {
if (serverPrivateKeyPath != null) {
serverPrivateKeyPathStream = IOUtils.getURL(serverPrivateKeyPath).openStream();
}
return serverPrivateKeyPathStream;
}
public void setServerPrivateKeyPathStream(InputStream serverPrivateKeyPathStream) {
this.serverPrivateKeyPathStream = serverPrivateKeyPathStream;
}
@Transient
public InputStream getServerTrustCertCollectionPathStream() throws IOException {
if (serverTrustCertCollectionPath != null) {
serverTrustCertCollectionPathStream =
IOUtils.getURL(serverTrustCertCollectionPath).openStream();
}
return serverTrustCertCollectionPathStream;
}
public void setServerTrustCertCollectionPathStream(InputStream serverTrustCertCollectionPathStream) {
this.serverTrustCertCollectionPathStream = serverTrustCertCollectionPathStream;
}
@Transient
public InputStream getClientKeyCertChainPathStream() throws IOException {
if (clientKeyCertChainPath != null) {
clientKeyCertChainPathStream =
IOUtils.getURL(clientKeyCertChainPath).openStream();
}
return clientKeyCertChainPathStream;
}
public void setClientKeyCertChainPathStream(InputStream clientKeyCertChainPathStream) {
this.clientKeyCertChainPathStream = clientKeyCertChainPathStream;
}
@Transient
public InputStream getClientPrivateKeyPathStream() throws IOException {
if (clientPrivateKeyPath != null) {
clientPrivateKeyPathStream = IOUtils.getURL(clientPrivateKeyPath).openStream();
}
return clientPrivateKeyPathStream;
}
public void setClientPrivateKeyPathStream(InputStream clientPrivateKeyPathStream) {
this.clientPrivateKeyPathStream = clientPrivateKeyPathStream;
}
@Transient
public InputStream getClientTrustCertCollectionPathStream() throws IOException {
if (clientTrustCertCollectionPath != null) {
clientTrustCertCollectionPathStream =
IOUtils.getURL(clientTrustCertCollectionPath).openStream();
}
return clientTrustCertCollectionPathStream;
}
public void setClientTrustCertCollectionPathStream(InputStream clientTrustCertCollectionPathStream) {
this.clientTrustCertCollectionPathStream = clientTrustCertCollectionPathStream;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/RegistryConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/RegistryConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Map;
import static org.apache.dubbo.common.constants.CommonConstants.EXTRA_KEYS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.ENABLE_EMPTY_PROTECTION_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_MODE_KEY;
import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY;
import static org.apache.dubbo.common.utils.PojoUtils.updatePropertyIfAbsent;
/**
* Configuration for service registration and discovery.
*
* @export
*/
public class RegistryConfig extends AbstractConfig {
private static final long serialVersionUID = 5508512956753757169L;
public static final String NO_AVAILABLE = "N/A";
/**
* Register center address.
*/
private String address;
/**
* Username to login the register center.
*/
private String username;
/**
* Password to login the register center.
*/
private String password;
/**
* Default port for the register center.
*/
private Integer port;
/**
* Protocol used for the register center.
*/
private String protocol;
/**
* Network transmission type.
*/
private String transporter;
/**
* Server implementation.
*/
private String server;
/**
* Client implementation.
*/
private String client;
/**
* Affects how traffic distributes among registries, useful when subscribing to multiple registries.
* Available options:
* - "zone-aware": A certain type of traffic always goes to one Registry according to where the traffic is originated.
*/
private String cluster;
/**
* The region where the registry belongs, usually used to isolate traffics.
*/
private String zone;
/**
* The group that services registry belongs to.
*/
private String group;
/**
* Version of the registry.
*/
private String version;
/**
* Connect timeout in milliseconds for the register center.
*/
private Integer timeout;
/**
* Session timeout in milliseconds for the register center.
*/
private Integer session;
/**
* File for saving the register center dynamic list.
*/
private String file;
/**
* Wait time before stopping.
*/
private Integer wait;
/**
* Whether to check if the register center is available when booting up.
*/
private Boolean check;
/**
* Whether to allow dynamic service registration on the register center.
*/
private Boolean dynamic;
/**
* Whether to allow exporting service on the register center.
*/
private Boolean register;
/**
* Whether to allow subscribing to services on the register center.
*/
private Boolean subscribe;
/**
* Customized parameters.
*/
private Map<String, String> parameters;
/**
* Simplify the registry, useful for both providers and consumers.
*
* @since 2.7.0
*/
private Boolean simplified;
/**
* After simplifying the registry, add some parameters individually, useful for providers.
* Example: extra-keys = "A, b, c, d".
*
* @since 2.7.0
*/
private String extraKeys;
/**
* Indicates whether the address works as a configuration center or not.
*/
private Boolean useAsConfigCenter;
/**
* Indicates whether the address works as a remote metadata center or not.
*/
private Boolean useAsMetadataCenter;
/**
* List of RPC protocols accepted by this registry, e.g., "dubbo,rest".
*/
private String accepts;
/**
* Always use this registry first if set to true, useful when subscribing to multiple registries.
*/
private Boolean preferred;
/**
* Affects traffic distribution among registries, useful when subscribing to multiple registries.
* Takes effect only when no preferred registry is specified.
*/
private Integer weight;
/**
* Register mode.
*/
private String registerMode;
/**
* Enable empty protection.
*/
private Boolean enableEmptyProtection;
/**
* Security settings.
*/
private String secure;
public String getSecure() {
return secure;
}
public void setSecure(String secure) {
this.secure = secure;
}
public RegistryConfig() {}
public RegistryConfig(ApplicationModel applicationModel) {
super(applicationModel);
}
public RegistryConfig(String address) {
setAddress(address);
}
public RegistryConfig(ApplicationModel applicationModel, String address) {
super(applicationModel);
setAddress(address);
}
public RegistryConfig(String address, String protocol) {
setAddress(address);
setProtocol(protocol);
}
public RegistryConfig(ApplicationModel applicationModel, String address, String protocol) {
super(applicationModel);
setAddress(address);
setProtocol(protocol);
}
@Override
public String getId() {
return super.getId();
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
@Parameter(excluded = true)
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
if (address != null) {
try {
URL url = URL.valueOf(address);
// Refactor since 2.7.8
updatePropertyIfAbsent(this::getUsername, this::setUsername, url.getUsername());
updatePropertyIfAbsent(this::getPassword, this::setPassword, url.getPassword());
updatePropertyIfAbsent(this::getProtocol, this::setProtocol, url.getProtocol());
updatePropertyIfAbsent(this::getPort, this::setPort, url.getPort());
Map<String, String> params = url.getParameters();
if (CollectionUtils.isNotEmptyMap(params)) {
params.remove(BACKUP_KEY);
}
updateParameters(params);
} catch (Exception ignored) {
}
}
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* @return wait
* @see org.apache.dubbo.config.ProviderConfig#getWait()
* @deprecated
*/
@Deprecated
public Integer getWait() {
return wait;
}
/**
* @param wait
* @see org.apache.dubbo.config.ProviderConfig#setWait(Integer)
* @deprecated
*/
@Deprecated
public void setWait(Integer wait) {
this.wait = wait;
if (wait != null && wait > 0) {
System.setProperty(SHUTDOWN_WAIT_KEY, String.valueOf(wait));
}
}
public Boolean isCheck() {
return check;
}
public void setCheck(Boolean check) {
this.check = check;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
/**
* @return transport
* @see #getTransporter()
* @deprecated
*/
@Deprecated
@Parameter(excluded = true, attribute = false)
public String getTransport() {
return getTransporter();
}
/**
* @param transport
* @see #setTransporter(String)
* @deprecated
*/
@Deprecated
public void setTransport(String transport) {
setTransporter(transport);
}
public String getTransporter() {
return transporter;
}
public void setTransporter(String transporter) {
/*if(transporter != null && transporter.length() > 0 && ! this.getExtensionLoader(Transporter.class).hasExtension(transporter)){
throw new IllegalStateException("No such transporter type : " + transporter);
}*/
this.transporter = transporter;
}
public String getServer() {
return server;
}
public void setServer(String server) {
/*if(server != null && server.length() > 0 && ! this.getExtensionLoader(Transporter.class).hasExtension(server)){
throw new IllegalStateException("No such server type : " + server);
}*/
this.server = server;
}
public String getClient() {
return client;
}
public void setClient(String client) {
/*if(client != null && client.length() > 0 && ! this.getExtensionLoader(Transporter.class).hasExtension(client)){
throw new IllegalStateException("No such client type : " + client);
}*/
this.client = client;
}
public Integer getTimeout() {
return timeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
public Integer getSession() {
return session;
}
public void setSession(Integer session) {
this.session = session;
}
public Boolean isDynamic() {
return dynamic;
}
public void setDynamic(Boolean dynamic) {
this.dynamic = dynamic;
}
public Boolean isRegister() {
return register;
}
public void setRegister(Boolean register) {
this.register = register;
}
public Boolean isSubscribe() {
return subscribe;
}
public void setSubscribe(Boolean subscribe) {
this.subscribe = subscribe;
}
public String getCluster() {
return cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
public void updateParameters(Map<String, String> parameters) {
if (CollectionUtils.isEmptyMap(parameters)) {
return;
}
if (this.parameters == null) {
this.parameters = parameters;
} else {
this.parameters.putAll(parameters);
}
}
public Boolean getSimplified() {
return simplified;
}
public void setSimplified(Boolean simplified) {
this.simplified = simplified;
}
@Parameter(key = EXTRA_KEYS_KEY)
public String getExtraKeys() {
return extraKeys;
}
public void setExtraKeys(String extraKeys) {
this.extraKeys = extraKeys;
}
@Parameter(excluded = true)
public Boolean getUseAsConfigCenter() {
return useAsConfigCenter;
}
public void setUseAsConfigCenter(Boolean useAsConfigCenter) {
this.useAsConfigCenter = useAsConfigCenter;
}
@Parameter(excluded = true)
public Boolean getUseAsMetadataCenter() {
return useAsMetadataCenter;
}
public void setUseAsMetadataCenter(Boolean useAsMetadataCenter) {
this.useAsMetadataCenter = useAsMetadataCenter;
}
public String getAccepts() {
return accepts;
}
public void setAccepts(String accepts) {
this.accepts = accepts;
}
public Boolean getPreferred() {
return preferred;
}
public void setPreferred(Boolean preferred) {
this.preferred = preferred;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
@Parameter(key = REGISTER_MODE_KEY)
public String getRegisterMode() {
return registerMode;
}
public void setRegisterMode(String registerMode) {
this.registerMode = registerMode;
}
@Parameter(key = ENABLE_EMPTY_PROTECTION_KEY)
public Boolean getEnableEmptyProtection() {
return enableEmptyProtection;
}
public void setEnableEmptyProtection(Boolean enableEmptyProtection) {
this.enableEmptyProtection = enableEmptyProtection;
}
@Override
@Parameter(excluded = true, attribute = false)
public boolean isValid() {
// empty protocol will default to 'dubbo'
return !StringUtils.isEmpty(address) || !StringUtils.isEmpty(protocol);
}
@Override
@Parameter(excluded = true)
public Boolean isDefault() {
return isDefault;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/support/Parameter.java | dubbo-common/src/main/java/org/apache/dubbo/config/support/Parameter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.support;
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;
/**
* Parameter
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Parameter {
/**
* Specify the parameter key when append parameters to url
*/
String key() default "";
/**
* If required=true, the value must not be empty when append to url
*/
boolean required() default false;
/**
* If excluded=true, ignore it when append parameters to url
*/
boolean excluded() default false;
/**
* if escaped=true, escape it when append parameters to url
*/
boolean escaped() default false;
/**
* If attribute=false, ignore it when processing refresh()/getMetadata()/equals()/toString()
*/
boolean attribute() default true;
/**
* If append=true, append new value to exist value instead of overriding it.
*/
boolean append() default false;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/support/Nested.java | dubbo-common/src/main/java/org/apache/dubbo/config/support/Nested.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.support;
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;
/**
* Nested Class Parameter
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface Nested {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/nested/HistogramConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/nested/HistogramConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import java.io.Serializable;
/**
* Configuration for the histogram.
*/
public class HistogramConfig implements Serializable {
private static final long serialVersionUID = 8152538916051803031L;
/**
* Whether histograms are enabled or not. Default is not enabled (false).
*/
private Boolean enabled;
/**
* Buckets in milliseconds for the histograms. Defines the histogram bucket boundaries.
*/
private Integer[] bucketsMs;
/**
* Minimum expected value in milliseconds for the histograms. Values lower than this will be considered outliers.
*/
private Integer minExpectedMs;
/**
* Maximum expected value in milliseconds for the histograms. Values higher than this will be considered outliers.
*/
private Integer maxExpectedMs;
/**
* Whether enabledPercentiles are enabled or not. Default is not enabled (false).
*/
private Boolean enabledPercentiles;
/**
* Array of percentiles to be calculated for the histograms. Each percentile is a double value.
*/
private double[] percentiles;
/**
* Expiry time in minutes for distribution statistics. After this time, the statistics are expired.
*/
private Integer distributionStatisticExpiryMin;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Integer[] getBucketsMs() {
return bucketsMs;
}
public void setBucketsMs(Integer[] bucketsMs) {
this.bucketsMs = bucketsMs;
}
public Integer getMinExpectedMs() {
return minExpectedMs;
}
public void setMinExpectedMs(Integer minExpectedMs) {
this.minExpectedMs = minExpectedMs;
}
public Integer getMaxExpectedMs() {
return maxExpectedMs;
}
public void setMaxExpectedMs(Integer maxExpectedMs) {
this.maxExpectedMs = maxExpectedMs;
}
public Boolean getEnabledPercentiles() {
return enabledPercentiles;
}
public void setEnabledPercentiles(Boolean enabledPercentiles) {
this.enabledPercentiles = enabledPercentiles;
}
public double[] getPercentiles() {
return percentiles;
}
public void setPercentiles(double[] percentiles) {
this.percentiles = percentiles;
}
public Integer getDistributionStatisticExpiryMin() {
return distributionStatisticExpiryMin;
}
public void setDistributionStatisticExpiryMin(Integer distributionStatisticExpiryMin) {
this.distributionStatisticExpiryMin = distributionStatisticExpiryMin;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/nested/WebSocketConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/nested/WebSocketConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import java.io.Serializable;
public class WebSocketConfig implements Serializable {
private static final long serialVersionUID = -2504271061733141988L;
/**
* Whether to enable websocket support, requests are transport through the websocket container
* <p>The default value is false.
*/
private Boolean enabled;
/**
* The URL patterns that the websocket filter will be registered for.
* <p>The default value is '/*'.
*/
private String[] filterUrlPatterns;
/**
* The order of the websocket filter.
* <p>The default value is -1000000.
*/
private Integer filterOrder;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public String[] getFilterUrlPatterns() {
return filterUrlPatterns;
}
public void setFilterUrlPatterns(String[] filterUrlPatterns) {
this.filterUrlPatterns = filterUrlPatterns;
}
public Integer getFilterOrder() {
return filterOrder;
}
public void setFilterOrder(Integer filterOrder) {
this.filterOrder = filterOrder;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/nested/Http3Config.java | dubbo-common/src/main/java/org/apache/dubbo/config/nested/Http3Config.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import org.apache.dubbo.config.support.Parameter;
import java.io.Serializable;
public class Http3Config implements Serializable {
private static final long serialVersionUID = -4443828713331129834L;
public static final int DEFAULT_INITIAL_MAX_DATA = 8_388_608;
public static final int DEFAULT_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL = 1_048_576;
public static final int DEFAULT_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE = 1_048_576;
public static final int DEFAULT_INITIAL_MAX_STREAM_DATA_UNI = 1_048_576;
public static final long DEFAULT_INITIAL_MAX_STREAMS_BIDI = 1_073_741_824;
public static final long DEFAULT_INITIAL_MAX_STREAMS_UNI = 1_073_741_824;
/**
* Whether to enable HTTP/3 support
* <p>The default value is false.
*/
private Boolean enabled;
/**
* Whether to enable HTTP/3 negotiation
* If set to false, HTTP/2 alt-svc negotiation will be skipped, enabling HTTP/3 but disabling HTTP/2 on the consumer side.
* <p>The default value is true.
*/
private Boolean negotiation;
/**
* See <a href="https://docs.rs/quiche/0.6.0/quiche/struct.Config.html#method.set_initial_max_data">set_initial_max_data</a>.
* <p>The default value is 8MiB.
*/
private Integer initialMaxData;
/**
* If configured this will enable <a href="https://tools.ietf.org/html/draft-ietf-quic-datagram-01">Datagram support.</a>
*/
private Integer recvQueueLen;
/**
* If configured this will enable <a href="https://tools.ietf.org/html/draft-ietf-quic-datagram-01">Datagram support.</a>
*/
private Integer sendQueueLen;
/**
* See
* <a href="https://docs.rs/quiche/0.6.0/quiche/struct.Config.html#method.set_initial_max_stream_data_bidi_local">set_initial_max_stream_data_bidi_local</a>.
* <p>The default value is 1MiB.
*/
private Integer initialMaxStreamDataBidiLocal;
/**
* See
* <a href="https://docs.rs/quiche/0.6.0/quiche/struct.Config.html#method.set_initial_max_stream_data_bidi_remote">set_initial_max_stream_data_bidi_remote</a>.
* <p>The default value is 1MiB.
*/
private Integer initialMaxStreamDataBidiRemote;
/**
* See
* <a href="https://docs.rs/quiche/0.6.0/quiche/struct.Config.html#method.set_initial_max_stream_data_uni">set_initial_max_stream_data_uni</a>.
* <p>The default value is 0.
*/
private Integer initialMaxStreamDataUni;
/**
* See
* <a href="https://docs.rs/quiche/0.6.0/quiche/struct.Config.html#method.set_initial_max_streams_bidi">set_initial_max_streams_bidi</a>.
* <p>The default value is 1B(2^30).
*/
private Long initialMaxStreamsBidi;
/**
* See
* <a href="https://docs.rs/quiche/0.6.0/quiche/struct.Config.html#method.set_initial_max_streams_uni">set_initial_max_streams_uni</a>.
* <p>
* <p>The default value is 1B(2^30).
*/
private Long initialMaxStreamsUni;
/**
* See
* <a href="https://docs.rs/quiche/0.6.0/quiche/struct.Config.html#method.set_ack_delay_exponent">set_ack_delay_exponent</a>.
* <p>The default value is 3.
*/
private Integer maxAckDelayExponent;
/**
* See
* <a href="https://docs.rs/quiche/0.6.0/quiche/struct.Config.html#method.set_max_ack_delay">set_max_ack_delay</a>.
* <p>The default value is 25 milliseconds.
*/
private Integer maxAckDelay;
/**
* See
* <a href="https://docs.rs/quiche/0.6.0/quiche/struct.Config.html#method.set_disable_active_migration">set_disable_active_migration</a>.
* <p>The default value is {@code false}.
*/
private Boolean disableActiveMigration;
/**
* See
* <a href="https://docs.rs/quiche/0.6.0/quiche/struct.Config.html#method.enable_hystart">enable_hystart</a>.
* <p>The default value is {@code true}.
*/
private Boolean enableHystart;
/**
* Sets the congestion control algorithm to use.
* <p>Supported algorithms are {@code "RENO"} or {@code "CUBIC"} or {@code "BBR"}.
* <p>The default value is {@code "CUBIC"}.
*/
private String ccAlgorithm;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Boolean getNegotiation() {
return negotiation;
}
public void setNegotiation(Boolean negotiation) {
this.negotiation = negotiation;
}
public Integer getInitialMaxData() {
return initialMaxData;
}
@Parameter(excluded = true)
public int getInitialMaxDataOrDefault() {
return initialMaxData == null ? DEFAULT_INITIAL_MAX_DATA : initialMaxData;
}
public void setInitialMaxData(Integer initialMaxData) {
this.initialMaxData = initialMaxData;
}
public Integer getRecvQueueLen() {
return recvQueueLen;
}
public void setRecvQueueLen(Integer recvQueueLen) {
this.recvQueueLen = recvQueueLen;
}
public Integer getSendQueueLen() {
return sendQueueLen;
}
public void setSendQueueLen(Integer sendQueueLen) {
this.sendQueueLen = sendQueueLen;
}
public Integer getInitialMaxStreamDataBidiLocal() {
return initialMaxStreamDataBidiLocal;
}
@Parameter(excluded = true)
public int getInitialMaxStreamDataBidiLocalOrDefault() {
return initialMaxStreamDataBidiLocal == null
? DEFAULT_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL
: initialMaxStreamDataBidiLocal;
}
public void setInitialMaxStreamDataBidiLocal(Integer initialMaxStreamDataBidiLocal) {
this.initialMaxStreamDataBidiLocal = initialMaxStreamDataBidiLocal;
}
public Integer getInitialMaxStreamDataBidiRemote() {
return initialMaxStreamDataBidiRemote;
}
@Parameter(excluded = true)
public int getInitialMaxStreamDataBidiRemoteOrDefault() {
return initialMaxStreamDataBidiRemote == null
? DEFAULT_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE
: initialMaxStreamDataBidiRemote;
}
public void setInitialMaxStreamDataBidiRemote(Integer initialMaxStreamDataBidiRemote) {
this.initialMaxStreamDataBidiRemote = initialMaxStreamDataBidiRemote;
}
public Integer getInitialMaxStreamDataUni() {
return initialMaxStreamDataUni;
}
@Parameter(excluded = true)
public int getInitialMaxStreamDataUniOrDefault() {
return initialMaxStreamDataUni == null ? DEFAULT_INITIAL_MAX_STREAM_DATA_UNI : initialMaxStreamDataUni;
}
public void setInitialMaxStreamDataUni(Integer initialMaxStreamDataUni) {
this.initialMaxStreamDataUni = initialMaxStreamDataUni;
}
public Long getInitialMaxStreamsBidi() {
return initialMaxStreamsBidi;
}
@Parameter(excluded = true)
public long getInitialMaxStreamsBidiOrDefault() {
return initialMaxStreamsBidi == null ? DEFAULT_INITIAL_MAX_STREAMS_BIDI : initialMaxStreamsBidi;
}
public void setInitialMaxStreamsBidi(Long initialMaxStreamsBidi) {
this.initialMaxStreamsBidi = initialMaxStreamsBidi;
}
public Long getInitialMaxStreamsUni() {
return initialMaxStreamsUni;
}
@Parameter(excluded = true)
public long getInitialMaxStreamsUniOrDefault() {
return initialMaxStreamsUni == null ? DEFAULT_INITIAL_MAX_STREAMS_UNI : initialMaxStreamsUni;
}
public void setInitialMaxStreamsUni(Long initialMaxStreamsUni) {
this.initialMaxStreamsUni = initialMaxStreamsUni;
}
public Integer getMaxAckDelayExponent() {
return maxAckDelayExponent;
}
public void setMaxAckDelayExponent(Integer maxAckDelayExponent) {
this.maxAckDelayExponent = maxAckDelayExponent;
}
public Integer getMaxAckDelay() {
return maxAckDelay;
}
public void setMaxAckDelay(Integer maxAckDelay) {
this.maxAckDelay = maxAckDelay;
}
public Boolean getDisableActiveMigration() {
return disableActiveMigration;
}
public void setDisableActiveMigration(Boolean disableActiveMigration) {
this.disableActiveMigration = disableActiveMigration;
}
public Boolean getEnableHystart() {
return enableHystart;
}
public void setEnableHystart(Boolean enableHystart) {
this.enableHystart = enableHystart;
}
public String getCcAlgorithm() {
return ccAlgorithm;
}
public void setCcAlgorithm(String ccAlgorithm) {
this.ccAlgorithm = ccAlgorithm;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/nested/BaggageConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/nested/BaggageConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import org.apache.dubbo.config.support.Nested;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Configuration for the baggage.
*/
public class BaggageConfig implements Serializable {
private static final long serialVersionUID = -4750259290735346439L;
/**
* Whether baggage is enabled or not.
*/
private Boolean enabled = true;
/**
* Correlation configuration.
*/
@Nested
private Correlation correlation = new Correlation();
/**
* List of fields that are referenced the same in-process as it is on the wire.
* For example, the field "x-vcap-request-id" would be set as-is including the
* prefix.
*/
private List<String> remoteFields = new ArrayList<>();
public BaggageConfig() {}
public BaggageConfig(Boolean enabled) {
this.enabled = enabled;
}
public BaggageConfig(Boolean enabled, Correlation correlation, List<String> remoteFields) {
this.enabled = enabled;
this.correlation = correlation;
this.remoteFields = remoteFields;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Correlation getCorrelation() {
return correlation;
}
public void setCorrelation(Correlation correlation) {
this.correlation = correlation;
}
public List<String> getRemoteFields() {
return remoteFields;
}
public void setRemoteFields(List<String> remoteFields) {
this.remoteFields = remoteFields;
}
public static class Correlation implements Serializable {
/**
* Whether to enable correlation of the baggage context with logging contexts.
*/
private boolean enabled = true;
/**
* List of fields that should be correlated with the logging context. That
* means that these fields would end up as key-value pairs in e.g. MDC.
*/
private List<String> fields = new ArrayList<>();
public Correlation() {}
public Correlation(boolean enabled) {
this.enabled = enabled;
}
public Correlation(boolean enabled, List<String> fields) {
this.enabled = enabled;
this.fields = fields;
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public List<String> getFields() {
return this.fields;
}
public void setFields(List<String> fields) {
this.fields = fields;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/nested/PrometheusConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/nested/PrometheusConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import org.apache.dubbo.config.support.Nested;
import java.io.Serializable;
/**
* Configuration for the prometheus.
*/
public class PrometheusConfig implements Serializable {
private static final long serialVersionUID = 2238807632335823129L;
/**
* Prometheus exporter configuration
*/
@Nested
private Exporter exporter;
/**
* Prometheus push gateway configuration
*/
@Nested
private Pushgateway pushgateway;
public Exporter getExporter() {
return exporter;
}
public void setExporter(Exporter exporter) {
this.exporter = exporter;
}
public Pushgateway getPushgateway() {
return pushgateway;
}
public void setPushgateway(Pushgateway pushgateway) {
this.pushgateway = pushgateway;
}
public static class Exporter implements Serializable {
/**
* Enable prometheus exporter
*/
private Boolean enabled;
/**
* Enable http service discovery for prometheus
*/
private Boolean enableHttpServiceDiscovery;
/**
* Http service discovery url
*/
private String httpServiceDiscoveryUrl;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Boolean getEnableHttpServiceDiscovery() {
return enableHttpServiceDiscovery;
}
public void setEnableHttpServiceDiscovery(Boolean enableHttpServiceDiscovery) {
this.enableHttpServiceDiscovery = enableHttpServiceDiscovery;
}
public String getHttpServiceDiscoveryUrl() {
return httpServiceDiscoveryUrl;
}
public void setHttpServiceDiscoveryUrl(String httpServiceDiscoveryUrl) {
this.httpServiceDiscoveryUrl = httpServiceDiscoveryUrl;
}
}
public static class Pushgateway implements Serializable {
/**
* Enable publishing via a Prometheus Pushgateway
*/
private Boolean enabled;
/**
* Base URL for the Pushgateway
*/
private String baseUrl;
/**
* Login user of the Prometheus Pushgateway
*/
private String username;
/**
* Login password of the Prometheus Pushgateway
*/
private String password;
/**
* Frequency with which to push metrics
*/
private Integer pushInterval;
/**
* Job identifier for this application instance
*/
private String job;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getPushInterval() {
return pushInterval;
}
public void setPushInterval(Integer pushInterval) {
this.pushInterval = pushInterval;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/nested/TripleConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/nested/TripleConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import org.apache.dubbo.config.support.Nested;
import org.apache.dubbo.config.support.Parameter;
import java.io.Serializable;
/**
* Configuration for triple protocol.
*/
public class TripleConfig implements Serializable {
private static final long serialVersionUID = -3682252713701362155L;
public static final int DEFAULT_MAX_BODY_SIZE = 8_388_608;
public static final int DEFAULT_MAX_RESPONSE_BODY_SIZE = 8_388_608;
public static final int DEFAULT_MAX_CHUNK_SIZE = 8_388_608;
public static final int DEFAULT_MAX_HEADER_SIZE = 8_192;
public static final int DEFAULT_MAX_INITIAL_LINE_LENGTH = 4_096;
public static final int DEFAULT_INITIAL_BUFFER_SIZE = 16_384;
public static final int DEFAULT_HEADER_TABLE_SIZE = 4_096;
public static final boolean DEFAULT_ENABLE_PUSH = false;
public static final int DEFAULT_MAX_CONCURRENT_STREAMS = Integer.MAX_VALUE;
public static final int DEFAULT_INITIAL_WINDOW_SIZE = 8_388_608;
public static final int DEFAULT_CONNECTION_INITIAL_WINDOW_SIZE_KEY = 65_536;
public static final int DEFAULT_MAX_FRAME_SIZE = 8_388_608;
public static final int DEFAULT_MAX_HEADER_LIST_SIZE = 32_768;
public static final int DEFAULT_MAX_MESSAGE_SIZE = 50 * 1024 * 1024;
public static final String H2_SETTINGS_MAX_MESSAGE_SIZE_KEY = "dubbo.protocol.triple.max-message-size";
/**
* Whether enable verbose mode.
* When true, the application will produce detailed logging output
* to help with debugging and monitoring. This is useful for
* troubleshooting and understanding the application's behavior in detail.
* <p>The default value is false.
*/
private Boolean verbose;
/**
* Maximum allowed size for HTTP request bodies.
* Limits the size of request to prevent excessively large request.
* <p>The default value is 8MiB.
*/
private Integer maxBodySize;
/**
* Maximum allowed size for HTTP response bodies.
* Limits the size of responses to prevent excessively large response.
* <p>The default value is 8MiB.
*/
private Integer maxResponseBodySize;
/**
* Set the maximum chunk size.
* HTTP requests and responses can be quite large,
* in which case it's better to process the data as a stream of chunks.
* This sets the limit, in bytes, at which Netty will send a chunk down the pipeline.
* <p>The default value is 8MiB.
* <p>For HTTP/1
*/
private Integer maxChunkSize;
/**
* Set the maximum line length of header lines.
* This limits how much memory Netty will use when parsing HTTP header key-value pairs.
* You would typically set this to the same value as {@link #setMaxInitialLineLength(Integer)}.
* <p>The default value is 8KiB.
* <p>For HTTP/1
*/
private Integer maxHeaderSize;
/**
* Set the maximum length of the first line of the HTTP header.
* This limits how much memory Netty will use when parsed the initial HTTP header line.
* You would typically set this to the same value as {@link #setMaxHeaderSize(Integer)}.
* <p>The default value is 4096.
* <p>For HTTP/1
*/
private Integer maxInitialLineLength;
/**
* Set the initial size of the temporary buffer used when parsing the lines of the HTTP headers.
* <p>The default value is 16384 octets.
* <p>For HTTP/1
*/
private Integer initialBufferSize;
/**
* The header table size.
* <p>For HTTP/1
*/
private Integer headerTableSize;
/**
* Whether to enable push
* <p>The default value is false.
* <p>For HTTP/2
*/
private Boolean enablePush;
/**
* Maximum concurrent streams.
* <p>For HTTP/2
*/
private Integer maxConcurrentStreams;
/**
* Initial window size.
* <p>For HTTP/2
*/
private Integer initialWindowSize;
/**
* Connection initial window size.
* <p>For HTTP/2
*/
private Integer connectionInitialWindowSize;
/**
* Maximum frame size.
* <p>For HTTP/2
*/
private Integer maxFrameSize;
/**
* Maximum header list size.
* <p>For HTTP/2
*/
private Integer maxHeaderListSize;
/**
* Maximum message size.
*/
private Integer maxMessageSize;
@Nested
private RestConfig rest;
@Nested
private Http3Config http3;
@Nested
private ServletConfig servlet;
@Nested
private WebSocketConfig websocket;
public Boolean getVerbose() {
return verbose;
}
public void setVerbose(Boolean verbose) {
this.verbose = verbose;
}
public Integer getMaxBodySize() {
return maxBodySize;
}
@Parameter(excluded = true)
public int getMaxBodySizeOrDefault() {
return maxBodySize == null ? DEFAULT_MAX_BODY_SIZE : maxBodySize;
}
public void setMaxBodySize(Integer maxBodySize) {
this.maxBodySize = maxBodySize;
}
public Integer getMaxResponseBodySize() {
return maxResponseBodySize;
}
@Parameter(excluded = true)
public int getMaxResponseBodySizeOrDefault() {
return maxResponseBodySize == null ? DEFAULT_MAX_RESPONSE_BODY_SIZE : maxResponseBodySize;
}
public void setMaxResponseBodySize(Integer maxResponseBodySize) {
this.maxResponseBodySize = maxResponseBodySize;
}
public Integer getMaxChunkSize() {
return maxChunkSize;
}
@Parameter(excluded = true)
public int getMaxChunkSizeOrDefault() {
return maxChunkSize == null ? DEFAULT_MAX_CHUNK_SIZE : maxChunkSize;
}
public void setMaxChunkSize(Integer maxChunkSize) {
this.maxChunkSize = maxChunkSize;
}
public Integer getMaxHeaderSize() {
return maxHeaderSize;
}
@Parameter(excluded = true)
public int getMaxHeaderSizeOrDefault() {
return maxHeaderSize == null ? DEFAULT_MAX_HEADER_SIZE : maxHeaderSize;
}
public void setMaxHeaderSize(Integer maxHeaderSize) {
this.maxHeaderSize = maxHeaderSize;
}
public Integer getMaxInitialLineLength() {
return maxInitialLineLength;
}
@Parameter(excluded = true)
public int getMaxInitialLineLengthOrDefault() {
return maxInitialLineLength == null ? DEFAULT_MAX_INITIAL_LINE_LENGTH : maxInitialLineLength;
}
public void setMaxInitialLineLength(Integer maxInitialLineLength) {
this.maxInitialLineLength = maxInitialLineLength;
}
public Integer getInitialBufferSize() {
return initialBufferSize;
}
@Parameter(excluded = true)
public int getInitialBufferSizeOrDefault() {
return initialBufferSize == null ? DEFAULT_INITIAL_BUFFER_SIZE : initialBufferSize;
}
public void setInitialBufferSize(Integer initialBufferSize) {
this.initialBufferSize = initialBufferSize;
}
public Integer getHeaderTableSize() {
return headerTableSize;
}
@Parameter(excluded = true)
public int getHeaderTableSizeOrDefault() {
return headerTableSize == null ? DEFAULT_HEADER_TABLE_SIZE : headerTableSize;
}
public void setHeaderTableSize(Integer headerTableSize) {
this.headerTableSize = headerTableSize;
}
public Boolean getEnablePush() {
return enablePush;
}
@Parameter(excluded = true)
public boolean getEnablePushOrDefault() {
return enablePush == null ? DEFAULT_ENABLE_PUSH : enablePush;
}
public void setEnablePush(Boolean enablePush) {
this.enablePush = enablePush;
}
public Integer getMaxConcurrentStreams() {
return maxConcurrentStreams;
}
@Parameter(excluded = true)
public int getMaxConcurrentStreamsOrDefault() {
return maxConcurrentStreams == null ? DEFAULT_MAX_CONCURRENT_STREAMS : maxConcurrentStreams;
}
public void setMaxConcurrentStreams(Integer maxConcurrentStreams) {
this.maxConcurrentStreams = maxConcurrentStreams;
}
public Integer getInitialWindowSize() {
return initialWindowSize;
}
@Parameter(excluded = true)
public int getInitialWindowSizeOrDefault() {
return initialWindowSize == null ? DEFAULT_INITIAL_WINDOW_SIZE : initialWindowSize;
}
public void setInitialWindowSize(Integer initialWindowSize) {
this.initialWindowSize = initialWindowSize;
}
public Integer getConnectionInitialWindowSize() {
return connectionInitialWindowSize;
}
@Parameter(excluded = true)
public Integer getConnectionInitialWindowSizeOrDefault() {
return connectionInitialWindowSize == null
? DEFAULT_CONNECTION_INITIAL_WINDOW_SIZE_KEY
: connectionInitialWindowSize;
}
public void setConnectionInitialWindowSize(Integer connectionInitialWindowSize) {
this.connectionInitialWindowSize = connectionInitialWindowSize;
}
public Integer getMaxFrameSize() {
return maxFrameSize;
}
@Parameter(excluded = true)
public int getMaxFrameSizeOrDefault() {
return maxFrameSize == null ? DEFAULT_MAX_FRAME_SIZE : maxFrameSize;
}
public void setMaxFrameSize(Integer maxFrameSize) {
this.maxFrameSize = maxFrameSize;
}
public Integer getMaxHeaderListSize() {
return maxHeaderListSize;
}
@Parameter(excluded = true)
public int getMaxHeaderListSizeOrDefault() {
return maxHeaderListSize == null ? DEFAULT_MAX_HEADER_LIST_SIZE : maxHeaderListSize;
}
public void setMaxHeaderListSize(Integer maxHeaderListSize) {
this.maxHeaderListSize = maxHeaderListSize;
}
public Integer getMaxMessageSize() {
return maxMessageSize;
}
@Parameter(excluded = true, key = H2_SETTINGS_MAX_MESSAGE_SIZE_KEY)
public int getMaxMessageSizeOrDefault() {
return maxMessageSize == null ? DEFAULT_MAX_MESSAGE_SIZE : maxMessageSize;
}
public void setMaxMessageSize(Integer maxMessageSize) {
this.maxMessageSize = maxMessageSize;
}
public RestConfig getRest() {
return rest;
}
@Parameter(excluded = true)
public RestConfig getRestOrDefault() {
if (rest == null) {
rest = new RestConfig();
}
return rest;
}
public void setRest(RestConfig rest) {
this.rest = rest;
}
public Http3Config getHttp3() {
return http3;
}
@Parameter(excluded = true)
public Http3Config getHttp3OrDefault() {
if (http3 == null) {
http3 = new Http3Config();
}
return http3;
}
public void setHttp3(Http3Config http3) {
this.http3 = http3;
}
public ServletConfig getServlet() {
return servlet;
}
public void setServlet(ServletConfig servlet) {
this.servlet = servlet;
}
public WebSocketConfig getWebsocket() {
return websocket;
}
public void setWebsocket(WebSocketConfig websocket) {
this.websocket = websocket;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/nested/OpenAPIConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/nested/OpenAPIConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import java.io.Serializable;
import java.util.Map;
public class OpenAPIConfig implements Serializable {
private static final long serialVersionUID = 6943417456345001947L;
/**
* Whether to enable OpenAPI support
* <p>The default value is 'true'.
*/
private Boolean enabled;
/**
* Whether to cache the OpenAPI document.
* <p>The default value is 'true'.
*/
private Boolean cache;
/**
* The HTTP path where OpenAPI will be registered.
* <p>The default value is '/dubbo/openapi'.
*/
private String path;
/**
* The title of the OpenAPI information.
*/
private String infoTitle;
/**
* A brief description of the OpenAPI information.
*/
private String infoDescription;
/**
* The version number of the OpenAPI information.
*/
private String infoVersion;
/**
* The name of the contact.
*/
private String infoContactName;
/**
* The url of the contact.
*/
private String infoContactUrl;
/**
* The email address of the contact.
*/
private String infoContactEmail;
/**
* A description of the external documentation.
*/
private String externalDocsDescription;
/**
* The URL of the external documentation.
*/
private String externalDocsUrl;
/**
* A list of servers.
*/
private String[] servers;
/**
* The security scheme.
*/
private String securityScheme;
/**
* The security.
*/
private String security;
/**
* The strategy used to generate operation id and schema name.
*/
private String nameStrategy;
/**
* The default media types that are consumed.
*/
private String[] defaultConsumesMediaTypes;
/**
* The default media types that are produced.
*/
private String[] defaultProducesMediaTypes;
/**
* The default HTTP methods are used.
*/
private String[] defaultHttpMethods;
/**
* The default HTTP status codes are returned.
*/
private String[] defaultHttpStatusCodes;
/**
* Whether to flatten the inherited fields from the parent class into the schema.
* <p>The default value is {@code false}.
*/
private Boolean schemaFlatten;
/**
* Specifies the classes to be excluded from schema generation.
* <p>For example:
* <ul>
* <li>com.example.MyClass - Exclude the MyClass class.</li>
* <li>com.example. - Exclude all classes in the com.example package.</li>
* <li>!com.example.exclude. - Exclude all classes except those in the com.example.exclude package.</li>
* </ul>
* Note that the package name should end with a dot (.) or an exclamation mark (!) to indicate the exclusion scope.
* <p>Multiple classes or package names can be separated by commas, for
* example: com.example.MyClass,com.example.,!com.example.exclude
*/
private String[] schemaClassExcludes;
/**
* The custom settings.
*/
private Map<String, String> settings;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Boolean getCache() {
return cache;
}
public void setCache(Boolean cache) {
this.cache = cache;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getInfoTitle() {
return infoTitle;
}
public void setInfoTitle(String infoTitle) {
this.infoTitle = infoTitle;
}
public String getInfoDescription() {
return infoDescription;
}
public void setInfoDescription(String infoDescription) {
this.infoDescription = infoDescription;
}
public String getInfoVersion() {
return infoVersion;
}
public void setInfoVersion(String infoVersion) {
this.infoVersion = infoVersion;
}
public String getInfoContactName() {
return infoContactName;
}
public void setInfoContactName(String infoContactName) {
this.infoContactName = infoContactName;
}
public String getInfoContactUrl() {
return infoContactUrl;
}
public void setInfoContactUrl(String infoContactUrl) {
this.infoContactUrl = infoContactUrl;
}
public String getInfoContactEmail() {
return infoContactEmail;
}
public void setInfoContactEmail(String infoContactEmail) {
this.infoContactEmail = infoContactEmail;
}
public String getExternalDocsDescription() {
return externalDocsDescription;
}
public void setExternalDocsDescription(String externalDocsDescription) {
this.externalDocsDescription = externalDocsDescription;
}
public String getExternalDocsUrl() {
return externalDocsUrl;
}
public void setExternalDocsUrl(String externalDocsUrl) {
this.externalDocsUrl = externalDocsUrl;
}
public String[] getServers() {
return servers;
}
public void setServers(String[] servers) {
this.servers = servers;
}
public String getSecurityScheme() {
return securityScheme;
}
public void setSecurityScheme(String securityScheme) {
this.securityScheme = securityScheme;
}
public String getSecurity() {
return security;
}
public void setSecurity(String security) {
this.security = security;
}
public String getNameStrategy() {
return nameStrategy;
}
public void setNameStrategy(String nameStrategy) {
this.nameStrategy = nameStrategy;
}
public String[] getDefaultConsumesMediaTypes() {
return defaultConsumesMediaTypes;
}
public void setDefaultConsumesMediaTypes(String[] defaultConsumesMediaTypes) {
this.defaultConsumesMediaTypes = defaultConsumesMediaTypes;
}
public String[] getDefaultProducesMediaTypes() {
return defaultProducesMediaTypes;
}
public void setDefaultProducesMediaTypes(String[] defaultProducesMediaTypes) {
this.defaultProducesMediaTypes = defaultProducesMediaTypes;
}
public String[] getDefaultHttpMethods() {
return defaultHttpMethods;
}
public void setDefaultHttpMethods(String[] defaultHttpMethods) {
this.defaultHttpMethods = defaultHttpMethods;
}
public String[] getDefaultHttpStatusCodes() {
return defaultHttpStatusCodes;
}
public void setDefaultHttpStatusCodes(String[] defaultHttpStatusCodes) {
this.defaultHttpStatusCodes = defaultHttpStatusCodes;
}
public Boolean getSchemaFlatten() {
return schemaFlatten;
}
public void setSchemaFlatten(Boolean schemaFlatten) {
this.schemaFlatten = schemaFlatten;
}
public String[] getSchemaClassExcludes() {
return schemaClassExcludes;
}
public void setSchemaClassExcludes(String[] schemaClassExcludes) {
this.schemaClassExcludes = schemaClassExcludes;
}
public Map<String, String> getSettings() {
return settings;
}
public void setSettings(Map<String, String> settings) {
this.settings = settings;
}
public String getSetting(String key) {
return settings == null ? null : settings.get(key);
}
public String getSetting(String key, String defaultValue) {
return settings == null ? defaultValue : settings.getOrDefault(key, defaultValue);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/nested/SamplingConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/nested/SamplingConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import java.io.Serializable;
/**
* Configuration for the sampling.
*/
public class SamplingConfig implements Serializable {
private static final long serialVersionUID = -7456034528275916549L;
/**
* Probability in the range from 0.0 to 1.0 that a trace will be sampled.
*/
private float probability = 0.10f;
public SamplingConfig() {}
public SamplingConfig(float probability) {
this.probability = probability;
}
public float getProbability() {
return this.probability;
}
public void setProbability(float probability) {
this.probability = probability;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/nested/ServletConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/nested/ServletConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import java.io.Serializable;
public class ServletConfig implements Serializable {
private static final long serialVersionUID = 1091478303358670173L;
/**
* Whether to enable servlet support, requests are transport through the servlet container
* <p>The default value is false.
*/
private Boolean enabled;
/**
* Maximum concurrent streams.
* <p>For HTTP/2
* <p>Note that the default value for tomcat is 20. Highly recommended to change it to {@link Integer#MAX_VALUE}
* <p>If set to zero or a negative number, the actual value will be set to {@link Integer#MAX_VALUE}.
*/
private Integer maxConcurrentStreams;
/**
* The URL patterns that the servlet filter will be registered for.
* <p>The default value is '/*'.
*/
private String[] filterUrlPatterns;
/**
* The order of the servlet filter.
* <p>The default value is -1000000.
*/
private Integer filterOrder;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Integer getMaxConcurrentStreams() {
return maxConcurrentStreams;
}
public void setMaxConcurrentStreams(Integer maxConcurrentStreams) {
this.maxConcurrentStreams = maxConcurrentStreams;
}
public String[] getFilterUrlPatterns() {
return filterUrlPatterns;
}
public void setFilterUrlPatterns(String[] filterUrlPatterns) {
this.filterUrlPatterns = filterUrlPatterns;
}
public Integer getFilterOrder() {
return filterOrder;
}
public void setFilterOrder(Integer filterOrder) {
this.filterOrder = filterOrder;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/nested/RestConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/nested/RestConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import org.apache.dubbo.config.support.Nested;
import org.apache.dubbo.config.support.Parameter;
import java.io.Serializable;
import java.util.Map;
/**
* Configuration for triple rest protocol.
*/
public class RestConfig implements Serializable {
private static final long serialVersionUID = -8068568976367034755L;
public static final boolean DEFAULT_TRAILING_SLASH_MATCH = true;
public static final boolean DEFAULT_SUFFIX_PATTERN_MATCH = true;
public static final boolean DEFAULT_CASE_SENSITIVE_MATCH = true;
public static final String DEFAULT_FORMAT_PARAMETER_NAME = "format";
/**
* Whether to enable rest support
* <p>The default value is 'true'.
*/
private Boolean enabled;
/**
* Whether to enable the default mapping '/{interfaceName}/{methodName}'.
* <p>The default value is 'true'.
*/
private Boolean enableDefaultMapping;
/**
* Whether path matching should be match paths with a trailing slash.
* If enabled, a method mapped to "/users" also matches to "/users/".
* <p>The default value is {@code true}.
*/
private Boolean trailingSlashMatch;
/**
* Whether path matching uses suffix pattern matching (".*").
* If enabled, a method mapped to "/users" also matches to "/users.*".
* <p>This also enables suffix content negotiation, with the media-type
* inferred from the URL suffix, e.g., ".json" for "application/json".
* <p>The default value is {@code true}.
*/
private Boolean suffixPatternMatch;
/**
* Whether path matching should be case-sensitive.
* If enabled, a method mapped to "/users" won't match to "/Users/".
* <p>The default value is {@code true}.
*/
private Boolean caseSensitiveMatch;
/**
* The parameter name that can be used to specify the response format.
* <p>The default value is 'format'.
*/
private String formatParameterName;
/**
* The json framework to use, make sure that dependencies are imported.
*/
private String jsonFramework;
/**
* The disallowed content-types.
*/
private String[] disallowedContentTypes;
/**
* The cors configuration.
*/
@Nested
private CorsConfig cors;
/**
* The openapi configuration.
*/
@Nested
private OpenAPIConfig openapi;
/**
* The Mcp configuration.
*/
@Nested
private McpConfig mcp;
/**
* Multiple configurations for openapi.
*/
private Map<String, OpenAPIConfig> openapis;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Boolean getEnableDefaultMapping() {
return enableDefaultMapping;
}
public void setEnableDefaultMapping(Boolean enableDefaultMapping) {
this.enableDefaultMapping = enableDefaultMapping;
}
public Boolean getTrailingSlashMatch() {
return trailingSlashMatch;
}
@Parameter(excluded = true)
public boolean getTrailingSlashMatchOrDefault() {
return trailingSlashMatch == null ? DEFAULT_TRAILING_SLASH_MATCH : trailingSlashMatch;
}
public void setTrailingSlashMatch(Boolean trailingSlashMatch) {
this.trailingSlashMatch = trailingSlashMatch;
}
public Boolean getSuffixPatternMatch() {
return suffixPatternMatch;
}
@Parameter(excluded = true)
public boolean getSuffixPatternMatchOrDefault() {
return suffixPatternMatch == null ? DEFAULT_SUFFIX_PATTERN_MATCH : suffixPatternMatch;
}
public void setSuffixPatternMatch(Boolean suffixPatternMatch) {
this.suffixPatternMatch = suffixPatternMatch;
}
public Boolean getCaseSensitiveMatch() {
return caseSensitiveMatch;
}
@Parameter(excluded = true)
public boolean getCaseSensitiveMatchOrDefault() {
return caseSensitiveMatch == null ? DEFAULT_CASE_SENSITIVE_MATCH : caseSensitiveMatch;
}
public void setCaseSensitiveMatch(Boolean caseSensitiveMatch) {
this.caseSensitiveMatch = caseSensitiveMatch;
}
public String getFormatParameterName() {
return formatParameterName;
}
@Parameter(excluded = true)
public String getFormatParameterNameOrDefault() {
return formatParameterName == null ? DEFAULT_FORMAT_PARAMETER_NAME : formatParameterName;
}
public void setFormatParameterName(String formatParameterName) {
this.formatParameterName = formatParameterName;
}
public String getJsonFramework() {
return jsonFramework;
}
public void setJsonFramework(String jsonFramework) {
this.jsonFramework = jsonFramework;
}
public String[] getDisallowedContentTypes() {
return disallowedContentTypes;
}
public void setDisallowedContentTypes(String[] disallowedContentTypes) {
this.disallowedContentTypes = disallowedContentTypes;
}
public CorsConfig getCors() {
return cors;
}
@Parameter(excluded = true)
public CorsConfig getCorsOrDefault() {
if (cors == null) {
cors = new CorsConfig();
}
return cors;
}
public void setCors(CorsConfig cors) {
this.cors = cors;
}
@Parameter(excluded = true)
public OpenAPIConfig getOpenapi() {
return openapi;
}
@Parameter(attribute = false)
public void setOpenapi(OpenAPIConfig openapi) {
this.openapi = openapi;
}
@Parameter(excluded = true)
public McpConfig getMcp() {
return mcp;
}
@Parameter(attribute = false)
public void setMcp(McpConfig mcp) {
this.mcp = mcp;
}
@Parameter(excluded = true)
public Map<String, OpenAPIConfig> getOpenapis() {
return openapis;
}
@Parameter(attribute = false)
public void setOpenapis(Map<String, OpenAPIConfig> openapis) {
this.openapis = openapis;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/nested/CorsConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/nested/CorsConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import java.io.Serializable;
public class CorsConfig implements Serializable {
private static final long serialVersionUID = -7106481576053641726L;
/**
* A list of origins for which cross-origin requests are allowed. Values may be a specific domain, e.g.
* {@code "https://domain1.com"}, or the CORS defined special value {@code "*"} for all origins.
* <p>By default this is not set which means that no origins are allowed.
* However, an instance of this class is often initialized further, e.g. for {@code @CrossOrigin}, via
* {@code org.apache.dubbo.rpc.protocol.tri.rest.mapping.meta.CorsMeta.Builder#applyDefault()}.
*/
private String[] allowedOrigins;
/**
* Set the HTTP methods to allow, e.g. {@code "GET"}, {@code "POST"},
* {@code "PUT"}, etc. The special value {@code "*"} allows all methods.
* <p>If not set, only {@code "GET"} and {@code "HEAD"} are allowed.
* <p>By default this is not set.
*/
private String[] allowedMethods;
/**
* /**
* Set the list of headers that a pre-flight request can list as allowed
* for use during an actual request. The special value {@code "*"} allows
* actual requests to send any header.
* <p>By default this is not set.
*/
private String[] allowedHeaders;
/**
* Set the list of response headers that an actual response might have
* and can be exposed to the client. The special value {@code "*"}
* allows all headers to be exposed.
* <p>By default this is not set.
*/
private String[] exposedHeaders;
/**
* Whether user credentials are supported.
* <p>By default this is not set (i.e. user credentials are not supported).
*/
private Boolean allowCredentials;
/**
* Configure how long, as a duration, the response from a pre-flight request
* can be cached by clients.
*/
private Long maxAge;
public String[] getAllowedOrigins() {
return allowedOrigins;
}
public void setAllowedOrigins(String[] allowedOrigins) {
this.allowedOrigins = allowedOrigins;
}
public String[] getAllowedMethods() {
return allowedMethods;
}
public void setAllowedMethods(String[] allowedMethods) {
this.allowedMethods = allowedMethods;
}
public String[] getAllowedHeaders() {
return allowedHeaders;
}
public void setAllowedHeaders(String[] allowedHeaders) {
this.allowedHeaders = allowedHeaders;
}
public String[] getExposedHeaders() {
return exposedHeaders;
}
public void setExposedHeaders(String[] exposedHeaders) {
this.exposedHeaders = exposedHeaders;
}
public Boolean getAllowCredentials() {
return allowCredentials;
}
public void setAllowCredentials(Boolean allowCredentials) {
this.allowCredentials = allowCredentials;
}
public Long getMaxAge() {
return maxAge;
}
public void setMaxAge(Long maxAge) {
this.maxAge = maxAge;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/nested/PropagationConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/nested/PropagationConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import java.io.Serializable;
/**
* Configuration for the propagation.
*/
public class PropagationConfig implements Serializable {
private static final long serialVersionUID = -2570106396211532046L;
public static final String B3 = "B3";
public static final String W3C = "W3C";
/**
* Tracing context propagation type.
*/
private String type = W3C;
public PropagationConfig() {}
public PropagationConfig(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/nested/AggregationConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/nested/AggregationConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import java.io.Serializable;
/**
* Configuration for the metric aggregation.
*/
public class AggregationConfig implements Serializable {
private static final long serialVersionUID = 4878693820314125085L;
/**
* Enable aggregation or not.
*/
private Boolean enabled;
/**
* Enable QPS (Queries Per Second) aggregation or not.
*/
private Boolean enableQps;
/**
* Enable Response Time Percentile (Pxx) aggregation or not.
*/
private Boolean enableRtPxx;
/**
* Enable Response Time aggregation or not.
*/
private Boolean enableRt;
/**
* Enable Request aggregation or not.
*/
private Boolean enableRequest;
/**
* The number of buckets for time window quantile.
*/
private Integer bucketNum;
/**
* The time window in seconds for time window quantile.
*/
private Integer timeWindowSeconds;
/**
* The time window in milliseconds for QPS (Queries Per Second) aggregation.
*/
private Integer qpsTimeWindowMillSeconds;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Integer getBucketNum() {
return bucketNum;
}
public void setBucketNum(Integer bucketNum) {
this.bucketNum = bucketNum;
}
public Integer getTimeWindowSeconds() {
return timeWindowSeconds;
}
public void setTimeWindowSeconds(Integer timeWindowSeconds) {
this.timeWindowSeconds = timeWindowSeconds;
}
public Boolean getEnableQps() {
return enableQps;
}
public void setEnableQps(Boolean enableQps) {
this.enableQps = enableQps;
}
public Boolean getEnableRtPxx() {
return enableRtPxx;
}
public void setEnableRtPxx(Boolean enableRtPxx) {
this.enableRtPxx = enableRtPxx;
}
public Boolean getEnableRt() {
return enableRt;
}
public void setEnableRt(Boolean enableRt) {
this.enableRt = enableRt;
}
public Boolean getEnableRequest() {
return enableRequest;
}
public void setEnableRequest(Boolean enableRequest) {
this.enableRequest = enableRequest;
}
public Integer getQpsTimeWindowMillSeconds() {
return qpsTimeWindowMillSeconds;
}
public void setQpsTimeWindowMillSeconds(Integer qpsTimeWindowMillSeconds) {
this.qpsTimeWindowMillSeconds = qpsTimeWindowMillSeconds;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/nested/McpConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/nested/McpConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import org.apache.dubbo.config.support.Nested;
import java.io.Serializable;
public class McpConfig implements Serializable {
private static final long serialVersionUID = 6943417856234001947L;
/**
* Whether to enable MCP Server support
* <p>The default value is 'true'.
*/
private Boolean enabled;
/**
* The port of MCP Server
* <p>The default value is '0'.
*/
private Integer port;
/**
* the path of mcp
*/
@Nested
private MCPPath path;
/**
* streamable or sse
*/
private String protocol;
/**
* Session timeout in milliseconds for long connection
* unit: seconds
*/
private Integer sessionTimeout;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public MCPPath getPath() {
return path;
}
public void setPath(MCPPath path) {
this.path = path;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public Integer getSessionTimeout() {
return sessionTimeout;
}
public void setSessionTimeout(Integer sessionTimeout) {
this.sessionTimeout = sessionTimeout;
}
public static class MCPPath implements Serializable {
private static final long serialVersionUID = 6943417856234837947L;
/**
* The path of mcp message
* <p>The default value is '/mcp/message'.
*/
private String message;
/**
* The path of mcp sse
* <p>The default value is '/mcp/sse'.
*/
private String sse;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getSse() {
return sse;
}
public void setSse(String sse) {
this.sse = sse;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/nested/ExporterConfig.java | dubbo-common/src/main/java/org/apache/dubbo/config/nested/ExporterConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import org.apache.dubbo.config.support.Nested;
import java.io.Serializable;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
/**
* Configuration for the exporter.
*/
public class ExporterConfig implements Serializable {
private static final long serialVersionUID = -559392305178067845L;
/**
* Configuration for the Zipkin.
*/
@Nested
private ZipkinConfig zipkinConfig;
/**
* Configuration for the OTLP.
*/
@Nested
private OtlpConfig otlpConfig;
public ZipkinConfig getZipkinConfig() {
return zipkinConfig;
}
public void setZipkinConfig(ZipkinConfig zipkinConfig) {
this.zipkinConfig = zipkinConfig;
}
public OtlpConfig getOtlpConfig() {
return otlpConfig;
}
public void setOtlpConfig(OtlpConfig otlpConfig) {
this.otlpConfig = otlpConfig;
}
public static class ZipkinConfig implements Serializable {
/**
* URL to the Zipkin API.
*/
private String endpoint;
/**
* Connection timeout for requests to Zipkin. (seconds)
*/
private Duration connectTimeout = Duration.ofSeconds(1);
/**
* Read timeout for requests to Zipkin. (seconds)
*/
private Duration readTimeout = Duration.ofSeconds(10);
public ZipkinConfig() {}
public ZipkinConfig(String endpoint) {
this.endpoint = endpoint;
}
public ZipkinConfig(String endpoint, Duration connectTimeout, Duration readTimeout) {
this.endpoint = endpoint;
this.connectTimeout = connectTimeout;
this.readTimeout = readTimeout;
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public Duration getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(Duration connectTimeout) {
this.connectTimeout = connectTimeout;
}
public Duration getReadTimeout() {
return readTimeout;
}
public void setReadTimeout(Duration readTimeout) {
this.readTimeout = readTimeout;
}
}
public static class OtlpConfig implements Serializable {
/**
* URL to the Otlp API.
*/
private String endpoint;
/**
* The maximum time to wait for the collector to process an exported batch of spans. (seconds)
*/
private Duration timeout = Duration.ofSeconds(10);
/**
* The method used to compress payloads. If unset, compression is disabled. Currently
* supported compression methods include "gzip" and "none".
*/
private String compressionMethod = "none";
private Map<String, String> headers = new HashMap<>();
public OtlpConfig() {}
public OtlpConfig(String endpoint) {
this.endpoint = endpoint;
}
public OtlpConfig(String endpoint, Duration timeout) {
this.endpoint = endpoint;
this.timeout = timeout;
}
public OtlpConfig(String endpoint, Duration timeout, String compressionMethod) {
this.endpoint = endpoint;
this.timeout = timeout;
this.compressionMethod = compressionMethod;
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public Duration getTimeout() {
return timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public String getCompressionMethod() {
return compressionMethod;
}
public void setCompressionMethod(String compressionMethod) {
this.compressionMethod = compressionMethod;
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Service.java | dubbo-common/src/main/java/org/apache/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 org.apache.dubbo.config.annotation;
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
* @since 2.7.0
* @deprecated Recommend {@link DubboService} as the substitute
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Inherited
@Deprecated
public @interface Service {
/**
* Interface class, default value is void.class
*/
Class<?> interfaceClass() default void.class;
/**
* Interface class name, default value is empty string
*/
String interfaceName() default "";
/**
* Service version, default value is empty string
*/
String version() default "";
/**
* Service group, default value is empty string
*/
String group() default "";
/**
* Service path, default value is empty string
*/
String path() default "";
/**
* Whether to export service, default value is true
*/
boolean export() default true;
/**
* Service token, default value is false
*/
String token() default "";
/**
* Whether the service is deprecated, default value is false
*/
boolean deprecated() default false;
/**
* Whether the service is dynamic, default value is true
*/
boolean dynamic() default true;
/**
* Access log for the service, default value is ""
*/
String accesslog() default "";
/**
* Maximum concurrent executes for the service, default value is 0 - no limits
*/
int executes() default -1;
/**
* Whether to register the service to register center, default value is true
*/
boolean register() default true;
/**
* Service weight value, default value is 0
*/
int weight() default -1;
/**
* Service doc, default value is ""
*/
String document() default "";
/**
* Delay time for service registration, default value is 0
*/
int delay() default -1;
/**
* @see Service#stub()
* @deprecated
*/
String local() default "";
/**
* Service stub name, use interface name + Local if not set
*/
String stub() default "";
/**
* Cluster strategy, legal values include: failover, failfast, failsafe, failback, forking
*/
String cluster() default "";
/**
* How the proxy is generated, legal values include: jdk, javassist
*/
String proxy() default "";
/**
* Maximum connections service provider can accept, default value is 0 - connection is shared
*/
int connections() default -1;
/**
* The callback instance limit peer connection
* <p>
* see org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CALLBACK_INSTANCES
*/
int callbacks() default -1;
/**
* Callback method name when connected, default value is empty string
*/
String onconnect() default "";
/**
* Callback method name when disconnected, default value is empty string
*/
String ondisconnect() default "";
/**
* Service owner, default value is empty string
*/
String owner() default "";
/**
* Service layer, default value is empty string
*/
String layer() default "";
/**
* Service invocation retry times
*
* @see org.apache.dubbo.common.constants.CommonConstants#DEFAULT_RETRIES
*/
int retries() default -1;
/**
* Load balance strategy, legal values include: random, roundrobin, leastactive
*
* @see org.apache.dubbo.common.constants.CommonConstants#DEFAULT_LOADBALANCE
*/
String loadbalance() default "";
/**
* Whether to enable async invocation, default value is false
*/
boolean async() default false;
/**
* Maximum active requests allowed, default value is 0
*/
int actives() default -1;
/**
* Whether the async request has already been sent, the default value is false
*/
boolean sent() default false;
/**
* Service mock name, use interface name + Mock if not set
*/
String mock() default "";
/**
* Whether to use JSR303 validation, legal values are: true, false
*/
String validation() default "";
/**
* Timeout value for service invocation, default value is 0
*/
int timeout() default -1;
/**
* Specify cache implementation for service invocation, legal values include: lru, threadlocal, jcache
*/
String cache() default "";
/**
* Filters for service invocation
*
* @see Filter
*/
String[] filter() default {};
/**
* Listeners for service exporting and unexporting
*
* @see ExporterListener
*/
String[] listener() default {};
/**
* Customized parameter key-value pair, for example: {key1, value1, key2, value2}
*/
String[] parameters() default {};
/**
* Application spring bean name
* @deprecated Do not set it and use the global Application Config
*/
@Deprecated
String application() default "";
/**
* Module spring bean name
*/
String module() default "";
/**
* Provider spring bean name
*/
String provider() default "";
/**
* Protocol spring bean names
*/
String[] protocol() default {};
/**
* Monitor spring bean name
*/
String monitor() default "";
/**
* Registry spring bean name
*/
String[] registry() default {};
/**
* Service tag name
*/
String tag() default "";
/**
* methods support
*
* @return
*/
Method[] methods() default {};
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/ProvidedBy.java | dubbo-common/src/main/java/org/apache/dubbo/config/annotation/ProvidedBy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.annotation;
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;
/**
* Class-level annotation used for declaring Dubbo interface.
* Example:
* @ProvidedBy("dubbo-samples-xds-provider")
* public interface GreetingService {
* String sayHello(String name);
* }
*
* @Component("annotatedConsumer")
* public class GreetingServiceConsumer {
* @DubboReference(version = "1.0.0")
* private GreetingService greetingService;
* }
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Inherited
public @interface ProvidedBy {
/**
* Interface app name, default value is empty string
*/
String[] name() default {};
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/DubboService.java | dubbo-common/src/main/java/org/apache/dubbo/config/annotation/DubboService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.annotation;
import org.apache.dubbo.common.constants.ClusterRules;
import org.apache.dubbo.common.constants.LoadbalanceRules;
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;
/**
* Class-level annotation used for declaring Dubbo service.
* <p/>
* <b>1. Using with java config bean:</b>
* <p/>
* <b>This usage is recommended</b>.<br/>
* It is more flexible on bean methods than on implementation classes, and is more compatible with Spring.
* <pre>
* @Configuration
* class ProviderConfiguration {
*
* @Bean
* @DubboService(group="demo")
* public DemoService demoServiceImpl() {
* return new DemoServiceImpl();
* }
* }
* </pre>
*
* <b>2. Using on implementation class of service: </b>
* <pre>
* @DubboService(group="demo")
* public class DemoServiceImpl implements DemoService {
* ...
* }
* </pre>
*
* This usage causes the implementation class to rely on the Dubbo module.
*
*
* @since 2.7.7
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Inherited
public @interface DubboService {
/**
* Interface class, default value is void.class
*/
Class<?> interfaceClass() default void.class;
/**
* Interface class name, default value is empty string
*/
String interfaceName() default "";
/**
* Service version, default value is empty string
*/
String version() default "";
/**
* Service group, default value is empty string
*/
String group() default "";
/**
* Service path, default value is empty string
*/
String path() default "";
/**
* Whether to export service, default value is true
*/
boolean export() default true;
/**
* Service token, default value is empty string
*/
String token() default "";
/**
* Whether the service is deprecated, default value is false
*/
boolean deprecated() default false;
/**
* Whether the service is dynamic, default value is true
*/
boolean dynamic() default true;
/**
* Access log for the service, default value is empty string
*/
String accesslog() default "";
/**
* Maximum concurrent executes for the service, default value is -1 - no limits
*/
int executes() default -1;
/**
* Whether to register the service to register center, default value is true
*/
boolean register() default true;
/**
* Service weight value, default value is -1
*/
int weight() default -1;
/**
* Service doc, default value is empty string
*/
String document() default "";
/**
* Delay time for service registration, default value is -1
*/
int delay() default -1;
/**
* @see DubboService#stub()
* @deprecated
*/
String local() default "";
/**
* Service stub name, use interface name + Local if not set
*/
String stub() default "";
/**
* Cluster strategy, legal values include: failover, failfast, failsafe, failback, forking
* you can use {@link org.apache.dubbo.common.constants.ClusterRules#FAIL_FAST} ……
*/
String cluster() default ClusterRules.EMPTY;
/**
* How the proxy is generated, legal values include: jdk, javassist
*/
String proxy() default "";
/**
* Maximum connections service provider can accept, default value is -1 - connection is shared
*/
int connections() default -1;
/**
* The callback instance limit peer connection
* <p>
* see org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CALLBACK_INSTANCES
*/
int callbacks() default -1;
/**
* Callback method name when connected, default value is empty string
*/
String onconnect() default "";
/**
* Callback method name when disconnected, default value is empty string
*/
String ondisconnect() default "";
/**
* Service owner, default value is empty string
*/
String owner() default "";
/**
* Service layer, default value is empty string
*/
String layer() default "";
/**
* Service invocation retry times
*
* @see org.apache.dubbo.common.constants.CommonConstants#DEFAULT_RETRIES
*/
int retries() default -1;
/**
* Load balance strategy, legal values include: random, roundrobin, leastactive
*
* you can use {@link org.apache.dubbo.common.constants.LoadbalanceRules#RANDOM} ……
*/
String loadbalance() default LoadbalanceRules.EMPTY;
/**
* Whether to enable async invocation, default value is false
*/
boolean async() default false;
/**
* Maximum active requests allowed, default value is -1
*/
int actives() default -1;
/**
* Whether the async request has already been sent, the default value is false
*/
boolean sent() default false;
/**
* Service mock name, use interface name + Mock if not set
*/
String mock() default "";
/**
* Whether to use JSR303 validation, legal values are: true, false
*/
String validation() default "";
/**
* Timeout value for service invocation, default value is -1
*/
int timeout() default -1;
/**
* Specify cache implementation for service invocation, legal values include: lru, threadlocal, jcache
*/
String cache() default "";
/**
* Filters for service invocation
*
* @see Filter
*/
String[] filter() default {};
/**
* Listeners for service exporting and unexporting
*
* @see ExporterListener
*/
String[] listener() default {};
/**
* Customized parameter key-value pair, for example:
* <pre>
* ["a","b"] ==> {a=b}
* [" a "," b "] ==> {a=b}
* ["a=b"] ==>{a=b}
* ["a:b"] ==>{a=b}
* ["a=b","c","d"] ==>{a=b,c=d}
* ["a","a:b"] ==>{a="a:b"}
* ["a","a,b"] ==>{a="a,b"}
* </pre>
* @see org.apache.dubbo.config.spring.util.DubboAnnotationUtils#convertParameters(java.lang.String[])
*/
String[] parameters() default {};
/**
* Application spring bean name
* @deprecated This attribute was deprecated, use bind application/module of spring ApplicationContext
*/
@Deprecated
String application() default "";
/**
* Module spring bean name
*/
String module() default "";
/**
* Provider spring bean name
*/
String provider() default "";
/**
* Protocol spring bean names
*/
String[] protocol() default {};
/**
* Monitor spring bean name
*/
String monitor() default "";
/**
* Registry spring bean name
*/
String[] registry() default {};
/**
* Service tag name
*/
String tag() default "";
/**
* methods support
*
* @return
*/
Method[] methods() default {};
/**
* the scope for referring/exporting a service, if it's local, it means searching in current JVM only.
* @see org.apache.dubbo.rpc.Constants#SCOPE_LOCAL
* @see org.apache.dubbo.rpc.Constants#SCOPE_REMOTE
*/
String scope() default "";
/**
* Weather the service is export asynchronously
*/
boolean exportAsync() default false;
/**
* bean name of service executor(thread pool), used for thread pool isolation between services
* @return
*/
String executor() default "";
/**
* Payload max length.
*/
String payload() default "";
/**
* The serialization type
*/
String serialization() default "";
/**
* If the parameter has a value, the consumer will read the parameter first.
* If the Dubbo Sdk you are using contains the serialization type, the serialization method specified by the argument is used.
* <p>
* When this parameter is null or the serialization type specified by this parameter does not exist in the Dubbo SDK, the serialization type specified by serialization is used.
* If the Dubbo SDK if still does not exist, the default type of the Dubbo SDK is used.
* For Dubbo SDK >= 3.2, <code>preferSerialization</code> takes precedence over <code>serialization</code>
* <p>
* The configuration supports multiple, which are separated by commas.Such as:<code>fastjson2,fastjson,hessian2</code>
*/
String preferSerialization() default "";
/**
* Whether to expose methods in this service as MCP tools, default value is false
* This controls whether methods in this service class can be exposed as MCP tools.
* Specific method-level configuration should be done via method annotations.
*/
boolean mcpEnabled() default false;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Argument.java | dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Argument.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.annotation;
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;
/**
* @since 2.6.5
*
* 2018/9/29
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE})
@Inherited
public @interface Argument {
// argument: index -1 represents not set
int index() default -1;
// argument type
String type() default "";
// callback interface
boolean callback() default false;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/DubboReference.java | dubbo-common/src/main/java/org/apache/dubbo/config/annotation/DubboReference.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.annotation;
import org.apache.dubbo.common.constants.ClusterRules;
import org.apache.dubbo.common.constants.LoadbalanceRules;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.config.AbstractReferenceConfig;
import org.apache.dubbo.config.ReferenceConfigBase;
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;
/**
* An annotation used for referencing a Dubbo service.
* <p>
* <b>It is recommended to use @DubboReference on the @Bean method in the Java-config class, but not on the fields or setter methods to be injected.</b>
* </p>
* <p>
* Step 1: Register ReferenceBean in Java-config class:
* <pre class="code">
* @Configuration
* public class ReferenceConfiguration {
* @Bean
* @DubboReference(group = "demo")
* public ReferenceBean<HelloService> helloService() {
* return new ReferenceBean();
* }
*
* @Bean
* @DubboReference(group = "demo", interfaceClass = HelloService.class)
* public ReferenceBean<GenericService> genericHelloService() {
* return new ReferenceBean();
* }
* }
* </pre>
* <p>
* Step 2: Inject ReferenceBean by @Autowired
* <pre class="code">
* public class FooController {
* @Autowired
* private HelloService helloService;
*
* @Autowired
* private GenericService genericHelloService;
* }
* </pre>
*
* @see org.apache.dubbo.config.spring.reference.ReferenceBeanBuilder
* @see org.apache.dubbo.config.spring.ReferenceBean
* @since 2.7.7
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
public @interface DubboReference {
/**
* Interface class, default value is void.class
*/
Class<?> interfaceClass() default void.class;
/**
* Interface class name, default value is empty string
*/
String interfaceName() default "";
/**
* Service version, default value is empty string
*/
String version() default "";
/**
* Service group, default value is empty string
*/
String group() default "";
/**
* Service target URL for direct invocation, if this is specified, then registry center takes no effect.
*/
String url() default "";
/**
* Client transport type, default value is "netty"
*/
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;
/**
* When enable, prefer to call local service in the same JVM if it's present, default value is true
*
* @deprecated using scope="local" or scope="remote" instead
*/
@Deprecated
boolean injvm() default true;
/**
* Check if service provider is available during boot up, default value is true
*/
boolean check() default true;
/**
* Whether eager initialize the reference bean when all properties are set, default value is true ( null as true)
*
* @see ReferenceConfigBase#shouldInit()
*/
boolean init() default true;
/**
* Whether to make connection when the client is created, the default value is false
*/
boolean lazy() default false;
/**
* Export an stub service for event dispatch, default value is false.
* <p>
* see org.apache.dubbo.rpc.Constants#STUB_EVENT_METHODS_KEY
*/
boolean stubevent() default false;
/**
* Whether to reconnect if connection is lost, if not specify, reconnect is enabled by default, and the interval
* for retry connecting is 2000 ms
* <p>
* see org.apache.dubbo.remoting.Constants#DEFAULT_RECONNECT_PERIOD
*/
String reconnect() default "";
/**
* Whether to stick to the same node in the cluster, the default value is false
* <p>
* see Constants#DEFAULT_CLUSTER_STICKY
*/
boolean sticky() default false;
/**
* How the proxy is generated, legal values include: jdk, javassist
*/
String proxy() default "";
/**
* Service stub name, use interface name + Stub if not set
*/
String stub() default "";
/**
* Cluster strategy, legal values include: failover, failfast, failsafe, failback, forking
* you can use {@link org.apache.dubbo.common.constants.ClusterRules#FAIL_FAST} ……
*/
String cluster() default ClusterRules.EMPTY;
/**
* Maximum connections service provider can accept, default value is 0 - connection is shared
*/
int connections() default -1;
/**
* The callback instance limit peer connection
* <p>
* see org.apache.dubbo.rpc.Constants#DEFAULT_CALLBACK_INSTANCES
*/
int callbacks() default -1;
/**
* Callback method name when connected, default value is empty string
*/
String onconnect() default "";
/**
* Callback method name when disconnected, default value is empty string
*/
String ondisconnect() default "";
/**
* Service owner, default value is empty string
*/
String owner() default "";
/**
* Service layer, default value is empty string
*/
String layer() default "";
/**
* Service invocation retry times
* <p>
* see Constants#DEFAULT_RETRIES
*/
int retries() default -1;
/**
* Load balance strategy, legal values include: random, roundrobin, leastactive
* you can use {@link org.apache.dubbo.common.constants.LoadbalanceRules#RANDOM} ……
*/
String loadbalance() default LoadbalanceRules.EMPTY;
/**
* Whether to enable async invocation, default value is false
*/
boolean async() default false;
/**
* Maximum active requests allowed, default value is 0
*/
int actives() default -1;
/**
* Whether the async request has already been sent, the default value is false
*/
boolean sent() default false;
/**
* Service mock name, use interface name + Mock if not set
*/
String mock() default "";
/**
* Whether to use JSR303 validation, legal values are: true, false
*/
String validation() default "";
/**
* Timeout value for service invocation, default value is 0
*/
int timeout() default -1;
/**
* Specify cache implementation for service invocation, legal values include: lru, threadlocal, jcache
*/
String cache() default "";
/**
* Filters for service invocation
* <p>
* see Filter
*/
String[] filter() default {};
/**
* Listeners for service exporting and unexporting
* <p>
* see ExporterListener
*/
String[] listener() default {};
/**
* Customized parameter key-value pair, for example: {key1, value1, key2, value2} or {"key1=value1", "key2=value2"}
*/
String[] parameters() default {};
/**
* Application name
*
* @deprecated This attribute was deprecated, use bind application/module of spring ApplicationContext
*/
@Deprecated
String application() default "";
/**
* Module associated name
*/
String module() default "";
/**
* Consumer associated name
*/
String consumer() default "";
/**
* Monitor associated name
*/
String monitor() default "";
/**
* Registry associated name
*/
String[] registry() default {};
/**
* The communication protocol of Dubbo Service
*
* @return the default value is ""
* @since 2.6.6
*/
String protocol() default "";
/**
* Service tag name
*/
String tag() default "";
/**
* Service merger
*/
String merger() default "";
/**
* methods support
*/
Method[] methods() default {};
/**
* The id
* NOTE: The id attribute is ignored when using @DubboReference on @Bean method
*
* @return default value is empty
* @since 2.7.3
*/
String id() default "";
/**
* @return The service names that the Dubbo interface subscribed
* @see RegistryConstants#SUBSCRIBED_SERVICE_NAMES_KEY
* @since 2.7.8
* @deprecated using {@link DubboReference#providedBy()}
*/
@Deprecated
String[] services() default {};
/**
* declares which app or service this interface belongs to
*
* @see RegistryConstants#PROVIDED_BY
*/
String[] providedBy() default {};
/**
* The service port of the provider
*
* @see AbstractReferenceConfig#providerPort
* @since 3.1.0
*/
int providerPort() default -1;
/**
* assign the namespace that provider belong to
* @see AbstractReferenceConfig#providerNamespace
* @since 3.1.1
*/
String providerNamespace() default "";
/**
* the scope for referring/exporting a service, if it's local, it means searching in current JVM only.
*
* @see org.apache.dubbo.rpc.Constants#SCOPE_LOCAL
* @see org.apache.dubbo.rpc.Constants#SCOPE_REMOTE
*/
String scope() default "";
/**
* Weather the reference is refer asynchronously
*/
boolean referAsync() default false;
/**
* unload Cluster related in mesh mode
*
* @see ReferenceConfigBase#unloadClusterRelated
* @since 3.1.0
*/
boolean unloadClusterRelated() default false;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Reference.java | dubbo-common/src/main/java/org/apache/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 org.apache.dubbo.config.annotation;
import org.apache.dubbo.config.ReferenceConfigBase;
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
* @since 2.7.0
* @deprecated Recommend {@link DubboReference} as the substitute
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Deprecated
public @interface Reference {
/**
* Interface class, default value is void.class
*/
Class<?> interfaceClass() default void.class;
/**
* Interface class name, default value is empty string
*/
String interfaceName() default "";
/**
* Service version, default value is empty string
*/
String version() default "";
/**
* Service group, default value is empty string
*/
String group() default "";
/**
* Service target URL for direct invocation, if this is specified, then registry center takes no effect.
*/
String url() default "";
/**
* Client transport type, default value is "netty"
*/
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;
/**
* When enable, prefer to call local service in the same JVM if it's present, default value is true
*/
boolean injvm() default true;
/**
* Check if service provider is available during boot up, default value is true
*/
boolean check() default true;
/**
* Whether eager initialize the reference bean when all properties are set, default value is true ( null as true)
* @see ReferenceConfigBase#shouldInit()
*/
boolean init() default true;
/**
* Whether to make connection when the client is created, the default value is false
*/
boolean lazy() default false;
/**
* Export an stub service for event dispatch, default value is false.
* <p>
* see org.apache.dubbo.rpc.Constants#STUB_EVENT_METHODS_KEY
*/
boolean stubevent() default false;
/**
* Whether to reconnect if connection is lost, if not specify, reconnect is enabled by default, and the interval
* for retry connecting is 2000 ms
* <p>
* see org.apache.dubbo.remoting.Constants#DEFAULT_RECONNECT_PERIOD
*/
String reconnect() default "";
/**
* Whether to stick to the same node in the cluster, the default value is false
* <p>
* see Constants#DEFAULT_CLUSTER_STICKY
*/
boolean sticky() default false;
/**
* How the proxy is generated, legal values include: jdk, javassist
*/
String proxy() default "";
/**
* Service stub name, use interface name + Local if not set
*/
String stub() default "";
/**
* Cluster strategy, legal values include: failover, failfast, failsafe, failback, forking
*/
String cluster() default "";
/**
* Maximum connections service provider can accept, default value is 0 - connection is shared
*/
int connections() default -1;
/**
* The callback instance limit peer connection
* <p>
* see org.apache.dubbo.rpc.Constants#DEFAULT_CALLBACK_INSTANCES
*/
int callbacks() default -1;
/**
* Callback method name when connected, default value is empty string
*/
String onconnect() default "";
/**
* Callback method name when disconnected, default value is empty string
*/
String ondisconnect() default "";
/**
* Service owner, default value is empty string
*/
String owner() default "";
/**
* Service layer, default value is empty string
*/
String layer() default "";
/**
* Service invocation retry times
* <p>
* see Constants#DEFAULT_RETRIES
*/
int retries() default -1;
/**
* Load balance strategy, legal values include: random, roundrobin, leastactive
* <p>
* see Constants#DEFAULT_LOADBALANCE
*/
String loadbalance() default "";
/**
* Whether to enable async invocation, default value is false
*/
boolean async() default false;
/**
* Maximum active requests allowed, default value is 0
*/
int actives() default -1;
/**
* Whether the async request has already been sent, the default value is false
*/
boolean sent() default false;
/**
* Service mock name, use interface name + Mock if not set
*/
String mock() default "";
/**
* Whether to use JSR303 validation, legal values are: true, false
*/
String validation() default "";
/**
* Timeout value for service invocation, default value is 0
*/
int timeout() default -1;
/**
* Specify cache implementation for service invocation, legal values include: lru, threadlocal, jcache
*/
String cache() default "";
/**
* Filters for service invocation
* <p>
* see Filter
*/
String[] filter() default {};
/**
* Listeners for service exporting and unexporting
* <p>
* see ExporterListener
*/
String[] listener() default {};
/**
* Customized parameter key-value pair, for example: {key1, value1, key2, value2}
*/
String[] parameters() default {};
/**
* Application associated name
* @deprecated Do not set it and use the global Application Config
*/
@Deprecated
String application() default "";
/**
* Module associated name
*/
String module() default "";
/**
* Consumer associated name
*/
String consumer() default "";
/**
* Monitor associated name
*/
String monitor() default "";
/**
* Registry associated name
*/
String[] registry() default {};
/**
* The communication protocol of Dubbo Service
*
* @return the default value is ""
* @since 2.6.6
*/
String protocol() default "";
/**
* Service tag name
*/
String tag() default "";
/**
* methods support
*
* @return
*/
Method[] methods() default {};
/**
* The id
*
* @return default value is empty
* @since 2.7.3
*/
String id() default "";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Method.java | dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Method.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.annotation;
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;
/**
* @since 2.6.5
* *
* * 2018/9/29
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE})
@Inherited
public @interface Method {
String name();
int timeout() default -1;
int retries() default -1;
String loadbalance() default "";
boolean async() default false;
boolean sent() default true;
int actives() default -1;
int executes() default -1;
boolean deprecated() default false;
boolean sticky() default false;
boolean isReturn() default true;
String oninvoke() default "";
String onreturn() default "";
String onthrow() default "";
String cache() default "";
String validation() default "";
String merger() default "";
Argument[] arguments() default {};
/**
* Customized parameter key-value pair, for example: {key1, value1, key2, value2} or {"key1=value1", "key2=value2"}
*/
String[] parameters() default {};
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/context/AbstractConfigManager.java | dubbo-common/src/main/java/org/apache/dubbo/config/context/AbstractConfigManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.context;
import org.apache.dubbo.common.config.CompositeConfiguration;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.config.Environment;
import org.apache.dubbo.common.config.PropertiesConfiguration;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.context.LifecycleAdapter;
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.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConfigKeys;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ReferenceConfigBase;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfigBase;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.config.TracingConfig;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import static java.lang.Boolean.TRUE;
import static java.util.Collections.emptyMap;
import static java.util.Optional.ofNullable;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_PROPERTY_TYPE_MISMATCH;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION;
import static org.apache.dubbo.config.AbstractConfig.getTagName;
public abstract class AbstractConfigManager extends LifecycleAdapter {
private static final String CONFIG_NAME_READ_METHOD = "getName";
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AbstractConfigManager.class);
private static final Set<Class<? extends AbstractConfig>> uniqueConfigTypes = new ConcurrentHashSet<>();
final ConcurrentHashMap<String, Map<String, AbstractConfig>> configsCache = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, AtomicInteger> configIdIndexes = new ConcurrentHashMap<>();
protected Set<AbstractConfig> duplicatedConfigs = new ConcurrentHashSet<>();
protected final ScopeModel scopeModel;
protected final ApplicationModel applicationModel;
private final Collection<Class<? extends AbstractConfig>> supportedConfigTypes;
private final Environment environment;
private ConfigValidator configValidator;
private final AtomicBoolean initialized = new AtomicBoolean(false);
protected ConfigMode configMode = ConfigMode.STRICT;
protected boolean ignoreDuplicatedInterface = false;
static {
// init unique config types
// unique config in application
uniqueConfigTypes.add(ApplicationConfig.class);
uniqueConfigTypes.add(MonitorConfig.class);
uniqueConfigTypes.add(MetricsConfig.class);
uniqueConfigTypes.add(TracingConfig.class);
uniqueConfigTypes.add(SslConfig.class);
// unique config in each module
uniqueConfigTypes.add(ModuleConfig.class);
}
public AbstractConfigManager(
ScopeModel scopeModel, Collection<Class<? extends AbstractConfig>> supportedConfigTypes) {
this.scopeModel = scopeModel;
this.applicationModel = ScopeModelUtil.getApplicationModel(scopeModel);
this.supportedConfigTypes = supportedConfigTypes;
environment = scopeModel.modelEnvironment();
}
@Override
public void initialize() throws IllegalStateException {
if (!initialized.compareAndSet(false, true)) {
return;
}
CompositeConfiguration configuration = scopeModel.modelEnvironment().getConfiguration();
// dubbo.config.mode
String configModeStr = (String) configuration.getProperty(ConfigKeys.DUBBO_CONFIG_MODE);
try {
if (StringUtils.hasText(configModeStr)) {
this.configMode = ConfigMode.valueOf(configModeStr.toUpperCase());
}
} catch (Exception e) {
String msg = "Illegal '" + ConfigKeys.DUBBO_CONFIG_MODE + "' config value [" + configModeStr
+ "], available values " + Arrays.toString(ConfigMode.values());
logger.error(COMMON_PROPERTY_TYPE_MISMATCH, "", "", msg, e);
throw new IllegalArgumentException(msg, e);
}
// dubbo.config.ignore-duplicated-interface
String ignoreDuplicatedInterfaceStr =
(String) configuration.getProperty(ConfigKeys.DUBBO_CONFIG_IGNORE_DUPLICATED_INTERFACE);
if (ignoreDuplicatedInterfaceStr != null) {
this.ignoreDuplicatedInterface = Boolean.parseBoolean(ignoreDuplicatedInterfaceStr);
}
// print
Map<String, Object> map = new LinkedHashMap<>();
map.put(ConfigKeys.DUBBO_CONFIG_MODE, configMode);
map.put(ConfigKeys.DUBBO_CONFIG_IGNORE_DUPLICATED_INTERFACE, this.ignoreDuplicatedInterface);
logger.info("Config settings: " + map);
}
/**
* Add the dubbo {@link AbstractConfig config}
*
* @param config the dubbo {@link AbstractConfig config}
*/
public final <T extends AbstractConfig> T addConfig(AbstractConfig config) {
if (config == null) {
return null;
}
// ignore MethodConfig
if (!isSupportConfigType(config.getClass())) {
throw new IllegalArgumentException("Unsupported config type: " + config);
}
if (config.getScopeModel() != scopeModel) {
config.setScopeModel(scopeModel);
}
Class<? extends AbstractConfig> targetConfigType = getTargetConfigType(config.getClass());
Map<String, AbstractConfig> configsMap = ConcurrentHashMapUtils.computeIfAbsent(
configsCache, getTagName(targetConfigType), type -> new ConcurrentHashMap<>());
// fast check duplicated equivalent config before write lock
if (!(config instanceof ReferenceConfigBase || config instanceof ServiceConfigBase)) {
for (AbstractConfig value : configsMap.values()) {
if (value.equals(config)) {
return (T) value;
}
}
}
// lock by config type
synchronized (configsMap) {
return (T) addIfAbsent(config, configsMap, targetConfigType);
}
}
protected boolean isSupportConfigType(Class<? extends AbstractConfig> type) {
return getTargetConfigType(type) != null;
}
protected Class<? extends AbstractConfig> getTargetConfigType(Class<? extends AbstractConfig> type) {
for (Class<? extends AbstractConfig> supportedConfigType : supportedConfigTypes) {
if (supportedConfigType.isAssignableFrom(type)) {
return supportedConfigType;
}
}
return null;
}
/**
* Add config
*
* @param config
* @param configsMap
* @return the existing equivalent config or the new adding config
* @throws IllegalStateException
*/
private <C extends AbstractConfig> C addIfAbsent(
C config, Map<String, C> configsMap, Class<? extends AbstractConfig> targetConfigType)
throws IllegalStateException {
if (config == null || configsMap == null) {
return config;
}
// find by value
Optional<C> prevConfig = findDuplicatedConfig(configsMap, config);
if (prevConfig.isPresent()) {
return prevConfig.get();
}
String key = config.getId();
if (key == null) {
do {
// generate key if id is not set
key = generateConfigId(config);
} while (configsMap.containsKey(key));
}
C existedConfig = configsMap.get(key);
if (existedConfig != null && !isEquals(existedConfig, config)) {
String type = targetConfigType.getSimpleName();
logger.warn(
COMMON_UNEXPECTED_EXCEPTION,
"",
"",
String.format(
"Duplicate %s found, there already has one default %s or more than two %ss have the same id, "
+ "you can try to give each %s a different id, override previous config with later config. id: %s, prev: %s, later: %s",
type, type, type, type, key, existedConfig, config));
}
// override existed config if any
configsMap.put(key, config);
return config;
}
protected <C extends AbstractConfig> boolean removeIfAbsent(C config, Map<String, C> configsMap) {
if (config.getId() != null) {
return configsMap.remove(config.getId(), config);
}
return configsMap.values().removeIf(c -> config == c);
}
protected boolean isUniqueConfig(AbstractConfig config) {
if (uniqueConfigTypes.contains(config.getClass())) {
return true;
}
for (Class<? extends AbstractConfig> uniqueConfigType : uniqueConfigTypes) {
if (uniqueConfigType.isAssignableFrom(config.getClass())) {
return true;
}
}
return false;
}
protected <C extends AbstractConfig> C getSingleConfig(String configType) throws IllegalStateException {
Map<String, AbstractConfig> configsMap = getConfigsMap(configType);
int size = configsMap.size();
if (size < 1) {
// throw new IllegalStateException("No such " + configType.getName() + " is found");
return null;
} else if (size > 1) {
throw new IllegalStateException("Expected single instance of " + configType + ", but found " + size
+ " instances, please remove redundant configs. instances: " + configsMap.values());
}
return (C) configsMap.values().iterator().next();
}
protected <C extends AbstractConfig> Optional<C> findDuplicatedConfig(Map<String, C> configsMap, C config) {
// find by value
Optional<C> prevConfig = findConfigByValue(configsMap.values(), config);
if (prevConfig.isPresent()) {
if (prevConfig.get() == config) {
// the new one is same as existing one
return prevConfig;
}
// ignore duplicated equivalent config
if (logger.isInfoEnabled() && duplicatedConfigs.add(config)) {
logger.info("Ignore duplicated config: " + config);
}
return prevConfig;
}
// check unique config
return checkUniqueConfig(configsMap, config);
}
public <C extends AbstractConfig> Map<String, C> getConfigsMap(Class<C> cls) {
return getConfigsMap(getTagName(cls));
}
protected <C extends AbstractConfig> Map<String, C> getConfigsMap(String configType) {
return (Map<String, C>) configsCache.getOrDefault(configType, emptyMap());
}
protected <C extends AbstractConfig> Collection<C> getConfigs(String configType) {
return (Collection<C>) getConfigsMap(configType).values();
}
public <C extends AbstractConfig> Collection<C> getConfigs(Class<C> configType) {
return (Collection<C>) getConfigsMap(getTagName(configType)).values();
}
/**
* Get config by id
*
* @param configType
* @param id
* @return
*/
protected <C extends AbstractConfig> C getConfigById(String configType, String id) {
return (C) getConfigsMap(configType).get(id);
}
/**
* Get config instance by id or by name
*
* @param cls Config type
* @param idOrName the id or name of the config
* @return
*/
public <T extends AbstractConfig> Optional<T> getConfig(Class<T> cls, String idOrName) {
T config = getConfigById(getTagName(cls), idOrName);
if (config == null) {
config = getConfigByName(cls, idOrName);
}
return ofNullable(config);
}
/**
* Get config by name if existed
*
* @param cls
* @param name
* @return
*/
protected <C extends AbstractConfig> C getConfigByName(Class<? extends C> cls, String name) {
Map<String, ? extends C> configsMap = getConfigsMap(cls);
if (configsMap.isEmpty()) {
return null;
}
// try to find config by name
if (ReflectUtils.hasMethod(cls, CONFIG_NAME_READ_METHOD)) {
List<C> list = configsMap.values().stream()
.filter(cfg -> name.equals(getConfigName(cfg)))
.collect(Collectors.toList());
if (list.size() > 1) {
throw new IllegalStateException("Found more than one config by name: " + name + ", instances: " + list
+ ". Please remove redundant configs or get config by id.");
} else if (list.size() == 1) {
return list.get(0);
}
}
return null;
}
private <C extends AbstractConfig> String getConfigName(C config) {
try {
return ReflectUtils.getProperty(config, CONFIG_NAME_READ_METHOD);
} catch (Exception e) {
return null;
}
}
protected <C extends AbstractConfig> Optional<C> findConfigByValue(Collection<C> values, C config) {
// 1. find same config instance (speed up raw api usage)
Optional<C> prevConfig = values.stream().filter(val -> val == config).findFirst();
if (prevConfig.isPresent()) {
return prevConfig;
}
// 2. find equal config
prevConfig = values.stream().filter(val -> isEquals(val, config)).findFirst();
return prevConfig;
}
protected boolean isEquals(AbstractConfig oldOne, AbstractConfig newOne) {
if (oldOne == newOne) {
return true;
}
if (oldOne == null || newOne == null) {
return false;
}
if (oldOne.getClass() != newOne.getClass()) {
return false;
}
// make both are refreshed or none is refreshed
if (oldOne.isRefreshed() || newOne.isRefreshed()) {
if (!oldOne.isRefreshed()) {
oldOne.refresh();
}
if (!newOne.isRefreshed()) {
newOne.refresh();
}
}
return oldOne.equals(newOne);
}
protected <C extends AbstractConfig> String generateConfigId(C config) {
String tagName = getTagName(config.getClass());
int idx = ConcurrentHashMapUtils.computeIfAbsent(configIdIndexes, tagName, clazz -> new AtomicInteger(0))
.incrementAndGet();
return tagName + "#" + idx;
}
public <C extends AbstractConfig> List<C> getDefaultConfigs(Class<C> cls) {
return getDefaultConfigs(getConfigsMap(getTagName(cls)));
}
static <C extends AbstractConfig> Boolean isDefaultConfig(C config) {
return config.isDefault();
}
static <C extends AbstractConfig> List<C> getDefaultConfigs(Map<String, C> configsMap) {
// find isDefault() == true
List<C> list = configsMap.values().stream()
.filter(c -> TRUE.equals(AbstractConfigManager.isDefaultConfig(c)))
.collect(Collectors.toList());
if (!list.isEmpty()) {
return list;
}
// find isDefault() == null
list = configsMap.values().stream()
.filter(c -> AbstractConfigManager.isDefaultConfig(c) == null)
.collect(Collectors.toList());
return list;
// exclude isDefault() == false
}
protected <C extends AbstractConfig> Optional<C> checkUniqueConfig(Map<String, C> configsMap, C config) {
if (configsMap.size() > 0 && isUniqueConfig(config)) {
C oldOne = configsMap.values().iterator().next();
String configName = oldOne.getClass().getSimpleName();
String msgPrefix = "Duplicate Configs found for " + configName + ", only one unique " + configName
+ " is allowed for one application. previous: " + oldOne + ", later: " + config
+ ". According to config mode [" + configMode + "], ";
switch (configMode) {
case STRICT: {
if (!isEquals(oldOne, config)) {
throw new IllegalStateException(
msgPrefix + "please remove redundant configs and keep only one.");
}
break;
}
case IGNORE: {
// ignore later config
if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) {
logger.warn(
COMMON_UNEXPECTED_EXCEPTION,
"",
"",
msgPrefix + "keep previous config and ignore later config");
}
return Optional.of(oldOne);
}
case OVERRIDE: {
// clear previous config, add new config
configsMap.clear();
if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) {
logger.warn(
COMMON_UNEXPECTED_EXCEPTION,
"",
"",
msgPrefix + "override previous config with later config");
}
break;
}
case OVERRIDE_ALL: {
// override old one's properties with the new one
oldOne.overrideWithConfig(config, true);
if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) {
logger.warn(
COMMON_UNEXPECTED_EXCEPTION,
"",
"",
msgPrefix + "override previous config with later config");
}
return Optional.of(oldOne);
}
case OVERRIDE_IF_ABSENT: {
// override old one's properties with the new one
oldOne.overrideWithConfig(config, false);
if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) {
logger.warn(
COMMON_UNEXPECTED_EXCEPTION,
"",
"",
msgPrefix + "override previous config with later config");
}
return Optional.of(oldOne);
}
}
}
return Optional.empty();
}
public abstract void loadConfigs();
public <T extends AbstractConfig> List<T> loadConfigsOfTypeFromProps(Class<T> cls) {
List<T> tmpConfigs = new ArrayList<>();
PropertiesConfiguration properties = environment.getPropertiesConfiguration();
// load multiple configs with id
Set<String> configIds = this.getConfigIdsFromProps(cls);
configIds.forEach(id -> {
if (!this.getConfig(cls, id).isPresent()) {
T config;
try {
config = createConfig(cls, scopeModel);
config.setId(id);
} catch (Exception e) {
throw new IllegalStateException(
"create config instance failed, id: " + id + ", type:" + cls.getSimpleName());
}
String key = null;
boolean addDefaultNameConfig = false;
try {
// add default name config (same as id), e.g. dubbo.protocols.rest.port=1234
key = DUBBO + "." + AbstractConfig.getPluralTagName(cls) + "." + id + ".name";
if (properties.getProperty(key) == null) {
properties.setProperty(key, id);
addDefaultNameConfig = true;
}
config.refresh();
this.addConfig(config);
tmpConfigs.add(config);
} catch (Exception e) {
logger.error(
COMMON_PROPERTY_TYPE_MISMATCH,
"",
"",
"load config failed, id: " + id + ", type:" + cls.getSimpleName(),
e);
throw new IllegalStateException("load config failed, id: " + id + ", type:" + cls.getSimpleName());
} finally {
if (addDefaultNameConfig && key != null) {
properties.remove(key);
}
}
}
});
// If none config of the type, try load single config
if (this.getConfigs(cls).isEmpty()) {
// load single config
List<Map<String, String>> configurationMaps = environment.getConfigurationMaps();
if (ConfigurationUtils.hasSubProperties(configurationMaps, AbstractConfig.getTypePrefix(cls))) {
T config;
try {
config = createConfig(cls, scopeModel);
config.refresh();
} catch (Exception e) {
throw new IllegalStateException(
"create default config instance failed, type:" + cls.getSimpleName(), e);
}
this.addConfig(config);
tmpConfigs.add(config);
}
}
return tmpConfigs;
}
private <T extends AbstractConfig> T createConfig(Class<T> cls, ScopeModel scopeModel)
throws ReflectiveOperationException {
T config = cls.getDeclaredConstructor().newInstance();
config.setScopeModel(scopeModel);
return config;
}
/**
* Search props and extract config ids of specify type.
* <pre>
* # properties
* dubbo.registries.registry1.address=xxx
* dubbo.registries.registry2.port=xxx
*
* # extract
* Set configIds = getConfigIds(RegistryConfig.class)
*
* # result
* configIds: ["registry1", "registry2"]
* </pre>
*
* @param clazz config type
* @return ids of specify config type
*/
private Set<String> getConfigIdsFromProps(Class<? extends AbstractConfig> clazz) {
String prefix = CommonConstants.DUBBO + "." + AbstractConfig.getPluralTagName(clazz) + ".";
return ConfigurationUtils.getSubIds(environment.getConfigurationMaps(), prefix);
}
protected <T extends AbstractConfig> void checkDefaultAndValidateConfigs(Class<T> configType) {
try {
if (shouldAddDefaultConfig(configType)) {
T config = createConfig(configType, scopeModel);
config.refresh();
if (!isNeedValidation(config) || config.isValid()) {
this.addConfig(config);
} else {
logger.info("Ignore invalid config: " + config);
}
}
} catch (Exception e) {
throw new IllegalStateException("Add default config failed: " + configType.getSimpleName(), e);
}
// validate configs
Collection<T> configs = this.getConfigs(configType);
if (getConfigValidator() != null) {
for (T config : configs) {
getConfigValidator().validate(config);
}
}
// check required default
if (isRequired(configType) && configs.isEmpty()) {
throw new IllegalStateException("Default config not found for " + configType.getSimpleName());
}
}
/**
* The component configuration that does not affect the main process does not need to be verified.
*
* @param config
* @param <T>
* @return
*/
protected <T extends AbstractConfig> boolean isNeedValidation(T config) {
return !(config instanceof MetadataReportConfig);
}
private ConfigValidator getConfigValidator() {
if (configValidator == null) {
configValidator = applicationModel.getBeanFactory().getBean(ConfigValidator.class);
}
return configValidator;
}
/**
* The configuration that does not affect the main process is not necessary.
*
* @param clazz
* @param <T>
* @return
*/
protected <T extends AbstractConfig> boolean isRequired(Class<T> clazz) {
return clazz != RegistryConfig.class
&& clazz != MetadataReportConfig.class
&& clazz != MonitorConfig.class
&& clazz != MetricsConfig.class
&& clazz != TracingConfig.class;
}
private <T extends AbstractConfig> boolean shouldAddDefaultConfig(Class<T> clazz) {
// Configurations that are not required will not be automatically added to the default configuration
if (!isRequired(clazz)) {
return false;
}
return this.getDefaultConfigs(clazz).isEmpty();
}
public void refreshAll() {}
/**
* In some scenario, we may need to add and remove ServiceConfig or ReferenceConfig dynamically.
*
* @param config the config instance to remove.
* @return
*/
public boolean removeConfig(AbstractConfig config) {
if (config == null) {
return false;
}
Map<String, AbstractConfig> configs = configsCache.get(getTagName(config.getClass()));
if (CollectionUtils.isNotEmptyMap(configs)) {
// lock by config type
synchronized (configs) {
return removeIfAbsent(config, configs);
}
}
return false;
}
@Override
public void destroy() throws IllegalStateException {
clear();
}
public void clear() {
this.configsCache.clear();
this.configIdIndexes.clear();
this.duplicatedConfigs.clear();
}
public boolean isInitialized() {
return initialized.get();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigConfigurationAdapter.java | dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigConfigurationAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.context;
import org.apache.dubbo.common.config.Configuration;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.AbstractConfig;
import java.util.Map;
/**
* This class receives an {@link AbstractConfig} and exposes its attributes through {@link Configuration}
*/
public class ConfigConfigurationAdapter implements Configuration {
private final Map<String, String> metaData;
public ConfigConfigurationAdapter(AbstractConfig config, String prefix) {
if (StringUtils.hasText(prefix)) {
metaData = config.getMetaData(prefix);
} else {
metaData = config.getMetaData();
}
}
@Override
public Object getInternalProperty(String key) {
return metaData.get(key);
}
public Map<String, String> getProperties() {
return metaData;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigMode.java | dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigMode.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.context;
/**
* Config processing mode for unique config type, e.g. ApplicationConfig, ModuleConfig, MonitorConfig, SslConfig, MetricsConfig
* @see ConfigManager#uniqueConfigTypes
*/
public enum ConfigMode {
/**
* Strict mode: accept only one config for unique config type, throw exceptions if found more than one config for a unique config type.
*/
STRICT,
/**
* Override mode: accept last config, override previous config
*/
OVERRIDE,
/**
* Override mode: accept last config, override previous config regardless of whether the attribute of previous config is absent or not
*/
OVERRIDE_ALL,
/**
* Override mode: accept last config, override previous config only when the attribute of previous config is absent
*/
OVERRIDE_IF_ABSENT,
/**
* Ignore mode: accept first config, ignore later configs
*/
IGNORE
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.