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/rpc/model/DubboStub.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/DubboStub.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.model; /** * Marker interface implemented by all stub. Used to detect * whether objects are Dubbo-generated stub. */ public interface DubboStub {}
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/rpc/model/ScopeModelInitializer.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelInitializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; @SPI(scope = ExtensionScope.SELF) public interface ScopeModelInitializer { default void initializeFrameworkModel(FrameworkModel frameworkModel) {} default void initializeApplicationModel(ApplicationModel applicationModel) {} default void initializeModuleModel(ModuleModel moduleModel) {} }
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/rpc/model/FrameworkServiceRepository.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkServiceRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.StringUtils; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import static org.apache.dubbo.common.BaseServiceMetadata.interfaceFromServiceKey; import static org.apache.dubbo.common.BaseServiceMetadata.versionFromServiceKey; /** * Service repository for framework */ public class FrameworkServiceRepository { private final FrameworkModel frameworkModel; // useful to find a provider model quickly with group/serviceInterfaceName:version private final ConcurrentMap<String, ProviderModel> providers = new ConcurrentHashMap<>(); // useful to find a provider model quickly with serviceInterfaceName:version private final ConcurrentMap<String, List<ProviderModel>> providersWithoutGroup = new ConcurrentHashMap<>(); public FrameworkServiceRepository(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } public void registerProvider(ProviderModel providerModel) { String key = providerModel.getServiceKey(); ProviderModel previous = providers.putIfAbsent(key, providerModel); if (previous != null && previous != providerModel) { // TODO callback service multi instances // throw new IllegalStateException("Register duplicate provider for key: " + key); } String keyWithoutGroup = keyWithoutGroup(key); ConcurrentHashMapUtils.computeIfAbsent( providersWithoutGroup, keyWithoutGroup, (k) -> new CopyOnWriteArrayList<>()) .add(providerModel); } public void unregisterProvider(ProviderModel providerModel) { providers.remove(providerModel.getServiceKey()); String keyWithoutGroup = keyWithoutGroup(providerModel.getServiceKey()); providersWithoutGroup.remove(keyWithoutGroup); } public ProviderModel lookupExportedServiceWithoutGroup(String key) { if (providersWithoutGroup.containsKey(key)) { List<ProviderModel> providerModels = providersWithoutGroup.get(key); return providerModels.size() > 0 ? providerModels.get(0) : null; } else { return null; } } public List<ProviderModel> lookupExportedServicesWithoutGroup(String key) { return providersWithoutGroup.get(key); } public ProviderModel lookupExportedService(String serviceKey) { return providers.get(serviceKey); } public List<ProviderModel> allProviderModels() { return Collections.unmodifiableList(new ArrayList<>(providers.values())); } public List<ConsumerModel> allConsumerModels() { List<ConsumerModel> consumerModels = new LinkedList<>(); frameworkModel .getApplicationModels() .forEach(applicationModel -> consumerModels.addAll( applicationModel.getApplicationServiceRepository().allConsumerModels())); return Collections.unmodifiableList(consumerModels); } private static String keyWithoutGroup(String serviceKey) { String interfaceName = interfaceFromServiceKey(serviceKey); String version = versionFromServiceKey(serviceKey); if (StringUtils.isEmpty(version)) { return interfaceName; } return interfaceName + CommonConstants.GROUP_CHAR_SEPARATOR + version; } }
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/rpc/model/ModuleModel.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ModuleEnvironment; import org.apache.dubbo.common.context.ModuleExt; import org.apache.dubbo.common.deploy.ApplicationDeployer; import org.apache.dubbo.common.deploy.DeployState; import org.apache.dubbo.common.deploy.ModuleDeployer; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.config.context.ModuleConfigManager; import java.util.HashMap; import java.util.Set; import java.util.concurrent.locks.Lock; /** * Model of a service module */ public class ModuleModel extends ScopeModel { private static final Logger logger = LoggerFactory.getLogger(ModuleModel.class); public static final String NAME = "ModuleModel"; private final ApplicationModel applicationModel; private volatile ModuleServiceRepository serviceRepository; private volatile ModuleEnvironment moduleEnvironment; private volatile ModuleConfigManager moduleConfigManager; private volatile ModuleDeployer deployer; private boolean lifeCycleManagedExternally = false; protected ModuleModel(ApplicationModel applicationModel) { this(applicationModel, false); } protected ModuleModel(ApplicationModel applicationModel, boolean isInternal) { super(applicationModel, ExtensionScope.MODULE, isInternal); synchronized (instLock) { Assert.notNull(applicationModel, "ApplicationModel can not be null"); this.applicationModel = applicationModel; applicationModel.addModule(this, isInternal); if (LOGGER.isInfoEnabled()) { LOGGER.info(getDesc() + " is created"); } initialize(); this.serviceRepository = new ModuleServiceRepository(this); initModuleExt(); ExtensionLoader<ScopeModelInitializer> initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); Set<ScopeModelInitializer> initializers = initializerExtensionLoader.getSupportedExtensionInstances(); for (ScopeModelInitializer initializer : initializers) { initializer.initializeModuleModel(this); } Assert.notNull(getServiceRepository(), "ModuleServiceRepository can not be null"); Assert.notNull(getConfigManager(), "ModuleConfigManager can not be null"); Assert.assertTrue(getConfigManager().isInitialized(), "ModuleConfigManager can not be initialized"); // notify application check state ApplicationDeployer applicationDeployer = applicationModel.getDeployer(); if (applicationDeployer != null) { applicationDeployer.notifyModuleChanged(this, DeployState.PENDING); } } } // already synchronized in constructor private void initModuleExt() { Set<ModuleExt> exts = this.getExtensionLoader(ModuleExt.class).getSupportedExtensionInstances(); for (ModuleExt ext : exts) { ext.initialize(); } } @Override protected void onDestroy() { synchronized (instLock) { // 1. remove from applicationModel applicationModel.removeModule(this); // 2. set stopping if (deployer != null) { deployer.preDestroy(); } // 3. release services if (deployer != null) { deployer.postDestroy(); } // destroy other resources notifyDestroy(); if (serviceRepository != null) { serviceRepository.destroy(); serviceRepository = null; } if (moduleEnvironment != null) { moduleEnvironment.destroy(); moduleEnvironment = null; } if (moduleConfigManager != null) { moduleConfigManager.destroy(); moduleConfigManager = null; } // destroy application if none pub module applicationModel.tryDestroy(); } } public ApplicationModel getApplicationModel() { return applicationModel; } public ModuleServiceRepository getServiceRepository() { return serviceRepository; } @Override public void addClassLoader(ClassLoader classLoader) { super.addClassLoader(classLoader); if (moduleEnvironment != null) { moduleEnvironment.refreshClassLoaders(); } } @Override public ModuleEnvironment modelEnvironment() { if (moduleEnvironment == null) { moduleEnvironment = (ModuleEnvironment) this.getExtensionLoader(ModuleExt.class).getExtension(ModuleEnvironment.NAME); } return moduleEnvironment; } public ModuleConfigManager getConfigManager() { if (moduleConfigManager == null) { moduleConfigManager = (ModuleConfigManager) this.getExtensionLoader(ModuleExt.class).getExtension(ModuleConfigManager.NAME); } return moduleConfigManager; } public ModuleDeployer getDeployer() { return deployer; } public void setDeployer(ModuleDeployer deployer) { this.deployer = deployer; } @Override protected Lock acquireDestroyLock() { return getApplicationModel().getFrameworkModel().acquireDestroyLock(); } /** * for ut only */ @Deprecated public void setModuleEnvironment(ModuleEnvironment moduleEnvironment) { this.moduleEnvironment = moduleEnvironment; } public ConsumerModel registerInternalConsumer( Class<?> internalService, URL url, ServiceDescriptor serviceDescriptor, Object proxyObject) { ServiceMetadata serviceMetadata = new ServiceMetadata(); serviceMetadata.setVersion(url.getVersion()); serviceMetadata.setGroup(url.getGroup()); serviceMetadata.setDefaultGroup(url.getGroup()); serviceMetadata.setServiceInterfaceName(internalService.getName()); serviceMetadata.setServiceType(internalService); String serviceKey = URL.buildKey(internalService.getName(), url.getGroup(), url.getVersion()); serviceMetadata.setServiceKey(serviceKey); ConsumerModel consumerModel = new ConsumerModel( serviceMetadata.getServiceKey(), proxyObject, serviceDescriptor == null ? serviceRepository.lookupService(serviceMetadata.getServiceInterfaceName()) : serviceDescriptor, this, serviceMetadata, new HashMap<>(0), ClassUtils.getClassLoader(internalService)); logger.info("[INSTANCE_REGISTER] Dynamically registering consumer model " + serviceKey + " into model " + this.getDesc()); serviceRepository.registerConsumer(consumerModel); return consumerModel; } public ConsumerModel registerInternalConsumer( Class<?> internalService, URL url, ServiceDescriptor serviceDescriptor) { return registerInternalConsumer(internalService, url, serviceDescriptor, null); } public ConsumerModel registerInternalConsumer(Class<?> internalService, URL url) { return registerInternalConsumer(internalService, url, null, null); } public boolean isLifeCycleManagedExternally() { return lifeCycleManagedExternally; } public void setLifeCycleManagedExternally(boolean lifeCycleManagedExternally) { this.lifeCycleManagedExternally = lifeCycleManagedExternally; } }
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/rpc/model/ModelConstants.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModelConstants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.model; public interface ModelConstants { String DEPLOYER = "deployer"; /** * Keep Dubbo running when spring is stopped */ String KEEP_RUNNING_ON_SPRING_CLOSED = "keepRunningOnSpringClosed"; String KEEP_RUNNING_ON_SPRING_CLOSED_KEY = "dubbo.module.keepRunningOnSpringClosed"; }
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/rpc/model/ApplicationInitListener.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationInitListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; @SPI(scope = ExtensionScope.APPLICATION) public interface ApplicationInitListener { /** * init the application */ void init(); }
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/rpc/model/ApplicationModel.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.config.Environment; import org.apache.dubbo.common.context.ApplicationExt; import org.apache.dubbo.common.deploy.ApplicationDeployer; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; /** * {@link ExtensionLoader}, {@code DubboBootstrap} and this class are at present designed to be * singleton or static (by itself totally static or uses some static fields). So the instances * returned from them are of process scope. If you want to support multiple dubbo servers in one * single process, you may need to refactor those three classes. * <p> * Represent an application which is using Dubbo and store basic metadata info for using * during the processing of RPC invoking. * <p> * ApplicationModel includes many ProviderModel which is about published services * and many Consumer Model which is about subscribed services. * <p> */ public class ApplicationModel extends ScopeModel { protected static final Logger LOGGER = LoggerFactory.getLogger(ApplicationModel.class); public static final String NAME = "ApplicationModel"; private final List<ModuleModel> moduleModels = new CopyOnWriteArrayList<>(); private final List<ModuleModel> pubModuleModels = new CopyOnWriteArrayList<>(); private volatile Environment environment; private volatile ConfigManager configManager; private volatile ServiceRepository serviceRepository; private volatile ApplicationDeployer deployer; private final FrameworkModel frameworkModel; private final ModuleModel internalModule; private volatile ModuleModel defaultModule; // internal module index is 0, default module index is 1 private final AtomicInteger moduleIndex = new AtomicInteger(0); // --------- static methods ----------// public static ApplicationModel ofNullable(ApplicationModel applicationModel) { if (applicationModel != null) { return applicationModel; } else { return defaultModel(); } } /** * During destroying the default FrameworkModel, the FrameworkModel.defaultModel() or ApplicationModel.defaultModel() * will return a broken model, maybe cause unpredictable problem. * Recommendation: Avoid using the default model as much as possible. * * @return the global default ApplicationModel */ public static ApplicationModel defaultModel() { // should get from default FrameworkModel, avoid out of sync return FrameworkModel.defaultModel().defaultApplication(); } // ------------- instance methods ---------------// protected ApplicationModel(FrameworkModel frameworkModel) { this(frameworkModel, false); } protected ApplicationModel(FrameworkModel frameworkModel, boolean isInternal) { super(frameworkModel, ExtensionScope.APPLICATION, isInternal); synchronized (instLock) { Assert.notNull(frameworkModel, "FrameworkModel can not be null"); this.frameworkModel = frameworkModel; frameworkModel.addApplication(this); if (LOGGER.isInfoEnabled()) { LOGGER.info(getDesc() + " is created"); } initialize(); this.internalModule = new ModuleModel(this, true); this.serviceRepository = new ServiceRepository(this); ExtensionLoader<ApplicationInitListener> extensionLoader = this.getExtensionLoader(ApplicationInitListener.class); Set<String> listenerNames = extensionLoader.getSupportedExtensions(); for (String listenerName : listenerNames) { extensionLoader.getExtension(listenerName).init(); } initApplicationExts(); ExtensionLoader<ScopeModelInitializer> initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); Set<ScopeModelInitializer> initializers = initializerExtensionLoader.getSupportedExtensionInstances(); for (ScopeModelInitializer initializer : initializers) { initializer.initializeApplicationModel(this); } Assert.notNull(getApplicationServiceRepository(), "ApplicationServiceRepository can not be null"); Assert.notNull(getApplicationConfigManager(), "ApplicationConfigManager can not be null"); Assert.assertTrue( getApplicationConfigManager().isInitialized(), "ApplicationConfigManager can not be initialized"); } } // already synchronized in constructor private void initApplicationExts() { Set<ApplicationExt> exts = this.getExtensionLoader(ApplicationExt.class).getSupportedExtensionInstances(); for (ApplicationExt ext : exts) { ext.initialize(); } } @Override protected void onDestroy() { synchronized (instLock) { // 1. remove from frameworkModel frameworkModel.removeApplication(this); // 2. pre-destroy, set stopping if (deployer != null) { // destroy registries and unregister services from registries first to notify consumers to stop // consuming this instance. deployer.preDestroy(); } // 3. Try to destroy protocols to stop this instance from receiving new requests from connections frameworkModel.tryDestroyProtocols(); // 4. destroy application resources for (ModuleModel moduleModel : moduleModels) { if (moduleModel != internalModule) { moduleModel.destroy(); } } // 5. destroy internal module later internalModule.destroy(); // 6. post-destroy, release registry resources if (deployer != null) { deployer.postDestroy(); } // 7. destroy other resources (e.g. ZookeeperTransporter ) notifyDestroy(); if (environment != null) { environment.destroy(); environment = null; } if (configManager != null) { configManager.destroy(); configManager = null; } if (serviceRepository != null) { serviceRepository.destroy(); serviceRepository = null; } // 8. destroy framework if none application frameworkModel.tryDestroy(); } } public FrameworkModel getFrameworkModel() { return frameworkModel; } public ModuleModel newModule() { synchronized (instLock) { return new ModuleModel(this); } } @Override public Environment modelEnvironment() { if (environment == null) { environment = (Environment) this.getExtensionLoader(ApplicationExt.class).getExtension(Environment.NAME); } return environment; } public ConfigManager getApplicationConfigManager() { if (configManager == null) { configManager = (ConfigManager) this.getExtensionLoader(ApplicationExt.class).getExtension(ConfigManager.NAME); } return configManager; } public ServiceRepository getApplicationServiceRepository() { return serviceRepository; } public ExecutorRepository getApplicationExecutorRepository() { return ExecutorRepository.getInstance(this); } public boolean NotExistApplicationConfig() { return !getApplicationConfigManager().getApplication().isPresent(); } public ApplicationConfig getCurrentConfig() { return getApplicationConfigManager().getApplicationOrElseThrow(); } public String getApplicationName() { return getCurrentConfig().getName(); } public String tryGetApplicationName() { Optional<ApplicationConfig> appCfgOptional = getApplicationConfigManager().getApplication(); return appCfgOptional.isPresent() ? appCfgOptional.get().getName() : null; } void addModule(ModuleModel moduleModel, boolean isInternal) { synchronized (instLock) { if (!this.moduleModels.contains(moduleModel)) { checkDestroyed(); this.moduleModels.add(moduleModel); moduleModel.setInternalId(buildInternalId(getInternalId(), moduleIndex.getAndIncrement())); if (!isInternal) { pubModuleModels.add(moduleModel); } } } } public void removeModule(ModuleModel moduleModel) { synchronized (instLock) { this.moduleModels.remove(moduleModel); this.pubModuleModels.remove(moduleModel); if (moduleModel == defaultModule) { defaultModule = findDefaultModule(); } } } void tryDestroy() { synchronized (instLock) { if (this.moduleModels.isEmpty() || (this.moduleModels.size() == 1 && this.moduleModels.get(0) == internalModule)) { destroy(); } } } private void checkDestroyed() { if (isDestroyed()) { throw new IllegalStateException("ApplicationModel is destroyed"); } } public List<ModuleModel> getModuleModels() { return Collections.unmodifiableList(moduleModels); } public List<ModuleModel> getPubModuleModels() { return Collections.unmodifiableList(pubModuleModels); } public ModuleModel getDefaultModule() { if (defaultModule == null) { synchronized (instLock) { if (defaultModule == null) { defaultModule = findDefaultModule(); if (defaultModule == null) { defaultModule = this.newModule(); } } } } return defaultModule; } private ModuleModel findDefaultModule() { synchronized (instLock) { for (ModuleModel moduleModel : moduleModels) { if (moduleModel != internalModule) { return moduleModel; } } return null; } } public ModuleModel getInternalModule() { return internalModule; } @Override public void addClassLoader(ClassLoader classLoader) { super.addClassLoader(classLoader); if (environment != null) { environment.refreshClassLoaders(); } } @Override public void removeClassLoader(ClassLoader classLoader) { super.removeClassLoader(classLoader); if (environment != null) { environment.refreshClassLoaders(); } } @Override protected boolean checkIfClassLoaderCanRemoved(ClassLoader classLoader) { return super.checkIfClassLoaderCanRemoved(classLoader) && !containsClassLoader(classLoader); } protected boolean containsClassLoader(ClassLoader classLoader) { return moduleModels.stream() .anyMatch(moduleModel -> moduleModel.getClassLoaders().contains(classLoader)); } public ApplicationDeployer getDeployer() { return deployer; } public void setDeployer(ApplicationDeployer deployer) { this.deployer = deployer; } @Override protected Lock acquireDestroyLock() { return frameworkModel.acquireDestroyLock(); } // =============================== Deprecated Methods Start ======================================= /** * @deprecated use {@link ServiceRepository#allConsumerModels()} */ @Deprecated public static Collection<ConsumerModel> allConsumerModels() { return defaultModel().getApplicationServiceRepository().allConsumerModels(); } /** * @deprecated use {@link ServiceRepository#allProviderModels()} */ @Deprecated public static Collection<ProviderModel> allProviderModels() { return defaultModel().getApplicationServiceRepository().allProviderModels(); } /** * @deprecated use {@link FrameworkServiceRepository#lookupExportedService(String)} */ @Deprecated public static ProviderModel getProviderModel(String serviceKey) { return defaultModel().getDefaultModule().getServiceRepository().lookupExportedService(serviceKey); } /** * @deprecated ConsumerModel should fetch from context */ @Deprecated public static ConsumerModel getConsumerModel(String serviceKey) { return defaultModel().getDefaultModule().getServiceRepository().lookupReferredService(serviceKey); } /** * @deprecated Replace to {@link ScopeModel#modelEnvironment()} */ @Deprecated public static Environment getEnvironment() { return defaultModel().modelEnvironment(); } /** * @deprecated Replace to {@link ApplicationModel#getApplicationConfigManager()} */ @Deprecated public static ConfigManager getConfigManager() { return defaultModel().getApplicationConfigManager(); } /** * @deprecated Replace to {@link ApplicationModel#getApplicationServiceRepository()} */ @Deprecated public static ServiceRepository getServiceRepository() { return defaultModel().getApplicationServiceRepository(); } /** * @deprecated Replace to {@link ApplicationModel#getApplicationExecutorRepository()} */ @Deprecated public static ExecutorRepository getExecutorRepository() { return defaultModel().getApplicationExecutorRepository(); } /** * @deprecated Replace to {@link ApplicationModel#getCurrentConfig()} */ @Deprecated public static ApplicationConfig getApplicationConfig() { return defaultModel().getCurrentConfig(); } /** * @deprecated Replace to {@link ApplicationModel#getApplicationName()} */ @Deprecated public static String getName() { return defaultModel().getCurrentConfig().getName(); } /** * @deprecated Replace to {@link ApplicationModel#getApplicationName()} */ @Deprecated public static String getApplication() { return getName(); } // only for unit test @Deprecated public static void reset() { if (FrameworkModel.defaultModel().getDefaultAppModel() != null) { FrameworkModel.defaultModel().getDefaultAppModel().destroy(); } } /** * @deprecated only for ut */ @Deprecated public void setEnvironment(Environment environment) { this.environment = environment; } /** * @deprecated only for ut */ @Deprecated public void setConfigManager(ConfigManager configManager) { this.configManager = configManager; } /** * @deprecated only for ut */ @Deprecated public void setServiceRepository(ServiceRepository serviceRepository) { this.serviceRepository = serviceRepository; } // =============================== Deprecated Methods End ======================================= }
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/rpc/model/ConsumerModel.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.utils.Assert; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.TreeSet; /** * This model is bound to your reference's configuration, for example, group, version or method level configuration. */ public class ConsumerModel extends ServiceModel { private final Set<String> apps = new TreeSet<>(); private final Map<String, AsyncMethodInfo> methodConfigs; private Map<Method, ConsumerMethodModel> methodModels = new HashMap<>(); /** * This constructor creates an instance of ConsumerModel and passed objects should not be null. * If service name, service instance, proxy object,methods should not be null. If these are null * then this constructor will throw {@link IllegalArgumentException} * * @param serviceKey Name of the service. * @param proxyObject Proxy object. */ public ConsumerModel( String serviceKey, Object proxyObject, ServiceDescriptor serviceDescriptor, Map<String, AsyncMethodInfo> methodConfigs, ClassLoader interfaceClassLoader) { super(proxyObject, serviceKey, serviceDescriptor, null, interfaceClassLoader); Assert.notEmptyString(serviceKey, "Service name can't be null or blank"); this.methodConfigs = methodConfigs == null ? new HashMap<>() : methodConfigs; } public ConsumerModel( String serviceKey, Object proxyObject, ServiceDescriptor serviceDescriptor, ServiceMetadata metadata, Map<String, AsyncMethodInfo> methodConfigs, ClassLoader interfaceClassLoader) { super(proxyObject, serviceKey, serviceDescriptor, null, metadata, interfaceClassLoader); Assert.notEmptyString(serviceKey, "Service name can't be null or blank"); this.methodConfigs = methodConfigs == null ? new HashMap<>() : methodConfigs; } public ConsumerModel( String serviceKey, Object proxyObject, ServiceDescriptor serviceDescriptor, ModuleModel moduleModel, ServiceMetadata metadata, Map<String, AsyncMethodInfo> methodConfigs, ClassLoader interfaceClassLoader) { super(proxyObject, serviceKey, serviceDescriptor, moduleModel, metadata, interfaceClassLoader); Assert.notEmptyString(serviceKey, "Service name can't be null or blank"); this.methodConfigs = methodConfigs == null ? new HashMap<>() : methodConfigs; } public AsyncMethodInfo getMethodConfig(String methodName) { return methodConfigs.get(methodName); } public Set<String> getApps() { return apps; } public AsyncMethodInfo getAsyncInfo(String methodName) { return methodConfigs.get(methodName); } public void initMethodModels() { Class<?>[] interfaceList; if (getProxyObject() == null) { Class<?> serviceInterfaceClass = getServiceInterfaceClass(); if (serviceInterfaceClass != null) { interfaceList = new Class[] {serviceInterfaceClass}; } else { interfaceList = new Class[0]; } } else { interfaceList = getProxyObject().getClass().getInterfaces(); } for (Class<?> interfaceClass : interfaceList) { for (Method method : interfaceClass.getMethods()) { methodModels.put(method, new ConsumerMethodModel(method)); } } } /** * Return method model for the given method on consumer side * * @param method method object * @return method model */ public ConsumerMethodModel getMethodModel(Method method) { return methodModels.get(method); } /** * Return method model for the given method on consumer side * * @param method method object * @return method model */ public ConsumerMethodModel getMethodModel(String method) { Optional<Map.Entry<Method, ConsumerMethodModel>> consumerMethodModelEntry = methodModels.entrySet().stream() .filter(entry -> entry.getKey().getName().equals(method)) .findFirst(); return consumerMethodModelEntry.map(Map.Entry::getValue).orElse(null); } /** * @param method methodName * @param argsType method arguments type * @return */ public ConsumerMethodModel getMethodModel(String method, String[] argsType) { Optional<ConsumerMethodModel> consumerMethodModel = methodModels.entrySet().stream() .filter(entry -> entry.getKey().getName().equals(method)) .map(Map.Entry::getValue) .filter(methodModel -> Arrays.equals(argsType, methodModel.getParameterTypes())) .findFirst(); return consumerMethodModel.orElse(null); } /** * Return all method models for the current service * * @return method model list */ public List<ConsumerMethodModel> getAllMethodModels() { return new ArrayList<>(methodModels.values()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ConsumerModel that = (ConsumerModel) o; return Objects.equals(apps, that.apps) && Objects.equals(methodConfigs, that.methodConfigs) && Objects.equals(methodModels, that.methodModels); } @Override public int hashCode() { return Objects.hash(super.hashCode(), apps, methodConfigs, methodModels); } }
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/rpc/model/StubServiceDescriptor.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/StubServiceDescriptor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; public class StubServiceDescriptor implements ServiceDescriptor { private final String interfaceName; private final Class<?> serviceInterfaceClass; // to accelerate search private final Map<String, List<MethodDescriptor>> methods = new HashMap<>(); private final Map<String, Map<String, MethodDescriptor>> descToMethods = new HashMap<>(); private final ConcurrentNavigableMap<String, FullServiceDefinition> serviceDefinitions = new ConcurrentSkipListMap<>(); public StubServiceDescriptor(String interfaceName, Class<?> interfaceClass) { this.interfaceName = interfaceName; this.serviceInterfaceClass = interfaceClass; } public void addMethod(MethodDescriptor methodDescriptor) { doAddMethod(methodDescriptor.getMethodName(), methodDescriptor); if (methods.containsKey(methodDescriptor.getJavaMethodName())) { return; } doAddMethod(methodDescriptor.getJavaMethodName(), methodDescriptor); } private void doAddMethod(String methodName, MethodDescriptor methodDescriptor) { methods.put(methodName, Collections.singletonList(methodDescriptor)); descToMethods .computeIfAbsent(methodName, k -> new HashMap<>()) .put(methodDescriptor.getParamDesc(), methodDescriptor); } public FullServiceDefinition getFullServiceDefinition(String serviceKey) { return serviceDefinitions.computeIfAbsent( serviceKey, (k) -> ServiceDefinitionBuilder.buildFullDefinition(serviceInterfaceClass, Collections.emptyMap())); } public String getInterfaceName() { return interfaceName; } public Class<?> getServiceInterfaceClass() { return serviceInterfaceClass; } public Set<MethodDescriptor> getAllMethods() { Set<MethodDescriptor> methodModels = new HashSet<>(); methods.forEach((k, v) -> methodModels.addAll(v)); return methodModels; } /** * Does not use Optional as return type to avoid potential performance decrease. * */ public MethodDescriptor getMethod(String methodName, String params) { Map<String, MethodDescriptor> methods = descToMethods.get(methodName); if (CollectionUtils.isNotEmptyMap(methods)) { return methods.get(params); } return null; } /** * Does not use Optional as return type to avoid potential performance decrease. * */ public MethodDescriptor getMethod(String methodName, Class<?>[] paramTypes) { List<MethodDescriptor> methodModels = methods.get(methodName); if (CollectionUtils.isNotEmpty(methodModels)) { for (MethodDescriptor descriptor : methodModels) { if (Arrays.equals(paramTypes, descriptor.getParameterClasses())) { return descriptor; } } } return null; } public List<MethodDescriptor> getMethods(String methodName) { return methods.get(methodName); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } StubServiceDescriptor that = (StubServiceDescriptor) o; return Objects.equals(interfaceName, that.interfaceName) && Objects.equals(serviceInterfaceClass, that.serviceInterfaceClass) && Objects.equals(methods, that.methods) && Objects.equals(descToMethods, that.descToMethods); } @Override public int hashCode() { return Objects.hash(interfaceName, serviceInterfaceClass, methods, descToMethods); } }
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/rpc/model/ReflectionServiceDescriptor.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ReflectionServiceDescriptor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; public class ReflectionServiceDescriptor implements ServiceDescriptor { private final String interfaceName; private final Class<?> serviceInterfaceClass; // to accelerate search private final Map<String, List<MethodDescriptor>> methods = new HashMap<>(); private final Map<String, Map<String, MethodDescriptor>> descToMethods = new HashMap<>(); private final ConcurrentNavigableMap<String, FullServiceDefinition> serviceDefinitions = new ConcurrentSkipListMap<>(); public ReflectionServiceDescriptor(String interfaceName, Class<?> interfaceClass) { this.interfaceName = interfaceName; this.serviceInterfaceClass = interfaceClass; } public void addMethod(MethodDescriptor methodDescriptor) { methods.computeIfAbsent(methodDescriptor.getMethodName(), k -> new ArrayList<>(1)) .add(methodDescriptor); } public ReflectionServiceDescriptor(Class<?> interfaceClass) { this.serviceInterfaceClass = interfaceClass; this.interfaceName = interfaceClass.getName(); initMethods(); } public FullServiceDefinition getFullServiceDefinition(String serviceKey) { return serviceDefinitions.computeIfAbsent( serviceKey, (k) -> ServiceDefinitionBuilder.buildFullDefinition(serviceInterfaceClass, Collections.emptyMap())); } private void initMethods() { Method[] methodsToExport = this.serviceInterfaceClass.getMethods(); for (Method method : methodsToExport) { method.setAccessible(true); MethodDescriptor methodDescriptor = new ReflectionMethodDescriptor(method); List<MethodDescriptor> methodModels = methods.computeIfAbsent(method.getName(), (k) -> new ArrayList<>(1)); methodModels.add(methodDescriptor); } methods.forEach((methodName, methodList) -> { Map<String, MethodDescriptor> descMap = descToMethods.computeIfAbsent(methodName, k -> new HashMap<>()); // not support BI_STREAM and SERVER_STREAM at the same time, for example, // void foo(Request, StreamObserver<Response>) ---> SERVER_STREAM // StreamObserver<Response> foo(StreamObserver<Request>) ---> BI_STREAM long streamMethodCount = methodList.stream() .peek(methodModel -> descMap.put(methodModel.getParamDesc(), methodModel)) .map(MethodDescriptor::getRpcType) .filter(rpcType -> rpcType == MethodDescriptor.RpcType.SERVER_STREAM || rpcType == MethodDescriptor.RpcType.BI_STREAM) .count(); if (streamMethodCount > 1L) throw new IllegalStateException("Stream method could not be overloaded.There are " + streamMethodCount + " stream method signatures. method(" + methodName + ")"); }); } public String getInterfaceName() { return interfaceName; } public Class<?> getServiceInterfaceClass() { return serviceInterfaceClass; } public Set<MethodDescriptor> getAllMethods() { Set<MethodDescriptor> methodModels = new HashSet<>(); methods.forEach((k, v) -> methodModels.addAll(v)); return methodModels; } /** * Does not use Optional as return type to avoid potential performance decrease. * * @param methodName * @param params * @return */ public MethodDescriptor getMethod(String methodName, String params) { Map<String, MethodDescriptor> methods = descToMethods.get(methodName); if (CollectionUtils.isNotEmptyMap(methods)) { return methods.get(params); } return null; } /** * Does not use Optional as return type to avoid potential performance decrease. * * @param methodName * @param paramTypes * @return */ public MethodDescriptor getMethod(String methodName, Class<?>[] paramTypes) { List<MethodDescriptor> methodModels = methods.get(methodName); if (CollectionUtils.isNotEmpty(methodModels)) { for (MethodDescriptor descriptor : methodModels) { if (Arrays.equals(paramTypes, descriptor.getParameterClasses())) { return descriptor; } } } return null; } public List<MethodDescriptor> getMethods(String methodName) { return methods.get(methodName); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ReflectionServiceDescriptor that = (ReflectionServiceDescriptor) o; return Objects.equals(interfaceName, that.interfaceName) && Objects.equals(serviceInterfaceClass, that.serviceInterfaceClass) && Objects.equals(methods, that.methods) && Objects.equals(descToMethods, that.descToMethods); } @Override public int hashCode() { return Objects.hash(interfaceName, serviceInterfaceClass, methods, descToMethods); } }
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/rpc/model/Pack.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/model/Pack.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.model; public interface Pack { /** * @param obj instance * @return byte array * @throws Exception when error occurs */ byte[] pack(Object obj) throws Exception; }
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/rpc/executor/DefaultIsolationExecutorSupportFactory.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/DefaultIsolationExecutorSupportFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.executor; import org.apache.dubbo.common.URL; public class DefaultIsolationExecutorSupportFactory implements IsolationExecutorSupportFactory { @Override public ExecutorSupport createIsolationExecutorSupport(URL url) { return new DefaultExecutorSupport(url); } }
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/rpc/executor/AbstractIsolationExecutorSupport.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/AbstractIsolationExecutorSupport.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.executor; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.rpc.model.FrameworkServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import java.util.List; import java.util.concurrent.Executor; public abstract class AbstractIsolationExecutorSupport implements ExecutorSupport { private final URL url; private final ExecutorRepository executorRepository; private final FrameworkServiceRepository frameworkServiceRepository; public AbstractIsolationExecutorSupport(URL url) { this.url = url; this.executorRepository = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()); this.frameworkServiceRepository = url.getOrDefaultFrameworkModel().getServiceRepository(); } @Override public Executor getExecutor(Object data) { ProviderModel providerModel = getProviderModel(data); if (providerModel == null) { return executorRepository.getExecutor(url); } List<URL> serviceUrls = providerModel.getServiceUrls(); if (serviceUrls == null || serviceUrls.isEmpty()) { return executorRepository.getExecutor(url); } for (URL serviceUrl : serviceUrls) { if (serviceUrl.getProtocol().equals(url.getProtocol()) && serviceUrl.getPort() == url.getPort()) { return executorRepository.getExecutor(providerModel, serviceUrl); } } return executorRepository.getExecutor(providerModel, serviceUrls.get(0)); } protected String getServiceKey(Object data) { return null; } protected ProviderModel getProviderModel(Object data) { String serviceKey = getServiceKey(data); return serviceKey == null ? null : frameworkServiceRepository.lookupExportedService(serviceKey); } }
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/rpc/executor/DefaultExecutorSupport.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/DefaultExecutorSupport.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.executor; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import java.util.concurrent.Executor; public class DefaultExecutorSupport implements ExecutorSupport { private final ExecutorRepository executorRepository; private final URL url; public DefaultExecutorSupport(URL url) { this.url = url; this.executorRepository = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()); } @Override public Executor getExecutor(Object data) { return executorRepository.getExecutor(url); } }
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/rpc/executor/ExecutorSupport.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/ExecutorSupport.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.executor; import java.util.concurrent.Executor; public interface ExecutorSupport { Executor getExecutor(Object data); }
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/rpc/executor/IsolationExecutorSupportFactory.java
dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.executor; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.rpc.model.ApplicationModel; @SPI("default") public interface IsolationExecutorSupportFactory { ExecutorSupport createIsolationExecutorSupport(URL url); static ExecutorSupport getIsolationExecutorSupport(URL url) { ApplicationModel applicationModel = url.getOrDefaultApplicationModel(); ExtensionLoader<IsolationExecutorSupportFactory> extensionLoader = applicationModel.getExtensionLoader(IsolationExecutorSupportFactory.class); IsolationExecutorSupportFactory factory = extensionLoader.getOrDefaultExtension(url.getProtocol()); return factory.createIsolationExecutorSupport(url); } }
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/URLStrParser.java
dubbo-common/src/main/java/org/apache/dubbo/common/URLStrParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.url.component.URLItemCache; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; import static org.apache.dubbo.common.utils.StringUtils.EMPTY_STRING; import static org.apache.dubbo.common.utils.StringUtils.decodeHexByte; import static org.apache.dubbo.common.utils.Utf8Utils.decodeUtf8; public final class URLStrParser { public static final String ENCODED_QUESTION_MARK = "%3F"; public static final String ENCODED_TIMESTAMP_KEY = "timestamp%3D"; public static final String ENCODED_PID_KEY = "pid%3D"; public static final String ENCODED_AND_MARK = "%26"; private static final char SPACE = 0x20; private static final ThreadLocal<TempBuf> DECODE_TEMP_BUF = ThreadLocal.withInitial(() -> new TempBuf(1024)); private URLStrParser() { // empty } /** * @param decodedURLStr : after {@link URL#decode} string * decodedURLStr format: protocol://username:password@host:port/path?k1=v1&k2=v2 * [protocol://][username:password@][host:port]/[path][?k1=v1&k2=v2] */ public static URL parseDecodedStr(String decodedURLStr) { Map<String, String> parameters = null; int pathEndIdx = decodedURLStr.indexOf('?'); if (pathEndIdx >= 0) { parameters = parseDecodedParams(decodedURLStr, pathEndIdx + 1); } else { pathEndIdx = decodedURLStr.length(); } String decodedBody = decodedURLStr.substring(0, pathEndIdx); return parseURLBody(decodedURLStr, decodedBody, parameters); } private static Map<String, String> parseDecodedParams(String str, int from) { int len = str.length(); if (from >= len) { return Collections.emptyMap(); } TempBuf tempBuf = DECODE_TEMP_BUF.get(); Map<String, String> params = new HashMap<>(); int nameStart = from; int valueStart = -1; int i; for (i = from; i < len; i++) { char ch = str.charAt(i); switch (ch) { case '=': if (nameStart == i) { nameStart = i + 1; } else if (valueStart < nameStart) { valueStart = i + 1; } break; case ';': case '&': addParam(str, false, nameStart, valueStart, i, params, tempBuf); nameStart = i + 1; break; default: // continue } } addParam(str, false, nameStart, valueStart, i, params, tempBuf); return params; } /** * @param fullURLStr : fullURLString * @param decodedBody : format: [protocol://][username:password@][host:port]/[path] * @param parameters : * @return URL */ private static URL parseURLBody(String fullURLStr, String decodedBody, Map<String, String> parameters) { int starIdx = 0, endIdx = decodedBody.length(); // ignore the url content following '#' int poundIndex = decodedBody.indexOf('#'); if (poundIndex != -1) { endIdx = poundIndex; } String protocol = null; int protoEndIdx = decodedBody.indexOf("://"); if (protoEndIdx >= 0) { if (protoEndIdx == 0) { throw new IllegalStateException("url missing protocol: \"" + fullURLStr + "\""); } protocol = decodedBody.substring(0, protoEndIdx); starIdx = protoEndIdx + 3; } else { // case: file:/path/to/file.txt protoEndIdx = decodedBody.indexOf(":/"); if (protoEndIdx >= 0) { if (protoEndIdx == 0) { throw new IllegalStateException("url missing protocol: \"" + fullURLStr + "\""); } protocol = decodedBody.substring(0, protoEndIdx); starIdx = protoEndIdx + 1; } } String path = null; int pathStartIdx = indexOf(decodedBody, '/', starIdx, endIdx); if (pathStartIdx >= 0) { path = decodedBody.substring(pathStartIdx + 1, endIdx); endIdx = pathStartIdx; } String username = null; String password = null; int pwdEndIdx = lastIndexOf(decodedBody, '@', starIdx, endIdx); if (pwdEndIdx > 0) { int passwordStartIdx = indexOf(decodedBody, ':', starIdx, pwdEndIdx); if (passwordStartIdx != -1) { // tolerate incomplete user pwd input, like '1234@' username = decodedBody.substring(starIdx, passwordStartIdx); password = decodedBody.substring(passwordStartIdx + 1, pwdEndIdx); } else { username = decodedBody.substring(starIdx, pwdEndIdx); } starIdx = pwdEndIdx + 1; } String host = null; int port = 0; int hostEndIdx = lastIndexOf(decodedBody, ':', starIdx, endIdx); if (hostEndIdx > 0 && hostEndIdx < decodedBody.length() - 1) { if (lastIndexOf(decodedBody, '%', starIdx, endIdx) > hostEndIdx) { // ipv6 address with scope id // e.g. fe80:0:0:0:894:aeec:f37d:23e1%en0 // see https://howdoesinternetwork.com/2013/ipv6-zone-id // ignore } else { port = Integer.parseInt(decodedBody.substring(hostEndIdx + 1, endIdx)); endIdx = hostEndIdx; } } if (endIdx > starIdx) { host = decodedBody.substring(starIdx, endIdx); } // check cache protocol = URLItemCache.intern(protocol); path = URLItemCache.checkPath(path); return new ServiceConfigURL(protocol, username, password, host, port, path, parameters); } public static String[] parseRawURLToArrays(String rawURLStr, int pathEndIdx) { String[] parts = new String[2]; int paramStartIdx = pathEndIdx + 3; // skip ENCODED_QUESTION_MARK if (pathEndIdx == -1) { pathEndIdx = rawURLStr.indexOf('?'); if (pathEndIdx == -1) { // url with no params, decode anyway rawURLStr = URL.decode(rawURLStr); } else { paramStartIdx = pathEndIdx + 1; } } if (pathEndIdx >= 0) { parts[0] = rawURLStr.substring(0, pathEndIdx); parts[1] = rawURLStr.substring(paramStartIdx); } else { parts = new String[] {rawURLStr}; } return parts; } public static Map<String, String> parseParams(String rawParams, boolean encoded) { if (encoded) { return parseEncodedParams(rawParams, 0); } return parseDecodedParams(rawParams, 0); } /** * @param encodedURLStr : after {@link URL#encode(String)} string * encodedURLStr after decode format: protocol://username:password@host:port/path?k1=v1&k2=v2 * [protocol://][username:password@][host:port]/[path][?k1=v1&k2=v2] */ public static URL parseEncodedStr(String encodedURLStr) { Map<String, String> parameters = null; int pathEndIdx = encodedURLStr.toUpperCase().indexOf("%3F"); // '?' if (pathEndIdx >= 0) { parameters = parseEncodedParams(encodedURLStr, pathEndIdx + 3); } else { pathEndIdx = encodedURLStr.length(); } // decodedBody format: [protocol://][username:password@][host:port]/[path] String decodedBody = decodeComponent(encodedURLStr, 0, pathEndIdx, false, DECODE_TEMP_BUF.get()); return parseURLBody(encodedURLStr, decodedBody, parameters); } private static Map<String, String> parseEncodedParams(String str, int from) { int len = str.length(); if (from >= len) { return Collections.emptyMap(); } TempBuf tempBuf = DECODE_TEMP_BUF.get(); Map<String, String> params = new HashMap<>(); int nameStart = from; int valueStart = -1; int i; for (i = from; i < len; i++) { char ch = str.charAt(i); if (ch == '%') { if (i + 3 > len) { throw new IllegalArgumentException("unterminated escape sequence at index " + i + " of: " + str); } ch = (char) decodeHexByte(str, i + 1); i += 2; } switch (ch) { case '=': if (nameStart == i) { nameStart = i + 1; } else if (valueStart < nameStart) { valueStart = i + 1; } break; case ';': case '&': addParam(str, true, nameStart, valueStart, i - 2, params, tempBuf); nameStart = i + 1; break; default: // continue } } addParam(str, true, nameStart, valueStart, i, params, tempBuf); return params; } private static boolean addParam( String str, boolean isEncoded, int nameStart, int valueStart, int valueEnd, Map<String, String> params, TempBuf tempBuf) { if (nameStart >= valueEnd) { return false; } if (valueStart <= nameStart) { valueStart = valueEnd + 1; } if (isEncoded) { String name = decodeComponent(str, nameStart, valueStart - 3, false, tempBuf); String value; if (valueStart >= valueEnd) { value = ""; } else { value = decodeComponent(str, valueStart, valueEnd, false, tempBuf); } URLItemCache.putParams(params, name, value); // compatible with lower versions registering "default." keys if (name.startsWith(DEFAULT_KEY_PREFIX)) { params.putIfAbsent(name.substring(DEFAULT_KEY_PREFIX.length()), value); } } else { String name = str.substring(nameStart, valueStart - 1); String value; if (valueStart >= valueEnd) { value = ""; } else { value = str.substring(valueStart, valueEnd); } URLItemCache.putParams(params, name, value); // compatible with lower versions registering "default." keys if (name.startsWith(DEFAULT_KEY_PREFIX)) { params.putIfAbsent(name.substring(DEFAULT_KEY_PREFIX.length()), value); } } return true; } private static String decodeComponent(String s, int from, int toExcluded, boolean isPath, TempBuf tempBuf) { int len = toExcluded - from; if (len <= 0) { return EMPTY_STRING; } int firstEscaped = -1; for (int i = from; i < toExcluded; i++) { char c = s.charAt(i); if (c == '%' || c == '+' && !isPath) { firstEscaped = i; break; } } if (firstEscaped == -1) { return s.substring(from, toExcluded); } // Each encoded byte takes 3 characters (e.g. "%20") int decodedCapacity = (toExcluded - firstEscaped) / 3; byte[] buf = tempBuf.byteBuf(decodedCapacity); char[] charBuf = tempBuf.charBuf(len); s.getChars(from, firstEscaped, charBuf, 0); int charBufIdx = firstEscaped - from; return decodeUtf8Component(s, firstEscaped, toExcluded, isPath, buf, charBuf, charBufIdx); } private static String decodeUtf8Component( String str, int firstEscaped, int toExcluded, boolean isPath, byte[] buf, char[] charBuf, int charBufIdx) { int bufIdx; for (int i = firstEscaped; i < toExcluded; i++) { char c = str.charAt(i); if (c != '%') { charBuf[charBufIdx++] = c != '+' || isPath ? c : SPACE; continue; } bufIdx = 0; do { if (i + 3 > toExcluded) { throw new IllegalArgumentException("unterminated escape sequence at index " + i + " of: " + str); } buf[bufIdx++] = decodeHexByte(str, i + 1); i += 3; } while (i < toExcluded && str.charAt(i) == '%'); i--; charBufIdx += decodeUtf8(buf, 0, bufIdx, charBuf, charBufIdx); } return new String(charBuf, 0, charBufIdx); } private static int indexOf(String str, char ch, int from, int toExclude) { from = Math.max(from, 0); toExclude = Math.min(toExclude, str.length()); if (from > toExclude) { return -1; } for (int i = from; i < toExclude; i++) { if (str.charAt(i) == ch) { return i; } } return -1; } private static int lastIndexOf(String str, char ch, int from, int toExclude) { from = Math.max(from, 0); toExclude = Math.min(toExclude, str.length() - 1); if (from > toExclude) { return -1; } for (int i = toExclude; i >= from; i--) { if (str.charAt(i) == ch) { return i; } } return -1; } private static final class TempBuf { private final char[] chars; private final byte[] bytes; TempBuf(int bufSize) { this.chars = new char[bufSize]; this.bytes = new byte[bufSize]; } public char[] charBuf(int size) { char[] chars = this.chars; if (size <= chars.length) { return chars; } return new char[size]; } public byte[] byteBuf(int size) { byte[] bytes = this.bytes; if (size <= bytes.length) { return bytes; } return new byte[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/Parameters.java
dubbo-common/src/main/java/org/apache/dubbo/common/Parameters.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; 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.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.HIDE_KEY_PREFIX; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * Parameters for backward compatibility for version prior to 2.0.5 * * @deprecated */ @Deprecated public class Parameters { protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Parameters.class); private final Map<String, String> parameters; public Parameters(String... pairs) { this(toMap(pairs)); } public Parameters(Map<String, String> parameters) { this.parameters = Collections.unmodifiableMap(parameters != null ? new HashMap<>(parameters) : new HashMap<>(0)); } private static Map<String, String> toMap(String... pairs) { return CollectionUtils.toStringMap(pairs); } public static Parameters parseParameters(String query) { return new Parameters(StringUtils.parseQueryString(query)); } public Map<String, String> getParameters() { return parameters; } /** * @deprecated will be removed in 3.3.0 */ @Deprecated public <T> T getExtension(Class<T> type, String key) { String name = getParameter(key); return ExtensionLoader.getExtensionLoader(type).getExtension(name); } /** * @deprecated will be removed in 3.3.0 */ @Deprecated public <T> T getExtension(Class<T> type, String key, String defaultValue) { String name = getParameter(key, defaultValue); return ExtensionLoader.getExtensionLoader(type).getExtension(name); } /** * @deprecated will be removed in 3.3.0 */ @Deprecated public <T> T getMethodExtension(Class<T> type, String method, String key) { String name = getMethodParameter(method, key); return ExtensionLoader.getExtensionLoader(type).getExtension(name); } /** * @deprecated will be removed in 3.3.0 */ @Deprecated public <T> T getMethodExtension(Class<T> type, String method, String key, String defaultValue) { String name = getMethodParameter(method, key, defaultValue); return ExtensionLoader.getExtensionLoader(type).getExtension(name); } public String getDecodedParameter(String key) { return getDecodedParameter(key, null); } public String getDecodedParameter(String key, String defaultValue) { String value = getParameter(key, defaultValue); if (value != null && value.length() > 0) { try { value = URLDecoder.decode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", e.getMessage(), e); } } return value; } public String getParameter(String key) { String value = parameters.get(key); if (StringUtils.isEmpty(value)) { value = parameters.get(HIDE_KEY_PREFIX + key); } if (StringUtils.isEmpty(value)) { value = parameters.get(DEFAULT_KEY_PREFIX + key); } if (StringUtils.isEmpty(value)) { value = parameters.get(HIDE_KEY_PREFIX + DEFAULT_KEY_PREFIX + key); } return value; } public String getParameter(String key, String defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return value; } public int getIntParameter(String key) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return 0; } return Integer.parseInt(value); } public int getIntParameter(String key, int defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Integer.parseInt(value); } public int getPositiveIntParameter(String key, int defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } int i = Integer.parseInt(value); if (i > 0) { return i; } return defaultValue; } public boolean getBooleanParameter(String key) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return false; } return Boolean.parseBoolean(value); } public boolean getBooleanParameter(String key, boolean defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Boolean.parseBoolean(value); } public boolean hasParameter(String key) { String value = getParameter(key); return value != null && value.length() > 0; } public String getMethodParameter(String method, String key) { String value = parameters.get(method + "." + key); if (StringUtils.isEmpty(value)) { value = parameters.get(HIDE_KEY_PREFIX + method + "." + key); } if (StringUtils.isEmpty(value)) { return getParameter(key); } return value; } public String getMethodParameter(String method, String key, String defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return value; } public int getMethodIntParameter(String method, String key) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return 0; } return Integer.parseInt(value); } public int getMethodIntParameter(String method, String key, int defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Integer.parseInt(value); } public int getMethodPositiveIntParameter(String method, String key, int defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } int i = Integer.parseInt(value); if (i > 0) { return i; } return defaultValue; } public boolean getMethodBooleanParameter(String method, String key) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return false; } return Boolean.parseBoolean(value); } public boolean getMethodBooleanParameter(String method, String key, boolean defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Boolean.parseBoolean(value); } public boolean hasMethodParameter(String method, String key) { String value = getMethodParameter(method, key); return value != null && value.length() > 0; } @Override public boolean equals(Object o) { if (this == o) { return true; } return parameters.equals(o); } @Override public int hashCode() { return parameters.hashCode(); } @Override public String toString() { return StringUtils.toQueryString(getParameters()); } }
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/Resetable.java
dubbo-common/src/main/java/org/apache/dubbo/common/Resetable.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; /** * Resetable. */ public interface Resetable { /** * reset. * * @param url */ void reset(URL url); }
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/Node.java
dubbo-common/src/main/java/org/apache/dubbo/common/Node.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; /** * Node. (API/SPI, Prototype, ThreadSafe) */ public interface Node { /** * get url. * * @return url. */ URL getUrl(); /** * is available. * * @return available. */ boolean isAvailable(); /** * destroy. */ void destroy(); }
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/BaseServiceMetadata.java
dubbo-common/src/main/java/org/apache/dubbo/common/BaseServiceMetadata.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ServiceModel; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_VERSION; /** * 2019-10-10 */ public class BaseServiceMetadata { public static final char COLON_SEPARATOR = ':'; protected String serviceKey; protected String serviceInterfaceName; protected String version; protected volatile String group; private ServiceModel serviceModel; public static String buildServiceKey(String path, String group, String version) { int length = path == null ? 0 : path.length(); length += group == null ? 0 : group.length(); length += version == null ? 0 : version.length(); length += 2; StringBuilder buf = new StringBuilder(length); if (StringUtils.isNotEmpty(group)) { buf.append(group).append('/'); } buf.append(path); if (StringUtils.isNotEmpty(version)) { buf.append(':').append(version); } return buf.toString(); } public static String versionFromServiceKey(String serviceKey) { int index = serviceKey.indexOf(":"); if (index == -1) { return DEFAULT_VERSION; } return serviceKey.substring(index + 1); } public static String groupFromServiceKey(String serviceKey) { int index = serviceKey.indexOf("/"); if (index == -1) { return null; } return serviceKey.substring(0, index); } public static String interfaceFromServiceKey(String serviceKey) { int groupIndex = serviceKey.indexOf("/"); int versionIndex = serviceKey.indexOf(":"); groupIndex = (groupIndex == -1) ? 0 : groupIndex + 1; versionIndex = (versionIndex == -1) ? serviceKey.length() : versionIndex; return serviceKey.substring(groupIndex, versionIndex); } /** * Format : interface:version * * @return */ public String getDisplayServiceKey() { StringBuilder serviceNameBuilder = new StringBuilder(); serviceNameBuilder.append(serviceInterfaceName); serviceNameBuilder.append(COLON_SEPARATOR).append(version); return serviceNameBuilder.toString(); } /** * revert of org.apache.dubbo.common.ServiceDescriptor#getDisplayServiceKey() * * @param displayKey * @return */ public static BaseServiceMetadata revertDisplayServiceKey(String displayKey) { String[] eles = StringUtils.split(displayKey, COLON_SEPARATOR); if (eles == null || eles.length < 1 || eles.length > 2) { return new BaseServiceMetadata(); } BaseServiceMetadata serviceDescriptor = new BaseServiceMetadata(); serviceDescriptor.setServiceInterfaceName(eles[0]); if (eles.length == 2) { serviceDescriptor.setVersion(eles[1]); } return serviceDescriptor; } public static String keyWithoutGroup(String interfaceName, String version) { if (StringUtils.isEmpty(version)) { return interfaceName + ":" + DEFAULT_VERSION; } return interfaceName + ":" + version; } public String getServiceKey() { return serviceKey; } public void generateServiceKey() { this.serviceKey = buildServiceKey(serviceInterfaceName, group, version); } public void setServiceKey(String serviceKey) { this.serviceKey = serviceKey; } public String getServiceInterfaceName() { return serviceInterfaceName; } public void setServiceInterfaceName(String serviceInterfaceName) { this.serviceInterfaceName = serviceInterfaceName; } 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 ServiceModel getServiceModel() { return serviceModel; } public void setServiceModel(ServiceModel serviceModel) { this.serviceModel = serviceModel; } }
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/URL.java
dubbo-common/src/main/java/org/apache/dubbo/common/URL.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.common; import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.config.InmemoryConfiguration; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.constants.RemotingConstants; import org.apache.dubbo.common.convert.ConverterUtil; import org.apache.dubbo.common.url.component.PathURLAddress; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.url.component.URLAddress; import org.apache.dubbo.common.url.component.URLParam; import org.apache.dubbo.common.url.component.URLPlainParam; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.LRUCache; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; 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 org.apache.dubbo.rpc.model.ServiceModel; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.TreeMap; import java.util.function.Predicate; import static org.apache.dubbo.common.BaseServiceMetadata.COLON_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.ADDRESS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_CHAR_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.HOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PASSWORD_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PORT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.USERNAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.utils.StringUtils.isBlank; /** * URL - Uniform Resource Locator (Immutable, ThreadSafe) * <p> * url example: * <ul> * <li>http://www.facebook.com/friends?param1=value1&amp;param2=value2 * <li>http://username:password@10.20.130.230:8080/list?version=1.0.0 * <li>ftp://username:password@192.168.1.7:21/1/read.txt * <li>registry://192.168.1.7:9090/org.apache.dubbo.service1?param1=value1&amp;param2=value2 * </ul> * <p> * Some strange example below: * <ul> * <li>192.168.1.3:20880<br> * for this case, url protocol = null, url host = 192.168.1.3, port = 20880, url path = null * <li>file:///home/user1/router.js?type=script<br> * for this case, url protocol = file, url host = null, url path = home/user1/router.js * <li>file://home/user1/router.js?type=script<br> * for this case, url protocol = file, url host = home, url path = user1/router.js * <li>file:///D:/1/router.js?type=script<br> * for this case, url protocol = file, url host = null, url path = D:/1/router.js * <li>file:/D:/1/router.js?type=script<br> * same as above file:///D:/1/router.js?type=script * <li>/home/user1/router.js?type=script <br> * for this case, url protocol = null, url host = null, url path = home/user1/router.js * <li>home/user1/router.js?type=script <br> * for this case, url protocol = null, url host = home, url path = user1/router.js * </ul> * * @see java.net.URL * @see java.net.URI */ public /*final**/ class URL implements Serializable { private static final long serialVersionUID = -1985165475234910535L; private static final Map<String, URL> cachedURLs = new LRUCache<>(); private final URLAddress urlAddress; private final URLParam urlParam; // ==== cache ==== private transient String serviceKey; private transient String protocolServiceKey; protected volatile Map<String, Object> attributes; protected URL() { this.urlAddress = null; this.urlParam = URLParam.parse(new HashMap<>()); this.attributes = null; } public URL(URLAddress urlAddress, URLParam urlParam) { this(urlAddress, urlParam, null); } public URL(URLAddress urlAddress, URLParam urlParam, Map<String, Object> attributes) { this.urlAddress = urlAddress; this.urlParam = null == urlParam ? URLParam.parse(new HashMap<>()) : urlParam; if (attributes != null && !attributes.isEmpty()) { this.attributes = attributes; } else { this.attributes = null; } } public URL(String protocol, String host, int port) { this(protocol, null, null, host, port, null, (Map<String, String>) null); } public URL( String protocol, String host, int port, String[] pairs) { // varargs ... conflict with the following path argument, use array instead. this(protocol, null, null, host, port, null, CollectionUtils.toStringMap(pairs)); } public URL(String protocol, String host, int port, Map<String, String> parameters) { this(protocol, null, null, host, port, null, parameters); } public URL(String protocol, String host, int port, String path) { this(protocol, null, null, host, port, path, (Map<String, String>) null); } public URL(String protocol, String host, int port, String path, String... pairs) { this(protocol, null, null, host, port, path, CollectionUtils.toStringMap(pairs)); } public URL(String protocol, String host, int port, String path, Map<String, String> parameters) { this(protocol, null, null, host, port, path, parameters); } public URL(String protocol, String username, String password, String host, int port, String path) { this(protocol, username, password, host, port, path, (Map<String, String>) null); } public URL(String protocol, String username, String password, String host, int port, String path, String... pairs) { this(protocol, username, password, host, port, path, CollectionUtils.toStringMap(pairs)); } public URL( String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters) { if (StringUtils.isEmpty(username) && StringUtils.isNotEmpty(password)) { throw new IllegalArgumentException("Invalid url, password without username!"); } this.urlAddress = new PathURLAddress(protocol, username, password, path, host, port); this.urlParam = URLParam.parse(parameters); this.attributes = null; } protected URL( String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters, boolean modifiable) { if (StringUtils.isEmpty(username) && StringUtils.isNotEmpty(password)) { throw new IllegalArgumentException("Invalid url, password without username!"); } this.urlAddress = new PathURLAddress(protocol, username, password, path, host, port); this.urlParam = URLParam.parse(parameters); this.attributes = null; } public static URL cacheableValueOf(String url) { URL cachedURL = cachedURLs.get(url); if (cachedURL != null) { return cachedURL; } cachedURL = valueOf(url, false); cachedURLs.put(url, cachedURL); return cachedURL; } /** * parse decoded url string, formatted dubbo://host:port/path?param=value, into strutted URL. * * @param url, decoded url string * @return */ public static URL valueOf(String url) { return valueOf(url, false); } public static URL valueOf(String url, ScopeModel scopeModel) { return valueOf(url).setScopeModel(scopeModel); } /** * parse normal or encoded url string into strutted URL: * - dubbo://host:port/path?param=value * - URL.encode("dubbo://host:port/path?param=value") * * @param url, url string * @param encoded, encoded or decoded * @return */ public static URL valueOf(String url, boolean encoded) { if (encoded) { return URLStrParser.parseEncodedStr(url); } return URLStrParser.parseDecodedStr(url); } public static URL valueOf(String url, String... reserveParams) { URL result = valueOf(url); if (reserveParams == null || reserveParams.length == 0) { return result; } Map<String, String> newMap = new HashMap<>(reserveParams.length); Map<String, String> oldMap = result.getParameters(); for (String reserveParam : reserveParams) { String tmp = oldMap.get(reserveParam); if (StringUtils.isNotEmpty(tmp)) { newMap.put(reserveParam, tmp); } } return result.clearParameters().addParameters(newMap); } public static URL valueOf(URL url, String[] reserveParams, String[] reserveParamPrefixes) { Map<String, String> newMap = new HashMap<>(); Map<String, String> oldMap = url.getParameters(); if (reserveParamPrefixes != null && reserveParamPrefixes.length != 0) { for (Map.Entry<String, String> entry : oldMap.entrySet()) { for (String reserveParamPrefix : reserveParamPrefixes) { if (entry.getKey().startsWith(reserveParamPrefix) && StringUtils.isNotEmpty(entry.getValue())) { newMap.put(entry.getKey(), entry.getValue()); } } } } if (reserveParams != null) { for (String reserveParam : reserveParams) { String tmp = oldMap.get(reserveParam); if (StringUtils.isNotEmpty(tmp)) { newMap.put(reserveParam, tmp); } } } return newMap.isEmpty() ? new ServiceConfigURL( url.getProtocol(), url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), url.getPath(), (Map<String, String>) null, url.getAttributes()) : new ServiceConfigURL( url.getProtocol(), url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), url.getPath(), newMap, url.getAttributes()); } public static String encode(String value) { if (StringUtils.isEmpty(value)) { return ""; } try { return URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } } public static String decode(String value) { if (StringUtils.isEmpty(value)) { return ""; } try { return URLDecoder.decode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } } static String appendDefaultPort(String address, int defaultPort) { if (StringUtils.isNotEmpty(address) && defaultPort > 0) { int i = address.indexOf(':'); if (i < 0) { return address + ":" + defaultPort; } else if (Integer.parseInt(address.substring(i + 1)) == 0) { return address.substring(0, i + 1) + defaultPort; } } return address; } public URLAddress getUrlAddress() { return urlAddress; } public URLParam getUrlParam() { return urlParam; } public String getProtocol() { return urlAddress == null ? null : urlAddress.getProtocol(); } public URL setProtocol(String protocol) { if (urlAddress == null) { return new ServiceConfigURL(protocol, getHost(), getPort(), getPath(), getParameters()); } else { URLAddress newURLAddress = urlAddress.setProtocol(protocol); return returnURL(newURLAddress); } } public String getUsername() { return urlAddress == null ? null : urlAddress.getUsername(); } public URL setUsername(String username) { if (urlAddress == null) { return new ServiceConfigURL(getProtocol(), getHost(), getPort(), getPath(), getParameters()) .setUsername(username); } else { URLAddress newURLAddress = urlAddress.setUsername(username); return returnURL(newURLAddress); } } public String getPassword() { return urlAddress == null ? null : urlAddress.getPassword(); } public URL setPassword(String password) { if (urlAddress == null) { return new ServiceConfigURL(getProtocol(), getHost(), getPort(), getPath(), getParameters()) .setPassword(password); } else { URLAddress newURLAddress = urlAddress.setPassword(password); return returnURL(newURLAddress); } } /** * refer to https://datatracker.ietf.org/doc/html/rfc3986 * * @return authority */ public String getAuthority() { StringBuilder ret = new StringBuilder(); ret.append(getUserInformation()); if (StringUtils.isNotEmpty(getHost())) { if (StringUtils.isNotEmpty(getUsername()) || StringUtils.isNotEmpty(getPassword())) { ret.append('@'); } ret.append(getHost()); if (getPort() != 0) { ret.append(':'); ret.append(getPort()); } } return ret.length() == 0 ? null : ret.toString(); } /** * refer to https://datatracker.ietf.org/doc/html/rfc3986 * * @return user information */ public String getUserInformation() { StringBuilder ret = new StringBuilder(); if (StringUtils.isEmpty(getUsername()) && StringUtils.isEmpty(getPassword())) { return ret.toString(); } if (StringUtils.isNotEmpty(getUsername())) { ret.append(getUsername()); } ret.append(':'); if (StringUtils.isNotEmpty(getPassword())) { ret.append(getPassword()); } return ret.length() == 0 ? null : ret.toString(); } public String getHost() { return urlAddress == null ? null : urlAddress.getHost(); } public URL setHost(String host) { if (urlAddress == null) { return new ServiceConfigURL(getProtocol(), host, getPort(), getPath(), getParameters()); } else { URLAddress newURLAddress = urlAddress.setHost(host); return returnURL(newURLAddress); } } public int getPort() { return urlAddress == null ? 0 : urlAddress.getPort(); } public URL setPort(int port) { if (urlAddress == null) { return new ServiceConfigURL(getProtocol(), getHost(), port, getPath(), getParameters()); } else { URLAddress newURLAddress = urlAddress.setPort(port); return returnURL(newURLAddress); } } public int getPort(int defaultPort) { int port = getPort(); return port <= 0 ? defaultPort : port; } public String getAddress() { return urlAddress == null ? null : urlAddress.getAddress(); } public URL setAddress(String address) { int i = address.lastIndexOf(':'); String host; int port = this.getPort(); if (i >= 0) { host = address.substring(0, i); port = Integer.parseInt(address.substring(i + 1)); } else { host = address; } if (urlAddress == null) { return new ServiceConfigURL(getProtocol(), host, port, getPath(), getParameters()); } else { URLAddress newURLAddress = urlAddress.setAddress(host, port); return returnURL(newURLAddress); } } public String getIp() { return urlAddress == null ? null : urlAddress.getIp(); } public String getBackupAddress() { return getBackupAddress(0); } public String getBackupAddress(int defaultPort) { StringBuilder address = new StringBuilder(appendDefaultPort(getAddress(), defaultPort)); String[] backups = getParameter(RemotingConstants.BACKUP_KEY, new String[0]); if (ArrayUtils.isNotEmpty(backups)) { for (String backup : backups) { address.append(','); address.append(appendDefaultPort(backup, defaultPort)); } } return address.toString(); } public List<URL> getBackupUrls() { List<URL> urls = new ArrayList<>(); urls.add(this); String[] backups = getParameter(RemotingConstants.BACKUP_KEY, new String[0]); if (ArrayUtils.isNotEmpty(backups)) { for (String backup : backups) { urls.add(this.setAddress(backup)); } } return urls; } public String getPath() { return urlAddress == null ? null : urlAddress.getPath(); } public URL setPath(String path) { if (urlAddress == null) { return new ServiceConfigURL(getProtocol(), getHost(), getPort(), path, getParameters()); } else { URLAddress newURLAddress = urlAddress.setPath(path); return returnURL(newURLAddress); } } public String getAbsolutePath() { String path = getPath(); if (path != null && !path.startsWith("/")) { return "/" + path; } return path; } public Map<String, String> getOriginalParameters() { return this.getParameters(); } public Map<String, String> getParameters() { return urlParam.getParameters(); } public Map<String, String> getAllParameters() { return this.getParameters(); } /** * Get the parameters to be selected(filtered) * * @param nameToSelect the {@link Predicate} to select the parameter name * @return non-null {@link Map} * @since 2.7.8 */ public Map<String, String> getParameters(Predicate<String> nameToSelect) { Map<String, String> selectedParameters = new LinkedHashMap<>(); for (Map.Entry<String, String> entry : getParameters().entrySet()) { String name = entry.getKey(); if (nameToSelect.test(name)) { selectedParameters.put(name, entry.getValue()); } } return Collections.unmodifiableMap(selectedParameters); } public String getParameterAndDecoded(String key) { return getParameterAndDecoded(key, null); } public String getParameterAndDecoded(String key, String defaultValue) { return decode(getParameter(key, defaultValue)); } public String getOriginalParameter(String key) { return getParameter(key); } public String getParameter(String key) { return urlParam.getParameter(key); } public String getParameter(String key, String defaultValue) { String value = getParameter(key); return StringUtils.isEmpty(value) ? defaultValue : value; } public String[] getParameter(String key, String[] defaultValue) { String value = getParameter(key); return StringUtils.isEmpty(value) ? defaultValue : COMMA_SPLIT_PATTERN.split(value); } public List<String> getParameter(String key, List<String> defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } String[] strArray = COMMA_SPLIT_PATTERN.split(value); return Arrays.asList(strArray); } /** * Get parameter * * @param key the key of parameter * @param valueType the type of parameter value * @param <T> the type of parameter value * @return get the parameter if present, or <code>null</code> * @since 2.7.8 */ public <T> T getParameter(String key, Class<T> valueType) { return getParameter(key, valueType, null); } /** * Get parameter * * @param key the key of parameter * @param valueType the type of parameter value * @param defaultValue the default value if parameter is absent * @param <T> the type of parameter value * @return get the parameter if present, or <code>defaultValue</code> will be used. * @since 2.7.8 */ public <T> T getParameter(String key, Class<T> valueType, T defaultValue) { String value = getParameter(key); T result = null; if (!isBlank(value)) { result = getOrDefaultFrameworkModel() .getBeanFactory() .getBean(ConverterUtil.class) .convertIfPossible(value, valueType); } if (result == null) { result = defaultValue; } return result; } public URL setScopeModel(ScopeModel scopeModel) { return putAttribute(CommonConstants.SCOPE_MODEL, scopeModel); } public ScopeModel getScopeModel() { return (ScopeModel) getAttribute(CommonConstants.SCOPE_MODEL); } public FrameworkModel getOrDefaultFrameworkModel() { return ScopeModelUtil.getFrameworkModel(getScopeModel()); } public ApplicationModel getOrDefaultApplicationModel() { return ScopeModelUtil.getApplicationModel(getScopeModel()); } public ApplicationModel getApplicationModel() { return ScopeModelUtil.getOrNullApplicationModel(getScopeModel()); } public ModuleModel getOrDefaultModuleModel() { return ScopeModelUtil.getModuleModel(getScopeModel()); } public URL setServiceModel(ServiceModel serviceModel) { return putAttribute(CommonConstants.SERVICE_MODEL, serviceModel); } public ServiceModel getServiceModel() { return (ServiceModel) getAttribute(CommonConstants.SERVICE_MODEL); } public URL getUrlParameter(String key) { String value = getParameterAndDecoded(key); if (StringUtils.isEmpty(value)) { return null; } return URL.valueOf(value); } public double getParameter(String key, double defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Double.parseDouble(value); } public float getParameter(String key, float defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Float.parseFloat(value); } public long getParameter(String key, long defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Long.parseLong(value); } public int getParameter(String key, int defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Integer.parseInt(value); } public short getParameter(String key, short defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Short.parseShort(value); } public byte getParameter(String key, byte defaultValue) { String value = getParameter(key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Byte.parseByte(value); } public float getPositiveParameter(String key, float defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } float value = getParameter(key, defaultValue); return value <= 0 ? defaultValue : value; } public double getPositiveParameter(String key, double defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } double value = getParameter(key, defaultValue); return value <= 0 ? defaultValue : value; } public long getPositiveParameter(String key, long defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } long value = getParameter(key, defaultValue); return value <= 0 ? defaultValue : value; } public int getPositiveParameter(String key, int defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } int value = getParameter(key, defaultValue); return value <= 0 ? defaultValue : value; } public short getPositiveParameter(String key, short defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } short value = getParameter(key, defaultValue); return value <= 0 ? defaultValue : value; } public byte getPositiveParameter(String key, byte defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } byte value = getParameter(key, defaultValue); return value <= 0 ? defaultValue : value; } public char getParameter(String key, char defaultValue) { String value = getParameter(key); return StringUtils.isEmpty(value) ? defaultValue : value.charAt(0); } public boolean getParameter(String key, boolean defaultValue) { String value = getParameter(key); return StringUtils.isEmpty(value) ? defaultValue : Boolean.parseBoolean(value); } public boolean hasParameter(String key) { String value = getParameter(key); return StringUtils.isNotEmpty(value); } public String getMethodParameterAndDecoded(String method, String key) { return URL.decode(getMethodParameter(method, key)); } public String getMethodParameterAndDecoded(String method, String key, String defaultValue) { return URL.decode(getMethodParameter(method, key, defaultValue)); } public String getMethodParameter(String method, String key) { return urlParam.getMethodParameter(method, key); } public String getMethodParameterStrict(String method, String key) { return urlParam.getMethodParameterStrict(method, key); } public String getMethodParameter(String method, String key, String defaultValue) { String value = getMethodParameter(method, key); return StringUtils.isEmpty(value) ? defaultValue : value; } public double getMethodParameter(String method, String key, double defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Double.parseDouble(value); } public float getMethodParameter(String method, String key, float defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Float.parseFloat(value); } public long getMethodParameter(String method, String key, long defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Long.parseLong(value); } public int getMethodParameter(String method, String key, int defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Integer.parseInt(value); } public short getMethodParameter(String method, String key, short defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Short.parseShort(value); } public byte getMethodParameter(String method, String key, byte defaultValue) { String value = getMethodParameter(method, key); if (StringUtils.isEmpty(value)) { return defaultValue; } return Byte.parseByte(value); } public double getMethodPositiveParameter(String method, String key, double defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } double value = getMethodParameter(method, key, defaultValue); return value <= 0 ? defaultValue : value; } public float getMethodPositiveParameter(String method, String key, float defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } float value = getMethodParameter(method, key, defaultValue); return value <= 0 ? defaultValue : value; } public long getMethodPositiveParameter(String method, String key, long defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } long value = getMethodParameter(method, key, defaultValue); return value <= 0 ? defaultValue : value; } public int getMethodPositiveParameter(String method, String key, int defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } int value = getMethodParameter(method, key, defaultValue); return value <= 0 ? defaultValue : value; } public short getMethodPositiveParameter(String method, String key, short defaultValue) { if (defaultValue <= 0) { throw new IllegalArgumentException("defaultValue <= 0"); } short value = getMethodParameter(method, key, defaultValue); return value <= 0 ? defaultValue : value; }
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/common/ProtocolServiceKey.java
dubbo-common/src/main/java/org/apache/dubbo/common/ProtocolServiceKey.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.StringUtils; import java.util.Objects; public class ProtocolServiceKey extends ServiceKey { private final String protocol; public ProtocolServiceKey(String interfaceName, String version, String group, String protocol) { super(interfaceName, version, group); this.protocol = protocol; } public String getProtocol() { return protocol; } public String getServiceKeyString() { return super.toString(); } public boolean isSameWith(ProtocolServiceKey protocolServiceKey) { // interface version group should be the same if (!super.equals(protocolServiceKey)) { return false; } // origin protocol is *, can not match any protocol if (CommonConstants.ANY_VALUE.equals(protocol)) { return false; } // origin protocol is null, can match any protocol if (StringUtils.isEmpty(protocol) || StringUtils.isEmpty(protocolServiceKey.getProtocol())) { return true; } // origin protocol is not *, match itself return Objects.equals(protocol, protocolServiceKey.getProtocol()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ProtocolServiceKey that = (ProtocolServiceKey) o; return Objects.equals(protocol, that.protocol); } @Override public int hashCode() { return Objects.hash(super.hashCode(), protocol); } @Override public String toString() { return super.toString() + CommonConstants.GROUP_CHAR_SEPARATOR + protocol; } public static class Matcher { public static boolean isMatch(ProtocolServiceKey rule, ProtocolServiceKey target) { // 1. 2. 3. match interface / version / group if (!ServiceKey.Matcher.isMatch(rule, target)) { return false; } // 4.match protocol // 4.1. if rule protocol is *, match all if (!CommonConstants.ANY_VALUE.equals(rule.getProtocol())) { // 4.2. if rule protocol is null, match all if (StringUtils.isNotEmpty(rule.getProtocol())) { // 4.3. if rule protocol contains ',', split and match each if (rule.getProtocol().contains(CommonConstants.COMMA_SEPARATOR)) { String[] protocols = rule.getProtocol().split("\\" + CommonConstants.COMMA_SEPARATOR, -1); boolean match = false; for (String protocol : protocols) { protocol = protocol.trim(); if (StringUtils.isEmpty(protocol) && StringUtils.isEmpty(target.getProtocol())) { match = true; break; } else if (protocol.equals(target.getProtocol())) { match = true; break; } } if (!match) { return false; } } // 4.3. if rule protocol is not contains ',', match directly else if (!Objects.equals(rule.getProtocol(), target.getProtocol())) { return false; } } } return true; } } }
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/BatchExecutorQueue.java
dubbo-common/src/main/java/org/apache/dubbo/common/BatchExecutorQueue.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; public class BatchExecutorQueue<T> { static final int DEFAULT_QUEUE_SIZE = 128; private final Queue<T> queue; private final AtomicBoolean scheduled; private final int chunkSize; public BatchExecutorQueue() { this(DEFAULT_QUEUE_SIZE); } public BatchExecutorQueue(int chunkSize) { this.queue = new ConcurrentLinkedQueue<>(); this.scheduled = new AtomicBoolean(false); this.chunkSize = chunkSize; } public void enqueue(T message, Executor executor) { queue.add(message); scheduleFlush(executor); } protected void scheduleFlush(Executor executor) { if (scheduled.compareAndSet(false, true)) { executor.execute(() -> this.run(executor)); } } private void run(Executor executor) { try { Queue<T> snapshot = new LinkedList<>(); T item; while ((item = queue.poll()) != null) { snapshot.add(item); } int i = 0; boolean flushedOnce = false; while ((item = snapshot.poll()) != null) { if (snapshot.size() == 0) { flushedOnce = false; break; } if (i == chunkSize) { i = 0; flush(item); flushedOnce = true; } else { prepare(item); i++; } } if (!flushedOnce && item != null) { flush(item); } } finally { scheduled.set(false); if (!queue.isEmpty()) { scheduleFlush(executor); } } } protected void prepare(T item) {} protected void flush(T item) {} }
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/URLBuilder.java
dubbo-common/src/main/java/org/apache/dubbo/common/URLBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ScopeModel; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Objects; import static org.apache.dubbo.common.constants.CommonConstants.SCOPE_MODEL; public final class URLBuilder extends ServiceConfigURL { private String protocol; private String username; private String password; // by default, host to registry private String host; // by default, port to registry private int port; private String path; private final Map<String, String> parameters; private final Map<String, Object> attributes; private Map<String, Map<String, String>> methodParameters; public URLBuilder() { protocol = null; username = null; password = null; host = null; port = 0; path = null; parameters = new HashMap<>(); attributes = new HashMap<>(); methodParameters = new HashMap<>(); } public URLBuilder(String protocol, String host, int port) { this(protocol, null, null, host, port, null, null); } public URLBuilder(String protocol, String host, int port, String[] pairs) { this(protocol, null, null, host, port, null, CollectionUtils.toStringMap(pairs)); } public URLBuilder(String protocol, String host, int port, Map<String, String> parameters) { this(protocol, null, null, host, port, null, parameters); } public URLBuilder(String protocol, String host, int port, String path) { this(protocol, null, null, host, port, path, null); } public URLBuilder(String protocol, String host, int port, String path, String... pairs) { this(protocol, null, null, host, port, path, CollectionUtils.toStringMap(pairs)); } public URLBuilder(String protocol, String host, int port, String path, Map<String, String> parameters) { this(protocol, null, null, host, port, path, parameters); } public URLBuilder( String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters) { this(protocol, username, password, host, port, path, parameters, null); } public URLBuilder( String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters, Map<String, Object> attributes) { this.protocol = protocol; this.username = username; this.password = password; this.host = host; this.port = port; this.path = path; this.parameters = parameters != null ? parameters : new HashMap<>(); this.attributes = attributes != null ? attributes : new HashMap<>(); } public static URLBuilder from(URL url) { String protocol = url.getProtocol(); String username = url.getUsername(); String password = url.getPassword(); String host = url.getHost(); int port = url.getPort(); String path = url.getPath(); Map<String, String> parameters = new HashMap<>(url.getParameters()); Map<String, Object> attributes = new HashMap<>(url.getAttributes()); return new URLBuilder(protocol, username, password, host, port, path, parameters, attributes); } public ServiceConfigURL build() { if (StringUtils.isEmpty(username) && StringUtils.isNotEmpty(password)) { throw new IllegalArgumentException("Invalid url, password without username!"); } port = Math.max(port, 0); // trim the leading "/" int firstNonSlash = 0; if (path != null) { while (firstNonSlash < path.length() && path.charAt(firstNonSlash) == '/') { firstNonSlash++; } if (firstNonSlash >= path.length()) { path = ""; } else if (firstNonSlash > 0) { path = path.substring(firstNonSlash); } } return new ServiceConfigURL(protocol, username, password, host, port, path, parameters, attributes); } @Override public URLBuilder putAttribute(String key, Object obj) { attributes.put(key, obj); return this; } @Override public URLBuilder removeAttribute(String key) { attributes.remove(key); return this; } @Override public URLBuilder setProtocol(String protocol) { this.protocol = protocol; return this; } @Override public URLBuilder setUsername(String username) { this.username = username; return this; } @Override public URLBuilder setPassword(String password) { this.password = password; return this; } @Override public URLBuilder setHost(String host) { this.host = host; return this; } @Override public URLBuilder setPort(int port) { this.port = port; return this; } @Override public URLBuilder setAddress(String address) { int i = address.lastIndexOf(':'); String host; int port = this.port; if (i >= 0) { host = address.substring(0, i); port = Integer.parseInt(address.substring(i + 1)); } else { host = address; } this.host = host; this.port = port; return this; } @Override public URLBuilder setPath(String path) { this.path = path; return this; } @Override public URLBuilder setScopeModel(ScopeModel scopeModel) { this.attributes.put(SCOPE_MODEL, scopeModel); return this; } @Override public URLBuilder addParameterAndEncoded(String key, String value) { if (StringUtils.isEmpty(value)) { return this; } return addParameter(key, URL.encode(value)); } @Override public URLBuilder addParameter(String key, boolean value) { return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, char value) { return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, byte value) { return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, short value) { return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, int value) { return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, long value) { return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, float value) { return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, double value) { return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, Enum<?> value) { if (value == null) { return this; } return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, Number value) { if (value == null) { return this; } return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, CharSequence value) { if (value == null || value.length() == 0) { return this; } return addParameter(key, String.valueOf(value)); } @Override public URLBuilder addParameter(String key, String value) { if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) { return this; } parameters.put(key, value); return this; } public URLBuilder addMethodParameter(String method, String key, String value) { if (StringUtils.isEmpty(method) || StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) { return this; } URL.putMethodParameter(method, key, value, methodParameters); return this; } @Override public URLBuilder addParameterIfAbsent(String key, String value) { if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) { return this; } if (hasParameter(key)) { return this; } parameters.put(key, value); return this; } public URLBuilder addMethodParameterIfAbsent(String method, String key, String value) { if (StringUtils.isEmpty(method) || StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) { return this; } if (hasMethodParameter(method, key)) { return this; } URL.putMethodParameter(method, key, value, methodParameters); return this; } @Override public URLBuilder addParameters(Map<String, String> parameters) { if (CollectionUtils.isEmptyMap(parameters)) { return this; } boolean hasAndEqual = true; for (Map.Entry<String, String> entry : parameters.entrySet()) { String oldValue = this.parameters.get(entry.getKey()); String newValue = entry.getValue(); if (!Objects.equals(oldValue, newValue)) { hasAndEqual = false; break; } } // return immediately if there's no change if (hasAndEqual) { return this; } this.parameters.putAll(parameters); return this; } public URLBuilder addMethodParameters(Map<String, Map<String, String>> methodParameters) { if (CollectionUtils.isEmptyMap(methodParameters)) { return this; } this.methodParameters.putAll(methodParameters); return this; } @Override public URLBuilder addParametersIfAbsent(Map<String, String> parameters) { if (CollectionUtils.isEmptyMap(parameters)) { return this; } for (Map.Entry<String, String> entry : parameters.entrySet()) { this.parameters.putIfAbsent(entry.getKey(), entry.getValue()); } return this; } @Override public URLBuilder addParameters(String... pairs) { if (ArrayUtils.isEmpty(pairs)) { return this; } if (pairs.length % 2 != 0) { throw new IllegalArgumentException("Map pairs can not be odd number."); } Map<String, String> map = new HashMap<>(); int len = pairs.length / 2; for (int i = 0; i < len; i++) { map.put(pairs[2 * i], pairs[2 * i + 1]); } return addParameters(map); } @Override public URLBuilder addParameterString(String query) { if (StringUtils.isEmpty(query)) { return this; } return addParameters(StringUtils.parseQueryString(query)); } @Override public URLBuilder removeParameter(String key) { if (StringUtils.isEmpty(key)) { return this; } return removeParameters(key); } @Override public URLBuilder removeParameters(Collection<String> keys) { if (CollectionUtils.isEmpty(keys)) { return this; } return removeParameters(keys.toArray(new String[0])); } @Override public URLBuilder removeParameters(String... keys) { if (ArrayUtils.isEmpty(keys)) { return this; } for (String key : keys) { parameters.remove(key); } return this; } @Override public URLBuilder clearParameters() { parameters.clear(); return this; } @Override public boolean hasParameter(String key) { String value = getParameter(key); return StringUtils.isNotEmpty(value); } @Override public boolean hasMethodParameter(String method, String key) { if (method == null) { String suffix = "." + key; for (String fullKey : parameters.keySet()) { if (fullKey.endsWith(suffix)) { return true; } } return false; } if (key == null) { String prefix = method + "."; for (String fullKey : parameters.keySet()) { if (fullKey.startsWith(prefix)) { return true; } } return false; } String value = getMethodParameter(method, key); return StringUtils.isNotEmpty(value); } @Override public String getParameter(String key) { return parameters.get(key); } @Override public String getMethodParameter(String method, String key) { Map<String, String> keyMap = methodParameters.get(method); String value = null; if (keyMap != null) { value = keyMap.get(key); } return value; } }
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/Version.java
dubbo-common/src/main/java/org/apache/dubbo/common/Version.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.CodeSource; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; public final class Version { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Version.class); private static final Pattern PREFIX_DIGITS_PATTERN = Pattern.compile("^([0-9]*).*"); // Dubbo RPC protocol version, for compatibility, it must not be between 2.0.10 ~ 2.6.2 public static final String DEFAULT_DUBBO_PROTOCOL_VERSION = "2.0.2"; // version 1.0.0 represents Dubbo rpc protocol before v2.6.2 public static final int LEGACY_DUBBO_PROTOCOL_VERSION = 10000; // 1.0.0 // Dubbo implementation version. private static String VERSION; private static String LATEST_COMMIT_ID; /** * For protocol compatibility purpose. * Because {@link #isSupportResponseAttachment} is checked for every call, int compare expect to has higher * performance than string. */ public static final int LOWEST_VERSION_FOR_RESPONSE_ATTACHMENT = 2000200; // 2.0.2 public static final int HIGHEST_PROTOCOL_VERSION = 2009900; // 2.0.99 private static final Map<String, Integer> VERSION2INT = new HashMap<>(); static { // get dubbo version and last commit id try { tryLoadVersionFromResource(); checkDuplicate(); } catch (Throwable e) { logger.warn( COMMON_UNEXPECTED_EXCEPTION, "", "", "continue the old logic, ignore exception " + e.getMessage(), e); } if (StringUtils.isEmpty(VERSION)) { VERSION = getVersion(Version.class, ""); } if (StringUtils.isEmpty(LATEST_COMMIT_ID)) { LATEST_COMMIT_ID = ""; } } private static void tryLoadVersionFromResource() throws IOException { Enumeration<URL> configLoader = Version.class.getClassLoader().getResources(CommonConstants.DUBBO_VERSIONS_KEY + "/dubbo-common"); if (configLoader.hasMoreElements()) { URL url = configLoader.nextElement(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { if (line.startsWith("revision=")) { VERSION = line.substring("revision=".length()); } else if (line.startsWith("git.commit.id=")) { LATEST_COMMIT_ID = line.substring("git.commit.id=".length()); } } } } } private Version() {} public static String getProtocolVersion() { return DEFAULT_DUBBO_PROTOCOL_VERSION; } public static String getVersion() { return VERSION; } public static String getLastCommitId() { return LATEST_COMMIT_ID; } /** * Compare versions * * @return the value {@code 0} if {@code version1 == version2}; * a value less than {@code 0} if {@code version1 < version2}; and * a value greater than {@code 0} if {@code version1 > version2} */ public static int compare(String version1, String version2) { return Integer.compare(getIntVersion(version1), getIntVersion(version2)); } /** * Check the framework release version number to decide if it's 2.7.0 or higher */ public static boolean isRelease270OrHigher(String version) { if (StringUtils.isEmpty(version)) { return false; } return getIntVersion(version) >= 2070000; } /** * Check the framework release version number to decide if it's 2.6.3 or higher * * @param version, the sdk version */ public static boolean isRelease263OrHigher(String version) { return getIntVersion(version) >= 2060300; } /** * Dubbo 2.x protocol version numbers are limited to 2.0.2/2000200 ~ 2.0.99/2009900, other versions are consider as * invalid or not from official release. * * @param version, the protocol version. * @return */ public static boolean isSupportResponseAttachment(String version) { if (StringUtils.isEmpty(version)) { return false; } int iVersion = getIntVersion(version); if (iVersion >= LOWEST_VERSION_FOR_RESPONSE_ATTACHMENT && iVersion <= HIGHEST_PROTOCOL_VERSION) { return true; } return false; } public static int getIntVersion(String version) { Integer v = VERSION2INT.get(version); if (v == null) { try { v = parseInt(version); // e.g., version number 2.6.3 will convert to 2060300 if (version.split("\\.").length == 3) { v = v * 100; } } catch (Exception e) { logger.warn( COMMON_UNEXPECTED_EXCEPTION, "", "", "Please make sure your version value has the right format: " + "\n 1. only contains digital number: 2.0.0; \n 2. with string suffix: 2.6.7-stable. " + "\nIf you are using Dubbo before v2.6.2, the version value is the same with the jar version."); v = LEGACY_DUBBO_PROTOCOL_VERSION; } VERSION2INT.put(version, v); } return v; } private static int parseInt(String version) { int v = 0; String[] vArr = version.split("\\."); int len = vArr.length; for (int i = 0; i < len; i++) { String subV = getPrefixDigits(vArr[i]); if (StringUtils.isNotEmpty(subV)) { v += Integer.parseInt(subV) * Math.pow(10, (len - i - 1) * 2); } } return v; } /** * get prefix digits from given version string */ private static String getPrefixDigits(String v) { Matcher matcher = PREFIX_DIGITS_PATTERN.matcher(v); if (matcher.find()) { return matcher.group(1); } return ""; } public static String getVersion(Class<?> cls, String defaultVersion) { try { // find version info from MANIFEST.MF first Package pkg = cls.getPackage(); String version = null; if (pkg != null) { version = pkg.getImplementationVersion(); if (StringUtils.isNotEmpty(version)) { return version; } version = pkg.getSpecificationVersion(); if (StringUtils.isNotEmpty(version)) { return version; } } // guess version from jar file name if nothing's found from MANIFEST.MF CodeSource codeSource = cls.getProtectionDomain().getCodeSource(); if (codeSource == null) { logger.info("No codeSource for class " + cls.getName() + " when getVersion, use default version " + defaultVersion); return defaultVersion; } URL location = codeSource.getLocation(); if (location == null) { logger.info("No location for class " + cls.getName() + " when getVersion, use default version " + defaultVersion); return defaultVersion; } String file = location.getFile(); if (!StringUtils.isEmpty(file) && file.endsWith(".jar")) { version = getFromFile(file); } // return default version if no version info is found return StringUtils.isEmpty(version) ? defaultVersion : version; } catch (Throwable e) { // return default version when any exception is thrown logger.error( COMMON_UNEXPECTED_EXCEPTION, "", "", "return default version, ignore exception " + e.getMessage(), e); return defaultVersion; } } /** * get version from file: path/to/group-module-x.y.z.jar, returns x.y.z */ private static String getFromFile(String file) { // remove suffix ".jar": "path/to/group-module-x.y.z" file = file.substring(0, file.length() - 4); // remove path: "group-module-x.y.z" int i = file.lastIndexOf('/'); if (i >= 0) { file = file.substring(i + 1); } // remove group: "module-x.y.z" i = file.indexOf("-"); if (i >= 0) { file = file.substring(i + 1); } // remove module: "x.y.z" while (file.length() > 0 && !Character.isDigit(file.charAt(0))) { i = file.indexOf("-"); if (i >= 0) { file = file.substring(i + 1); } else { break; } } return file; } private static void checkDuplicate() { try { checkArtifacts(loadArtifactIds()); } catch (Throwable e) { logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", e.getMessage(), e); } } private static void checkArtifacts(Set<String> artifactIds) throws IOException { if (!artifactIds.isEmpty()) { for (String artifactId : artifactIds) { checkArtifact(artifactId); } } } private static void checkArtifact(String artifactId) throws IOException { Enumeration<URL> artifactEnumeration = Version.class.getClassLoader().getResources(CommonConstants.DUBBO_VERSIONS_KEY + artifactId); while (artifactEnumeration.hasMoreElements()) { URL url = artifactEnumeration.nextElement(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { if (line.startsWith("#")) { continue; } String[] artifactInfo = line.split("="); if (artifactInfo.length == 2) { String key = artifactInfo[0]; String value = artifactInfo[1]; checkVersion(artifactId, url, key, value); } } } } } private static void checkVersion(String artifactId, URL url, String key, String value) { if ("revision".equals(key) && !value.equals(VERSION)) { String error = "Inconsistent version " + value + " found in " + artifactId + " from " + url.getPath() + ", " + "expected dubbo-common version is " + VERSION; logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", error); } if ("git.commit.id".equals(key) && !value.equals(LATEST_COMMIT_ID)) { String error = "Inconsistent git build commit id " + value + " found in " + artifactId + " from " + url.getPath() + ", " + "expected dubbo-common version is " + LATEST_COMMIT_ID; logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", error); } } private static Set<String> loadArtifactIds() throws IOException { Enumeration<URL> artifactsEnumeration = Version.class.getClassLoader().getResources(CommonConstants.DUBBO_VERSIONS_KEY + "/.artifacts"); Set<String> artifactIds = new HashSet<>(); while (artifactsEnumeration.hasMoreElements()) { URL url = artifactsEnumeration.nextElement(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { if (line.startsWith("#")) { continue; } if (StringUtils.isEmpty(line)) { continue; } artifactIds.add(line); } } } return artifactIds; } }
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/CommonScopeModelInitializer.java
dubbo-common/src/main/java/org/apache/dubbo/common/CommonScopeModelInitializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.config.ConfigurationCache; import org.apache.dubbo.common.convert.ConverterUtil; import org.apache.dubbo.common.lang.ShutdownHookCallbacks; import org.apache.dubbo.common.serialization.ClassHolder; import org.apache.dubbo.common.ssl.CertManager; import org.apache.dubbo.common.status.reporter.FrameworkStatusReportService; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; import org.apache.dubbo.common.utils.DefaultSerializeClassChecker; import org.apache.dubbo.common.utils.SerializeSecurityConfigurator; import org.apache.dubbo.common.utils.SerializeSecurityManager; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ScopeModelInitializer; public class CommonScopeModelInitializer implements ScopeModelInitializer { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) { ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory(); beanFactory.registerBean(FrameworkExecutorRepository.class); beanFactory.registerBean(ConverterUtil.class); beanFactory.registerBean(SerializeSecurityManager.class); beanFactory.registerBean(DefaultSerializeClassChecker.class); beanFactory.registerBean(CertManager.class); beanFactory.registerBean(ClassHolder.class); } @Override public void initializeApplicationModel(ApplicationModel applicationModel) { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); beanFactory.registerBean(ShutdownHookCallbacks.class); beanFactory.registerBean(FrameworkStatusReportService.class); beanFactory.registerBean(new ConfigurationCache()); } @Override public void initializeModuleModel(ModuleModel moduleModel) { ScopeBeanFactory beanFactory = moduleModel.getBeanFactory(); beanFactory.registerBean(new ConfigurationCache()); beanFactory.registerBean(SerializeSecurityConfigurator.class); } }
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/ServiceKey.java
dubbo-common/src/main/java/org/apache/dubbo/common/ServiceKey.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.StringUtils; import java.util.Objects; public class ServiceKey { private final String interfaceName; private final String group; private final String version; public ServiceKey(String interfaceName, String version, String group) { this.interfaceName = interfaceName; this.group = group; this.version = version; } public String getInterfaceName() { return interfaceName; } public String getGroup() { return group; } public String getVersion() { return version; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ServiceKey that = (ServiceKey) o; return Objects.equals(interfaceName, that.interfaceName) && Objects.equals(group, that.group) && Objects.equals(version, that.version); } @Override public int hashCode() { return Objects.hash(interfaceName, group, version); } @Override public String toString() { return BaseServiceMetadata.buildServiceKey(interfaceName, group, version); } public static class Matcher { public static boolean isMatch(ServiceKey rule, ServiceKey target) { // 1. match interface (accurate match) if (!Objects.equals(rule.getInterfaceName(), target.getInterfaceName())) { return false; } // 2. match version (accurate match) // 2.1. if rule version is *, match all if (!CommonConstants.ANY_VALUE.equals(rule.getVersion())) { // 2.2. if rule version is null, target version should be null if (StringUtils.isEmpty(rule.getVersion()) && !StringUtils.isEmpty(target.getVersion())) { return false; } if (!StringUtils.isEmpty(rule.getVersion())) { // 2.3. if rule version contains ',', split and match each if (rule.getVersion().contains(CommonConstants.COMMA_SEPARATOR)) { String[] versions = rule.getVersion().split("\\" + CommonConstants.COMMA_SEPARATOR, -1); boolean match = false; for (String version : versions) { version = version.trim(); if (StringUtils.isEmpty(version) && StringUtils.isEmpty(target.getVersion())) { match = true; break; } else if (version.equals(target.getVersion())) { match = true; break; } } if (!match) { return false; } } // 2.4. if rule version is not contains ',', match directly else if (!Objects.equals(rule.getVersion(), target.getVersion())) { return false; } } } // 3. match group (wildcard match) // 3.1. if rule group is *, match all if (!CommonConstants.ANY_VALUE.equals(rule.getGroup())) { // 3.2. if rule group is null, target group should be null if (StringUtils.isEmpty(rule.getGroup()) && !StringUtils.isEmpty(target.getGroup())) { return false; } if (!StringUtils.isEmpty(rule.getGroup())) { // 3.3. if rule group contains ',', split and match each if (rule.getGroup().contains(CommonConstants.COMMA_SEPARATOR)) { String[] groups = rule.getGroup().split("\\" + CommonConstants.COMMA_SEPARATOR, -1); boolean match = false; for (String group : groups) { group = group.trim(); if (StringUtils.isEmpty(group) && StringUtils.isEmpty(target.getGroup())) { match = true; break; } else if (group.equals(target.getGroup())) { match = true; break; } } if (!match) { return false; } } // 3.4. if rule group is not contains ',', match directly else if (!Objects.equals(rule.getGroup(), target.getGroup())) { return false; } } } return true; } } }
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/Experimental.java
dubbo-common/src/main/java/org/apache/dubbo/common/Experimental.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicating unstable API, may get removed or changed in future releases. */ @Retention(RetentionPolicy.CLASS) @Target({ ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.PACKAGE, ElementType.TYPE }) public @interface Experimental { String value(); }
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/Extension.java
dubbo-common/src/main/java/org/apache/dubbo/common/Extension.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; 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; /** * Marker for extension interface * <p/> * Changes on extension configuration file <br/> * Use <code>Protocol</code> as an example, its configuration file 'META-INF/dubbo/com.xxx.Protocol' is changes from: <br/> * <pre> * com.foo.XxxProtocol * com.foo.YyyProtocol * </pre> * <p> * to key-value pair <br/> * <pre> * xxx=com.foo.XxxProtocol * yyy=com.foo.YyyProtocol * </pre> * <br/> * The reason for this change is: * <p> * If there's third party library referenced by static field or by method in extension implementation, its class will * fail to initialize if the third party library doesn't exist. In this case, dubbo cannot figure out extension's id * therefore cannot be able to map the exception information with the extension, if the previous format is used. * <p/> * For example: * <p> * Fails to load Extension("mina"). When user configure to use mina, dubbo will complain the extension cannot be loaded, * instead of reporting which extract extension implementation fails and the extract reason. * </p> * * @deprecated because it's too general, switch to use {@link org.apache.dubbo.common.extension.SPI} */ @Deprecated @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface Extension { /** * @deprecated */ @Deprecated String value() 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/common/profiler/ProfilerEntry.java
dubbo-common/src/main/java/org/apache/dubbo/common/profiler/ProfilerEntry.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.profiler; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public class ProfilerEntry { private final List<ProfilerEntry> sub = new ArrayList<>(4); private final String message; private final ProfilerEntry parent; private final ProfilerEntry first; private final long startTime; private final AtomicInteger requestCount; private long endTime; public ProfilerEntry(String message) { this.message = message; this.parent = null; this.first = this; this.startTime = System.nanoTime(); this.requestCount = new AtomicInteger(1); } public ProfilerEntry(String message, ProfilerEntry parentEntry, ProfilerEntry firstEntry) { this.message = message; this.parent = parentEntry; this.first = firstEntry; this.startTime = System.nanoTime(); this.requestCount = parentEntry.getRequestCount(); } public List<ProfilerEntry> getSub() { return sub; } public String getMessage() { return message; } public ProfilerEntry getParent() { return parent; } public ProfilerEntry getFirst() { return first; } public long getStartTime() { return startTime; } public void setEndTime(long endTime) { this.endTime = endTime; } public long getEndTime() { return endTime; } public AtomicInteger getRequestCount() { return requestCount; } }
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/profiler/Profiler.java
dubbo-common/src/main/java/org/apache/dubbo/common/profiler/Profiler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.profiler; import org.apache.dubbo.common.threadlocal.InternalThreadLocal; import java.util.LinkedList; import java.util.List; public class Profiler { public static final String PROFILER_KEY = "DUBBO_INVOKE_PROFILER"; public static final int MAX_ENTRY_SIZE = 1000; private static final InternalThreadLocal<ProfilerEntry> bizProfiler = new InternalThreadLocal<>(); public static ProfilerEntry start(String message) { return new ProfilerEntry(message); } public static ProfilerEntry enter(ProfilerEntry entry, String message) { ProfilerEntry subEntry = new ProfilerEntry(message, entry, entry.getFirst()); if (subEntry.getRequestCount().incrementAndGet() < MAX_ENTRY_SIZE) { entry.getSub().add(subEntry); } // ignore if sub entry size is exceed return subEntry; } public static ProfilerEntry release(ProfilerEntry entry) { entry.setEndTime(System.nanoTime()); ProfilerEntry parent = entry.getParent(); if (parent != null) { return parent; } else { return entry; } } public static ProfilerEntry setToBizProfiler(ProfilerEntry entry) { try { return bizProfiler.get(); } finally { bizProfiler.set(entry); } } public static ProfilerEntry getBizProfiler() { return bizProfiler.get(); } public static void removeBizProfiler() { bizProfiler.remove(); } public static String buildDetail(ProfilerEntry entry) { long totalUsageTime = entry.getEndTime() - entry.getStartTime(); return "Start time: " + entry.getStartTime() + "\n" + String.join("\n", buildDetail(entry, entry.getStartTime(), totalUsageTime, 0)); } public static List<String> buildDetail(ProfilerEntry entry, long startTime, long totalUsageTime, int depth) { StringBuilder stringBuilder = new StringBuilder(); long usage = entry.getEndTime() - entry.getStartTime(); int percent = (int) (((usage) * 100) / totalUsageTime); long offset = entry.getStartTime() - startTime; List<String> lines = new LinkedList<>(); stringBuilder .append("+-[ Offset: ") .append(offset / 1000_000) .append('.') .append(String.format("%06d", offset % 1000_000)) .append("ms; Usage: ") .append(usage / 1000_000) .append('.') .append(String.format("%06d", usage % 1000_000)) .append("ms, ") .append(percent) .append("% ] ") .append(entry.getMessage()); lines.add(stringBuilder.toString()); List<ProfilerEntry> entrySub = entry.getSub(); for (int i = 0, entrySubSize = entrySub.size(); i < entrySubSize; i++) { ProfilerEntry sub = entrySub.get(i); List<String> subLines = buildDetail(sub, startTime, totalUsageTime, depth + 1); if (i < entrySubSize - 1) { lines.add(" " + subLines.get(0)); for (int j = 1, subLinesSize = subLines.size(); j < subLinesSize; j++) { String subLine = subLines.get(j); lines.add(" |" + subLine); } } else { lines.add(" " + subLines.get(0)); for (int j = 1, subLinesSize = subLines.size(); j < subLinesSize; j++) { String subLine = subLines.get(j); lines.add(" " + subLine); } } } return lines; } }
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/profiler/ProfilerSwitch.java
dubbo-common/src/main/java/org/apache/dubbo/common/profiler/ProfilerSwitch.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.profiler; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * TODO */ public class ProfilerSwitch { private static final AtomicBoolean enableDetailProfiler = new AtomicBoolean(false); private static final AtomicBoolean enableSimpleProfiler = new AtomicBoolean(true); private static final AtomicReference<Double> warnPercent = new AtomicReference<>(0.75); public static void enableSimpleProfiler() { enableSimpleProfiler.set(true); } public static void disableSimpleProfiler() { enableSimpleProfiler.set(false); } public static void enableDetailProfiler() { enableDetailProfiler.set(true); } public static void disableDetailProfiler() { enableDetailProfiler.set(false); } public static boolean isEnableDetailProfiler() { return enableDetailProfiler.get() && enableSimpleProfiler.get(); } public static boolean isEnableSimpleProfiler() { return enableSimpleProfiler.get(); } public static double getWarnPercent() { return warnPercent.get(); } public static void setWarnPercent(double percent) { warnPercent.set(percent); } }
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/system/OperatingSystemBeanManager.java
dubbo-common/src/main/java/org/apache/dubbo/common/system/OperatingSystemBeanManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.system; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.MethodUtils; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Objects; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CLASS_NOT_FOUND; /** * OperatingSystemBeanManager related. */ public class OperatingSystemBeanManager { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(OperatingSystemBeanManager.class); /** * com.ibm for J9 * com.sun for HotSpot */ private static final List<String> OPERATING_SYSTEM_BEAN_CLASS_NAMES = Arrays.asList("com.sun.management.OperatingSystemMXBean", "com.ibm.lang.management.OperatingSystemMXBean"); private static final OperatingSystemMXBean OPERATING_SYSTEM_BEAN; private static final Class<?> OPERATING_SYSTEM_BEAN_CLASS; private static final Method SYSTEM_CPU_USAGE_METHOD; private static final Method PROCESS_CPU_USAGE_METHOD; static { OPERATING_SYSTEM_BEAN = ManagementFactory.getOperatingSystemMXBean(); OPERATING_SYSTEM_BEAN_CLASS = loadOne(OPERATING_SYSTEM_BEAN_CLASS_NAMES); SYSTEM_CPU_USAGE_METHOD = deduceMethod("getSystemCpuLoad"); PROCESS_CPU_USAGE_METHOD = deduceMethod("getProcessCpuLoad"); } private OperatingSystemBeanManager() {} public static OperatingSystemMXBean getOperatingSystemBean() { return OPERATING_SYSTEM_BEAN; } public static double getSystemCpuUsage() { return MethodUtils.invokeAndReturnDouble(SYSTEM_CPU_USAGE_METHOD, OPERATING_SYSTEM_BEAN); } public static double getProcessCpuUsage() { return MethodUtils.invokeAndReturnDouble(PROCESS_CPU_USAGE_METHOD, OPERATING_SYSTEM_BEAN); } private static Class<?> loadOne(List<String> classNames) { for (String className : classNames) { try { return Class.forName(className); } catch (ClassNotFoundException e) { LOGGER.warn( COMMON_CLASS_NOT_FOUND, "", "", "[OperatingSystemBeanManager] Failed to load operating system bean class.", e); } } return null; } private static Method deduceMethod(String name) { if (Objects.isNull(OPERATING_SYSTEM_BEAN_CLASS)) { return null; } try { OPERATING_SYSTEM_BEAN_CLASS.cast(OPERATING_SYSTEM_BEAN); return OPERATING_SYSTEM_BEAN_CLASS.getDeclaredMethod(name); } catch (Exception e) { 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/beans/ScopeBeanException.java
dubbo-common/src/main/java/org/apache/dubbo/common/beans/ScopeBeanException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.beans; public class ScopeBeanException extends RuntimeException { public ScopeBeanException(String message, Throwable cause) { super(message, cause); } public ScopeBeanException(String message) { super(message); } }
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/beans/ScopeBeanExtensionInjector.java
dubbo-common/src/main/java/org/apache/dubbo/common/beans/ScopeBeanExtensionInjector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.beans; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.extension.ExtensionInjector; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ScopeModelAware; /** * Inject scope bean to SPI extension instance */ public class ScopeBeanExtensionInjector implements ExtensionInjector, ScopeModelAware { private ScopeBeanFactory beanFactory; @Override public void setScopeModel(final ScopeModel scopeModel) { this.beanFactory = scopeModel.getBeanFactory(); } @Override public <T> T getInstance(final Class<T> type, final String name) { return beanFactory == null ? null : beanFactory.getBean(name, 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/common/beans/support/InstantiationStrategy.java
dubbo-common/src/main/java/org/apache/dubbo/common/beans/support/InstantiationStrategy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.beans.support; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.extension.ExtensionLoader; 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.ScopeModelAccessor; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; /** * Interface to create instance for specify type, using both in {@link ExtensionLoader} and {@link ScopeBeanFactory}. */ public class InstantiationStrategy { private final ScopeModelAccessor scopeModelAccessor; public InstantiationStrategy() { this(null); } public InstantiationStrategy(ScopeModelAccessor scopeModelAccessor) { this.scopeModelAccessor = scopeModelAccessor; } @SuppressWarnings("unchecked") public <T> T instantiate(Class<T> type) throws ReflectiveOperationException { // should not use default constructor directly, maybe also has another constructor matched scope model arguments // 1. try to get default constructor Constructor<T> defaultConstructor = null; try { defaultConstructor = type.getConstructor(); } catch (NoSuchMethodException e) { // ignore no default constructor } // 2. use matched constructor if found List<Constructor<?>> matchedConstructors = new ArrayList<>(); Constructor<?>[] declaredConstructors = type.getConstructors(); for (Constructor<?> constructor : declaredConstructors) { if (isMatched(constructor)) { matchedConstructors.add(constructor); } } // remove default constructor from matchedConstructors if (defaultConstructor != null) { matchedConstructors.remove(defaultConstructor); } // match order: // 1. the only matched constructor with parameters // 2. default constructor if absent Constructor<?> targetConstructor; if (matchedConstructors.size() > 1) { throw new IllegalArgumentException("Expect only one but found " + matchedConstructors.size() + " matched constructors for type: " + type.getName() + ", matched constructors: " + matchedConstructors); } else if (matchedConstructors.size() == 1) { targetConstructor = matchedConstructors.get(0); } else if (defaultConstructor != null) { targetConstructor = defaultConstructor; } else { throw new IllegalArgumentException("None matched constructor was found for type: " + type.getName()); } // create instance with arguments Class<?>[] parameterTypes = targetConstructor.getParameterTypes(); Object[] args = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { args[i] = getArgumentValueForType(parameterTypes[i]); } return (T) targetConstructor.newInstance(args); } private boolean isMatched(Constructor<?> constructor) { for (Class<?> parameterType : constructor.getParameterTypes()) { if (!isSupportedConstructorParameterType(parameterType)) { return false; } } return true; } private boolean isSupportedConstructorParameterType(Class<?> parameterType) { return ScopeModel.class.isAssignableFrom(parameterType); } private Object getArgumentValueForType(Class<?> parameterType) { // get scope mode value if (scopeModelAccessor != null) { if (parameterType == ScopeModel.class) { return scopeModelAccessor.getScopeModel(); } else if (parameterType == FrameworkModel.class) { return scopeModelAccessor.getFrameworkModel(); } else if (parameterType == ApplicationModel.class) { return scopeModelAccessor.getApplicationModel(); } else if (parameterType == ModuleModel.class) { return scopeModelAccessor.getModuleModel(); } } 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/beans/factory/ScopeBeanFactory.java
dubbo-common/src/main/java/org/apache/dubbo/common/beans/factory/ScopeBeanFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.beans.factory; import org.apache.dubbo.common.beans.ScopeBeanException; import org.apache.dubbo.common.beans.support.InstantiationStrategy; import org.apache.dubbo.common.extension.ExtensionAccessor; import org.apache.dubbo.common.extension.ExtensionAccessorAware; import org.apache.dubbo.common.extension.ExtensionPostProcessor; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.Disposable; import org.apache.dubbo.common.resource.Initializable; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.Pair; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.TypeUtils; import org.apache.dubbo.rpc.model.ScopeModelAccessor; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_DESTROY_INVOKER; /** * A bean factory for internal sharing. */ public final class ScopeBeanFactory { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(ScopeBeanFactory.class); private final ScopeBeanFactory parent; private final ExtensionAccessor extensionAccessor; private final List<ExtensionPostProcessor> extensionPostProcessors; private final Map<Class<?>, AtomicInteger> beanNameIdCounterMap = CollectionUtils.newConcurrentHashMap(); private final List<BeanInfo> registeredBeanInfos = new CopyOnWriteArrayList<>(); private final List<BeanDefinition<?>> registeredBeanDefinitions = new CopyOnWriteArrayList<>(); private InstantiationStrategy instantiationStrategy; private final AtomicBoolean destroyed = new AtomicBoolean(); private final Set<Class<?>> registeredClasses = new ConcurrentHashSet<>(); private final Map<Pair<Class<?>, String>, Optional<Object>> beanCache = CollectionUtils.newConcurrentHashMap(); public ScopeBeanFactory(ScopeBeanFactory parent, ExtensionAccessor extensionAccessor) { this.parent = parent; this.extensionAccessor = extensionAccessor; extensionPostProcessors = extensionAccessor.getExtensionDirector().getExtensionPostProcessors(); initInstantiationStrategy(); } private void initInstantiationStrategy() { for (ExtensionPostProcessor extensionPostProcessor : extensionPostProcessors) { if (extensionPostProcessor instanceof ScopeModelAccessor) { instantiationStrategy = new InstantiationStrategy((ScopeModelAccessor) extensionPostProcessor); break; } } if (instantiationStrategy == null) { instantiationStrategy = new InstantiationStrategy(); } } public <T> T registerBean(Class<T> clazz) throws ScopeBeanException { return getOrRegisterBean(null, clazz); } public <T> T registerBean(String name, Class<T> clazz) throws ScopeBeanException { return getOrRegisterBean(name, clazz); } public <T> void registerBeanDefinition(Class<T> clazz) { registerBeanDefinition(null, clazz); } public <T> void registerBeanDefinition(String name, Class<T> clazz) { registeredBeanDefinitions.add(new BeanDefinition<>(name, clazz)); } public <T> void registerBeanFactory(Supplier<T> factory) { registerBeanFactory(null, factory); } @SuppressWarnings("unchecked") public <T> void registerBeanFactory(String name, Supplier<T> factory) { Class<T> clazz = (Class<T>) TypeUtils.getSuperGenericType(factory.getClass(), 0); if (clazz == null) { throw new ScopeBeanException("unable to determine bean class from factory's superclass or interface"); } registeredBeanDefinitions.add(new BeanDefinition<>(name, clazz, factory)); } private <T> T createAndRegisterBean(String name, Class<T> clazz) { checkDestroyed(); T instance = getBean(name, clazz); if (instance != null) { throw new ScopeBeanException( "already exists bean with same name and type, name=" + name + ", type=" + clazz.getName()); } try { instance = instantiationStrategy.instantiate(clazz); } catch (Throwable e) { throw new ScopeBeanException("create bean instance failed, type=" + clazz.getName(), e); } registerBean(name, instance); return instance; } public void registerBean(Object bean) { registerBean(null, bean); } public void registerBean(String name, Object bean) { checkDestroyed(); // avoid duplicated register same bean if (containsBean(name, bean)) { return; } Class<?> beanClass = bean.getClass(); if (name == null) { name = beanClass.getName() + "#" + getNextId(beanClass); } initializeBean(name, bean); registeredBeanInfos.add(new BeanInfo(name, bean)); beanCache.entrySet().removeIf(e -> e.getKey().getLeft().isAssignableFrom(beanClass)); } public <T> T getOrRegisterBean(Class<T> type) { return getOrRegisterBean(null, type); } @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") public <T> T getOrRegisterBean(String name, Class<T> type) { T bean = getBean(name, type); if (bean == null) { // lock by type synchronized (type) { bean = getBean(name, type); if (bean == null) { bean = createAndRegisterBean(name, type); } } } registeredClasses.add(type); return bean; } public <T> T getOrRegisterBean(Class<T> type, Function<? super Class<T>, ? extends T> mappingFunction) { return getOrRegisterBean(null, type, mappingFunction); } @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") public <T> T getOrRegisterBean( String name, Class<T> type, Function<? super Class<T>, ? extends T> mappingFunction) { T bean = getBean(name, type); if (bean == null) { // lock by type synchronized (type) { bean = getBean(name, type); if (bean == null) { bean = mappingFunction.apply(type); registerBean(name, bean); } } } return bean; } private void initializeBean(String name, Object bean) { checkDestroyed(); try { if (bean instanceof ExtensionAccessorAware) { ((ExtensionAccessorAware) bean).setExtensionAccessor(extensionAccessor); } for (ExtensionPostProcessor processor : extensionPostProcessors) { processor.postProcessAfterInitialization(bean, name); } if (bean instanceof Initializable) { ((Initializable) bean).initialize(extensionAccessor); } } catch (Exception e) { throw new ScopeBeanException( "register bean failed! name=" + name + ", type=" + bean.getClass().getName(), e); } } @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") private void initializeBeanDefinitions(Class<?> type) { for (int i = 0, size = registeredBeanDefinitions.size(); i < size; i++) { BeanDefinition<?> definition = registeredBeanDefinitions.get(i); if (definition.initialized) { continue; } Class<?> beanClass = definition.beanClass; if (!type.isAssignableFrom(beanClass)) { continue; } synchronized (type) { if (definition.initialized) { continue; } Object bean; Supplier<?> factory = definition.beanFactory; if (factory == null) { try { bean = instantiationStrategy.instantiate(beanClass); } catch (Throwable e) { throw new ScopeBeanException("create bean instance failed, type=" + beanClass.getName(), e); } } else { initializeBean(definition.name, factory); try { bean = factory.get(); } catch (Exception e) { throw new ScopeBeanException("create bean instance failed, type=" + beanClass.getName(), e); } } registerBean(definition.name, bean); definition.initialized = true; } } } private boolean containsBean(String name, Object bean) { for (BeanInfo beanInfo : registeredBeanInfos) { if (beanInfo.instance == bean && (name == null || name.equals(beanInfo.name))) { return true; } } return false; } private int getNextId(Class<?> beanClass) { return beanNameIdCounterMap .computeIfAbsent(beanClass, key -> new AtomicInteger()) .incrementAndGet(); } @SuppressWarnings("unchecked") public <T> List<T> getBeansOfType(Class<T> type) { initializeBeanDefinitions(type); List<T> currentBeans = (List<T>) registeredBeanInfos.stream() .filter(beanInfo -> type.isInstance(beanInfo.instance)) .map(beanInfo -> beanInfo.instance) .collect(Collectors.toList()); if (parent != null) { currentBeans.addAll(parent.getBeansOfType(type)); } return currentBeans; } public <T> T getBean(Class<T> type) { return getBean(null, type); } public <T> T getBean(String name, Class<T> type) { T bean = getBeanFromCache(name, type); if (bean == null && parent != null) { return parent.getBean(name, type); } return bean; } @SuppressWarnings("unchecked") private <T> T getBeanFromCache(String name, Class<T> type) { Pair<Class<?>, String> key = Pair.of(type, name); Optional<Object> value = beanCache.get(key); if (value == null) { initializeBeanDefinitions(type); value = beanCache.computeIfAbsent(key, k -> { try { return Optional.ofNullable(getBeanInternal(name, type)); } catch (ScopeBeanException e) { return Optional.of(e); } }); } Object bean = value.orElse(null); if (bean instanceof ScopeBeanException) { throw (ScopeBeanException) bean; } return (T) bean; } @SuppressWarnings("unchecked") private <T> T getBeanInternal(String name, Class<T> type) { // All classes are derived from java.lang.Object, cannot filter bean by it if (type == Object.class) { return null; } List<BeanInfo> candidates = null; BeanInfo firstCandidate = null; for (BeanInfo beanInfo : registeredBeanInfos) { // if required bean type is same class/superclass/interface of the registered bean if (type.isAssignableFrom(beanInfo.instance.getClass())) { if (StringUtils.isEquals(beanInfo.name, name)) { return (T) beanInfo.instance; } else { // optimize for only one matched bean if (firstCandidate == null) { firstCandidate = beanInfo; } else { if (candidates == null) { candidates = new ArrayList<>(); candidates.add(firstCandidate); } candidates.add(beanInfo); } } } } // if bean name not matched and only single candidate if (candidates != null) { if (candidates.size() == 1) { return (T) candidates.get(0).instance; } else if (candidates.size() > 1) { List<String> candidateBeanNames = candidates.stream().map(beanInfo -> beanInfo.name).collect(Collectors.toList()); throw new ScopeBeanException("expected single matching bean but found " + candidates.size() + " candidates for type [" + type.getName() + "]: " + candidateBeanNames); } } else if (firstCandidate != null) { return (T) firstCandidate.instance; } return null; } public void destroy() { if (destroyed.compareAndSet(false, true)) { for (BeanInfo beanInfo : registeredBeanInfos) { if (beanInfo.instance instanceof Disposable) { try { Disposable beanInstance = (Disposable) beanInfo.instance; beanInstance.destroy(); } catch (Throwable e) { LOGGER.error( CONFIG_FAILED_DESTROY_INVOKER, "", "", "An error occurred when destroy bean [name=" + beanInfo.name + ", bean=" + beanInfo.instance + "]: " + e, e); } } } registeredBeanInfos.clear(); registeredBeanDefinitions.clear(); beanCache.clear(); } } public boolean isDestroyed() { return destroyed.get(); } private void checkDestroyed() { if (destroyed.get()) { throw new IllegalStateException("ScopeBeanFactory is destroyed"); } } static final class BeanInfo { private final String name; private final Object instance; BeanInfo(String name, Object instance) { this.name = name; this.instance = instance; } } static final class BeanDefinition<T> { private final String name; private final Class<T> beanClass; private final Supplier<T> beanFactory; private volatile boolean initialized; BeanDefinition(String name, Class<T> beanClass) { this.name = name; this.beanClass = beanClass; beanFactory = null; } BeanDefinition(String name, Class<T> beanClass, Supplier<T> beanFactory) { this.name = name; this.beanClass = beanClass; this.beanFactory = beanFactory; } } public Set<Class<?>> getRegisteredClasses() { return registeredClasses; } }
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/threadlocal/InternalThreadLocal.java
dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocal.java
/* * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF 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.threadlocal; import java.util.Collections; import java.util.IdentityHashMap; import java.util.Set; /** * InternalThreadLocal * A special variant of {@link ThreadLocal} that yields higher access performance when accessed from a * {@link InternalThread}. * <p></p> * Internally, a {@link InternalThread} uses a constant index in an array, instead of using hash code and hash table, * to look for a variable. Although seemingly very subtle, it yields slight performance advantage over using a hash * table, and it is useful when accessed frequently. * <p></p> * This design is learning from {@see io.netty.util.concurrent.FastThreadLocal} which is in Netty. */ public class InternalThreadLocal<V> extends ThreadLocal<V> { private static final int VARIABLES_TO_REMOVE_INDEX = InternalThreadLocalMap.nextVariableIndex(); private final int index; public InternalThreadLocal() { index = InternalThreadLocalMap.nextVariableIndex(); } /** * Removes all {@link InternalThreadLocal} variables bound to the current thread. This operation is useful when you * are in a container environment, and you don't want to leave the thread local variables in the threads you do not * manage. */ @SuppressWarnings("unchecked") public static void removeAll() { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet(); if (threadLocalMap == null) { return; } try { Object v = threadLocalMap.indexedVariable(VARIABLES_TO_REMOVE_INDEX); if (v != null && v != InternalThreadLocalMap.UNSET) { Set<InternalThreadLocal<?>> variablesToRemove = (Set<InternalThreadLocal<?>>) v; InternalThreadLocal<?>[] variablesToRemoveArray = variablesToRemove.toArray(new InternalThreadLocal[0]); for (InternalThreadLocal<?> tlv : variablesToRemoveArray) { tlv.remove(threadLocalMap); } } } finally { InternalThreadLocalMap.remove(); } } /** * Returns the number of thread local variables bound to the current thread. */ public static int size() { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet(); if (threadLocalMap == null) { return 0; } else { return threadLocalMap.size(); } } public static void destroy() { InternalThreadLocalMap.destroy(); } @SuppressWarnings("unchecked") private static void addToVariablesToRemove(InternalThreadLocalMap threadLocalMap, InternalThreadLocal<?> variable) { Object v = threadLocalMap.indexedVariable(VARIABLES_TO_REMOVE_INDEX); Set<InternalThreadLocal<?>> variablesToRemove; if (v == InternalThreadLocalMap.UNSET || v == null) { variablesToRemove = Collections.newSetFromMap(new IdentityHashMap<InternalThreadLocal<?>, Boolean>()); threadLocalMap.setIndexedVariable(VARIABLES_TO_REMOVE_INDEX, variablesToRemove); } else { variablesToRemove = (Set<InternalThreadLocal<?>>) v; } variablesToRemove.add(variable); } @SuppressWarnings("unchecked") private static void removeFromVariablesToRemove(InternalThreadLocalMap threadLocalMap, InternalThreadLocal<?> variable) { Object v = threadLocalMap.indexedVariable(VARIABLES_TO_REMOVE_INDEX); if (v == InternalThreadLocalMap.UNSET || v == null) { return; } Set<InternalThreadLocal<?>> variablesToRemove = (Set<InternalThreadLocal<?>>) v; variablesToRemove.remove(variable); } /** * Returns the current value for the current thread */ @SuppressWarnings("unchecked") @Override public final V get() { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.get(); Object v = threadLocalMap.indexedVariable(index); if (v != InternalThreadLocalMap.UNSET) { return (V) v; } return initialize(threadLocalMap); } public final V getWithoutInitialize() { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.get(); Object v = threadLocalMap.indexedVariable(index); if (v != InternalThreadLocalMap.UNSET) { return (V) v; } return null; } private V initialize(InternalThreadLocalMap threadLocalMap) { V v = null; try { v = initialValue(); } catch (Exception e) { throw new RuntimeException(e); } threadLocalMap.setIndexedVariable(index, v); addToVariablesToRemove(threadLocalMap, this); return v; } /** * Sets the value for the current thread. */ @Override public final void set(V value) { if (value == null || value == InternalThreadLocalMap.UNSET) { remove(); } else { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.get(); if (threadLocalMap.setIndexedVariable(index, value)) { addToVariablesToRemove(threadLocalMap, this); } } } /** * Sets the value to uninitialized; a proceeding call to get() will trigger a call to initialValue(). */ @SuppressWarnings("unchecked") @Override public final void remove() { remove(InternalThreadLocalMap.getIfSet()); } /** * Sets the value to uninitialized for the specified thread local map; * a proceeding call to get() will trigger a call to initialValue(). * The specified thread local map must be for the current thread. */ @SuppressWarnings("unchecked") public final void remove(InternalThreadLocalMap threadLocalMap) { if (threadLocalMap == null) { return; } Object v = threadLocalMap.removeIndexedVariable(index); removeFromVariablesToRemove(threadLocalMap, this); if (v != InternalThreadLocalMap.UNSET) { try { onRemoval((V) v); } catch (Exception e) { throw new RuntimeException(e); } } } /** * Returns the initial value for this thread-local variable. */ @Override protected V initialValue() { return null; } /** * Invoked when this thread local variable is removed by {@link #remove()}. */ protected void onRemoval(@SuppressWarnings("unused") V value) throws Exception { } }
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/threadlocal/NamedInternalThreadFactory.java
dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/NamedInternalThreadFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.threadlocal; import org.apache.dubbo.common.utils.NamedThreadFactory; /** * NamedInternalThreadFactory * This is a threadFactory which produce {@link InternalThread} */ public class NamedInternalThreadFactory extends NamedThreadFactory { public NamedInternalThreadFactory() { super(); } public NamedInternalThreadFactory(String prefix) { super(prefix, false); } public NamedInternalThreadFactory(String prefix, boolean daemon) { super(prefix, daemon); } @Override public Thread newThread(Runnable runnable) { String name = mPrefix + mThreadNum.getAndIncrement(); InternalThread ret = new InternalThread(InternalRunnable.Wrap(runnable), name); ret.setDaemon(mDaemon); return ret; } }
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/threadlocal/InternalThreadLocalMap.java
dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalMap.java
/* * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF 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.threadlocal; import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger; /** * The internal data structure that stores the threadLocal variables for Netty and all {@link InternalThread}s. * Note that this class is for internal use only. Use {@link InternalThread} * unless you know what you are doing. */ public final class InternalThreadLocalMap { private Object[] indexedVariables; private static ThreadLocal<InternalThreadLocalMap> slowThreadLocalMap = new ThreadLocal<>(); private static final AtomicInteger NEXT_INDEX = new AtomicInteger(); static final Object UNSET = new Object(); /** * should not be modified after initialization, * do not set as final due to unit test */ // Reference: https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/util/ArrayList.java#l229 static int ARRAY_LIST_CAPACITY_MAX_SIZE = Integer.MAX_VALUE - 8; private static final int ARRAY_LIST_CAPACITY_EXPAND_THRESHOLD = 1 << 30; public static InternalThreadLocalMap getIfSet() { Thread thread = Thread.currentThread(); if (thread instanceof InternalThread) { return ((InternalThread) thread).threadLocalMap(); } return slowThreadLocalMap.get(); } public static InternalThreadLocalMap get() { Thread thread = Thread.currentThread(); if (thread instanceof InternalThread) { return fastGet((InternalThread) thread); } return slowGet(); } public static InternalThreadLocalMap getAndRemove() { try { Thread thread = Thread.currentThread(); if (thread instanceof InternalThread) { return ((InternalThread) thread).threadLocalMap(); } return slowThreadLocalMap.get(); } finally { remove(); } } public static void set(InternalThreadLocalMap internalThreadLocalMap) { Thread thread = Thread.currentThread(); if (thread instanceof InternalThread) { ((InternalThread) thread).setThreadLocalMap(internalThreadLocalMap); } slowThreadLocalMap.set(internalThreadLocalMap); } public static void remove() { Thread thread = Thread.currentThread(); if (thread instanceof InternalThread) { ((InternalThread) thread).setThreadLocalMap(null); } else { slowThreadLocalMap.remove(); } } public static void destroy() { slowThreadLocalMap = null; } public static int nextVariableIndex() { int index = NEXT_INDEX.getAndIncrement(); if (index >= ARRAY_LIST_CAPACITY_MAX_SIZE || index < 0) { NEXT_INDEX.set(ARRAY_LIST_CAPACITY_MAX_SIZE); throw new IllegalStateException("Too many thread-local indexed variables"); } return index; } public static int lastVariableIndex() { return NEXT_INDEX.get() - 1; } private InternalThreadLocalMap() { indexedVariables = newIndexedVariableTable(); } public Object indexedVariable(int index) { Object[] lookup = indexedVariables; return index < lookup.length ? lookup[index] : UNSET; } /** * @return {@code true} if and only if a new thread-local variable has been created */ public boolean setIndexedVariable(int index, Object value) { Object[] lookup = indexedVariables; if (index < lookup.length) { Object oldValue = lookup[index]; lookup[index] = value; return oldValue == UNSET; } else { expandIndexedVariableTableAndSet(index, value); return true; } } public Object removeIndexedVariable(int index) { Object[] lookup = indexedVariables; if (index < lookup.length) { Object v = lookup[index]; lookup[index] = UNSET; return v; } else { return UNSET; } } public int size() { int count = 0; for (Object o : indexedVariables) { if (o != UNSET) { ++count; } } //the fist element in `indexedVariables` is a set to keep all the InternalThreadLocal to remove //look at method `addToVariablesToRemove` return count - 1; } private static Object[] newIndexedVariableTable() { int variableIndex = NEXT_INDEX.get(); int newCapacity = variableIndex < 32 ? 32 : newCapacity(variableIndex); Object[] array = new Object[newCapacity]; Arrays.fill(array, UNSET); return array; } private static int newCapacity(int index) { int newCapacity; if (index < ARRAY_LIST_CAPACITY_EXPAND_THRESHOLD) { newCapacity = index; newCapacity |= newCapacity >>> 1; newCapacity |= newCapacity >>> 2; newCapacity |= newCapacity >>> 4; newCapacity |= newCapacity >>> 8; newCapacity |= newCapacity >>> 16; newCapacity ++; } else { newCapacity = ARRAY_LIST_CAPACITY_MAX_SIZE; } return newCapacity; } private static InternalThreadLocalMap fastGet(InternalThread thread) { InternalThreadLocalMap threadLocalMap = thread.threadLocalMap(); if (threadLocalMap == null) { thread.setThreadLocalMap(threadLocalMap = new InternalThreadLocalMap()); } return threadLocalMap; } private static InternalThreadLocalMap slowGet() { ThreadLocal<InternalThreadLocalMap> slowThreadLocalMap = InternalThreadLocalMap.slowThreadLocalMap; InternalThreadLocalMap ret = slowThreadLocalMap.get(); if (ret == null) { ret = new InternalThreadLocalMap(); slowThreadLocalMap.set(ret); } return ret; } private void expandIndexedVariableTableAndSet(int index, Object value) { Object[] oldArray = indexedVariables; final int oldCapacity = oldArray.length; int newCapacity = newCapacity(index); Object[] newArray = Arrays.copyOf(oldArray, newCapacity); Arrays.fill(newArray, oldCapacity, newArray.length, UNSET); newArray[index] = value; indexedVariables = newArray; } }
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/threadlocal/InternalRunnable.java
dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalRunnable.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.threadlocal; /** * InternalRunnable * There is a risk of memory leak when using {@link InternalThreadLocal} without calling * {@link InternalThreadLocal#removeAll()}. * This design is learning from {@see io.netty.util.concurrent.FastThreadLocalRunnable} which is in Netty. */ public class InternalRunnable implements Runnable { private final Runnable runnable; public InternalRunnable(Runnable runnable) { this.runnable = runnable; } /** * After the task execution is completed, it will call {@link InternalThreadLocal#removeAll()} to clear * unnecessary variables in the thread. */ @Override public void run() { try { runnable.run(); } finally { InternalThreadLocal.removeAll(); } } /** * Wrap ordinary Runnable into {@link InternalThreadLocal}. */ public static Runnable Wrap(Runnable runnable) { return runnable instanceof InternalRunnable ? runnable : new InternalRunnable(runnable); } }
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/threadlocal/InternalThread.java
dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThread.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.threadlocal; public class InternalThread extends Thread { private InternalThreadLocalMap threadLocalMap; public InternalThread() {} public InternalThread(Runnable target) { super(target); } public InternalThread(ThreadGroup group, Runnable target) { super(group, target); } public InternalThread(String name) { super(name); } public InternalThread(ThreadGroup group, String name) { super(group, name); } public InternalThread(Runnable target, String name) { super(target, name); } public InternalThread(ThreadGroup group, Runnable target, String name) { super(group, target, name); } public InternalThread(ThreadGroup group, Runnable target, String name, long stackSize) { super(group, target, name, stackSize); } /** * Returns the internal data structure that keeps the threadLocal variables bound to this thread. * Note that this method is for internal use only, and thus is subject to change at any time. */ public final InternalThreadLocalMap threadLocalMap() { return threadLocalMap; } /** * Sets the internal data structure that keeps the threadLocal variables bound to this thread. * Note that this method is for internal use only, and thus is subject to change at any time. */ public final void setThreadLocalMap(InternalThreadLocalMap threadLocalMap) { this.threadLocalMap = threadLocalMap; } }
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/extension/Activate.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/Activate.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.common.extension; import org.apache.dubbo.common.URL; 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; /** * Activate. This annotation is useful for automatically activate certain extensions with the given criteria, * for examples: <code>@Activate</code> can be used to load certain <code>Filter</code> extension when there are * multiple implementations. * <ol> * <li>{@link Activate#group()} specifies group criteria. Framework SPI defines the valid group values. * <li>{@link Activate#value()} specifies parameter key in {@link URL} criteria. * </ol> * SPI provider can call {@link ExtensionLoader#getActivateExtension(URL, String, String)} to find out all activated * extensions with the given criteria. * * @see SPI * @see URL * @see ExtensionLoader */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface Activate { /** * Activate the current extension when one of the groups matches. The group passed into * {@link ExtensionLoader#getActivateExtension(URL, String, String)} will be used for matching. * * @return group names to match * @see ExtensionLoader#getActivateExtension(URL, String, String) */ String[] group() default {}; /** * Activate the current extension when the specified keys appear in the URL's parameters. * <p> * For example, given <code>@Activate("cache, validation")</code>, the current extension will be return only when * there's either <code>cache</code> or <code>validation</code> key appeared in the URL's parameters. * </p> * * @return URL parameter keys * @see ExtensionLoader#getActivateExtension(URL, String) * @see ExtensionLoader#getActivateExtension(URL, String, String) */ String[] value() default {}; /** * Relative ordering info, optional * Deprecated since 2.7.0 * * @return extension list which should be put before the current one */ @Deprecated String[] before() default {}; /** * Relative ordering info, optional * Deprecated since 2.7.0 * * @return extension list which should be put after the current one */ @Deprecated String[] after() default {}; /** * Absolute ordering info, optional * * Ascending order, smaller values will be in the front of the list. * * @return absolute ordering info */ int order() default 0; /** * Activate loadClass when the current extension when the specified className all match * @return className names to all match */ String[] onClass() default {}; }
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/extension/ExtensionFactory.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.common.extension; /** * ExtensionFactory * @deprecated use {@link ExtensionInjector} instead */ @Deprecated @SPI(scope = ExtensionScope.FRAMEWORK) public interface ExtensionFactory extends ExtensionInjector { @Override default <T> T getInstance(Class<T> type, String name) { return getExtension(type, name); } /** * Get extension. * * @param type object type. * @param name object name. * @return object instance. */ <T> T getExtension(Class<T> type, String 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/extension/DisableInject.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/DisableInject.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface DisableInject {}
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/extension/Adaptive.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/Adaptive.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension; import org.apache.dubbo.common.URL; 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; /** * Provide helpful information for {@link ExtensionLoader} to inject dependency extension instance. * * @see ExtensionLoader * @see URL */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface Adaptive { /** * Decide which target extension to be injected. The name of the target extension is decided by the parameter passed * in the URL, and the parameter names are given by this method. * <p> * If the specified parameters are not found from {@link URL}, then the default extension will be used for * dependency injection (specified in its interface's {@link SPI}). * <p> * For example, given <code>String[] {"key1", "key2"}</code>: * <ol> * <li>find parameter 'key1' in URL, use its value as the extension's name</li> * <li>try 'key2' for extension's name if 'key1' is not found (or its value is empty) in URL</li> * <li>use default extension if 'key2' doesn't exist either</li> * <li>otherwise, throw {@link IllegalStateException}</li> * </ol> * If the parameter names are empty, then a default parameter name is generated from interface's * class name with the rule: divide classname from capital char into several parts, and separate the parts with * dot '.', for example, for {@code org.apache.dubbo.xxx.YyyInvokerWrapper}, the generated name is * <code>String[] {"yyy.invoker.wrapper"}</code>. * * @return parameter names in URL */ String[] value() 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/common/extension/ExtensionDirector.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionDirector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension; import org.apache.dubbo.rpc.model.ScopeModel; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; /** * ExtensionDirector is a scoped extension loader manager. * * <p></p> * <p>ExtensionDirector supports multiple levels, and the child can inherit the parent's extension instances. </p> * <p>The way to find and create an extension instance is similar to Java classloader.</p> */ public class ExtensionDirector implements ExtensionAccessor { private final ConcurrentMap<Class<?>, ExtensionLoader<?>> extensionLoadersMap = new ConcurrentHashMap<>(64); private final ConcurrentMap<Class<?>, ExtensionScope> extensionScopeMap = new ConcurrentHashMap<>(64); private final ExtensionDirector parent; private final ExtensionScope scope; private final List<ExtensionPostProcessor> extensionPostProcessors = new ArrayList<>(); private final ScopeModel scopeModel; private final AtomicBoolean destroyed = new AtomicBoolean(); public ExtensionDirector(ExtensionDirector parent, ExtensionScope scope, ScopeModel scopeModel) { this.parent = parent; this.scope = scope; this.scopeModel = scopeModel; } public void addExtensionPostProcessor(ExtensionPostProcessor processor) { if (!this.extensionPostProcessors.contains(processor)) { this.extensionPostProcessors.add(processor); } } public List<ExtensionPostProcessor> getExtensionPostProcessors() { return extensionPostProcessors; } @Override public ExtensionDirector getExtensionDirector() { return this; } @Override @SuppressWarnings("unchecked") public <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) { checkDestroyed(); if (type == null) { throw new IllegalArgumentException("Extension type == null"); } if (!type.isInterface()) { throw new IllegalArgumentException("Extension type (" + type + ") is not an interface!"); } if (!withExtensionAnnotation(type)) { throw new IllegalArgumentException("Extension type (" + type + ") is not an extension, because it is NOT annotated with @" + SPI.class.getSimpleName() + "!"); } // 1. find in local cache ExtensionLoader<T> loader = (ExtensionLoader<T>) extensionLoadersMap.get(type); ExtensionScope scope = extensionScopeMap.get(type); if (scope == null) { SPI annotation = type.getAnnotation(SPI.class); scope = annotation.scope(); extensionScopeMap.put(type, scope); } if (loader == null && scope == ExtensionScope.SELF) { // create an instance in self scope loader = createExtensionLoader0(type); } // 2. find in parent if (loader == null) { if (this.parent != null) { loader = this.parent.getExtensionLoader(type); } } // 3. create it if (loader == null) { loader = createExtensionLoader(type); } return loader; } private <T> ExtensionLoader<T> createExtensionLoader(Class<T> type) { ExtensionLoader<T> loader = null; if (isScopeMatched(type)) { // if scope is matched, just create it loader = createExtensionLoader0(type); } return loader; } @SuppressWarnings("unchecked") private <T> ExtensionLoader<T> createExtensionLoader0(Class<T> type) { checkDestroyed(); ExtensionLoader<T> loader; extensionLoadersMap.putIfAbsent(type, new ExtensionLoader<T>(type, this, scopeModel)); loader = (ExtensionLoader<T>) extensionLoadersMap.get(type); return loader; } private boolean isScopeMatched(Class<?> type) { final SPI defaultAnnotation = type.getAnnotation(SPI.class); return defaultAnnotation.scope().equals(scope); } private static boolean withExtensionAnnotation(Class<?> type) { return type.isAnnotationPresent(SPI.class); } public ExtensionDirector getParent() { return parent; } public void removeAllCachedLoader() {} public void destroy() { if (destroyed.compareAndSet(false, true)) { for (ExtensionLoader<?> extensionLoader : extensionLoadersMap.values()) { extensionLoader.destroy(); } extensionLoadersMap.clear(); extensionScopeMap.clear(); extensionPostProcessors.clear(); } } private void checkDestroyed() { if (destroyed.get()) { throw new IllegalStateException("ExtensionDirector is destroyed"); } } }
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/extension/ExtensionAccessor.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionAccessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension; import java.util.Collections; import java.util.List; import java.util.Set; /** * Uniform accessor for extension */ public interface ExtensionAccessor { ExtensionDirector getExtensionDirector(); default <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) { return getExtensionDirector().getExtensionLoader(type); } default <T> T getExtension(Class<T> type, String name) { ExtensionLoader<T> extensionLoader = getExtensionLoader(type); return extensionLoader != null ? extensionLoader.getExtension(name) : null; } default <T> T getAdaptiveExtension(Class<T> type) { ExtensionLoader<T> extensionLoader = getExtensionLoader(type); return extensionLoader != null ? extensionLoader.getAdaptiveExtension() : null; } default <T> T getDefaultExtension(Class<T> type) { ExtensionLoader<T> extensionLoader = getExtensionLoader(type); return extensionLoader != null ? extensionLoader.getDefaultExtension() : null; } default <T> List<T> getActivateExtensions(Class<T> type) { ExtensionLoader<T> extensionLoader = getExtensionLoader(type); return extensionLoader != null ? extensionLoader.getActivateExtensions() : Collections.emptyList(); } default <T> T getFirstActivateExtension(Class<T> type) { ExtensionLoader<T> extensionLoader = getExtensionLoader(type); if (extensionLoader == null) { throw new IllegalArgumentException("ExtensionLoader for [" + type + "] is not found"); } List<T> extensions = extensionLoader.getActivateExtensions(); if (extensions.isEmpty()) { throw new IllegalArgumentException("No activate extensions for [" + type + "] found"); } return extensions.get(0); } default Set<String> getSupportedExtensions(Class<?> type) { ExtensionLoader<?> extensionLoader = getExtensionLoader(type); return extensionLoader != null ? extensionLoader.getSupportedExtensions() : Collections.emptySet(); } }
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/extension/ExtensionAccessorAware.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionAccessorAware.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension; /** * SPI extension can implement this aware interface to obtain appropriate {@link ExtensionAccessor} instance. */ public interface ExtensionAccessorAware { void setExtensionAccessor(final ExtensionAccessor extensionAccessor); }
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/extension/ExtensionInjector.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionInjector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension; /** * An injector to provide resources for SPI extension. */ @SPI(scope = ExtensionScope.SELF) public interface ExtensionInjector extends ExtensionAccessorAware { /** * Get instance of specify type and name. * * @param type object type. * @param name object name. * @return object instance. */ <T> T getInstance(final Class<T> type, final String name); @Override default void setExtensionAccessor(final ExtensionAccessor extensionAccessor) {} }
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/extension/DubboInternalLoadingStrategy.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/DubboInternalLoadingStrategy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension; /** * Dubbo internal {@link LoadingStrategy} * * @since 2.7.7 */ public class DubboInternalLoadingStrategy implements LoadingStrategy { @Override public String directory() { return "META-INF/dubbo/internal/"; } @Override public int getPriority() { return MAX_PRIORITY; } @Override public String getName() { return "DUBBO_INTERNAL"; } }
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/extension/LoadingStrategy.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/LoadingStrategy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension; import org.apache.dubbo.common.lang.Prioritized; public interface LoadingStrategy extends Prioritized { String directory(); default boolean preferExtensionClassLoader() { return false; } default String[] excludedPackages() { return null; } /** * To restrict some class that should not be loaded from `org.apache.dubbo` package type SPI class. * For example, we can restrict the implementation class which package is `org.xxx.xxx` * can be loaded as SPI implementation. * * @return packages can be loaded in `org.apache.dubbo`'s SPI */ default String[] includedPackages() { // default match all return null; } /** * To restrict some class that should not be loaded from `org.alibaba.dubbo`(for compatible purpose) * package type SPI class. * For example, we can restrict the implementation class which package is `org.xxx.xxx` * can be loaded as SPI implementation * * @return packages can be loaded in `org.alibaba.dubbo`'s SPI */ default String[] includedPackagesInCompatibleType() { // default match all return null; } /** * To restrict some class that should load from Dubbo's ClassLoader. * For example, we can restrict the class declaration in `org.apache.dubbo` package should * be loaded from Dubbo's ClassLoader and users cannot declare these classes. * * @return class packages should load * @since 3.0.4 */ default String[] onlyExtensionClassLoaderPackages() { return new String[] {}; } /** * Indicates current {@link LoadingStrategy} supports overriding other lower prioritized instances or not. * * @return if supports, return <code>true</code>, or <code>false</code> * @since 2.7.7 */ default boolean overridden() { return false; } default String getName() { return this.getClass().getSimpleName(); } /** * when spi is loaded by dubbo framework classloader only, it indicates all LoadingStrategy should load this spi */ String ALL = "ALL"; }
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/extension/AdaptiveClassCodeGenerator.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * Code generator for Adaptive class */ public class AdaptiveClassCodeGenerator { private static final Logger logger = LoggerFactory.getLogger(AdaptiveClassCodeGenerator.class); private static final String CLASS_NAME_INVOCATION = "org.apache.dubbo.rpc.Invocation"; private static final String CODE_PACKAGE = "package %s;\n"; private static final String CODE_IMPORTS = "import %s;\n"; private static final String CODE_CLASS_DECLARATION = "public class %s$Adaptive implements %s {\n"; private static final String CODE_METHOD_DECLARATION = "public %s %s(%s) %s {\n%s}\n"; private static final String CODE_METHOD_ARGUMENT = "%s arg%d"; private static final String CODE_METHOD_THROWS = "throws %s"; private static final String CODE_UNSUPPORTED = "throw new UnsupportedOperationException(\"The method %s of interface %s is not adaptive method!\");\n"; private static final String CODE_URL_NULL_CHECK = "if (arg%d == null) throw new IllegalArgumentException(\"url == null\");\n%s url = arg%d;\n"; private static final String CODE_EXT_NAME_ASSIGNMENT = "String extName = %s;\n"; private static final String CODE_EXT_NAME_NULL_CHECK = "if(extName == null) " + "throw new IllegalStateException(\"Failed to get extension (%s) name from url (\" + url.toString() + \") use keys(%s)\");\n"; private static final String CODE_INVOCATION_ARGUMENT_NULL_CHECK = "if (arg%d == null) throw new IllegalArgumentException(\"invocation == null\"); " + "String methodName = arg%d.getMethodName();\n"; private static final String CODE_SCOPE_MODEL_ASSIGNMENT = "ScopeModel scopeModel = ScopeModelUtil.getOrDefault(url.getScopeModel(), %s.class);\n"; private static final String CODE_EXTENSION_ASSIGNMENT = "%s extension = (%<s)scopeModel.getExtensionLoader(%s.class).getExtension(extName);\n"; private static final String CODE_EXTENSION_METHOD_INVOKE_ARGUMENT = "arg%d"; private final Class<?> type; private final String defaultExtName; public AdaptiveClassCodeGenerator(Class<?> type, String defaultExtName) { this.type = type; this.defaultExtName = defaultExtName; } /** * test if given type has at least one method annotated with <code>Adaptive</code> */ private boolean hasAdaptiveMethod() { return Arrays.stream(type.getMethods()).anyMatch(m -> m.isAnnotationPresent(Adaptive.class)); } /** * generate and return class code */ public String generate() { return this.generate(false); } /** * generate and return class code * @param sort - whether sort methods */ public String generate(boolean sort) { // no need to generate adaptive class since there's no adaptive method found. if (!hasAdaptiveMethod()) { throw new IllegalStateException("No adaptive method exist on extension " + type.getName() + ", refuse to create the adaptive class!"); } StringBuilder code = new StringBuilder(); code.append(generatePackageInfo()); code.append(generateImports()); code.append(generateClassDeclaration()); Method[] methods = type.getMethods(); if (sort) { Arrays.sort(methods, Comparator.comparing(Method::toString)); } for (Method method : methods) { code.append(generateMethod(method)); } code.append('}'); if (logger.isDebugEnabled()) { logger.debug(code.toString()); } return code.toString(); } /** * generate package info */ private String generatePackageInfo() { return String.format(CODE_PACKAGE, type.getPackage().getName()); } /** * generate imports */ private String generateImports() { StringBuilder builder = new StringBuilder(); builder.append(String.format(CODE_IMPORTS, ScopeModel.class.getName())); builder.append(String.format(CODE_IMPORTS, ScopeModelUtil.class.getName())); return builder.toString(); } /** * generate class declaration */ private String generateClassDeclaration() { return String.format(CODE_CLASS_DECLARATION, type.getSimpleName(), type.getCanonicalName()); } /** * generate method not annotated with Adaptive with throwing unsupported exception */ private String generateUnsupported(Method method) { return String.format(CODE_UNSUPPORTED, method, type.getName()); } /** * get index of parameter with type URL */ private int getUrlTypeIndex(Method method) { int urlTypeIndex = -1; Class<?>[] pts = method.getParameterTypes(); for (int i = 0; i < pts.length; ++i) { if (pts[i].equals(URL.class)) { urlTypeIndex = i; break; } } return urlTypeIndex; } /** * generate method declaration */ private String generateMethod(Method method) { String methodReturnType = method.getReturnType().getCanonicalName(); String methodName = method.getName(); String methodContent = generateMethodContent(method); String methodArgs = generateMethodArguments(method); String methodThrows = generateMethodThrows(method); return String.format( CODE_METHOD_DECLARATION, methodReturnType, methodName, methodArgs, methodThrows, methodContent); } /** * generate method arguments */ private String generateMethodArguments(Method method) { Class<?>[] pts = method.getParameterTypes(); return IntStream.range(0, pts.length) .mapToObj(i -> String.format(CODE_METHOD_ARGUMENT, pts[i].getCanonicalName(), i)) .collect(Collectors.joining(", ")); } /** * generate method throws */ private String generateMethodThrows(Method method) { Class<?>[] ets = method.getExceptionTypes(); if (ets.length > 0) { String list = Arrays.stream(ets).map(Class::getCanonicalName).collect(Collectors.joining(", ")); return String.format(CODE_METHOD_THROWS, list); } else { return ""; } } /** * generate method URL argument null check */ private String generateUrlNullCheck(int index) { return String.format(CODE_URL_NULL_CHECK, index, URL.class.getName(), index); } /** * generate method content */ private String generateMethodContent(Method method) { Adaptive adaptiveAnnotation = method.getAnnotation(Adaptive.class); if (adaptiveAnnotation == null) { return generateUnsupported(method); } StringBuilder code = new StringBuilder(512); int urlTypeIndex = getUrlTypeIndex(method); // found parameter in URL type if (urlTypeIndex != -1) { // Null Point check code.append(generateUrlNullCheck(urlTypeIndex)); } else { // did not find parameter in URL type code.append(generateUrlAssignmentIndirectly(method)); } String[] value = getMethodAdaptiveValue(adaptiveAnnotation); boolean hasInvocation = hasInvocationArgument(method); code.append(generateInvocationArgumentNullCheck(method)); code.append(generateExtNameAssignment(value, hasInvocation)); // check extName == null? code.append(generateExtNameNullCheck(value)); code.append(generateScopeModelAssignment()); code.append(generateExtensionAssignment()); // return statement code.append(generateReturnAndInvocation(method)); return code.toString(); } /** * generate code for variable extName null check */ private String generateExtNameNullCheck(String[] value) { return String.format(CODE_EXT_NAME_NULL_CHECK, type.getName(), Arrays.toString(value)); } /** * generate extName assignment code */ private String generateExtNameAssignment(String[] value, boolean hasInvocation) { // TODO: refactor it String getNameCode = null; for (int i = value.length - 1; i >= 0; --i) { if (i == value.length - 1) { if (null != defaultExtName) { if (!CommonConstants.PROTOCOL_KEY.equals(value[i])) { if (hasInvocation) { getNameCode = String.format( "url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); } else { getNameCode = String.format("url.getParameter(\"%s\", \"%s\")", value[i], defaultExtName); } } else { getNameCode = String.format( "( url.getProtocol() == null ? \"%s\" : url.getProtocol() )", defaultExtName); } } else { if (!CommonConstants.PROTOCOL_KEY.equals(value[i])) { if (hasInvocation) { getNameCode = String.format( "url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); } else { getNameCode = String.format("url.getParameter(\"%s\")", value[i]); } } else { getNameCode = "url.getProtocol()"; } } } else { if (!CommonConstants.PROTOCOL_KEY.equals(value[i])) { if (hasInvocation) { getNameCode = String.format( "url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); } else { getNameCode = String.format("url.getParameter(\"%s\", %s)", value[i], getNameCode); } } else { getNameCode = String.format("url.getProtocol() == null ? (%s) : url.getProtocol()", getNameCode); } } } return String.format(CODE_EXT_NAME_ASSIGNMENT, getNameCode); } /** * @return */ private String generateScopeModelAssignment() { return String.format(CODE_SCOPE_MODEL_ASSIGNMENT, type.getName()); } private String generateExtensionAssignment() { return String.format(CODE_EXTENSION_ASSIGNMENT, type.getName(), type.getName()); } /** * generate method invocation statement and return it if necessary */ private String generateReturnAndInvocation(Method method) { String returnStatement = method.getReturnType().equals(void.class) ? "" : "return "; String args = IntStream.range(0, method.getParameters().length) .mapToObj(i -> String.format(CODE_EXTENSION_METHOD_INVOKE_ARGUMENT, i)) .collect(Collectors.joining(", ")); return returnStatement + String.format("extension.%s(%s);\n", method.getName(), args); } /** * test if method has argument of type <code>Invocation</code> */ private boolean hasInvocationArgument(Method method) { Class<?>[] pts = method.getParameterTypes(); return Arrays.stream(pts).anyMatch(p -> CLASS_NAME_INVOCATION.equals(p.getName())); } /** * generate code to test argument of type <code>Invocation</code> is null */ private String generateInvocationArgumentNullCheck(Method method) { Class<?>[] pts = method.getParameterTypes(); return IntStream.range(0, pts.length) .filter(i -> CLASS_NAME_INVOCATION.equals(pts[i].getName())) .mapToObj(i -> String.format(CODE_INVOCATION_ARGUMENT_NULL_CHECK, i, i)) .findFirst() .orElse(""); } /** * get value of adaptive annotation or if empty return splitted simple name */ private String[] getMethodAdaptiveValue(Adaptive adaptiveAnnotation) { String[] value = adaptiveAnnotation.value(); // value is not set, use the value generated from class name as the key if (value.length == 0) { String splitName = StringUtils.camelToSplitName(type.getSimpleName(), "."); value = new String[] {splitName}; } return value; } /** * get parameter with type <code>URL</code> from method parameter: * <p> * test if parameter has method which returns type <code>URL</code> * <p> * if not found, throws IllegalStateException */ private String generateUrlAssignmentIndirectly(Method method) { Class<?>[] pts = method.getParameterTypes(); Map<String, Integer> getterReturnUrl = new HashMap<>(); // find URL getter method for (int i = 0; i < pts.length; ++i) { for (Method m : pts[i].getMethods()) { String name = m.getName(); if ((name.startsWith("get") || name.length() > 3) && Modifier.isPublic(m.getModifiers()) && !Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0 && m.getReturnType() == URL.class) { getterReturnUrl.put(name, i); } } } if (getterReturnUrl.size() <= 0) { // getter method not found, throw throw new IllegalStateException("Failed to create adaptive class for interface " + type.getName() + ": not found url parameter or url attribute in parameters of method " + method.getName()); } Integer index = getterReturnUrl.get("getUrl"); if (index != null) { return generateGetUrlNullCheck(index, pts[index], "getUrl"); } else { Map.Entry<String, Integer> entry = getterReturnUrl.entrySet().iterator().next(); return generateGetUrlNullCheck(entry.getValue(), pts[entry.getValue()], entry.getKey()); } } /** * 1, test if argi is null * 2, test if argi.getXX() returns null * 3, assign url with argi.getXX() */ private String generateGetUrlNullCheck(int index, Class<?> type, String method) { // Null point check StringBuilder code = new StringBuilder(); code.append(String.format( "if (arg%d == null) throw new IllegalArgumentException(\"%s argument == null\");\n", index, type.getName())); code.append(String.format( "if (arg%d.%s() == null) throw new IllegalArgumentException(\"%s argument %s() == null\");\n", index, method, type.getName(), method)); code.append(String.format("%s url = arg%d.%s();\n", URL.class.getName(), index, method)); return code.toString(); } }
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/extension/ExtensionPostProcessor.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionPostProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension; /** * A Post-processor called before or after extension initialization. */ public interface ExtensionPostProcessor { default Object postProcessBeforeInitialization(Object instance, String name) throws Exception { return instance; } default Object postProcessAfterInitialization(Object instance, String name) throws Exception { return instance; } }
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/extension/ExtensionScope.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionScope.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; /** * Extension SPI Scope * @see SPI * @see ExtensionDirector */ public enum ExtensionScope { /** * The extension instance is used within framework, shared with all applications and modules. * * <p>Framework scope SPI extension can only obtain {@link FrameworkModel}, * cannot get the {@link ApplicationModel} and {@link ModuleModel}.</p> * * <p></p> * Consideration: * <ol> * <li>Some SPI need share data between applications inside framework</li> * <li>Stateless SPI is safe shared inside framework</li> * </ol> */ FRAMEWORK, /** * The extension instance is used within one application, shared with all modules of the application, * and different applications create different extension instances. * * <p>Application scope SPI extension can obtain {@link FrameworkModel} and {@link ApplicationModel}, * cannot get the {@link ModuleModel}.</p> * * <p></p> * Consideration: * <ol> * <li>Isolate extension data in different applications inside framework</li> * <li>Share extension data between all modules inside application</li> * </ol> */ APPLICATION, /** * The extension instance is used within one module, and different modules create different extension instances. * * <p>Module scope SPI extension can obtain {@link FrameworkModel}, {@link ApplicationModel} and {@link ModuleModel}.</p> * * <p></p> * Consideration: * <ol> * <li>Isolate extension data in different modules inside application</li> * </ol> */ MODULE, /** * self-sufficient, creates an instance for per scope, for special SPI extension, like {@link ExtensionInjector} */ SELF }
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/extension/DubboLoadingStrategy.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/DubboLoadingStrategy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension; /** * Dubbo {@link LoadingStrategy} * * @since 2.7.7 */ public class DubboLoadingStrategy implements LoadingStrategy { @Override public String directory() { return "META-INF/dubbo/"; } @Override public boolean overridden() { return true; } @Override public int getPriority() { return NORMAL_PRIORITY; } @Override public String getName() { return "DUBBO"; } }
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/extension/Wrapper.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/Wrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * The annotated class will only work as a wrapper when the condition matches. */ @Retention(RetentionPolicy.RUNTIME) public @interface Wrapper { /** * the extension names that need to be wrapped. * default is matching when this array is empty. */ String[] matches() default {}; /** * the extension names that need to be excluded. */ String[] mismatches() default {}; /** * absolute ordering, optional * ascending order, smaller values will be in the front of the list. * @return */ int order() default 0; }
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/extension/ExtensionLoader.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension; import org.apache.dubbo.common.Extension; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.aot.NativeDetector; import org.apache.dubbo.common.beans.support.InstantiationStrategy; import org.apache.dubbo.common.compact.Dubbo2ActivateUtils; import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.context.Lifecycle; import org.apache.dubbo.common.extension.support.ActivateComparator; import org.apache.dubbo.common.extension.support.WrapperComparator; import org.apache.dubbo.common.lang.Prioritized; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.resource.Disposable; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.ClassLoaderResourceLoader; 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.ConcurrentHashSet; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.Holder; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; 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.ScopeModelAccessor; import org.apache.dubbo.rpc.model.ScopeModelAware; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.annotation.Annotation; import java.lang.ref.SoftReference; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.ServiceLoader; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Pattern; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static java.util.ServiceLoader.load; import static java.util.stream.StreamSupport.stream; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ERROR_LOAD_EXTENSION; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_LOAD_ENV_VARIABLE; /** * {@link org.apache.dubbo.rpc.model.ApplicationModel}, {@code DubboBootstrap} and this class are * at present designed to be singleton or static (by itself totally static or uses some static fields). * So the instances returned from them are of process or classloader scope. If you want to support * multiple dubbo servers in a single process, you may need to refactor these three classes. * <p> * Load dubbo extensions * <ul> * <li>auto inject dependency extension </li> * <li>auto wrap extension in wrapper </li> * <li>default extension is an adaptive instance</li> * </ul> * * @see <a href="http://java.sun.com/j2se/1.5.0/docs/guide/jar/jar.html#Service%20Provider">Service Provider in Java 5</a> * @see org.apache.dubbo.common.extension.SPI * @see org.apache.dubbo.common.extension.Adaptive * @see org.apache.dubbo.common.extension.Activate */ public class ExtensionLoader<T> { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExtensionLoader.class); private static final Pattern NAME_SEPARATOR = Pattern.compile("\\s*[,]+\\s*"); private static final String SPECIAL_SPI_PROPERTIES = "special_spi.properties"; private final ConcurrentMap<Class<?>, Object> extensionInstances = new ConcurrentHashMap<>(64); private final Class<?> type; private final ExtensionInjector injector; private final ConcurrentMap<Class<?>, String> cachedNames = new ConcurrentHashMap<>(); private final ReentrantLock loadExtensionClassesLock = new ReentrantLock(); private final Holder<Map<String, Class<?>>> cachedClasses = new Holder<>(); private final Map<String, Object> cachedActivates = Collections.synchronizedMap(new LinkedHashMap<>()); private final Map<String, Set<String>> cachedActivateGroups = Collections.synchronizedMap(new LinkedHashMap<>()); private final Map<String, String[][]> cachedActivateValues = Collections.synchronizedMap(new LinkedHashMap<>()); private final ConcurrentMap<String, Holder<Object>> cachedInstances = new ConcurrentHashMap<>(); private final Holder<Object> cachedAdaptiveInstance = new Holder<>(); private volatile Class<?> cachedAdaptiveClass = null; private String cachedDefaultName; private volatile Throwable createAdaptiveInstanceError; private Set<Class<?>> cachedWrapperClasses; private final Map<String, IllegalStateException> exceptions = new ConcurrentHashMap<>(); private static volatile LoadingStrategy[] strategies = loadLoadingStrategies(); private static final Map<String, String> specialSPILoadingStrategyMap = getSpecialSPILoadingStrategyMap(); private static SoftReference<ConcurrentHashMap<java.net.URL, List<String>>> urlListMapCache = new SoftReference<>(new ConcurrentHashMap<>()); private static final List<String> ignoredInjectMethodsDesc = getIgnoredInjectMethodsDesc(); /** * Record all unacceptable exceptions when using SPI */ private final Set<String> unacceptableExceptions = new ConcurrentHashSet<>(); private final ExtensionDirector extensionDirector; private final List<ExtensionPostProcessor> extensionPostProcessors; private InstantiationStrategy instantiationStrategy; private final ActivateComparator activateComparator; private final ScopeModel scopeModel; private final AtomicBoolean destroyed = new AtomicBoolean(); public static void setLoadingStrategies(LoadingStrategy... strategies) { if (ArrayUtils.isNotEmpty(strategies)) { ExtensionLoader.strategies = strategies; } } /** * Load all {@link Prioritized prioritized} {@link LoadingStrategy Loading Strategies} via {@link ServiceLoader} * * @return non-null * @since 2.7.7 */ private static LoadingStrategy[] loadLoadingStrategies() { return stream(load(LoadingStrategy.class).spliterator(), false).sorted().toArray(LoadingStrategy[]::new); } /** * some spi are implements by dubbo framework only and scan multi classloaders resources may cause * application startup very slow * * @return */ private static Map<String, String> getSpecialSPILoadingStrategyMap() { Map map = new ConcurrentHashMap<>(); Properties properties = loadProperties(ExtensionLoader.class.getClassLoader(), SPECIAL_SPI_PROPERTIES); map.putAll(properties); return map; } /** * Get all {@link LoadingStrategy Loading Strategies} * * @return non-null * @see LoadingStrategy * @see Prioritized * @since 2.7.7 */ public static List<LoadingStrategy> getLoadingStrategies() { return asList(strategies); } private static List<String> getIgnoredInjectMethodsDesc() { List<String> ignoreInjectMethodsDesc = new ArrayList<>(); Arrays.stream(ScopeModelAware.class.getMethods()) .map(ReflectUtils::getDesc) .forEach(ignoreInjectMethodsDesc::add); Arrays.stream(ExtensionAccessorAware.class.getMethods()) .map(ReflectUtils::getDesc) .forEach(ignoreInjectMethodsDesc::add); return ignoreInjectMethodsDesc; } ExtensionLoader(Class<?> type, ExtensionDirector extensionDirector, ScopeModel scopeModel) { this.type = type; this.extensionDirector = extensionDirector; this.extensionPostProcessors = extensionDirector.getExtensionPostProcessors(); initInstantiationStrategy(); this.injector = (type == ExtensionInjector.class ? null : extensionDirector.getExtensionLoader(ExtensionInjector.class).getAdaptiveExtension()); this.activateComparator = new ActivateComparator(extensionDirector); this.scopeModel = scopeModel; } private void initInstantiationStrategy() { instantiationStrategy = extensionPostProcessors.stream() .filter(extensionPostProcessor -> extensionPostProcessor instanceof ScopeModelAccessor) .map(extensionPostProcessor -> new InstantiationStrategy((ScopeModelAccessor) extensionPostProcessor)) .findFirst() .orElse(new InstantiationStrategy()); } /** * @see ApplicationModel#getExtensionDirector() * @see FrameworkModel#getExtensionDirector() * @see ModuleModel#getExtensionDirector() * @see ExtensionDirector#getExtensionLoader(java.lang.Class) * @deprecated get extension loader from extension director of some module. */ @Deprecated public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) { return ApplicationModel.defaultModel().getDefaultModule().getExtensionLoader(type); } @Deprecated public static void resetExtensionLoader(Class type) {} public void destroy() { if (!destroyed.compareAndSet(false, true)) { return; } // destroy raw extension instance extensionInstances.forEach((type, instance) -> { if (instance instanceof Disposable) { Disposable disposable = (Disposable) instance; try { disposable.destroy(); } catch (Exception e) { logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", "Error destroying extension " + disposable, e); } } }); extensionInstances.clear(); // destroy wrapped extension instance for (Holder<Object> holder : cachedInstances.values()) { Object wrappedInstance = holder.get(); if (wrappedInstance instanceof Disposable) { Disposable disposable = (Disposable) wrappedInstance; try { disposable.destroy(); } catch (Exception e) { logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", "Error destroying extension " + disposable, e); } } } cachedInstances.clear(); } private void checkDestroyed() { if (destroyed.get()) { throw new IllegalStateException("ExtensionLoader is destroyed: " + type); } } public String getExtensionName(T extensionInstance) { return getExtensionName(extensionInstance.getClass()); } public String getExtensionName(Class<?> extensionClass) { getExtensionClasses(); // load class return cachedNames.get(extensionClass); } /** * This is equivalent to {@code getActivateExtension(url, key, null)} * * @param url url * @param key url parameter key which used to get extension point names * @return extension list which are activated. * @see #getActivateExtension(org.apache.dubbo.common.URL, String, String) */ public List<T> getActivateExtension(URL url, String key) { return getActivateExtension(url, key, null); } /** * This is equivalent to {@code getActivateExtension(url, values, null)} * * @param url url * @param values extension point names * @return extension list which are activated * @see #getActivateExtension(org.apache.dubbo.common.URL, String[], String) */ public List<T> getActivateExtension(URL url, String[] values) { return getActivateExtension(url, values, null); } /** * This is equivalent to {@code getActivateExtension(url, url.getParameter(key).split(","), null)} * * @param url url * @param key url parameter key which used to get extension point names * @param group group * @return extension list which are activated. * @see #getActivateExtension(org.apache.dubbo.common.URL, String[], String) */ public List<T> getActivateExtension(URL url, String key, String group) { String value = url.getParameter(key); return getActivateExtension(url, StringUtils.isEmpty(value) ? null : COMMA_SPLIT_PATTERN.split(value), group); } /** * Get activate extensions. * * @param url url * @param values extension point names * @param group group * @return extension list which are activated * @see org.apache.dubbo.common.extension.Activate */ @SuppressWarnings("deprecation") public List<T> getActivateExtension(URL url, String[] values, String group) { checkDestroyed(); // solve the bug of using @SPI's wrapper method to report a null pointer exception. Map<Class<?>, T> activateExtensionsMap = new TreeMap<>(activateComparator); List<String> names = values == null ? new ArrayList<>(0) : Arrays.stream(values).map(StringUtils::trim).collect(Collectors.toList()); Set<String> namesSet = new HashSet<>(names); if (!namesSet.contains(REMOVE_VALUE_PREFIX + DEFAULT_KEY)) { if (cachedActivateGroups.size() == 0) { synchronized (cachedActivateGroups) { // cache all extensions if (cachedActivateGroups.size() == 0) { getExtensionClasses(); for (Map.Entry<String, Object> entry : cachedActivates.entrySet()) { String name = entry.getKey(); Object activate = entry.getValue(); String[] activateGroup, activateValue; if (activate instanceof Activate) { activateGroup = ((Activate) activate).group(); activateValue = ((Activate) activate).value(); } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded() && Dubbo2ActivateUtils.getActivateClass().isAssignableFrom(activate.getClass())) { activateGroup = Dubbo2ActivateUtils.getGroup((Annotation) activate); activateValue = Dubbo2ActivateUtils.getValue((Annotation) activate); } else { continue; } cachedActivateGroups.put(name, new HashSet<>(Arrays.asList(activateGroup))); String[][] keyPairs = new String[activateValue.length][]; for (int i = 0; i < activateValue.length; i++) { if (activateValue[i].contains(":")) { keyPairs[i] = new String[2]; String[] arr = activateValue[i].split(":"); keyPairs[i][0] = arr[0]; keyPairs[i][1] = arr[1]; } else { keyPairs[i] = new String[1]; keyPairs[i][0] = activateValue[i]; } } cachedActivateValues.put(name, keyPairs); } } } } // traverse all cached extensions cachedActivateGroups.forEach((name, activateGroup) -> { if (isMatchGroup(group, activateGroup) && !namesSet.contains(name) && !namesSet.contains(REMOVE_VALUE_PREFIX + name) && isActive(cachedActivateValues.get(name), url)) { activateExtensionsMap.put(getExtensionClass(name), getExtension(name)); } }); } if (namesSet.contains(DEFAULT_KEY)) { // will affect order // `ext1,default,ext2` means ext1 will happens before all of the default extensions while ext2 will after // them ArrayList<T> extensionsResult = new ArrayList<>(activateExtensionsMap.size() + names.size()); for (String name : names) { if (name.startsWith(REMOVE_VALUE_PREFIX) || namesSet.contains(REMOVE_VALUE_PREFIX + name)) { continue; } if (DEFAULT_KEY.equals(name)) { extensionsResult.addAll(activateExtensionsMap.values()); continue; } if (containsExtension(name)) { extensionsResult.add(getExtension(name)); } } return extensionsResult; } else { // add extensions, will be sorted by its order for (String name : names) { if (name.startsWith(REMOVE_VALUE_PREFIX) || namesSet.contains(REMOVE_VALUE_PREFIX + name)) { continue; } if (DEFAULT_KEY.equals(name)) { continue; } if (containsExtension(name)) { activateExtensionsMap.put(getExtensionClass(name), getExtension(name)); } } return new ArrayList<>(activateExtensionsMap.values()); } } public List<T> getActivateExtensions() { checkDestroyed(); List<T> activateExtensions = new ArrayList<>(); TreeMap<Class<?>, T> activateExtensionsMap = new TreeMap<>(activateComparator); getExtensionClasses(); for (Map.Entry<String, Object> entry : cachedActivates.entrySet()) { String name = entry.getKey(); Object activate = entry.getValue(); if (!(activate instanceof Activate)) { continue; } activateExtensionsMap.put(getExtensionClass(name), getExtension(name)); } if (!activateExtensionsMap.isEmpty()) { activateExtensions.addAll(activateExtensionsMap.values()); } return activateExtensions; } private boolean isMatchGroup(String group, Set<String> groups) { if (StringUtils.isEmpty(group)) { return true; } if (CollectionUtils.isNotEmpty(groups)) { return groups.contains(group); } return false; } private boolean isActive(String[][] keyPairs, URL url) { if (keyPairs.length == 0) { return true; } for (String[] keyPair : keyPairs) { // @Active(value="key1:value1, key2:value2") String key; String keyValue = null; if (keyPair.length > 1) { key = keyPair[0]; keyValue = keyPair[1]; } else { key = keyPair[0]; } String realValue = url.getParameter(key); if (StringUtils.isEmpty(realValue)) { realValue = url.getAnyMethodParameter(key); } if ((keyValue != null && keyValue.equals(realValue)) || (keyValue == null && ConfigUtils.isNotEmpty(realValue))) { return true; } } return false; } /** * Get extension's instance. Return <code>null</code> if extension is not found or is not initialized. Pls. note * that this method will not trigger extension load. * <p> * In order to trigger extension load, call {@link #getExtension(String)} instead. * * @see #getExtension(String) */ @SuppressWarnings("unchecked") public T getLoadedExtension(String name) { checkDestroyed(); if (StringUtils.isEmpty(name)) { throw new IllegalArgumentException("Extension name == null"); } Holder<Object> holder = getOrCreateHolder(name); return (T) holder.get(); } private Holder<Object> getOrCreateHolder(String name) { Holder<Object> holder = cachedInstances.get(name); if (holder == null) { cachedInstances.putIfAbsent(name, new Holder<>()); holder = cachedInstances.get(name); } return holder; } /** * Return the list of extensions which are already loaded. * <p> * Usually {@link #getSupportedExtensions()} should be called in order to get all extensions. * * @see #getSupportedExtensions() */ public Set<String> getLoadedExtensions() { return Collections.unmodifiableSet(new TreeSet<>(cachedInstances.keySet())); } @SuppressWarnings("unchecked") public List<T> getLoadedExtensionInstances() { checkDestroyed(); List<T> instances = new ArrayList<>(); cachedInstances.values().forEach(holder -> instances.add((T) holder.get())); return instances; } /** * Find the extension with the given name. * * @throws IllegalStateException If the specified extension is not found. */ public T getExtension(String name) { T extension = getExtension(name, true); if (extension == null) { throw new IllegalArgumentException("Not find extension: " + name); } return extension; } @SuppressWarnings("unchecked") public T getExtension(String name, boolean wrap) { checkDestroyed(); if (StringUtils.isEmpty(name)) { throw new IllegalArgumentException("Extension name == null"); } if ("true".equals(name)) { return getDefaultExtension(); } String cacheKey = name; if (!wrap) { cacheKey += "_origin"; } final Holder<Object> holder = getOrCreateHolder(cacheKey); Object instance = holder.get(); if (instance == null) { synchronized (holder) { instance = holder.get(); if (instance == null) { instance = createExtension(name, wrap); holder.set(instance); } } } return (T) instance; } /** * Get the extension by specified name if found, or {@link #getDefaultExtension() returns the default one} * * @param name the name of extension * @return non-null */ public T getOrDefaultExtension(String name) { return containsExtension(name) ? getExtension(name) : getDefaultExtension(); } /** * Return default extension, return <code>null</code> if it's not configured. */ public T getDefaultExtension() { getExtensionClasses(); if (StringUtils.isBlank(cachedDefaultName) || "true".equals(cachedDefaultName)) { return null; } return getExtension(cachedDefaultName); } public boolean hasExtension(String name) { checkDestroyed(); if (StringUtils.isEmpty(name)) { throw new IllegalArgumentException("Extension name == null"); } Class<?> c = this.getExtensionClass(name); return c != null; } public Set<String> getSupportedExtensions() { checkDestroyed(); Map<String, Class<?>> classes = getExtensionClasses(); return Collections.unmodifiableSet(new TreeSet<>(classes.keySet())); } public Set<T> getSupportedExtensionInstances() { checkDestroyed(); List<T> instances = new LinkedList<>(); Set<String> supportedExtensions = getSupportedExtensions(); if (CollectionUtils.isNotEmpty(supportedExtensions)) { for (String name : supportedExtensions) { instances.add(getExtension(name)); } } // sort the Prioritized instances instances.sort(Prioritized.COMPARATOR); return new LinkedHashSet<>(instances); } /** * Return default extension name, return <code>null</code> if not configured. */ public String getDefaultExtensionName() { getExtensionClasses(); return cachedDefaultName; } /** * Register new extension via API * * @param name extension name * @param clazz extension class * @throws IllegalStateException when extension with the same name has already been registered. */ public void addExtension(String name, Class<?> clazz) { checkDestroyed(); getExtensionClasses(); // load classes if (!type.isAssignableFrom(clazz)) { throw new IllegalStateException("Input type " + clazz + " doesn't implement the Extension " + type); } if (clazz.isInterface()) { throw new IllegalStateException("Input type " + clazz + " can't be interface!"); } if (!clazz.isAnnotationPresent(Adaptive.class)) { if (StringUtils.isBlank(name)) { throw new IllegalStateException("Extension name is blank (Extension " + type + ")!"); } if (cachedClasses.get().containsKey(name)) { throw new IllegalStateException("Extension name " + name + " already exists (Extension " + type + ")!"); } cachedNames.put(clazz, name); cachedClasses.get().put(name, clazz); } else { if (cachedAdaptiveClass != null) { throw new IllegalStateException("Adaptive Extension already exists (Extension " + type + ")!"); } cachedAdaptiveClass = clazz; } } /** * Replace the existing extension via API * * @param name extension name * @param clazz extension class * @throws IllegalStateException when extension to be placed doesn't exist * @deprecated not recommended any longer, and use only when test */ @Deprecated public void replaceExtension(String name, Class<?> clazz) { checkDestroyed(); getExtensionClasses(); // load classes if (!type.isAssignableFrom(clazz)) { throw new IllegalStateException("Input type " + clazz + " doesn't implement Extension " + type); } if (clazz.isInterface()) { throw new IllegalStateException("Input type " + clazz + " can't be interface!"); } if (!clazz.isAnnotationPresent(Adaptive.class)) { if (StringUtils.isBlank(name)) { throw new IllegalStateException("Extension name is blank (Extension " + type + ")!"); } if (!cachedClasses.get().containsKey(name)) { throw new IllegalStateException("Extension name " + name + " doesn't exist (Extension " + type + ")!"); } cachedNames.put(clazz, name); cachedClasses.get().put(name, clazz); cachedInstances.remove(name); } else { if (cachedAdaptiveClass == null) { throw new IllegalStateException("Adaptive Extension doesn't exist (Extension " + type + ")!"); } cachedAdaptiveClass = clazz; cachedAdaptiveInstance.set(null); } } @SuppressWarnings("unchecked") public T getAdaptiveExtension() { checkDestroyed(); Object instance = cachedAdaptiveInstance.get(); if (instance == null) { if (createAdaptiveInstanceError != null) { throw new IllegalStateException( "Failed to create adaptive instance: " + createAdaptiveInstanceError.toString(), createAdaptiveInstanceError); } synchronized (cachedAdaptiveInstance) { instance = cachedAdaptiveInstance.get(); if (instance == null) { try { instance = createAdaptiveExtension(); cachedAdaptiveInstance.set(instance); } catch (Throwable t) { createAdaptiveInstanceError = t; throw new IllegalStateException("Failed to create adaptive instance: " + t.toString(), t); } } } } return (T) instance; } private IllegalStateException findException(String name) { StringBuilder buf = new StringBuilder("No such extension " + type.getName() + " by name " + name); int i = 1; for (Map.Entry<String, IllegalStateException> entry : exceptions.entrySet()) { if (entry.getKey().toLowerCase().startsWith(name.toLowerCase())) { if (i == 1) { buf.append(", possible causes: "); } buf.append("\r\n("); buf.append(i++); buf.append(") "); buf.append(entry.getKey()); buf.append(":\r\n"); buf.append(StringUtils.toString(entry.getValue())); } } if (i == 1) { buf.append(", no related exception was found, please check whether related SPI module is missing."); } return new IllegalStateException(buf.toString()); } @SuppressWarnings("unchecked") private T createExtension(String name, boolean wrap) { Class<?> clazz = getExtensionClasses().get(name); if (clazz == null || unacceptableExceptions.contains(name)) { throw findException(name); } try { T instance = (T) extensionInstances.get(clazz); if (instance == null) { extensionInstances.putIfAbsent(clazz, createExtensionInstance(clazz)); instance = (T) extensionInstances.get(clazz); instance = postProcessBeforeInitialization(instance, name); injectExtension(instance); instance = postProcessAfterInitialization(instance, name); } if (wrap) { List<Class<?>> wrapperClassesList = new ArrayList<>(); if (cachedWrapperClasses != null) { wrapperClassesList.addAll(cachedWrapperClasses); wrapperClassesList.sort(WrapperComparator.COMPARATOR); Collections.reverse(wrapperClassesList); } if (CollectionUtils.isNotEmpty(wrapperClassesList)) { for (Class<?> wrapperClass : wrapperClassesList) { Wrapper wrapper = wrapperClass.getAnnotation(Wrapper.class); boolean match = (wrapper == null) || ((ArrayUtils.isEmpty(wrapper.matches()) || ArrayUtils.contains(wrapper.matches(), name)) && !ArrayUtils.contains(wrapper.mismatches(), name)); if (match) {
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/common/extension/ServicesLoadingStrategy.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/ServicesLoadingStrategy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension; /** * Services {@link LoadingStrategy} * * @since 2.7.7 */ public class ServicesLoadingStrategy implements LoadingStrategy { @Override public String directory() { return "META-INF/services/"; } @Override public boolean overridden() { return true; } @Override public int getPriority() { return MIN_PRIORITY; } @Override public String getName() { return "SERVICES"; } }
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/extension/SPI.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/SPI.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker for extension interface * <p/> * Changes on extension configuration file <br/> * Use <code>Protocol</code> as an example, its configuration file 'META-INF/dubbo/com.xxx.Protocol' is changed from: <br/> * <pre> * com.foo.XxxProtocol * com.foo.YyyProtocol * </pre> * <p> * to key-value pair <br/> * <pre> * xxx=com.foo.XxxProtocol * yyy=com.foo.YyyProtocol * </pre> * <br/> * The reason for this change is: * <p> * If there's third party library referenced by static field or by method in extension implementation, its class will * fail to initialize if the third party library doesn't exist. In this case, dubbo cannot figure out extension's id * therefore cannot be able to map the exception information with the extension, if the previous format is used. * <p/> * For example: * <p> * Fails to load Extension("mina"). When user configure to use mina, dubbo will complain the extension cannot be loaded, * instead of reporting which extract extension implementation fails and the extract reason. * </p> */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface SPI { /** * default extension name */ String value() default ""; /** * scope of SPI, default value is application scope. */ ExtensionScope scope() default ExtensionScope.APPLICATION; }
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/extension/inject/SpiExtensionInjector.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/inject/SpiExtensionInjector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension.inject; import org.apache.dubbo.common.extension.ExtensionAccessor; import org.apache.dubbo.common.extension.ExtensionInjector; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.extension.SPI; public class SpiExtensionInjector implements ExtensionInjector { private ExtensionAccessor extensionAccessor; @Override public void setExtensionAccessor(final ExtensionAccessor extensionAccessor) { this.extensionAccessor = extensionAccessor; } @Override public <T> T getInstance(final Class<T> type, final String name) { if (!type.isInterface() || !type.isAnnotationPresent(SPI.class)) { return null; } ExtensionLoader<T> loader = extensionAccessor.getExtensionLoader(type); if (loader == null) { return null; } if (!loader.getSupportedExtensions().isEmpty()) { return loader.getAdaptiveExtension(); } 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/extension/inject/AdaptiveExtensionInjector.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/inject/AdaptiveExtensionInjector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension.inject; import org.apache.dubbo.common.context.Lifecycle; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.ExtensionAccessor; import org.apache.dubbo.common.extension.ExtensionInjector; import org.apache.dubbo.common.extension.ExtensionLoader; import java.util.Collection; import java.util.Collections; import java.util.Objects; import java.util.stream.Collectors; @Adaptive public class AdaptiveExtensionInjector implements ExtensionInjector, Lifecycle { private Collection<ExtensionInjector> injectors = Collections.emptyList(); private ExtensionAccessor extensionAccessor; public AdaptiveExtensionInjector() {} @Override public void setExtensionAccessor(final ExtensionAccessor extensionAccessor) { this.extensionAccessor = extensionAccessor; } @Override public void initialize() throws IllegalStateException { ExtensionLoader<ExtensionInjector> loader = extensionAccessor.getExtensionLoader(ExtensionInjector.class); injectors = loader.getSupportedExtensions().stream() .map(loader::getExtension) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } @Override public <T> T getInstance(final Class<T> type, final String name) { return injectors.stream() .map(injector -> injector.getInstance(type, name)) .filter(Objects::nonNull) .findFirst() .orElse(null); } @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/extension/support/ActivateComparator.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/ActivateComparator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension.support; import org.apache.dubbo.common.compact.Dubbo2ActivateUtils; import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.ExtensionDirector; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.common.utils.ArrayUtils; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * OrderComparator */ public class ActivateComparator implements Comparator<Class<?>> { private final List<ExtensionDirector> extensionDirectors; private final Map<Class<?>, ActivateInfo> activateInfoMap = new ConcurrentHashMap<>(); public ActivateComparator(ExtensionDirector extensionDirector) { extensionDirectors = new ArrayList<>(); extensionDirectors.add(extensionDirector); } public ActivateComparator(List<ExtensionDirector> extensionDirectors) { this.extensionDirectors = extensionDirectors; } @Override public int compare(Class o1, Class o2) { if (o1 == null && o2 == null) { return 0; } if (o1 == null) { return -1; } if (o2 == null) { return 1; } if (o1.equals(o2)) { return 0; } Class<?> inf = findSpi(o1); ActivateInfo a1 = parseActivate(o1); ActivateInfo a2 = parseActivate(o2); if ((a1.applicableToCompare() || a2.applicableToCompare()) && inf != null) { if (a1.applicableToCompare()) { String n2 = null; for (ExtensionDirector director : extensionDirectors) { ExtensionLoader<?> extensionLoader = director.getExtensionLoader(inf); n2 = extensionLoader.getExtensionName(o2); if (n2 != null) { break; } } if (a1.isLess(n2)) { return -1; } if (a1.isMore(n2)) { return 1; } } if (a2.applicableToCompare()) { String n1 = null; for (ExtensionDirector director : extensionDirectors) { ExtensionLoader<?> extensionLoader = director.getExtensionLoader(inf); n1 = extensionLoader.getExtensionName(o1); if (n1 != null) { break; } } if (a2.isLess(n1)) { return 1; } if (a2.isMore(n1)) { return -1; } } return a1.order > a2.order ? 1 : -1; } // In order to avoid the problem of inconsistency between the loading order of two filters // in different loading scenarios without specifying the order attribute of the filter, // when the order is the same, compare its filterName if (a1.order > a2.order) { return 1; } else if (a1.order == a2.order) { return o1.getSimpleName().compareTo(o2.getSimpleName()) > 0 ? 1 : -1; } else { return -1; } } private Class<?> findSpi(Class<?> clazz) { if (clazz.getInterfaces().length == 0) { return null; } for (Class<?> intf : clazz.getInterfaces()) { if (intf.isAnnotationPresent(SPI.class)) { return intf; } Class<?> result = findSpi(intf); if (result != null) { return result; } } return null; } @SuppressWarnings("deprecation") private ActivateInfo parseActivate(Class<?> clazz) { ActivateInfo info = activateInfoMap.get(clazz); if (info != null) { return info; } info = new ActivateInfo(); if (clazz.isAnnotationPresent(Activate.class)) { Activate activate = clazz.getAnnotation(Activate.class); info.before = activate.before(); info.after = activate.after(); info.order = activate.order(); } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded() && clazz.isAnnotationPresent(Dubbo2ActivateUtils.getActivateClass())) { Annotation activate = clazz.getAnnotation(Dubbo2ActivateUtils.getActivateClass()); info.before = Dubbo2ActivateUtils.getBefore(activate); info.after = Dubbo2ActivateUtils.getAfter(activate); info.order = Dubbo2ActivateUtils.getOrder(activate); } else { info.order = 0; } activateInfoMap.put(clazz, info); return info; } private static class ActivateInfo { private String[] before; private String[] after; private int order; private boolean applicableToCompare() { return ArrayUtils.isNotEmpty(before) || ArrayUtils.isNotEmpty(after); } private boolean isLess(String name) { return Arrays.asList(before).contains(name); } private boolean isMore(String name) { return Arrays.asList(after).contains(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/extension/support/WrapperComparator.java
dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/WrapperComparator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension.support; import org.apache.dubbo.common.compact.Dubbo2ActivateUtils; import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.Wrapper; import java.lang.annotation.Annotation; import java.util.Comparator; /** * OrderComparator * Derived from {@link ActivateComparator} */ public class WrapperComparator implements Comparator<Object> { public static final Comparator<Object> COMPARATOR = new WrapperComparator(); @Override public int compare(Object o1, Object o2) { if (o1 == null && o2 == null) { return 0; } if (o1 == null) { return -1; } if (o2 == null) { return 1; } if (o1.equals(o2)) { return 0; } Class clazz1 = (Class) o1; Class clazz2 = (Class) o2; OrderInfo a1 = parseOrder(clazz1); OrderInfo a2 = parseOrder(clazz2); int n1 = a1.order; int n2 = a2.order; // never return 0 even if n1 equals n2, otherwise, o1 and o2 will override each other in collection like HashSet return n1 > n2 ? 1 : -1; } @SuppressWarnings("deprecation") private OrderInfo parseOrder(Class<?> clazz) { OrderInfo info = new OrderInfo(); if (clazz.isAnnotationPresent(Activate.class)) { // TODO: backward compatibility Activate activate = clazz.getAnnotation(Activate.class); info.order = activate.order(); } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded() && clazz.isAnnotationPresent(Dubbo2ActivateUtils.getActivateClass())) { // TODO: backward compatibility Annotation activate = clazz.getAnnotation(Dubbo2ActivateUtils.getActivateClass()); info.order = Dubbo2ActivateUtils.getOrder(activate); } else if (clazz.isAnnotationPresent(Wrapper.class)) { Wrapper wrapper = clazz.getAnnotation(Wrapper.class); info.order = wrapper.order(); } return info; } private static class OrderInfo { private int order; } }
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/lang/Prioritized.java
dubbo-common/src/main/java/org/apache/dubbo/common/lang/Prioritized.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.lang; import java.util.Comparator; import static java.lang.Integer.compare; /** * {@code Prioritized} interface can be implemented by objects that * should be sorted, for example the tasks in executable queue. * * @since 2.7.5 */ public interface Prioritized extends Comparable<Prioritized> { /** * The {@link Comparator} of {@link Prioritized} */ Comparator<Object> COMPARATOR = (one, two) -> { boolean b1 = one instanceof Prioritized; boolean b2 = two instanceof Prioritized; if (b1 && !b2) { // one is Prioritized, two is not return -1; } else if (b2 && !b1) { // two is Prioritized, one is not return 1; } else if (b1 && b2) { // one and two both are Prioritized return ((Prioritized) one).compareTo((Prioritized) two); } else { // no different return 0; } }; /** * The maximum priority */ int MAX_PRIORITY = Integer.MIN_VALUE; /** * The minimum priority */ int MIN_PRIORITY = Integer.MAX_VALUE; /** * Normal Priority */ int NORMAL_PRIORITY = 0; /** * Get the priority * * @return the default is {@link #NORMAL_PRIORITY} */ default int getPriority() { return NORMAL_PRIORITY; } @Override default int compareTo(Prioritized that) { return compare(this.getPriority(), that.getPriority()); } }
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/lang/ShutdownHookCallback.java
dubbo-common/src/main/java/org/apache/dubbo/common/lang/ShutdownHookCallback.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.lang; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; /** * A callback interface invoked when Dubbo application is stopped. * <p>Note: This class is not directly related to Java ShutdownHook.</p> * <p/> * <p>Call chains:</p> * <ol> * <li>Java Shutdown Hook -> ApplicationDeployer.destroy() -> execute ShutdownHookCallback</li> * <li>Stop dubbo application -> ApplicationDeployer.destroy() -> execute ShutdownHookCallback</li> * </ol> * * @since 2.7.5 * @see org.apache.dubbo.common.deploy.ApplicationDeployListener * @see org.apache.dubbo.rpc.model.ScopeModelDestroyListener */ @SPI(scope = ExtensionScope.APPLICATION) public interface ShutdownHookCallback extends Prioritized { /** * Callback execution * * @throws Throwable if met with some errors */ void callback() throws Throwable; }
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/lang/Nullable.java
dubbo-common/src/main/java/org/apache/dubbo/common/lang/Nullable.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.lang; 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; @Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Nullable {}
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/lang/ShutdownHookCallbacks.java
dubbo-common/src/main/java/org/apache/dubbo/common/lang/ShutdownHookCallbacks.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.lang; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.resource.Disposable; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collection; import java.util.LinkedList; import java.util.List; import static java.util.Collections.sort; import static org.apache.dubbo.common.function.ThrowableAction.execute; /** * The composed {@link ShutdownHookCallback} class to manipulate one and more {@link ShutdownHookCallback} instances * * @since 2.7.5 */ public class ShutdownHookCallbacks implements Disposable { private final List<ShutdownHookCallback> callbacks = new LinkedList<>(); private final ApplicationModel applicationModel; public ShutdownHookCallbacks(ApplicationModel applicationModel) { this.applicationModel = applicationModel; loadCallbacks(); } public ShutdownHookCallbacks addCallback(ShutdownHookCallback callback) { synchronized (this) { if (!callbacks.contains(callback)) { this.callbacks.add(callback); } } return this; } public Collection<ShutdownHookCallback> getCallbacks() { synchronized (this) { sort(this.callbacks); return this.callbacks; } } public void destroy() { synchronized (this) { callbacks.clear(); } } private void loadCallbacks() { ExtensionLoader<ShutdownHookCallback> loader = applicationModel.getExtensionLoader(ShutdownHookCallback.class); loader.getSupportedExtensionInstances().forEach(this::addCallback); } public void callback() { getCallbacks().forEach(callback -> execute(callback::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/common/logger/Level.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/Level.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger; /** * Level */ public enum Level { /** * ALL */ ALL, /** * TRACE */ TRACE, /** * DEBUG */ DEBUG, /** * INFO */ INFO, /** * WARN */ WARN, /** * ERROR */ ERROR, /** * OFF */ OFF }
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/logger/LoggerFactory.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/LoggerFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.jcl.JclLoggerAdapter; import org.apache.dubbo.common.logger.jdk.JdkLoggerAdapter; import org.apache.dubbo.common.logger.log4j.Log4jLoggerAdapter; import org.apache.dubbo.common.logger.log4j2.Log4j2LoggerAdapter; import org.apache.dubbo.common.logger.slf4j.Slf4jLoggerAdapter; import org.apache.dubbo.common.logger.support.FailsafeErrorTypeAwareLogger; import org.apache.dubbo.common.logger.support.FailsafeLogger; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.Pair; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Logger factory */ public class LoggerFactory { private static final ConcurrentMap<String, FailsafeLogger> LOGGERS = new ConcurrentHashMap<>(); private static final ConcurrentMap<Object, FailsafeErrorTypeAwareLogger> ERROR_TYPE_AWARE_LOGGERS = new ConcurrentHashMap<>(); private static volatile LoggerAdapter loggerAdapter; // search common-used logging frameworks static { String logger = SystemPropertyConfigUtils.getSystemProperty(CommonConstants.DubboProperty.DUBBO_APPLICATION_LOGGER, ""); switch (logger) { case Slf4jLoggerAdapter.NAME: setLoggerAdapter(new Slf4jLoggerAdapter()); break; case JclLoggerAdapter.NAME: setLoggerAdapter(new JclLoggerAdapter()); break; case Log4jLoggerAdapter.NAME: setLoggerAdapter(new Log4jLoggerAdapter()); break; case JdkLoggerAdapter.NAME: setLoggerAdapter(new JdkLoggerAdapter()); break; case Log4j2LoggerAdapter.NAME: setLoggerAdapter(new Log4j2LoggerAdapter()); break; default: List<Class<? extends LoggerAdapter>> candidates = Arrays.asList( Log4jLoggerAdapter.class, Slf4jLoggerAdapter.class, Log4j2LoggerAdapter.class, JclLoggerAdapter.class, JdkLoggerAdapter.class); boolean found = false; // try to use the first available adapter for (Class<? extends LoggerAdapter> clazz : candidates) { try { LoggerAdapter loggerAdapter = clazz.getDeclaredConstructor().newInstance(); loggerAdapter.getLogger(LoggerFactory.class); if (loggerAdapter.isConfigured()) { setLoggerAdapter(loggerAdapter); found = true; break; } } catch (Exception | LinkageError ignored) { // ignore } } if (found) { break; } System.err.println("Dubbo: Unable to find a proper configured logger to log out."); for (Class<? extends LoggerAdapter> clazz : candidates) { try { LoggerAdapter loggerAdapter = clazz.getDeclaredConstructor().newInstance(); loggerAdapter.getLogger(LoggerFactory.class); setLoggerAdapter(loggerAdapter); found = true; break; } catch (Throwable ignored) { // ignore } } if (found) { System.err.println( "Dubbo: Using default logger: " + loggerAdapter.getClass().getName() + ". " + "If you cannot see any log, please configure -Ddubbo.application.logger property to your preferred logging framework."); } else { System.err.println( "Dubbo: Unable to find any available logger adapter to log out. Dubbo logs will be ignored. " + "Please configure -Ddubbo.application.logger property and add corresponding logging library to classpath."); } } } private LoggerFactory() {} public static void setLoggerAdapter(FrameworkModel frameworkModel, String loggerAdapter) { if (loggerAdapter != null && loggerAdapter.length() > 0) { setLoggerAdapter( frameworkModel.getExtensionLoader(LoggerAdapter.class).getExtension(loggerAdapter)); } } /** * Set logger provider * * @param loggerAdapter logger provider */ public static void setLoggerAdapter(LoggerAdapter loggerAdapter) { if (loggerAdapter != null) { if (loggerAdapter == LoggerFactory.loggerAdapter) { return; } loggerAdapter.getLogger(LoggerFactory.class.getName()); LoggerFactory.loggerAdapter = loggerAdapter; for (Map.Entry<String, FailsafeLogger> entry : LOGGERS.entrySet()) { entry.getValue().setLogger(LoggerFactory.loggerAdapter.getLogger(entry.getKey())); } } } /** * Get logger provider * * @param key the returned logger will be named after clazz * @return logger */ public static Logger getLogger(Class<?> key) { return ConcurrentHashMapUtils.computeIfAbsent( LOGGERS, key.getName(), name -> new FailsafeLogger(loggerAdapter.getLogger(name))); } /** * Get logger provider * * @param key the returned logger will be named after key * @return logger provider */ public static Logger getLogger(String key) { return ConcurrentHashMapUtils.computeIfAbsent( LOGGERS, key, k -> new FailsafeLogger(loggerAdapter.getLogger(k))); } /** * Get error type aware logger by Class object. * * @param key the returned logger will be named after clazz * @return error type aware logger */ public static ErrorTypeAwareLogger getErrorTypeAwareLogger(Class<?> key) { final String name = key.getName(); return ConcurrentHashMapUtils.computeIfAbsent( ERROR_TYPE_AWARE_LOGGERS, name, k -> new FailsafeErrorTypeAwareLogger(loggerAdapter.getLogger(name))); } /** * Get error type aware logger by a String key. * * @param key the returned logger will be named after key * @return error type aware logger */ public static ErrorTypeAwareLogger getErrorTypeAwareLogger(String key) { return ConcurrentHashMapUtils.computeIfAbsent( ERROR_TYPE_AWARE_LOGGERS, key, k -> new FailsafeErrorTypeAwareLogger(loggerAdapter.getLogger(key))); } /** * Get error type aware logger by FQCN and Class object. * * @param fqcn the full qualified class name of caller * @param key the returned logger will be named after clazz * @return error type aware logger */ public static ErrorTypeAwareLogger getErrorTypeAwareLogger(String fqcn, Class<?> key) { final String name = key.getName(); return ConcurrentHashMapUtils.computeIfAbsent( ERROR_TYPE_AWARE_LOGGERS, Pair.of(name, fqcn), p -> new FailsafeErrorTypeAwareLogger(loggerAdapter.getLogger(fqcn, name))); } /** * Get error type aware logger by FQCN and a String key. * * @param fqcn the full qualified class name of caller * @param key the returned logger will be named after key * @return error type aware logger */ public static ErrorTypeAwareLogger getErrorTypeAwareLogger(String fqcn, String key) { return ConcurrentHashMapUtils.computeIfAbsent( ERROR_TYPE_AWARE_LOGGERS, Pair.of(key, fqcn), p -> new FailsafeErrorTypeAwareLogger(loggerAdapter.getLogger(fqcn, key))); } /** * Get logging level * * @return logging level */ public static Level getLevel() { return loggerAdapter.getLevel(); } /** * Set the current logging level * * @param level logging level */ public static void setLevel(Level level) { loggerAdapter.setLevel(level); } /** * Get the current logging file * * @return current logging file */ public static File getFile() { return loggerAdapter.getFile(); } /** * Get the available adapter names * * @return available adapter names */ public static List<String> getAvailableAdapter() { Map<Class<? extends LoggerAdapter>, String> candidates = new HashMap<>(); candidates.put(Log4jLoggerAdapter.class, "log4j"); candidates.put(Slf4jLoggerAdapter.class, "slf4j"); candidates.put(Log4j2LoggerAdapter.class, "log4j2"); candidates.put(JclLoggerAdapter.class, "jcl"); candidates.put(JdkLoggerAdapter.class, "jdk"); List<String> result = new LinkedList<>(); for (Map.Entry<Class<? extends LoggerAdapter>, String> entry : candidates.entrySet()) { try { LoggerAdapter loggerAdapter = entry.getKey().getDeclaredConstructor().newInstance(); loggerAdapter.getLogger(LoggerFactory.class); result.add(entry.getValue()); } catch (Exception ignored) { // ignored } } return result; } /** * Get the current adapter name * * @return current adapter name */ public static String getCurrentAdapter() { Map<Class<? extends LoggerAdapter>, String> candidates = new HashMap<>(); candidates.put(Log4jLoggerAdapter.class, "log4j"); candidates.put(Slf4jLoggerAdapter.class, "slf4j"); candidates.put(Log4j2LoggerAdapter.class, "log4j2"); candidates.put(JclLoggerAdapter.class, "jcl"); candidates.put(JdkLoggerAdapter.class, "jdk"); String name = candidates.get(loggerAdapter.getClass()); if (name == null) { name = loggerAdapter.getClass().getSimpleName(); } return 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/logger/FluentLoggerImpl.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/FluentLoggerImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger; import org.apache.dubbo.common.logger.helpers.FormattingTuple; import org.apache.dubbo.common.logger.helpers.MessageFormatter; import org.apache.dubbo.common.utils.StringUtils; import java.util.function.Supplier; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; final class FluentLoggerImpl implements FluentLogger { private final ErrorTypeAwareLogger delegate; private final FluentLoggerImpl root; private String cause = StringUtils.EMPTY_STRING; private String extendedInformation = StringUtils.EMPTY_STRING; private Supplier<String> messageSupplier; private String message; private Object[] args; FluentLoggerImpl(Class<?> key) { delegate = LoggerFactory.getErrorTypeAwareLogger(FluentLoggerImpl.class.getName(), key); root = this; } FluentLoggerImpl(String key) { delegate = LoggerFactory.getErrorTypeAwareLogger(FluentLoggerImpl.class.getName(), key); root = this; } private FluentLoggerImpl(FluentLoggerImpl logger) { delegate = logger.delegate; root = logger; } @Override public FluentLogger cause(String cause) { if (cause == null) { return this; } FluentLoggerImpl logger = getLogger(); logger.cause = cause; return logger; } @Override public FluentLogger more(String extendedInformation) { if (extendedInformation == null) { return this; } FluentLoggerImpl logger = getLogger(); logger.extendedInformation = extendedInformation; return logger; } @Override public FluentLogger msg(String message) { FluentLoggerImpl logger = getLogger(); logger.message = message; return logger; } @Override public FluentLogger msg(String message, Object... args) { FluentLoggerImpl logger = getLogger(); logger.message = message; logger.args = args; return logger; } @Override public FluentLogger msg(Supplier<String> supplier) { FluentLoggerImpl logger = getLogger(); logger.messageSupplier = supplier; return logger; } @Override public void trace() { if (message != null) { if (args != null && args.length > 0) { if (delegate.isTraceEnabled()) { delegate.trace(message, formatArgs(args)); } } else { delegate.trace(message); } } else if (messageSupplier != null) { if (delegate.isTraceEnabled()) { delegate.trace(messageSupplier.get()); } } else { warnMessageMissing(); } } @Override public void trace(Throwable t) { if (message != null) { int len = args == null ? 0 : args.length; if (len > 0) { if (delegate.isTraceEnabled()) { Object[] arr = new Object[len + 1]; System.arraycopy(args, 0, arr, 0, len); arr[len] = t; delegate.trace(message, formatArgs(arr)); } } else { delegate.trace(message, t); } } else if (messageSupplier != null) { if (delegate.isTraceEnabled()) { delegate.trace(messageSupplier.get(), t); } } else { warnMessageMissing(); } } @Override public void trace(String message) { delegate.trace(message); } @Override public void trace(String message, Object... args) { if (args == null || args.length == 0) { delegate.trace(message); } else if (delegate.isTraceEnabled()) { delegate.trace(message, formatArgs(args)); } } @Override public void trace(String message, Throwable t) { delegate.trace(message, t); } @Override public void debug() { if (message != null) { if (args != null && args.length > 0) { if (delegate.isDebugEnabled()) { delegate.debug(message, formatArgs(args)); } } else { delegate.debug(message); } } else if (messageSupplier != null) { if (delegate.isDebugEnabled()) { delegate.debug(messageSupplier.get()); } } else { warnMessageMissing(); } } @Override public void debug(Throwable t) { if (message != null) { int len = args == null ? 0 : args.length; if (len > 0) { if (delegate.isDebugEnabled()) { Object[] arr = new Object[len + 1]; System.arraycopy(args, 0, arr, 0, len); arr[len] = t; delegate.debug(message, formatArgs(arr)); } } else { delegate.debug(message, t); } } else if (messageSupplier != null) { if (delegate.isDebugEnabled()) { delegate.debug(messageSupplier.get(), t); } } else { warnMessageMissing(); } } @Override public void debug(String message) { delegate.debug(message); } @Override public void debug(String message, Object... args) { if (args == null || args.length == 0) { delegate.debug(message); } else if (delegate.isDebugEnabled()) { delegate.debug(message, formatArgs(args)); } } @Override public void debug(String message, Throwable t) { delegate.debug(message, t); } @Override public void info() { if (message != null) { if (args != null && args.length > 0) { if (delegate.isInfoEnabled()) { delegate.info(message, formatArgs(args)); } } else { delegate.info(message); } } else if (messageSupplier != null) { if (delegate.isInfoEnabled()) { delegate.info(messageSupplier.get()); } } else { warnMessageMissing(); } } @Override public void info(Throwable t) { if (message != null) { int len = args == null ? 0 : args.length; if (len > 0) { if (delegate.isInfoEnabled()) { Object[] arr = new Object[len + 1]; System.arraycopy(args, 0, arr, 0, len); arr[len] = t; delegate.info(message, formatArgs(arr)); } } else { delegate.info(message, t); } } else if (messageSupplier != null) { if (delegate.isInfoEnabled()) { delegate.info(messageSupplier.get(), t); } } else { warnMessageMissing(); } } @Override public void info(String message, Object... args) { if (args == null || args.length == 0) { delegate.info(message); } else if (delegate.isInfoEnabled()) { delegate.info(message, formatArgs(args)); } } @Override public void info(String message) { delegate.info(message); } @Override public void info(String message, Throwable t) { delegate.info(message, t); } @Override public void internalWarn() { warn(INTERNAL_ERROR); } @Override public void internalWarn(Throwable t) { warn(INTERNAL_ERROR, t); } @Override public void internalWarn(String message) { warn(INTERNAL_ERROR, message); } @Override public void internalWarn(String message, Object... args) { warn(INTERNAL_ERROR, message, args); } @Override public void internalWarn(String message, Throwable t) { warn(INTERNAL_ERROR, message, t); } @Override public void warn(String code) { if (message != null) { if (args != null && args.length > 0) { formatAndWarn(code, message, args); } else { delegate.warn(code, cause, extendedInformation, message); } } else if (messageSupplier != null) { if (delegate.isWarnEnabled()) { delegate.warn(code, cause, extendedInformation, messageSupplier.get()); } } else { warnMessageMissing(); } } @Override public void warn(String code, Throwable t) { if (message != null) { if (args != null && args.length > 0) { if (delegate.isWarnEnabled()) { FormattingTuple tuple = MessageFormatter.arrayFormat(message, formatArgs(args)); delegate.warn(code, cause, extendedInformation, tuple.getMessage(), t); } } else { delegate.warn(code, cause, extendedInformation, message, t); } } else if (messageSupplier != null && delegate.isWarnEnabled()) { delegate.warn(code, cause, extendedInformation, messageSupplier.get(), t); } } @Override public void warn(String code, String message, Object... args) { if (args == null || args.length == 0) { delegate.warn(code, cause, extendedInformation, message); return; } formatAndWarn(code, message, args); } private void formatAndWarn(String code, String message, Object... args) { if (!delegate.isWarnEnabled()) { return; } FormattingTuple tuple = MessageFormatter.arrayFormat(message, formatArgs(args)); if (tuple.getThrowable() == null) { delegate.warn(code, cause, extendedInformation, tuple.getMessage()); } else { delegate.warn(code, cause, extendedInformation, tuple.getMessage(), tuple.getThrowable()); } } @Override public void warn(String code, String message, Throwable t) { delegate.warn(code, cause, extendedInformation, message, t); } @Override public void internalError() { error(INTERNAL_ERROR); } @Override public void internalError(Throwable t) { error(INTERNAL_ERROR, t); } @Override public void internalError(String message) { error(INTERNAL_ERROR, message); } @Override public void internalError(String message, Object... args) { error(INTERNAL_ERROR, message, args); } @Override public void internalError(String message, Throwable t) { error(INTERNAL_ERROR, message, t); } @Override public void error(String code) { if (message != null) { if (args != null && args.length > 0) { formatAndError(code, message, args); } else { delegate.error(code, cause, extendedInformation, message); } } else if (messageSupplier != null) { if (delegate.isErrorEnabled()) { delegate.error(code, cause, extendedInformation, messageSupplier.get()); } } else { warnMessageMissing(); } } @Override public void error(String code, Throwable t) { if (message != null) { if (args != null && args.length > 0) { if (delegate.isErrorEnabled()) { FormattingTuple tuple = MessageFormatter.arrayFormat(message, formatArgs(args)); delegate.error(code, cause, extendedInformation, tuple.getMessage(), t); } } else { delegate.error(code, cause, extendedInformation, message, t); } } else if (messageSupplier != null) { if (delegate.isErrorEnabled()) { delegate.error(code, cause, extendedInformation, messageSupplier.get(), t); } } else { warnMessageMissing(); } } @Override public void error(String code, String message, Object... args) { if (args == null || args.length == 0) { delegate.error(code, cause, extendedInformation, message); return; } formatAndError(code, message, args); } private void formatAndError(String code, String message, Object... args) { if (!delegate.isErrorEnabled()) { return; } FormattingTuple tuple = MessageFormatter.arrayFormat(message, formatArgs(args)); if (tuple.getThrowable() == null) { delegate.error(code, cause, extendedInformation, tuple.getMessage()); } else { delegate.error(code, cause, extendedInformation, tuple.getMessage(), tuple.getThrowable()); } } @Override public void error(String code, String message, Throwable t) { delegate.error(code, cause, extendedInformation, message, t); } @Override public void log(Level level) { switch (level) { case TRACE: trace(); break; case DEBUG: debug(); break; case INFO: info(); break; case WARN: internalWarn(); break; case ERROR: internalError(); break; default: } } @Override public void log(Level level, Throwable t) { switch (level) { case TRACE: trace(t); break; case DEBUG: debug(t); break; case INFO: info(t); break; case WARN: internalWarn(t); break; case ERROR: internalError(t); break; default: } } @Override public void log(Level level, String msg) { switch (level) { case TRACE: trace(msg); break; case DEBUG: debug(msg); break; case INFO: info(msg); break; case WARN: internalWarn(msg); break; case ERROR: internalError(msg); break; default: } } @Override public void log(Level level, String msg, Object... args) { switch (level) { case TRACE: trace(msg, args); break; case DEBUG: debug(msg, args); break; case INFO: info(msg, args); break; case WARN: internalWarn(msg, args); break; case ERROR: internalError(msg, args); break; default: } } @Override public void log(Level level, String msg, Throwable t) { switch (level) { case TRACE: trace(msg, t); break; case DEBUG: debug(msg, t); break; case INFO: info(msg, t); break; case WARN: internalWarn(msg, t); break; case ERROR: internalError(msg, t); break; default: } } @Override public void log(String code, Level level) { switch (level) { case TRACE: trace(); break; case DEBUG: debug(); break; case INFO: info(); break; case WARN: warn(code); break; case ERROR: error(code); break; default: } } @Override public void log(String code, Level level, String msg, Object... args) { switch (level) { case TRACE: trace(msg, args); break; case DEBUG: debug(msg, args); break; case INFO: info(msg, args); break; case WARN: warn(code, msg, args); break; case ERROR: error(code, msg, args); break; default: } } @Override public void log(String code, Level level, String msg, Throwable t) { switch (level) { case TRACE: trace(msg, t); break; case DEBUG: debug(msg, t); break; case INFO: info(msg, t); break; case WARN: warn(code, msg, t); break; case ERROR: error(code, msg, t); break; default: } } @Override public boolean isTraceEnabled() { return delegate.isTraceEnabled(); } @Override public boolean isDebugEnabled() { return delegate.isDebugEnabled(); } @Override public boolean isInfoEnabled() { return delegate.isInfoEnabled(); } @Override public boolean isWarnEnabled() { return delegate.isWarnEnabled(); } @Override public boolean isErrorEnabled() { return delegate.isErrorEnabled(); } private FluentLoggerImpl getLogger() { return this == root ? new FluentLoggerImpl(this) : this; } private void warnMessageMissing() { delegate.warn(INTERNAL_ERROR, cause, extendedInformation, "Message must not be empty"); } private static Object[] formatArgs(Object[] args) { for (int i = 0; i < args.length; i++) { if (args[i] instanceof Supplier) { args[i] = ((Supplier<?>) args[i]).get(); } } return args; } }
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/logger/ErrorTypeAwareLogger.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/ErrorTypeAwareLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger; import org.apache.dubbo.common.constants.LoggerCodeConstants; /** * Logger interface with the ability of displaying solution of different types of error. * * <p> * This logger will log a message like this: * * <blockquote><pre> * ... (original logging message) This may be caused by (... cause), * go to https://dubbo.apache.org/faq/[Cat]/[X] to find instructions. (... extendedInformation) * </pre></blockquote> * * Where "[Cat]/[X]" is the error code ("code" in arguments). The link is clickable, leading user to * the "Error code and its corresponding solutions" page. * * @see LoggerCodeConstants Detailed Format of Error Code and Error Code Constants */ public interface ErrorTypeAwareLogger extends Logger { /** * Logs a message with warn log level. * * @param code error code * @param cause error cause * @param extendedInformation extended information * @param msg log this message */ void warn(String code, String cause, String extendedInformation, String msg); /** * Logs a message with warn log level. * * @param code error code * @param cause error cause * @param extendedInformation extended information * @param msg log this message * @param e log this cause */ void warn(String code, String cause, String extendedInformation, String msg, Throwable e); /** * Logs a message with error log level. * * @param code error code * @param cause error cause * @param extendedInformation extended information * @param msg log this message */ void error(String code, String cause, String extendedInformation, String msg); /** * Logs a message with error log level. * * @param code error code * @param cause error cause * @param extendedInformation extended information * @param msg log this message * @param e log this cause */ void error(String code, String cause, String extendedInformation, String msg, Throwable 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/common/logger/LoggerAdapter.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/LoggerAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.common.logger; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import java.io.File; /** * Logger provider */ @SPI(scope = ExtensionScope.FRAMEWORK) public interface LoggerAdapter { /** * Get a logger * * @param key the returned logger will be named after clazz * @return logger */ Logger getLogger(Class<?> key); /** * Get a logger * * @param key the returned logger will be named after key * @return logger */ Logger getLogger(String key); /** * Get a logger * * @param fqcn the full qualified class name of caller * @param key the returned logger will be named after clazz * @return logger */ default Logger getLogger(String fqcn, Class<?> key) { return getLogger(key); } /** * Get a logger * * @param fqcn the full qualified class name of caller * @param key the returned logger will be named after key * @return logger */ default Logger getLogger(String fqcn, String key) { return getLogger(key); } /** * Get the current logging level * * @return current logging level */ Level getLevel(); /** * Set the current logging level * * @param level logging level */ void setLevel(Level level); /** * Get the current logging file * * @return current logging file */ File getFile(); /** * Set the current logging file * * @param file logging file */ void setFile(File file); /** * Return is the current logger has been configured. * Used to check if logger is available to use. * * @return true if the current logger has been configured */ default boolean isConfigured() { return true; } }
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/logger/FluentLogger.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/FluentLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger; import java.util.function.Supplier; public interface FluentLogger { FluentLogger cause(String cause); FluentLogger more(String extendedInformation); FluentLogger msg(String msg); FluentLogger msg(String msg, Object... args); FluentLogger msg(Supplier<String> supplier); void trace(); void trace(Throwable t); void trace(String msg); void trace(String msg, Object... args); void trace(String msg, Throwable t); void debug(); void debug(Throwable t); void debug(String msg); void debug(String msg, Object... args); void debug(String msg, Throwable t); void info(); void info(Throwable t); void info(String msg, Object... args); void info(String msg); void info(String msg, Throwable t); void internalWarn(); void internalWarn(Throwable t); void internalWarn(String msg); void internalWarn(String msg, Object... args); void internalWarn(String msg, Throwable t); void warn(String code); void warn(String code, Throwable t); void warn(String code, String msg, Object... args); void warn(String code, String msg, Throwable t); void internalError(); void internalError(Throwable t); void internalError(String msg); void internalError(String msg, Object... args); void internalError(String msg, Throwable t); void error(String code); void error(String code, Throwable t); void error(String code, String msg, Object... args); void error(String code, String msg, Throwable t); void log(Level level); void log(Level level, Throwable t); void log(Level level, String msg); void log(Level level, String msg, Object... args); void log(Level level, String msg, Throwable t); void log(String code, Level level); void log(String code, Level level, String msg, Object... args); void log(String code, Level level, String msg, Throwable t); boolean isTraceEnabled(); boolean isDebugEnabled(); boolean isInfoEnabled(); boolean isWarnEnabled(); boolean isErrorEnabled(); static FluentLogger of(Class<?> key) { return new FluentLoggerImpl(key); } static FluentLogger of(String key) { return new FluentLoggerImpl(key); } interface S extends Supplier<String> {} }
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/logger/Logger.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/Logger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger; /** * Logger interface * <p> * This interface is referred from commons-logging */ public interface Logger { /** * Logs a message with trace log level. * * @param msg log this message */ void trace(String msg); /** * Logs a message with trace log level. * * @param msg log this message * @param arguments a list of arguments */ void trace(String msg, Object... arguments); /** * Logs an error with trace log level. * * @param e log this cause */ void trace(Throwable e); /** * Logs an error with trace log level. * * @param msg log this message * @param e log this cause */ void trace(String msg, Throwable e); /** * Logs a message with debug log level. * * @param msg log this message */ void debug(String msg); /** * Logs a message with debug log level. * * @param msg log this message * @param arguments a list of arguments */ void debug(String msg, Object... arguments); /** * Logs an error with debug log level. * * @param e log this cause */ void debug(Throwable e); /** * Logs an error with debug log level. * * @param msg log this message * @param e log this cause */ void debug(String msg, Throwable e); /** * Logs a message with info log level. * * @param msg log this message */ void info(String msg); /** * Logs a message with info log level. * * @param msg log this message * @param arguments a list of arguments */ void info(String msg, Object... arguments); /** * Logs an error with info log level. * * @param e log this cause */ void info(Throwable e); /** * Logs an error with info log level. * * @param msg log this message * @param e log this cause */ void info(String msg, Throwable e); /** * Logs a message with warn log level. * * @param msg log this message */ void warn(String msg); /** * Logs a message with warn log level. * * @param msg log this message * @param arguments a list of arguments */ void warn(String msg, Object... arguments); /** * Logs a message with warn log level. * * @param e log this message */ void warn(Throwable e); /** * Logs a message with warn log level. * * @param msg log this message * @param e log this cause */ void warn(String msg, Throwable e); /** * Logs a message with error log level. * * @param msg log this message */ void error(String msg); /** * Logs a message with error log level. * * @param msg log this message * @param arguments a list of arguments */ void error(String msg, Object... arguments); /** * Logs an error with error log level. * * @param e log this cause */ void error(Throwable e); /** * Logs an error with error log level. * * @param msg log this message * @param e log this cause */ void error(String msg, Throwable e); /** * Is trace logging currently enabled? * * @return true if trace is enabled */ boolean isTraceEnabled(); /** * Is debug logging currently enabled? * * @return true if debug is enabled */ boolean isDebugEnabled(); /** * Is info logging currently enabled? * * @return true if info is enabled */ boolean isInfoEnabled(); /** * Is warn logging currently enabled? * * @return true if warn is enabled */ boolean isWarnEnabled(); /** * Is error logging currently enabled? * * @return true if error is enabled */ boolean isErrorEnabled(); }
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/logger/ListenableLogger.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/ListenableLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger; /** * Loggers that can register to listen to log messages. */ public interface ListenableLogger extends ErrorTypeAwareLogger { /** * Register a listener to this logger,and get notified when a log happens. * * @param listener log listener */ void registerListen(LogListener listener); }
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/logger/LogListener.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/LogListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger; /** * Log Listener, can registered to an {@link ListenableLogger}. */ public interface LogListener { void onMessage(String code, String msg); }
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/logger/jdk/JdkLoggerAdapter.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/jdk/JdkLoggerAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger.jdk; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerAdapter; import java.io.File; import java.io.InputStream; import java.lang.reflect.Field; import java.util.logging.FileHandler; import java.util.logging.Handler; import java.util.logging.LogManager; public class JdkLoggerAdapter implements LoggerAdapter { public static final String NAME = "jdk"; private static final String GLOBAL_LOGGER_NAME = "global"; private File file; private boolean propertiesLoaded = false; public JdkLoggerAdapter() { try { InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("logging.properties"); if (in != null) { LogManager.getLogManager().readConfiguration(in); propertiesLoaded = true; } else { System.err.println("No such logging.properties in classpath for jdk logging config!"); } } catch (Exception t) { System.err.println( "Failed to load logging.properties in classpath for jdk logging config, cause: " + t.getMessage()); } try { Handler[] handlers = java.util.logging.Logger.getLogger(GLOBAL_LOGGER_NAME).getHandlers(); for (Handler handler : handlers) { if (handler instanceof FileHandler) { FileHandler fileHandler = (FileHandler) handler; Field field = fileHandler.getClass().getField("files"); File[] files = (File[]) field.get(fileHandler); if (files != null && files.length > 0) { file = files[0]; } } } } catch (Exception ignored) { // ignore } } private static java.util.logging.Level toJdkLevel(Level level) { if (level == Level.ALL) { return java.util.logging.Level.ALL; } if (level == Level.TRACE) { return java.util.logging.Level.FINER; } if (level == Level.DEBUG) { return java.util.logging.Level.FINE; } if (level == Level.INFO) { return java.util.logging.Level.INFO; } if (level == Level.WARN) { return java.util.logging.Level.WARNING; } if (level == Level.ERROR) { return java.util.logging.Level.SEVERE; } // if (level == Level.OFF) return java.util.logging.Level.OFF; } private static Level fromJdkLevel(java.util.logging.Level level) { if (level == java.util.logging.Level.ALL) { return Level.ALL; } if (level == java.util.logging.Level.FINER) { return Level.TRACE; } if (level == java.util.logging.Level.FINE) { return Level.DEBUG; } if (level == java.util.logging.Level.INFO) { return Level.INFO; } if (level == java.util.logging.Level.WARNING) { return Level.WARN; } if (level == java.util.logging.Level.SEVERE) { return Level.ERROR; } // if (level == java.util.logging.Level.OFF) return Level.OFF; } @Override public Logger getLogger(Class<?> key) { return new JdkLogger(java.util.logging.Logger.getLogger(key == null ? "" : key.getName())); } @Override public Logger getLogger(String key) { return new JdkLogger(java.util.logging.Logger.getLogger(key)); } @Override public Level getLevel() { return fromJdkLevel( java.util.logging.Logger.getLogger(GLOBAL_LOGGER_NAME).getLevel()); } @Override public void setLevel(Level level) { java.util.logging.Logger.getLogger(GLOBAL_LOGGER_NAME).setLevel(toJdkLevel(level)); } @Override public File getFile() { return file; } @Override public void setFile(File file) { // ignore } @Override public boolean isConfigured() { return propertiesLoaded; } }
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/logger/jdk/JdkLogger.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/jdk/JdkLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger.jdk; import org.apache.dubbo.common.logger.Logger; import java.util.logging.Level; import org.slf4j.helpers.FormattingTuple; import org.slf4j.helpers.MessageFormatter; public class JdkLogger implements Logger { private final java.util.logging.Logger logger; public JdkLogger(java.util.logging.Logger logger) { this.logger = logger; } @Override public void trace(String msg) { logger.log(Level.FINER, msg); } @Override public void trace(String msg, Object... arguments) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); logger.log(Level.FINER, ft.getMessage(), ft.getThrowable()); } @Override public void trace(Throwable e) { logger.log(Level.FINER, e.getMessage(), e); } @Override public void trace(String msg, Throwable e) { logger.log(Level.FINER, msg, e); } @Override public void debug(String msg) { logger.log(Level.FINE, msg); } @Override public void debug(String msg, Object... arguments) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); logger.log(Level.FINE, ft.getMessage(), ft.getThrowable()); } @Override public void debug(Throwable e) { logger.log(Level.FINE, e.getMessage(), e); } @Override public void debug(String msg, Throwable e) { logger.log(Level.FINE, msg, e); } @Override public void info(String msg) { logger.log(Level.INFO, msg); } @Override public void info(String msg, Object... arguments) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); logger.log(Level.INFO, ft.getMessage(), ft.getThrowable()); } @Override public void info(String msg, Throwable e) { logger.log(Level.INFO, msg, e); } @Override public void warn(String msg) { logger.log(Level.WARNING, msg); } @Override public void warn(String msg, Object... arguments) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); logger.log(Level.WARNING, ft.getMessage(), ft.getThrowable()); } @Override public void warn(String msg, Throwable e) { logger.log(Level.WARNING, msg, e); } @Override public void error(String msg) { logger.log(Level.SEVERE, msg); } @Override public void error(String msg, Object... arguments) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); logger.log(Level.SEVERE, ft.getMessage(), ft.getThrowable()); } @Override public void error(String msg, Throwable e) { logger.log(Level.SEVERE, msg, e); } @Override public void error(Throwable e) { logger.log(Level.SEVERE, e.getMessage(), e); } @Override public void info(Throwable e) { logger.log(Level.INFO, e.getMessage(), e); } @Override public void warn(Throwable e) { logger.log(Level.WARNING, e.getMessage(), e); } @Override public boolean isTraceEnabled() { return logger.isLoggable(Level.FINER); } @Override public boolean isDebugEnabled() { return logger.isLoggable(Level.FINE); } @Override public boolean isInfoEnabled() { return logger.isLoggable(Level.INFO); } @Override public boolean isWarnEnabled() { return logger.isLoggable(Level.WARNING); } @Override public boolean isErrorEnabled() { return logger.isLoggable(Level.SEVERE); } }
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/logger/support/FailsafeLogger.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/support/FailsafeLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger.support; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.utils.NetUtils; public class FailsafeLogger implements Logger { private Logger logger; private static boolean disabled = false; public FailsafeLogger(Logger logger) { this.logger = logger; } public static void setDisabled(boolean disabled) { FailsafeLogger.disabled = disabled; } static boolean getDisabled() { return disabled; } public Logger getLogger() { return logger; } public void setLogger(Logger logger) { this.logger = logger; } private String appendContextMessage(String msg) { return " [DUBBO] " + msg + ", dubbo version: " + Version.getVersion() + ", current host: " + NetUtils.getLocalHost(); } @Override public void trace(String msg, Throwable e) { if (disabled || !logger.isTraceEnabled()) { return; } try { logger.trace(appendContextMessage(msg), e); } catch (Throwable ignored) { } } @Override public void trace(Throwable e) { if (disabled || !logger.isTraceEnabled()) { return; } try { logger.trace(e); } catch (Throwable ignored) { } } @Override public void trace(String msg) { if (disabled || !logger.isTraceEnabled()) { return; } try { logger.trace(appendContextMessage(msg)); } catch (Throwable ignored) { } } @Override public void trace(String msg, Object... arguments) { if (disabled || !logger.isTraceEnabled()) { return; } try { logger.trace(appendContextMessage(msg), arguments); } catch (Throwable ignored) { } } @Override public void debug(String msg, Throwable e) { if (disabled || !logger.isDebugEnabled()) { return; } try { logger.debug(appendContextMessage(msg), e); } catch (Throwable ignored) { } } @Override public void debug(Throwable e) { if (disabled || !logger.isDebugEnabled()) { return; } try { logger.debug(e); } catch (Throwable ignored) { } } @Override public void debug(String msg) { if (disabled || !logger.isDebugEnabled()) { return; } try { logger.debug(appendContextMessage(msg)); } catch (Throwable ignored) { } } @Override public void debug(String msg, Object... arguments) { if (disabled || !logger.isDebugEnabled()) { return; } try { logger.debug(appendContextMessage(msg), arguments); } catch (Throwable ignored) { } } @Override public void info(String msg, Throwable e) { if (disabled || !logger.isInfoEnabled()) { return; } try { logger.info(appendContextMessage(msg), e); } catch (Throwable ignored) { } } @Override public void info(String msg) { if (disabled || !logger.isInfoEnabled()) { return; } try { logger.info(appendContextMessage(msg)); } catch (Throwable ignored) { } } @Override public void info(String msg, Object... arguments) { if (disabled || !logger.isInfoEnabled()) { return; } try { logger.info(appendContextMessage(msg), arguments); } catch (Throwable ignored) { } } @Override public void warn(String msg, Throwable e) { if (disabled || !logger.isWarnEnabled()) { return; } try { logger.warn(appendContextMessage(msg), e); } catch (Throwable ignored) { } } @Override public void warn(String msg) { if (disabled || !logger.isWarnEnabled()) { return; } try { logger.warn(appendContextMessage(msg)); } catch (Throwable ignored) { } } @Override public void warn(String msg, Object... arguments) { if (disabled || !logger.isWarnEnabled()) { return; } try { logger.warn(appendContextMessage(msg), arguments); } catch (Throwable ignored) { } } @Override public void error(String msg, Throwable e) { if (disabled || !logger.isErrorEnabled()) { return; } try { logger.error(appendContextMessage(msg), e); } catch (Throwable ignored) { } } @Override public void error(String msg) { if (disabled || !logger.isErrorEnabled()) { return; } try { logger.error(appendContextMessage(msg)); } catch (Throwable ignored) { } } @Override public void error(String msg, Object... arguments) { if (disabled || !logger.isErrorEnabled()) { return; } try { logger.error(appendContextMessage(msg), arguments); } catch (Throwable ignored) { } } @Override public void error(Throwable e) { if (disabled || !logger.isErrorEnabled()) { return; } try { logger.error(e); } catch (Throwable ignored) { } } @Override public void info(Throwable e) { if (disabled || !logger.isInfoEnabled()) { return; } try { logger.info(e); } catch (Throwable ignored) { } } @Override public void warn(Throwable e) { if (disabled || !logger.isWarnEnabled()) { return; } try { logger.warn(e); } catch (Throwable ignored) { } } @Override public boolean isTraceEnabled() { if (disabled) { return false; } try { return logger.isTraceEnabled(); } catch (Throwable ignored) { return false; } } @Override public boolean isDebugEnabled() { if (disabled) { return false; } try { return logger.isDebugEnabled(); } catch (Throwable ignored) { return false; } } @Override public boolean isInfoEnabled() { if (disabled) { return false; } try { return logger.isInfoEnabled(); } catch (Throwable ignored) { return false; } } @Override public boolean isWarnEnabled() { if (disabled) { return false; } try { return logger.isWarnEnabled(); } catch (Throwable ignored) { return false; } } @Override public boolean isErrorEnabled() { if (disabled) { return false; } try { return logger.isErrorEnabled(); } catch (Throwable ignored) { return 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/common/logger/support/FailsafeErrorTypeAwareLogger.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/support/FailsafeErrorTypeAwareLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger.support; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.logger.ListenableLogger; import org.apache.dubbo.common.logger.LogListener; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.utils.NetUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; /** * A fail-safe (ignoring exception thrown by logger) wrapper of error type aware logger. */ public class FailsafeErrorTypeAwareLogger extends FailsafeLogger implements ListenableLogger { /** * Template address for formatting. */ private static final String INSTRUCTIONS_URL = "https://dubbo.apache.org/faq/%d/%d"; private static final Pattern ERROR_CODE_PATTERN = Pattern.compile("\\d+-\\d+"); /** * Listeners that listened to all Loggers. */ private static final List<LogListener> GLOBAL_LISTENERS = Collections.synchronizedList(new ArrayList<>()); /** * Listeners that listened to this listener. */ private final AtomicReference<List<LogListener>> listeners = new AtomicReference<>(); public FailsafeErrorTypeAwareLogger(Logger logger) { super(logger); } private String appendContextMessageWithInstructions( String code, String cause, String extendedInformation, String msg) { return " [DUBBO] " + msg + ", dubbo version: " + Version.getVersion() + ", current host: " + NetUtils.getLocalHost() + ", error code: " + code + ". This may be caused by " + cause + ", " + "go to " + getErrorUrl(code) + " to find instructions. " + extendedInformation; } private String getErrorUrl(String code) { String trimmedString = code.trim(); if (!ERROR_CODE_PATTERN.matcher(trimmedString).matches()) { error("Invalid error code: " + code + ", the format of error code is: X-X (where X is a number)."); return ""; } String[] segments = trimmedString.split("[-]"); int[] errorCodeSegments = new int[2]; try { errorCodeSegments[0] = Integer.parseInt(segments[0]); errorCodeSegments[1] = Integer.parseInt(segments[1]); } catch (NumberFormatException numberFormatException) { error( "Invalid error code: " + code + ", the format of error code is: X-X (where X is a number).", numberFormatException); return ""; } return String.format(INSTRUCTIONS_URL, errorCodeSegments[0], errorCodeSegments[1]); } @Override public void warn(String code, String cause, String extendedInformation, String msg) { if (getDisabled()) { return; } try { onEvent(code, msg); if (!getLogger().isWarnEnabled()) { return; } getLogger().warn(appendContextMessageWithInstructions(code, cause, extendedInformation, msg)); } catch (Throwable t) { // ignored. } } @Override public void warn(String code, String cause, String extendedInformation, String msg, Throwable e) { if (getDisabled()) { return; } try { onEvent(code, msg); if (!getLogger().isWarnEnabled()) { return; } getLogger().warn(appendContextMessageWithInstructions(code, cause, extendedInformation, msg), e); } catch (Throwable t) { // ignored. } } @Override public void error(String code, String cause, String extendedInformation, String msg) { if (getDisabled()) { return; } try { onEvent(code, msg); if (!getLogger().isErrorEnabled()) { return; } getLogger().error(appendContextMessageWithInstructions(code, cause, extendedInformation, msg)); } catch (Throwable t) { // ignored. } } @Override public void error(String code, String cause, String extendedInformation, String msg, Throwable e) { if (getDisabled()) { return; } try { onEvent(code, msg); if (!getLogger().isErrorEnabled()) { return; } getLogger().error(appendContextMessageWithInstructions(code, cause, extendedInformation, msg), e); } catch (Throwable t) { // ignored. } } public static void registerGlobalListen(LogListener listener) { GLOBAL_LISTENERS.add(listener); } @Override public void registerListen(LogListener listener) { listeners.getAndUpdate(logListeners -> { if (logListeners == null) { logListeners = Collections.synchronizedList(new ArrayList<>()); } logListeners.add(listener); return logListeners; }); } private void onEvent(String code, String msg) { Optional.ofNullable(listeners.get()) .ifPresent(logListeners -> logListeners.forEach(logListener -> { try { logListener.onMessage(code, msg); } catch (Exception e) { // ignored. } })); GLOBAL_LISTENERS.forEach(logListener -> { try { logListener.onMessage(code, msg); } catch (Exception e) { // ignored. } }); } }
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/logger/log4j2/Log4j2LoggerAdapter.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j2/Log4j2LoggerAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger.log4j2; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerAdapter; import java.io.File; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.config.Configurator; import org.apache.logging.log4j.spi.ExtendedLogger; public class Log4j2LoggerAdapter implements LoggerAdapter { public static final String NAME = "log4j2"; private Level level; public Log4j2LoggerAdapter() { try { org.apache.logging.log4j.Logger logger = LogManager.getRootLogger(); this.level = fromLog4j2Level(logger.getLevel()); } catch (Exception t) { // ignore } } private static org.apache.logging.log4j.Level toLog4j2Level(Level level) { if (level == Level.ALL) { return org.apache.logging.log4j.Level.ALL; } if (level == Level.TRACE) { return org.apache.logging.log4j.Level.TRACE; } if (level == Level.DEBUG) { return org.apache.logging.log4j.Level.DEBUG; } if (level == Level.INFO) { return org.apache.logging.log4j.Level.INFO; } if (level == Level.WARN) { return org.apache.logging.log4j.Level.WARN; } if (level == Level.ERROR) { return org.apache.logging.log4j.Level.ERROR; } return org.apache.logging.log4j.Level.OFF; } private static Level fromLog4j2Level(org.apache.logging.log4j.Level level) { if (level == org.apache.logging.log4j.Level.ALL) { return Level.ALL; } if (level == org.apache.logging.log4j.Level.TRACE) { return Level.TRACE; } if (level == org.apache.logging.log4j.Level.DEBUG) { return Level.DEBUG; } if (level == org.apache.logging.log4j.Level.INFO) { return Level.INFO; } if (level == org.apache.logging.log4j.Level.WARN) { return Level.WARN; } if (level == org.apache.logging.log4j.Level.ERROR) { return Level.ERROR; } return Level.OFF; } @Override public Logger getLogger(Class<?> key) { return new Log4j2Logger((ExtendedLogger) LogManager.getLogger(key)); } @Override public Logger getLogger(String key) { return new Log4j2Logger((ExtendedLogger) LogManager.getLogger(key)); } @Override public Logger getLogger(String fqcn, Class<?> key) { return new Log4j2Logger(fqcn, (ExtendedLogger) LogManager.getLogger(key)); } @Override public Logger getLogger(String fqcn, String key) { return new Log4j2Logger(fqcn, (ExtendedLogger) LogManager.getLogger(key)); } @Override public Level getLevel() { return level; } @Override public void setLevel(Level level) { this.level = level; Configurator.setLevel(LogManager.getRootLogger(), toLog4j2Level(level)); } @Override public File getFile() { return null; } @Override public void setFile(File file) { // ignore } @Override public boolean isConfigured() { return true; } }
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/logger/log4j2/Log4j2Logger.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j2/Log4j2Logger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger.log4j2; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.support.FailsafeLogger; import org.apache.logging.log4j.Level; public class Log4j2Logger implements Logger { private final String fqcn; private final org.apache.logging.log4j.spi.ExtendedLogger logger; public Log4j2Logger(org.apache.logging.log4j.spi.ExtendedLogger logger) { this.fqcn = FailsafeLogger.class.getName(); this.logger = logger; } public Log4j2Logger(String fqcn, org.apache.logging.log4j.spi.ExtendedLogger logger) { this.fqcn = fqcn; this.logger = logger; } @Override public void trace(String msg) { logger.logIfEnabled(fqcn, Level.TRACE, null, msg); } @Override public void trace(String msg, Object... arguments) { logger.logIfEnabled(fqcn, Level.TRACE, null, msg, arguments); } @Override public void trace(Throwable e) { logger.logIfEnabled(fqcn, Level.TRACE, null, e == null ? null : e.getMessage(), e); } @Override public void trace(String msg, Throwable e) { logger.logIfEnabled(fqcn, Level.TRACE, null, msg, e); } @Override public void debug(String msg) { logger.logIfEnabled(fqcn, Level.DEBUG, null, msg); } @Override public void debug(String msg, Object... arguments) { logger.logIfEnabled(fqcn, Level.DEBUG, null, msg, arguments); } @Override public void debug(Throwable e) { logger.logIfEnabled(fqcn, Level.DEBUG, null, e == null ? null : e.getMessage(), e); } @Override public void debug(String msg, Throwable e) { logger.logIfEnabled(fqcn, Level.DEBUG, null, msg, e); } @Override public void info(String msg) { logger.logIfEnabled(fqcn, Level.INFO, null, msg); } @Override public void info(String msg, Object... arguments) { logger.logIfEnabled(fqcn, Level.INFO, null, msg, arguments); } @Override public void info(Throwable e) { logger.logIfEnabled(fqcn, Level.INFO, null, e == null ? null : e.getMessage(), e); } @Override public void info(String msg, Throwable e) { logger.logIfEnabled(fqcn, Level.INFO, null, msg, e); } @Override public void warn(String msg) { logger.logIfEnabled(fqcn, Level.WARN, null, msg); } @Override public void warn(String msg, Object... arguments) { logger.logIfEnabled(fqcn, Level.WARN, null, msg, arguments); } @Override public void warn(Throwable e) { logger.logIfEnabled(fqcn, Level.WARN, null, e == null ? null : e.getMessage(), e); } @Override public void warn(String msg, Throwable e) { logger.logIfEnabled(fqcn, Level.WARN, null, msg, e); } @Override public void error(String msg) { logger.logIfEnabled(fqcn, Level.ERROR, null, msg); } @Override public void error(String msg, Object... arguments) { logger.logIfEnabled(fqcn, Level.ERROR, null, msg, arguments); } @Override public void error(Throwable e) { logger.logIfEnabled(fqcn, Level.ERROR, null, e == null ? null : e.getMessage(), e); } @Override public void error(String msg, Throwable e) { logger.logIfEnabled(fqcn, Level.ERROR, null, msg, e); } @Override public boolean isTraceEnabled() { return logger.isTraceEnabled(); } @Override public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override public boolean isWarnEnabled() { return logger.isWarnEnabled(); } @Override public boolean isErrorEnabled() { return logger.isErrorEnabled(); } // test purpose only public org.apache.logging.log4j.Logger getLogger() { return logger; } }
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/logger/helpers/FormattingTuple.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/helpers/FormattingTuple.java
/* * Copyright (c) 2004-2011 QOS.ch * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.apache.dubbo.common.logger.helpers; /** * Holds the results of formatting done by {@link MessageFormatter}. * This is a copy of org.slf4j.helpers.FormattingTuple from slf4j-api. */ public class FormattingTuple { static public FormattingTuple NULL = new FormattingTuple(null); private String message; private Throwable throwable; private Object[] argArray; public FormattingTuple(String message) { this(message, null, null); } public FormattingTuple(String message, Object[] argArray, Throwable throwable) { this.message = message; this.throwable = throwable; this.argArray = argArray; } public String getMessage() { return message; } public Object[] getArgArray() { return argArray; } public Throwable getThrowable() { return throwable; } }
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/logger/helpers/MessageFormatter.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/helpers/MessageFormatter.java
/* * Copyright (c) 2004-2011 QOS.ch * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.apache.dubbo.common.logger.helpers; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; /** * This is a copy of org.slf4j.helpers.MessageFormatter from slf4j-api. * Formats messages according to very simple substitution rules. Substitutions * can be made 1, 2 or more arguments. * * <p> * For example, * * <pre> * MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;) * </pre> * <p> * will return the string "Hi there.". * <p> * The {} pair is called the <em>formatting anchor</em>. It serves to designate * the location where arguments need to be substituted within the message * pattern. * <p> * In case your message contains the '{' or the '}' character, you do not have * to do anything special unless the '}' character immediately follows '{'. For * example, * * <pre> * MessageFormatter.format(&quot;Set {1,2,3} is not equal to {}.&quot;, &quot;1,2&quot;); * </pre> * <p> * will return the string "Set {1,2,3} is not equal to 1,2.". * * <p> * If for whatever reason you need to place the string "{}" in the message * without its <em>formatting anchor</em> meaning, then you need to escape the * '{' character with '\', that is the backslash character. Only the '{' * character should be escaped. There is no need to escape the '}' character. * For example, * * <pre> * MessageFormatter.format(&quot;Set \\{} is not equal to {}.&quot;, &quot;1,2&quot;); * </pre> * <p> * will return the string "Set {} is not equal to 1,2.". * * <p> * The escaping behavior just described can be overridden by escaping the escape * character '\'. Calling * * <pre> * MessageFormatter.format(&quot;File name is C:\\\\{}.&quot;, &quot;file.zip&quot;); * </pre> * <p> * will return the string "File name is C:\file.zip". * * <p> * The formatting conventions are different than those of {@link MessageFormat} * which ships with the Java platform. This is justified by the fact that * SLF4J's implementation is 10 times faster than that of {@link MessageFormat}. * This local performance difference is both measurable and significant in the * larger context of the complete logging processing chain. * * <p> * See also {@link #format(String, Object)}, * {@link #format(String, Object, Object)} and * {@link #arrayFormat(String, Object[])} methods for more details. * */ final public class MessageFormatter { static final char DELIM_START = '{'; static final char DELIM_STOP = '}'; static final String DELIM_STR = "{}"; private static final char ESCAPE_CHAR = '\\'; /** * Performs single argument substitution for the 'messagePattern' passed as * parameter. * <p> * For example, * * <pre> * MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;); * </pre> * <p> * will return the string "Hi there.". * <p> * * @param messagePattern The message pattern which will be parsed and formatted * @param arg The argument to be substituted in place of the formatting anchor * @return The formatted message */ final public static FormattingTuple format(String messagePattern, Object arg) { return arrayFormat(messagePattern, new Object[]{arg}); } /** * Performs a two argument substitution for the 'messagePattern' passed as * parameter. * <p> * For example, * * <pre> * MessageFormatter.format(&quot;Hi {}. My name is {}.&quot;, &quot;Alice&quot;, &quot;Bob&quot;); * </pre> * <p> * will return the string "Hi Alice. My name is Bob.". * * @param messagePattern The message pattern which will be parsed and formatted * @param arg1 The argument to be substituted in place of the first formatting * anchor * @param arg2 The argument to be substituted in place of the second formatting * anchor * @return The formatted message */ final public static FormattingTuple format(final String messagePattern, Object arg1, Object arg2) { return arrayFormat(messagePattern, new Object[]{arg1, arg2}); } final public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray) { Throwable throwableCandidate = MessageFormatter.getThrowableCandidate(argArray); Object[] args = argArray; if (throwableCandidate != null) { args = MessageFormatter.trimmedCopy(argArray); } return arrayFormat(messagePattern, args, throwableCandidate); } final public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray, Throwable throwable) { if (messagePattern == null) { return new FormattingTuple(null, argArray, throwable); } if (argArray == null) { return new FormattingTuple(messagePattern); } int i = 0; int j; // use string builder for better multicore performance StringBuilder sbuf = new StringBuilder(messagePattern.length() + 50); int L; for (L = 0; L < argArray.length; L++) { j = messagePattern.indexOf(DELIM_STR, i); if (j == -1) { // no more variables if (i == 0) { // this is a simple string return new FormattingTuple(messagePattern, argArray, throwable); } else { // add the tail string which contains no variables and return // the result. sbuf.append(messagePattern, i, messagePattern.length()); return new FormattingTuple(sbuf.toString(), argArray, throwable); } } else { if (isEscapedDelimeter(messagePattern, j)) { if (!isDoubleEscaped(messagePattern, j)) { L--; // DELIM_START was escaped, thus should not be incremented sbuf.append(messagePattern, i, j - 1); sbuf.append(DELIM_START); i = j + 1; } else { // The escape character preceding the delimiter start is // itself escaped: "abc x:\\{}" // we have to consume one backward slash sbuf.append(messagePattern, i, j - 1); deeplyAppendParameter(sbuf, argArray[L], new HashMap<Object[], Object>()); i = j + 2; } } else { // normal case sbuf.append(messagePattern, i, j); deeplyAppendParameter(sbuf, argArray[L], new HashMap<Object[], Object>()); i = j + 2; } } } // append the characters following the last {} pair. sbuf.append(messagePattern, i, messagePattern.length()); return new FormattingTuple(sbuf.toString(), argArray, throwable); } final static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) { if (delimeterStartIndex == 0) { return false; } char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1); if (potentialEscape == ESCAPE_CHAR) { return true; } else { return false; } } final static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) { if (delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR) { return true; } else { return false; } } // special treatment of array values was suggested by 'lizongbo' private static void deeplyAppendParameter(StringBuilder sbuf, Object o, Map<Object[], Object> seenMap) { if (o == null) { sbuf.append("null"); return; } if (!o.getClass().isArray()) { safeObjectAppend(sbuf, o); } else { // check for primitive array types because they // unfortunately cannot be cast to Object[] if (o instanceof boolean[]) { booleanArrayAppend(sbuf, (boolean[]) o); } else if (o instanceof byte[]) { byteArrayAppend(sbuf, (byte[]) o); } else if (o instanceof char[]) { charArrayAppend(sbuf, (char[]) o); } else if (o instanceof short[]) { shortArrayAppend(sbuf, (short[]) o); } else if (o instanceof int[]) { intArrayAppend(sbuf, (int[]) o); } else if (o instanceof long[]) { longArrayAppend(sbuf, (long[]) o); } else if (o instanceof float[]) { floatArrayAppend(sbuf, (float[]) o); } else if (o instanceof double[]) { doubleArrayAppend(sbuf, (double[]) o); } else { objectArrayAppend(sbuf, (Object[]) o, seenMap); } } } private static void safeObjectAppend(StringBuilder sbuf, Object o) { try { String oAsString = o.toString(); sbuf.append(oAsString); } catch (Throwable t) { System.err.println("SLF4J: Failed toString() invocation on an object of type [" + o.getClass().getName() + "]"); System.err.println("Reported exception:"); StackTraceElement[] stackTrace = t.getStackTrace(); StringBuilder stackBuilder = new StringBuilder(); for (StackTraceElement traceElement : stackTrace) { stackBuilder.append("\tat ").append(traceElement).append("\n"); } System.err.println(stackBuilder); sbuf.append("[FAILED toString()]"); } } private static void objectArrayAppend(StringBuilder sbuf, Object[] a, Map<Object[], Object> seenMap) { sbuf.append('['); if (!seenMap.containsKey(a)) { seenMap.put(a, null); final int len = a.length; for (int i = 0; i < len; i++) { deeplyAppendParameter(sbuf, a[i], seenMap); if (i != len - 1) sbuf.append(", "); } // allow repeats in siblings seenMap.remove(a); } else { sbuf.append("..."); } sbuf.append(']'); } private static void booleanArrayAppend(StringBuilder sbuf, boolean[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) sbuf.append(", "); } sbuf.append(']'); } private static void byteArrayAppend(StringBuilder sbuf, byte[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) sbuf.append(", "); } sbuf.append(']'); } private static void charArrayAppend(StringBuilder sbuf, char[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) sbuf.append(", "); } sbuf.append(']'); } private static void shortArrayAppend(StringBuilder sbuf, short[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) sbuf.append(", "); } sbuf.append(']'); } private static void intArrayAppend(StringBuilder sbuf, int[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) sbuf.append(", "); } sbuf.append(']'); } private static void longArrayAppend(StringBuilder sbuf, long[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) sbuf.append(", "); } sbuf.append(']'); } private static void floatArrayAppend(StringBuilder sbuf, float[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) sbuf.append(", "); } sbuf.append(']'); } private static void doubleArrayAppend(StringBuilder sbuf, double[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) sbuf.append(", "); } sbuf.append(']'); } /** * Helper method to determine if an {@link Object} array contains a {@link Throwable} as last element * * @param argArray The arguments off which we want to know if it contains a {@link Throwable} as last element * @return if the last {@link Object} in argArray is a {@link Throwable} this method will return it, * otherwise it returns null */ public static Throwable getThrowableCandidate(final Object[] argArray) { if (argArray == null || argArray.length == 0) { return null; } final Object lastEntry = argArray[argArray.length - 1]; if (lastEntry instanceof Throwable) { return (Throwable) lastEntry; } return null; } /** * Helper method to get all but the last element of an array * * @param argArray The arguments from which we want to remove the last element * @return a copy of the array without the last element */ public static Object[] trimmedCopy(final Object[] argArray) { if (argArray == null || argArray.length == 0) { throw new IllegalStateException("non-sensical empty or null argument array"); } final int trimmedLen = argArray.length - 1; Object[] trimmed = new Object[trimmedLen]; if (trimmedLen > 0) { System.arraycopy(argArray, 0, trimmed, 0, trimmedLen); } return trimmed; } }
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/logger/slf4j/Slf4jLoggerAdapter.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/slf4j/Slf4jLoggerAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger.slf4j; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerAdapter; import org.apache.dubbo.common.utils.ClassUtils; import java.io.File; import org.slf4j.LoggerFactory; public class Slf4jLoggerAdapter implements LoggerAdapter { public static final String NAME = "slf4j"; private Level level; private File file; private static final org.slf4j.Logger ROOT_LOGGER = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); public Slf4jLoggerAdapter() { this.level = Slf4jLogger.getLevel(ROOT_LOGGER); } @Override public Logger getLogger(String key) { return new Slf4jLogger(org.slf4j.LoggerFactory.getLogger(key)); } @Override public Logger getLogger(Class<?> key) { return new Slf4jLogger(org.slf4j.LoggerFactory.getLogger(key)); } @Override public Logger getLogger(String fqcn, Class<?> key) { return new Slf4jLogger(fqcn, org.slf4j.LoggerFactory.getLogger(key)); } @Override public Logger getLogger(String fqcn, String key) { return new Slf4jLogger(fqcn, org.slf4j.LoggerFactory.getLogger(key)); } @Override public Level getLevel() { return level; } @Override public void setLevel(Level level) { System.err.printf( "The level of slf4j logger current can not be set, using the default level: %s \n", Slf4jLogger.getLevel(ROOT_LOGGER)); this.level = level; } @Override public File getFile() { return file; } @Override public void setFile(File file) { this.file = file; } @Override public boolean isConfigured() { try { ClassUtils.forName("org.slf4j.impl.StaticLoggerBinder"); return true; } catch (ClassNotFoundException ignore) { // ignore } return 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/common/logger/slf4j/Slf4jLogger.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/slf4j/Slf4jLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger.slf4j; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.support.FailsafeLogger; import org.slf4j.helpers.FormattingTuple; import org.slf4j.helpers.MessageFormatter; import org.slf4j.spi.LocationAwareLogger; public class Slf4jLogger implements Logger { private final String fqcn; private final org.slf4j.Logger logger; private final LocationAwareLogger locationAwareLogger; public Slf4jLogger(org.slf4j.Logger logger) { if (logger instanceof LocationAwareLogger) { locationAwareLogger = (LocationAwareLogger) logger; } else { locationAwareLogger = null; } this.fqcn = FailsafeLogger.class.getName(); this.logger = logger; } public Slf4jLogger(String fqcn, org.slf4j.Logger logger) { if (logger instanceof LocationAwareLogger) { locationAwareLogger = (LocationAwareLogger) logger; } else { locationAwareLogger = null; } this.fqcn = fqcn; this.logger = logger; } @Override public void trace(String msg) { if (locationAwareLogger != null) { locationAwareLogger.log(null, fqcn, LocationAwareLogger.TRACE_INT, msg, null, null); return; } logger.trace(msg); } @Override public void trace(String msg, Object... arguments) { if (locationAwareLogger != null && locationAwareLogger.isTraceEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); locationAwareLogger.log( null, fqcn, LocationAwareLogger.TRACE_INT, msg, ft.getArgArray(), ft.getThrowable()); return; } logger.trace(msg, arguments); } @Override public void trace(Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log( null, fqcn, LocationAwareLogger.TRACE_INT, e == null ? null : e.getMessage(), null, e); return; } logger.trace(e == null ? null : e.getMessage(), e); } @Override public void trace(String msg, Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log(null, fqcn, LocationAwareLogger.TRACE_INT, msg, null, e); return; } logger.trace(msg, e); } @Override public void debug(String msg) { if (locationAwareLogger != null) { locationAwareLogger.log(null, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, null); return; } logger.debug(msg); } @Override public void debug(String msg, Object... arguments) { if (locationAwareLogger != null && locationAwareLogger.isDebugEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); locationAwareLogger.log( null, fqcn, LocationAwareLogger.DEBUG_INT, msg, ft.getArgArray(), ft.getThrowable()); return; } logger.debug(msg, arguments); } @Override public void debug(Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log( null, fqcn, LocationAwareLogger.DEBUG_INT, e == null ? null : e.getMessage(), null, e); return; } logger.debug(e == null ? null : e.getMessage(), e); } @Override public void debug(String msg, Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log(null, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, e); return; } logger.debug(msg, e); } @Override public void info(String msg) { if (locationAwareLogger != null) { locationAwareLogger.log(null, fqcn, LocationAwareLogger.INFO_INT, msg, null, null); return; } logger.info(msg); } @Override public void info(String msg, Object... arguments) { if (locationAwareLogger != null && locationAwareLogger.isInfoEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); locationAwareLogger.log(null, fqcn, LocationAwareLogger.INFO_INT, msg, ft.getArgArray(), ft.getThrowable()); return; } logger.info(msg, arguments); } @Override public void info(Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log( null, fqcn, LocationAwareLogger.INFO_INT, e == null ? null : e.getMessage(), null, e); return; } logger.info(e == null ? null : e.getMessage(), e); } @Override public void info(String msg, Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log(null, fqcn, LocationAwareLogger.INFO_INT, msg, null, e); return; } logger.info(msg, e); } @Override public void warn(String msg) { if (locationAwareLogger != null) { locationAwareLogger.log(null, fqcn, LocationAwareLogger.WARN_INT, msg, null, null); return; } logger.warn(msg); } @Override public void warn(String msg, Object... arguments) { if (locationAwareLogger != null && locationAwareLogger.isWarnEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); locationAwareLogger.log(null, fqcn, LocationAwareLogger.WARN_INT, msg, ft.getArgArray(), ft.getThrowable()); return; } logger.warn(msg, arguments); } @Override public void warn(Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log( null, fqcn, LocationAwareLogger.WARN_INT, e == null ? null : e.getMessage(), null, e); return; } logger.warn(e == null ? null : e.getMessage(), e); } @Override public void warn(String msg, Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log(null, fqcn, LocationAwareLogger.WARN_INT, msg, null, e); return; } logger.warn(msg, e); } @Override public void error(String msg) { if (locationAwareLogger != null) { locationAwareLogger.log(null, fqcn, LocationAwareLogger.ERROR_INT, msg, null, null); return; } logger.error(msg); } @Override public void error(String msg, Object... arguments) { if (locationAwareLogger != null && locationAwareLogger.isErrorEnabled()) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); locationAwareLogger.log( null, fqcn, LocationAwareLogger.ERROR_INT, msg, ft.getArgArray(), ft.getThrowable()); return; } logger.error(msg, arguments); } @Override public void error(Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log( null, fqcn, LocationAwareLogger.ERROR_INT, e == null ? null : e.getMessage(), null, e); return; } logger.error(e == null ? null : e.getMessage(), e); } @Override public void error(String msg, Throwable e) { if (locationAwareLogger != null) { locationAwareLogger.log(null, fqcn, LocationAwareLogger.ERROR_INT, msg, null, e); return; } logger.error(msg, e); } @Override public boolean isTraceEnabled() { return logger.isTraceEnabled(); } @Override public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override public boolean isWarnEnabled() { return logger.isWarnEnabled(); } @Override public boolean isErrorEnabled() { return logger.isErrorEnabled(); } public static Level getLevel(org.slf4j.Logger logger) { if (logger.isTraceEnabled()) { return Level.TRACE; } if (logger.isDebugEnabled()) { return Level.DEBUG; } if (logger.isInfoEnabled()) { return Level.INFO; } if (logger.isWarnEnabled()) { return Level.WARN; } if (logger.isErrorEnabled()) { return Level.ERROR; } return Level.OFF; } public Level getLevel() { return getLevel(logger); } }
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/logger/log4j/Log4jLogger.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j/Log4jLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger.log4j; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.support.FailsafeLogger; import org.apache.log4j.Level; import org.slf4j.helpers.FormattingTuple; import org.slf4j.helpers.MessageFormatter; public class Log4jLogger implements Logger { private final String fqcn; private final org.apache.log4j.Logger logger; public Log4jLogger(org.apache.log4j.Logger logger) { this.fqcn = FailsafeLogger.class.getName(); this.logger = logger; } public Log4jLogger(String fqcn, org.apache.log4j.Logger logger) { this.fqcn = fqcn; this.logger = logger; } @Override public void trace(String msg) { logger.log(fqcn, Level.TRACE, msg, null); } @Override public void trace(String msg, Object... arguments) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); logger.log(fqcn, Level.TRACE, ft.getMessage(), ft.getThrowable()); } @Override public void trace(Throwable e) { logger.log(fqcn, Level.TRACE, e == null ? null : e.getMessage(), e); } @Override public void trace(String msg, Throwable e) { logger.log(fqcn, Level.TRACE, msg, e); } @Override public void debug(String msg) { logger.log(fqcn, Level.DEBUG, msg, null); } @Override public void debug(String msg, Object... arguments) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); logger.log(fqcn, Level.DEBUG, ft.getMessage(), ft.getThrowable()); } @Override public void debug(Throwable e) { logger.log(fqcn, Level.DEBUG, e == null ? null : e.getMessage(), e); } @Override public void debug(String msg, Throwable e) { logger.log(fqcn, Level.DEBUG, msg, e); } @Override public void info(String msg) { logger.log(fqcn, Level.INFO, msg, null); } @Override public void info(String msg, Object... arguments) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); logger.log(fqcn, Level.INFO, ft.getMessage(), ft.getThrowable()); } @Override public void info(Throwable e) { logger.log(fqcn, Level.INFO, e == null ? null : e.getMessage(), e); } @Override public void info(String msg, Throwable e) { logger.log(fqcn, Level.INFO, msg, e); } @Override public void warn(String msg) { logger.log(fqcn, Level.WARN, msg, null); } @Override public void warn(String msg, Object... arguments) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); logger.log(fqcn, Level.WARN, ft.getMessage(), ft.getThrowable()); } @Override public void warn(Throwable e) { logger.log(fqcn, Level.WARN, e == null ? null : e.getMessage(), e); } @Override public void warn(String msg, Throwable e) { logger.log(fqcn, Level.WARN, msg, e); } @Override public void error(String msg) { logger.log(fqcn, Level.ERROR, msg, null); } @Override public void error(String msg, Object... arguments) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); logger.log(fqcn, Level.ERROR, ft.getMessage(), ft.getThrowable()); } @Override public void error(Throwable e) { logger.log(fqcn, Level.ERROR, e == null ? null : e.getMessage(), e); } @Override public void error(String msg, Throwable e) { logger.log(fqcn, Level.ERROR, msg, e); } @Override public boolean isTraceEnabled() { return logger.isTraceEnabled(); } @Override public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override public boolean isWarnEnabled() { return logger.isEnabledFor(Level.WARN); } @Override public boolean isErrorEnabled() { return logger.isEnabledFor(Level.ERROR); } }
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/logger/log4j/Log4jLoggerAdapter.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j/Log4jLoggerAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger.log4j; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerAdapter; import java.io.File; import java.util.Enumeration; import org.apache.log4j.Appender; import org.apache.log4j.FileAppender; import org.apache.log4j.LogManager; public class Log4jLoggerAdapter implements LoggerAdapter { public static final String NAME = "log4j"; private File file; @SuppressWarnings("unchecked") public Log4jLoggerAdapter() { try { org.apache.log4j.Logger logger = LogManager.getRootLogger(); if (logger != null) { Enumeration<Appender> appenders = logger.getAllAppenders(); if (appenders != null) { while (appenders.hasMoreElements()) { Appender appender = appenders.nextElement(); if (appender instanceof FileAppender) { FileAppender fileAppender = (FileAppender) appender; String filename = fileAppender.getFile(); file = new File(filename); break; } } } } } catch (Exception t) { // ignore } } private static org.apache.log4j.Level toLog4jLevel(Level level) { if (level == Level.ALL) { return org.apache.log4j.Level.ALL; } if (level == Level.TRACE) { return org.apache.log4j.Level.TRACE; } if (level == Level.DEBUG) { return org.apache.log4j.Level.DEBUG; } if (level == Level.INFO) { return org.apache.log4j.Level.INFO; } if (level == Level.WARN) { return org.apache.log4j.Level.WARN; } if (level == Level.ERROR) { return org.apache.log4j.Level.ERROR; } // if (level == Level.OFF) return org.apache.log4j.Level.OFF; } private static Level fromLog4jLevel(org.apache.log4j.Level level) { if (level == org.apache.log4j.Level.ALL) { return Level.ALL; } if (level == org.apache.log4j.Level.TRACE) { return Level.TRACE; } if (level == org.apache.log4j.Level.DEBUG) { return Level.DEBUG; } if (level == org.apache.log4j.Level.INFO) { return Level.INFO; } if (level == org.apache.log4j.Level.WARN) { return Level.WARN; } if (level == org.apache.log4j.Level.ERROR) { return Level.ERROR; } // if (level == org.apache.log4j.Level.OFF) return Level.OFF; } @Override public Logger getLogger(Class<?> key) { return new Log4jLogger(LogManager.getLogger(key)); } @Override public Logger getLogger(String key) { return new Log4jLogger(LogManager.getLogger(key)); } @Override public Logger getLogger(String fqcn, Class<?> key) { return new Log4jLogger(fqcn, LogManager.getLogger(key)); } @Override public Logger getLogger(String fqcn, String key) { return new Log4jLogger(fqcn, LogManager.getLogger(key)); } @Override public Level getLevel() { return fromLog4jLevel(LogManager.getRootLogger().getLevel()); } @Override public void setLevel(Level level) { LogManager.getRootLogger().setLevel(toLog4jLevel(level)); } @Override public File getFile() { return file; } @Override public void setFile(File file) { // ignore } @Override public boolean isConfigured() { boolean hasAppender = false; try { org.apache.log4j.Logger logger = LogManager.getRootLogger(); if (logger != null) { Enumeration<Appender> appenders = logger.getAllAppenders(); if (appenders != null) { while (appenders.hasMoreElements()) { hasAppender = true; Appender appender = appenders.nextElement(); if (appender instanceof FileAppender) { FileAppender fileAppender = (FileAppender) appender; String filename = fileAppender.getFile(); file = new File(filename); break; } } } } } catch (Exception t) { // ignore } return hasAppender; } }
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/logger/jcl/JclLogger.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLogger.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger.jcl; import org.apache.dubbo.common.logger.Logger; import org.apache.commons.logging.Log; import org.slf4j.helpers.FormattingTuple; import org.slf4j.helpers.MessageFormatter; /** * Adaptor to commons logging, depends on commons-logging.jar. For more information about commons logging, pls. refer to * <a target="_blank" href="http://www.apache.org/">http://www.apache.org/</a> */ public class JclLogger implements Logger { private final Log logger; public JclLogger(Log logger) { this.logger = logger; } @Override public void trace(String msg) { logger.trace(msg); } @Override public void trace(String msg, Object... arguments) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); logger.trace(ft.getMessage(), ft.getThrowable()); } @Override public void trace(Throwable e) { logger.trace(e); } @Override public void trace(String msg, Throwable e) { logger.trace(msg, e); } @Override public void debug(String msg) { logger.debug(msg); } @Override public void debug(String msg, Object... arguments) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); logger.debug(ft.getMessage(), ft.getThrowable()); } @Override public void debug(Throwable e) { logger.debug(e); } @Override public void debug(String msg, Throwable e) { logger.debug(msg, e); } @Override public void info(String msg) { logger.info(msg); } @Override public void info(String msg, Object... arguments) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); logger.info(ft.getMessage(), ft.getThrowable()); } @Override public void info(Throwable e) { logger.info(e); } @Override public void info(String msg, Throwable e) { logger.info(msg, e); } @Override public void warn(String msg) { logger.warn(msg); } @Override public void warn(String msg, Object... arguments) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); logger.warn(ft.getMessage(), ft.getThrowable()); } @Override public void warn(Throwable e) { logger.warn(e); } @Override public void warn(String msg, Throwable e) { logger.warn(msg, e); } @Override public void error(String msg) { logger.error(msg); } @Override public void error(String msg, Object... arguments) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); logger.error(ft.getMessage(), ft.getThrowable()); } @Override public void error(Throwable e) { logger.error(e); } @Override public void error(String msg, Throwable e) { logger.error(msg, e); } @Override public boolean isTraceEnabled() { return logger.isTraceEnabled(); } @Override public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override public boolean isWarnEnabled() { return logger.isWarnEnabled(); } @Override public boolean isErrorEnabled() { return logger.isErrorEnabled(); } }
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/logger/jcl/JclLoggerAdapter.java
dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLoggerAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.logger.jcl; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerAdapter; import java.io.File; import org.apache.commons.logging.LogFactory; public class JclLoggerAdapter implements LoggerAdapter { public static final String NAME = "jcl"; private Level level; private File file; @Override public Logger getLogger(String key) { return new JclLogger(LogFactory.getLog(key)); } @Override public Logger getLogger(Class<?> key) { return new JclLogger(LogFactory.getLog(key)); } @Override public Level getLevel() { return level; } @Override public void setLevel(Level level) { this.level = level; } @Override public File getFile() { return file; } @Override public void setFile(File file) { this.file = file; } }
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/resource/GlobalResourcesRepository.java
dubbo-common/src/main/java/org/apache/dubbo/common/resource/GlobalResourcesRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.resource; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NamedThreadFactory; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * Global resource repository between all framework models. * It will be destroyed only after all framework model is destroyed. */ public class GlobalResourcesRepository { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(GlobalResourcesRepository.class); private static volatile GlobalResourcesRepository instance; private volatile ExecutorService executorService; private final List<Disposable> oneoffDisposables = new CopyOnWriteArrayList<>(); private static final List<Disposable> globalReusedDisposables = new CopyOnWriteArrayList<>(); private GlobalResourcesRepository() {} public static GlobalResourcesRepository getInstance() { if (instance == null) { synchronized (GlobalResourcesRepository.class) { if (instance == null) { instance = new GlobalResourcesRepository(); } } } return instance; } /** * Register a global reused disposable. The disposable will be executed when all dubbo FrameworkModels are destroyed. * Note: the global disposable should be registered in static code, it's reusable and will not be removed when dubbo shutdown. * * @param disposable */ public static void registerGlobalDisposable(Disposable disposable) { if (!globalReusedDisposables.contains(disposable)) { synchronized (GlobalResourcesRepository.class) { if (!globalReusedDisposables.contains(disposable)) { globalReusedDisposables.add(disposable); } } } } public void removeGlobalDisposable(Disposable disposable) { if (globalReusedDisposables.contains(disposable)) { synchronized (GlobalResourcesRepository.class) { if (globalReusedDisposables.contains(disposable)) { this.globalReusedDisposables.remove(disposable); } } } } public static ExecutorService getGlobalExecutorService() { return getInstance().getExecutorService(); } public ExecutorService getExecutorService() { if (executorService == null || executorService.isShutdown()) { synchronized (this) { if (executorService == null || executorService.isShutdown()) { if (logger.isInfoEnabled()) { logger.info("Creating global shared handler ..."); } executorService = Executors.newCachedThreadPool(new NamedThreadFactory("Dubbo-global-shared-handler", true)); } } } return executorService; } public synchronized void destroy() { if (logger.isInfoEnabled()) { logger.info("Destroying global resources ..."); } if (executorService != null) { executorService.shutdownNow(); try { if (!executorService.awaitTermination( ConfigurationUtils.reCalShutdownTime(DEFAULT_SERVER_SHUTDOWN_TIMEOUT), TimeUnit.MILLISECONDS)) { logger.warn( COMMON_UNEXPECTED_EXCEPTION, "", "", "Wait global executor service terminated timeout."); } } catch (InterruptedException e) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "destroy resources failed: " + e.getMessage(), e); } executorService = null; } // call one-off disposables for (Disposable disposable : new ArrayList<>(oneoffDisposables)) { try { disposable.destroy(); } catch (Exception e) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "destroy resources failed: " + e.getMessage(), e); } } // clear one-off disposable oneoffDisposables.clear(); // call global disposable, don't clear globalReusedDisposables for reuse purpose for (Disposable disposable : new ArrayList<>(globalReusedDisposables)) { try { disposable.destroy(); } catch (Exception e) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "destroy resources failed: " + e.getMessage(), e); } } if (logger.isInfoEnabled()) { logger.info("Dubbo is completely destroyed"); } } /** * Register a one-off disposable, the disposable is removed automatically on first shutdown. * * @param disposable */ public void registerDisposable(Disposable disposable) { if (!oneoffDisposables.contains(disposable)) { synchronized (this) { if (!oneoffDisposables.contains(disposable)) { oneoffDisposables.add(disposable); } } } } public void removeDisposable(Disposable disposable) { if (oneoffDisposables.contains(disposable)) { synchronized (this) { if (oneoffDisposables.contains(disposable)) { oneoffDisposables.remove(disposable); } } } } // for test public static List<Disposable> getGlobalReusedDisposables() { return globalReusedDisposables; } // for test public List<Disposable> getOneoffDisposables() { return oneoffDisposables; } }
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/resource/Disposable.java
dubbo-common/src/main/java/org/apache/dubbo/common/resource/Disposable.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.resource; /** * An interface for destroying resources */ public interface Disposable { void destroy(); }
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/resource/Initializable.java
dubbo-common/src/main/java/org/apache/dubbo/common/resource/Initializable.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.resource; import org.apache.dubbo.common.extension.ExtensionAccessor; /** * An interface for Initializing resources */ public interface Initializable { default void initialize(ExtensionAccessor accessor) { initialize(); } default void initialize() {} }
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/resource/GlobalResourceInitializer.java
dubbo-common/src/main/java/org/apache/dubbo/common/resource/GlobalResourceInitializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.resource; import org.apache.dubbo.common.concurrent.CallableSafeInitializer; import java.util.concurrent.Callable; import java.util.function.Consumer; /** * A initializer to release resource automatically on dubbo shutdown */ public class GlobalResourceInitializer<T> extends CallableSafeInitializer<T> { /** * The Dispose action to be executed on shutdown. */ private Consumer<T> disposeAction; private Disposable disposable; public GlobalResourceInitializer(Callable<T> initializer) { super(initializer); } public GlobalResourceInitializer(Callable<T> initializer, Consumer<T> disposeAction) { super(initializer); this.disposeAction = disposeAction; } public GlobalResourceInitializer(Callable<T> callable, Disposable disposable) { super(callable); this.disposable = disposable; } @Override protected T initialize() { T value = super.initialize(); // register disposable to release automatically if (this.disposable != null) { GlobalResourcesRepository.getInstance().registerDisposable(this.disposable); } else { GlobalResourcesRepository.getInstance().registerDisposable(() -> this.remove(disposeAction)); } return value; } }
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/stream/StreamObserver.java
dubbo-common/src/main/java/org/apache/dubbo/common/stream/StreamObserver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.stream; /** * StreamObserver is a common streaming API. It is an observer for receiving messages. * Implementations are NOT required to be thread-safe. * * @param <T> type of message */ public interface StreamObserver<T> { /** * onNext * * @param data to process */ void onNext(T data); /** * onError * * @param throwable error */ void onError(Throwable throwable); /** * onCompleted */ void onCompleted(); }
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/cache/FileCacheStoreFactory.java
dubbo-common/src/main/java/org/apache/dubbo/common/cache/FileCacheStoreFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.cache; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.USER_HOME; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CACHE_PATH_INACCESSIBLE; /** * ClassLoader Level static share. * Prevent FileCacheStore being operated in multi-application */ public final class FileCacheStoreFactory { /** * Forbids instantiation. */ private FileCacheStoreFactory() { throw new UnsupportedOperationException("No instance of 'FileCacheStoreFactory' for you! "); } private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FileCacheStoreFactory.class); private static final ConcurrentMap<String, FileCacheStore> cacheMap = new ConcurrentHashMap<>(); private static final String SUFFIX = ".dubbo.cache"; private static final char ESCAPE_MARK = '%'; private static final Set<Character> LEGAL_CHARACTERS = Collections.unmodifiableSet(new HashSet<Character>() { { // - $ . _ 0-9 a-z A-Z add('-'); add('$'); add('.'); add('_'); for (char c = '0'; c <= '9'; c++) { add(c); } for (char c = 'a'; c <= 'z'; c++) { add(c); } for (char c = 'A'; c <= 'Z'; c++) { add(c); } } }); public static FileCacheStore getInstance(String basePath, String cacheName) { return getInstance(basePath, cacheName, true); } public static FileCacheStore getInstance(String basePath, String cacheName, boolean enableFileCache) { if (basePath == null) { // default case: ~/.dubbo basePath = SystemPropertyConfigUtils.getSystemProperty(USER_HOME) + File.separator + ".dubbo"; } if (basePath.endsWith(File.separator)) { basePath = basePath.substring(0, basePath.length() - 1); } File candidate = new File(basePath); Path path = candidate.toPath(); // ensure cache store path exists if (!candidate.isDirectory()) { try { Files.createDirectories(path); } catch (IOException e) { // 0-3 - cache path inaccessible logger.error( COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", "Cache store path can't be created: ", e); throw new RuntimeException("Cache store path can't be created: " + candidate, e); } } cacheName = safeName(cacheName); if (!cacheName.endsWith(SUFFIX)) { cacheName = cacheName + SUFFIX; } String cacheFilePath = basePath + File.separator + cacheName; return ConcurrentHashMapUtils.computeIfAbsent(cacheMap, cacheFilePath, k -> getFile(k, enableFileCache)); } /** * sanitize a name for valid file or directory name * * @param name origin file name * @return sanitized version of name */ private static String safeName(String name) { int len = name.length(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { char c = name.charAt(i); if (LEGAL_CHARACTERS.contains(c)) { sb.append(c); } else { sb.append(ESCAPE_MARK); sb.append(String.format("%04x", (int) c)); } } return sb.toString(); } /** * Get a file object for the given name * * @param name the file name * @return a file object */ private static FileCacheStore getFile(String name, boolean enableFileCache) { if (!enableFileCache) { return FileCacheStore.Empty.getInstance(name); } try { FileCacheStore.Builder builder = FileCacheStore.newBuilder(); tryFileLock(builder, name); File file = new File(name); if (!file.exists()) { Path pathObjectOfFile = file.toPath(); Files.createFile(pathObjectOfFile); } builder.cacheFilePath(name).cacheFile(file); return builder.build(); } catch (Throwable t) { logger.warn( COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", "Failed to create file store cache. Local file cache will be disabled. Cache file name: " + name, t); return FileCacheStore.Empty.getInstance(name); } } private static void tryFileLock(FileCacheStore.Builder builder, String fileName) throws PathNotExclusiveException { File lockFile = new File(fileName + ".lock"); FileLock dirLock; try { lockFile.createNewFile(); if (!lockFile.exists()) { throw new AssertionError("Failed to create lock file " + lockFile); } FileChannel lockFileChannel = new RandomAccessFile(lockFile, "rw").getChannel(); dirLock = lockFileChannel.tryLock(); } catch (OverlappingFileLockException ofle) { dirLock = null; } catch (IOException ioe) { throw new RuntimeException(ioe); } if (dirLock == null) { throw new PathNotExclusiveException( fileName + " is not exclusive. Maybe multiple Dubbo instances are using the same folder."); } lockFile.deleteOnExit(); builder.directoryLock(dirLock).lockFile(lockFile); } static void removeCache(String cacheFileName) { cacheMap.remove(cacheFileName); } private static class PathNotExclusiveException extends Exception { public PathNotExclusiveException(String msg) { super(msg); } } }
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/cache/FileCacheStore.java
dubbo-common/src/main/java/org/apache/dubbo/common/cache/FileCacheStore.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.cache; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.channels.FileLock; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CACHE_MAX_ENTRY_COUNT_LIMIT_EXCEED; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CACHE_MAX_FILE_SIZE_LIMIT_EXCEED; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CACHE_PATH_INACCESSIBLE; /** * Local file interaction class that can back different caches. * <p> * All items in local file are of human friendly format. */ public class FileCacheStore { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FileCacheStore.class); private final String cacheFilePath; private final File cacheFile; private final File lockFile; private final FileLock directoryLock; private FileCacheStore(String cacheFilePath, File cacheFile, File lockFile, FileLock directoryLock) { this.cacheFilePath = cacheFilePath; this.cacheFile = cacheFile; this.lockFile = lockFile; this.directoryLock = directoryLock; } public synchronized Map<String, String> loadCache(int entrySize) throws IOException { Map<String, String> properties = new HashMap<>(); try (BufferedReader reader = new BufferedReader(new FileReader(cacheFile))) { int count = 1; String line = reader.readLine(); while (line != null && count <= entrySize) { // content has '=' need to be encoded before write if (!line.startsWith("#") && line.contains("=")) { String[] pairs = line.split("="); properties.put(pairs[0], pairs[1]); count++; } line = reader.readLine(); } if (count > entrySize) { logger.warn( COMMON_CACHE_MAX_FILE_SIZE_LIMIT_EXCEED, "mis-configuration of system properties", "Check Java system property 'dubbo.mapping.cache.entrySize' and 'dubbo.meta.cache.entrySize'.", "Cache file was truncated for exceeding the maximum entry size: " + entrySize); } } catch (IOException e) { logger.warn(COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", "Load cache failed ", e); throw e; } return properties; } private void unlock() { if (directoryLock != null && directoryLock.isValid()) { try { directoryLock.release(); directoryLock.channel().close(); deleteFile(lockFile); } catch (IOException e) { logger.error( COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", "Failed to release cache path's lock file:" + lockFile, e); throw new RuntimeException("Failed to release cache path's lock file:" + lockFile, e); } } } public synchronized void refreshCache(Map<String, String> properties, String comment, long maxFileSize) { if (CollectionUtils.isEmptyMap(properties)) { return; } try (LimitedLengthBufferedWriter bw = new LimitedLengthBufferedWriter( new OutputStreamWriter(new FileOutputStream(cacheFile, false), StandardCharsets.UTF_8), maxFileSize)) { bw.write("#" + comment); bw.newLine(); bw.write("#" + new Date()); bw.newLine(); for (Map.Entry<String, String> e : properties.entrySet()) { String key = e.getKey(); String val = e.getValue(); bw.write(key + "=" + val); bw.newLine(); } bw.flush(); long remainSize = bw.getRemainSize(); if (remainSize < 0) { logger.warn( COMMON_CACHE_MAX_ENTRY_COUNT_LIMIT_EXCEED, "mis-configuration of system properties", "Check Java system property 'dubbo.mapping.cache.maxFileSize' and 'dubbo.meta.cache.maxFileSize'.", "Cache file was truncated for exceeding the maximum file size " + maxFileSize + " byte. Exceeded by " + (-remainSize) + " byte."); } } catch (IOException e) { logger.warn(COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", "Update cache error.", e); } } private static void deleteFile(File f) { Path pathOfFile = f.toPath(); try { Files.delete(pathOfFile); } catch (IOException ioException) { logger.debug("Failed to delete file " + f.getAbsolutePath(), ioException); } } public synchronized void destroy() { unlock(); FileCacheStoreFactory.removeCache(cacheFilePath); } public static Builder newBuilder() { return new Builder(); } public static class Builder { private String cacheFilePath; private File cacheFile; private File lockFile; private FileLock directoryLock; private Builder() {} public Builder cacheFilePath(String cacheFilePath) { this.cacheFilePath = cacheFilePath; return this; } public Builder cacheFile(File cacheFile) { this.cacheFile = cacheFile; return this; } public Builder lockFile(File lockFile) { this.lockFile = lockFile; return this; } public Builder directoryLock(FileLock directoryLock) { this.directoryLock = directoryLock; return this; } public FileCacheStore build() { return new FileCacheStore(cacheFilePath, cacheFile, lockFile, directoryLock); } } /** * An empty (or fallback) implementation of FileCacheStore. Used when cache file creation failed. */ protected static class Empty extends FileCacheStore { private Empty(String cacheFilePath) { super(cacheFilePath, null, null, null); } public static Empty getInstance(String cacheFilePath) { return new Empty(cacheFilePath); } @Override public synchronized Map<String, String> loadCache(int entrySize) throws IOException { return Collections.emptyMap(); } @Override public synchronized void refreshCache(Map<String, String> properties, String comment, long maxFileSize) { // No-op. } } /** * A BufferedWriter which limits the length (in bytes). When limit exceed, this writer stops writing. */ private static class LimitedLengthBufferedWriter extends BufferedWriter { private long remainSize; public LimitedLengthBufferedWriter(Writer out, long maxSize) { super(out); this.remainSize = maxSize == 0 ? Long.MAX_VALUE : maxSize; } @Override public void write(String str) throws IOException { remainSize -= str.getBytes(StandardCharsets.UTF_8).length; if (remainSize < 0) { return; } super.write(str); } public long getRemainSize() { return remainSize; } } }
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/deploy/DeployState.java
dubbo-common/src/main/java/org/apache/dubbo/common/deploy/DeployState.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.deploy; /** * Deploy state enum */ public enum DeployState { /** * Unknown state */ UNKNOWN, /** * Pending, wait for start */ PENDING, /** * Starting */ STARTING, /** * Started */ STARTED, /** * Completion */ COMPLETION, /** * Stopping */ STOPPING, /** * Stopped */ STOPPED, /** * Failed */ FAILED }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false